X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/854a92fc2755ace61c405df335ddf69b02a3d932..a2ef262a164fc735b9b8471ac0c8001eea2b9bf6:/hotline/server.go diff --git a/hotline/server.go b/hotline/server.go index 5b8aad0..0ee2dd7 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -4,22 +4,23 @@ import ( "bufio" "bytes" "context" + "crypto/rand" "encoding/binary" "errors" "fmt" "github.com/go-playground/validator/v10" - "go.uber.org/zap" + "golang.org/x/text/encoding/charmap" "gopkg.in/yaml.v3" "io" - "io/fs" - "io/ioutil" - "math/big" - "math/rand" + "log" + "log/slog" "net" "os" + "path" "path/filepath" "strings" "sync" + "sync/atomic" "time" ) @@ -29,32 +30,36 @@ var contextKeyReq = contextKey("req") type requestCtx struct { remoteAddr string - login string - name string } -const ( - userIdleSeconds = 300 // time in seconds before an inactive user is marked idle - idleCheckInterval = 10 // time in seconds to check for idle users - trackerUpdateFrequency = 300 // time in seconds between tracker re-registration -) +// Converts bytes from Mac Roman encoding to UTF-8 +var txtDecoder = charmap.Macintosh.NewDecoder() -var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client +// Converts bytes from UTF-8 to Mac Roman encoding +var txtEncoder = charmap.Macintosh.NewEncoder() type Server struct { - Port int - Accounts map[string]*Account - Agreement []byte - Clients map[uint16]*ClientConn + NetInterface string + Port int + Accounts map[string]*Account + Agreement []byte + + Clients map[[2]byte]*ClientConn fileTransfers map[[4]byte]*FileTransfer - Config *Config - ConfigDir string - Logger *zap.SugaredLogger - PrivateChats map[uint32]*PrivateChat - NextGuestID *uint16 + Config *Config + ConfigDir string + Logger *slog.Logger + banner []byte + + PrivateChatsMu sync.Mutex + PrivateChats map[[4]byte]*PrivateChat + + nextClientID atomic.Uint32 TrackerPassID [4]byte - Stats *Stats + + statsMu sync.Mutex + Stats *Stats FS FileStore // Storage backend to use for File storage @@ -71,39 +76,42 @@ type Server struct { banList map[string]*time.Time } +func (s *Server) CurrentStats() Stats { + s.statsMu.Lock() + defer s.statsMu.Unlock() + + stats := s.Stats + stats.CurrentlyConnected = len(s.Clients) + + return *stats +} + type PrivateChat struct { Subject string - ClientConn map[uint16]*ClientConn + ClientConn map[[2]byte]*ClientConn } -func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error { - s.Logger.Infow("Hotline server started", - "version", VERSION, - "API port", fmt.Sprintf(":%v", s.Port), - "Transfer port", fmt.Sprintf(":%v", s.Port+1), - ) - +func (s *Server) ListenAndServe(ctx context.Context) error { var wg sync.WaitGroup wg.Add(1) go func() { - ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port)) + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port)) if err != nil { - s.Logger.Fatal(err) + log.Fatal(err) } - s.Logger.Fatal(s.Serve(ctx, ln)) + log.Fatal(s.Serve(ctx, ln)) }() wg.Add(1) go func() { - ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1)) + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1)) if err != nil { - s.Logger.Fatal(err) - + log.Fatal(err) } - s.Logger.Fatal(s.ServeFileTransfers(ctx, ln)) + log.Fatal(s.ServeFileTransfers(ctx, ln)) }() wg.Wait() @@ -122,40 +130,29 @@ func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error defer func() { _ = conn.Close() }() err = s.handleFileTransfer( - context.WithValue(ctx, contextKeyReq, requestCtx{ - remoteAddr: conn.RemoteAddr().String(), - }), + context.WithValue(ctx, contextKeyReq, requestCtx{remoteAddr: conn.RemoteAddr().String()}), conn, ) if err != nil { - s.Logger.Errorw("file transfer error", "reason", err) + s.Logger.Error("file transfer error", "reason", err) } }() } } func (s *Server) sendTransaction(t Transaction) error { - clientID, err := byteToInt(*t.clientID) - if err != nil { - return err - } - s.mux.Lock() - client := s.Clients[uint16(clientID)] - if client == nil { - return fmt.Errorf("invalid client id %v", *t.clientID) - } - + client, ok := s.Clients[t.clientID] s.mux.Unlock() - b, err := t.MarshalBinary() - if err != nil { - return err + if !ok || client == nil { + return nil } - if _, err := client.Connection.Write(b); err != nil { - return err + _, err := io.Copy(client.Connection, &t) + if err != nil { + return fmt.Errorf("failed to send transaction to client %v: %v", t.clientID, err) } return nil @@ -166,7 +163,7 @@ func (s *Server) processOutbox() { t := <-s.outbox go func() { if err := s.sendTransaction(t); err != nil { - s.Logger.Errorw("error sending transaction", "err", err) + s.Logger.Error("error sending transaction", "err", err) } }() } @@ -178,21 +175,21 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { for { conn, err := ln.Accept() if err != nil { - s.Logger.Errorw("error accepting connection", "err", err) + s.Logger.Error("error accepting connection", "err", err) } connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{ remoteAddr: conn.RemoteAddr().String(), }) go func() { - s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr()) + s.Logger.Info("Connection established", "RemoteAddr", conn.RemoteAddr()) defer conn.Close() if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil { if err == io.EOF { - s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr()) + s.Logger.Info("Client disconnected", "RemoteAddr", conn.RemoteAddr()) } else { - s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err) + s.Logger.Error("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err) } } }() @@ -204,21 +201,22 @@ const ( ) // NewServer constructs a new Server from a config dir -func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) { +// TODO: move config file reads out of this function +func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, fs FileStore) (*Server, error) { server := Server{ + NetInterface: netInterface, Port: netPort, Accounts: make(map[string]*Account), Config: new(Config), - Clients: make(map[uint16]*ClientConn), + Clients: make(map[[2]byte]*ClientConn), fileTransfers: make(map[[4]byte]*FileTransfer), - PrivateChats: make(map[uint32]*PrivateChat), + PrivateChats: make(map[[4]byte]*PrivateChat), ConfigDir: configDir, Logger: logger, - NextGuestID: new(uint16), outbox: make(chan Transaction), - Stats: &Stats{StartTime: time.Now()}, + Stats: &Stats{Since: time.Now()}, ThreadedNews: &ThreadedNews{}, - FS: FS, + FS: fs, banList: make(map[string]*time.Time), } @@ -239,26 +237,36 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File } // try to load the ban list, but ignore errors as this file may not be present or may be empty - _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml")) + //_ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml")) - if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil { - return nil, err + _ = loadFromYAMLFile(filepath.Join(configDir, "Banlist.yaml"), &server.banList) + + err = loadFromYAMLFile(filepath.Join(configDir, "ThreadedNews.yaml"), &server.ThreadedNews) + if err != nil { + return nil, fmt.Errorf("error loading threaded news: %w", err) } - if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil { - return nil, err + err = server.loadConfig(filepath.Join(configDir, "config.yaml")) + if err != nil { + return nil, fmt.Errorf("error loading config: %w", err) } if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil { return nil, err } - server.Config.FileRoot = filepath.Join(configDir, "Files") + // If the FileRoot is an absolute path, use it, otherwise treat as a relative path to the config dir. + if !filepath.IsAbs(server.Config.FileRoot) { + server.Config.FileRoot = filepath.Join(configDir, server.Config.FileRoot) + } - *server.NextGuestID = 1 + server.banner, err = os.ReadFile(filepath.Join(server.ConfigDir, server.Config.BannerFile)) + if err != nil { + return nil, fmt.Errorf("error opening banner: %w", err) + } if server.Config.EnableTrackerRegistration { - server.Logger.Infow( + server.Logger.Info( "Tracker registration enabled", "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency), "trackers", server.Config.Trackers, @@ -268,16 +276,16 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File for { tr := &TrackerRegistration{ UserCount: server.userCount(), - PassID: server.TrackerPassID[:], + PassID: server.TrackerPassID, Name: server.Config.Name, Description: server.Config.Description, } binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port)) for _, t := range server.Config.Trackers { - if err := register(t, tr); err != nil { - server.Logger.Errorw("unable to register with tracker %v", "error", err) + if err := register(&RealDialer{}, t, tr); err != nil { + server.Logger.Error("unable to register with tracker %v", "error", err) } - server.Logger.Debugw("Sent Tracker registration", "addr", t) + server.Logger.Debug("Sent Tracker registration", "addr", t) } time.Sleep(trackerUpdateFrequency * time.Second) @@ -308,16 +316,15 @@ func (s *Server) keepaliveHandler() { if c.IdleTime > userIdleSeconds && !c.Idle { c.Idle = true - flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags))) - flagBitmap.SetBit(flagBitmap, userFlagAway, 1) - binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64())) - + c.flagsMU.Lock() + c.Flags.Set(UserFlagAway, 1) + c.flagsMU.Unlock() c.sendAll( - tranNotifyChangeUser, - NewField(fieldUserID, *c.ID), - NewField(fieldUserFlags, c.Flags), - NewField(fieldUserName, c.UserName), - NewField(fieldUserIconID, c.Icon), + TranNotifyChangeUser, + NewField(FieldUserID, c.ID[:]), + NewField(FieldUserFlags, c.Flags[:]), + NewField(FieldUserName, c.UserName), + NewField(FieldUserIconID, c.Icon), ) } } @@ -333,7 +340,7 @@ func (s *Server) writeBanList() error { if err != nil { return err } - err = ioutil.WriteFile( + err = os.WriteFile( filepath.Join(s.ConfigDir, "Banlist.yaml"), out, 0666, @@ -362,31 +369,23 @@ func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *Clie defer s.mux.Unlock() clientConn := &ClientConn{ - ID: &[]byte{0, 0}, - Icon: []byte{0, 0}, - Flags: []byte{0, 0}, - UserName: []byte{}, + Icon: []byte{0, 0}, // TODO: make array type Connection: conn, Server: s, - Version: []byte{}, - AutoReply: []byte{}, - transfers: map[int]map[[4]byte]*FileTransfer{}, - Agreed: false, RemoteAddr: remoteAddr, - } - clientConn.transfers = map[int]map[[4]byte]*FileTransfer{ - FileDownload: {}, - FileUpload: {}, - FolderDownload: {}, - FolderUpload: {}, - bannerDownload: {}, + transfers: map[int]map[[4]byte]*FileTransfer{ + FileDownload: {}, + FileUpload: {}, + FolderDownload: {}, + FolderUpload: {}, + bannerDownload: {}, + }, } - *s.NextGuestID++ - ID := *s.NextGuestID + s.nextClientID.Add(1) - binary.BigEndian.PutUint16(*clientConn.ID, ID) - s.Clients[ID] = clientConn + binary.BigEndian.PutUint16(clientConn.ID[:], uint16(s.nextClientID.Load())) + s.Clients[clientConn.ID] = clientConn return clientConn } @@ -396,32 +395,48 @@ func (s *Server) NewUser(login, name, password string, access accessBitmap) erro s.mux.Lock() defer s.mux.Unlock() - account := Account{ - Login: login, - Name: name, - Password: hashAndSalt([]byte(password)), - Access: access, + account := NewAccount(login, name, password, access) + + // Create account file, returning an error if one already exists. + file, err := os.OpenFile( + filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), + os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644, + ) + if err != nil { + return fmt.Errorf("error creating account file: %w", err) } - out, err := yaml.Marshal(&account) + defer file.Close() + + b, err := yaml.Marshal(account) if err != nil { return err } - s.Accounts[login] = &account - return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666) + _, err = file.Write(b) + if err != nil { + return fmt.Errorf("error writing account file: %w", err) + } + + s.Accounts[login] = account + + return nil } func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error { s.mux.Lock() defer s.mux.Unlock() - // update renames the user login + // If the login has changed, rename the account file. if login != newLogin { - err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml")) + err := os.Rename( + filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), + filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"), + ) if err != nil { - return err + return fmt.Errorf("error renaming account file: %w", err) } s.Accounts[newLogin] = s.Accounts[login] + s.Accounts[newLogin].Login = newLogin delete(s.Accounts, login) } @@ -436,7 +451,7 @@ func (s *Server) UpdateUser(login, newLogin, name, password string, access acces } if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil { - return err + return fmt.Errorf("error writing account file: %w", err) } return nil @@ -447,50 +462,46 @@ func (s *Server) DeleteUser(login string) error { s.mux.Lock() defer s.mux.Unlock() + err := s.FS.Remove(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml")) + if err != nil { + return err + } + delete(s.Accounts, login) - return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml")) + return nil } func (s *Server) connectedUsers() []Field { - s.mux.Lock() - defer s.mux.Unlock() + //s.mux.Lock() + //defer s.mux.Unlock() var connectedUsers []Field for _, c := range sortedClients(s.Clients) { - if !c.Agreed { - continue - } - user := User{ - ID: *c.ID, + b, err := io.ReadAll(&User{ + ID: c.ID, Icon: c.Icon, - Flags: c.Flags, + Flags: c.Flags[:], Name: string(c.UserName), + }) + if err != nil { + return nil } - connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload())) + connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, b)) } return connectedUsers } -func (s *Server) loadBanList(path string) error { +// loadFromYAMLFile loads data from a YAML file into the provided data structure. +func loadFromYAMLFile(path string, data interface{}) error { fh, err := os.Open(path) if err != nil { return err } - decoder := yaml.NewDecoder(fh) - - return decoder.Decode(s.banList) -} + defer fh.Close() -// loadThreadedNews loads the threaded news data from disk -func (s *Server) loadThreadedNews(threadedNewsPath string) error { - fh, err := os.Open(threadedNewsPath) - if err != nil { - return err - } decoder := yaml.NewDecoder(fh) - - return decoder.Decode(s.ThreadedNews) + return decoder.Decode(data) } // loadAccounts loads account data from disk @@ -501,19 +512,13 @@ func (s *Server) loadAccounts(userDir string) error { } if len(matches) == 0 { - return errors.New("no user accounts found in " + userDir) + return fmt.Errorf("no accounts found in directory: %s", userDir) } for _, file := range matches { - fh, err := s.FS.Open(file) - if err != nil { - return err - } - - account := Account{} - decoder := yaml.NewDecoder(fh) - if err := decoder.Decode(&account); err != nil { - return err + var account Account + if err = loadFromYAMLFile(file, &account); err != nil { + return fmt.Errorf("error loading account %s: %w", file, err) } s.Accounts[account.Login] = &account @@ -541,12 +546,41 @@ func (s *Server) loadConfig(path string) error { return nil } +func sendBanMessage(rwc io.Writer, message string) { + t := NewTransaction( + TranServerMsg, + [2]byte{0, 0}, + NewField(FieldData, []byte(message)), + NewField(FieldChatOptions, []byte{0, 0}), + ) + _, _ = io.Copy(rwc, &t) + time.Sleep(1 * time.Second) +} + // handleNewConnection takes a new net.Conn and performs the initial login sequence func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error { defer dontPanic(s.Logger) - if err := Handshake(rwc); err != nil { - return err + // Check if remoteAddr is present in the ban list + ipAddr := strings.Split(remoteAddr, ":")[0] + if banUntil, ok := s.banList[ipAddr]; ok { + // permaban + if banUntil == nil { + sendBanMessage(rwc, "You are permanently banned on this server") + s.Logger.Debug("Disconnecting permanently banned IP", "remoteAddr", ipAddr) + return nil + } + + // temporary ban + if time.Now().Before(*banUntil) { + sendBanMessage(rwc, "You are temporarily banned on this server") + s.Logger.Debug("Disconnecting temporarily banned IP", "remoteAddr", ipAddr) + return nil + } + } + + if err := performHandshake(rwc); err != nil { + return fmt.Errorf("error performing handshake: %w", err) } // Create a new scanner for parsing incoming bytes into transaction tokens @@ -555,47 +589,23 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser scanner.Scan() + // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the + // scanner re-uses the buffer for subsequent scans. + buf := make([]byte, len(scanner.Bytes())) + copy(buf, scanner.Bytes()) + var clientLogin Transaction - if _, err := clientLogin.Write(scanner.Bytes()); err != nil { - return err + if _, err := clientLogin.Write(buf); err != nil { + return fmt.Errorf("error writing login transaction: %w", err) } c := s.NewClientConn(rwc, remoteAddr) - - // check if remoteAddr is present in the ban list - if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok { - // permaban - if banUntil == nil { - s.outbox <- *NewTransaction( - tranServerMsg, - c.ID, - NewField(fieldData, []byte("You are permanently banned on this server")), - NewField(fieldChatOptions, []byte{0, 0}), - ) - time.Sleep(1 * time.Second) - return nil - } else if time.Now().Before(*banUntil) { - s.outbox <- *NewTransaction( - tranServerMsg, - c.ID, - NewField(fieldData, []byte("You are temporarily banned on this server")), - NewField(fieldChatOptions, []byte{0, 0}), - ) - time.Sleep(1 * time.Second) - return nil - } - - } defer c.Disconnect() - encodedLogin := clientLogin.GetField(fieldUserLogin).Data - encodedPassword := clientLogin.GetField(fieldUserPassword).Data - c.Version = clientLogin.GetField(fieldVersion).Data + encodedPassword := clientLogin.GetField(FieldUserPassword).Data + c.Version = clientLogin.GetField(FieldVersion).Data - var login string - for _, char := range encodedLogin { - login += string(rune(255 - uint(char))) - } + login := string(encodeString(clientLogin.GetField(FieldUserLogin).Data)) if login == "" { login = GuestAccount } @@ -604,84 +614,92 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser // If authentication fails, send error reply and close connection if !c.Authenticate(login, encodedPassword) { - t := c.NewErrReply(&clientLogin, "Incorrect login.") - b, err := t.MarshalBinary() + t := c.NewErrReply(&clientLogin, "Incorrect login.")[0] + + _, err := io.Copy(rwc, &t) if err != nil { return err } - if _, err := rwc.Write(b); err != nil { - return err - } - c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version)) + c.logger.Info("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version)) return nil } - if clientLogin.GetField(fieldUserIconID).Data != nil { - c.Icon = clientLogin.GetField(fieldUserIconID).Data + if clientLogin.GetField(FieldUserIconID).Data != nil { + c.Icon = clientLogin.GetField(FieldUserIconID).Data } + c.Lock() c.Account = c.Server.Accounts[login] + c.Unlock() - if clientLogin.GetField(fieldUserName).Data != nil { + if clientLogin.GetField(FieldUserName).Data != nil { if c.Authorize(accessAnyName) { - c.UserName = clientLogin.GetField(fieldUserName).Data + c.UserName = clientLogin.GetField(FieldUserName).Data } else { c.UserName = []byte(c.Account.Name) } } if c.Authorize(accessDisconUser) { - c.Flags = []byte{0, 2} + c.Flags.Set(UserFlagAdmin, 1) } s.outbox <- c.NewReply(&clientLogin, - NewField(fieldVersion, []byte{0x00, 0xbe}), - NewField(fieldCommunityBannerID, []byte{0, 0}), - NewField(fieldServerName, []byte(s.Config.Name)), + NewField(FieldVersion, []byte{0x00, 0xbe}), + NewField(FieldCommunityBannerID, []byte{0, 0}), + NewField(FieldServerName, []byte(s.Config.Name)), ) // Send user access privs so client UI knows how to behave - c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:])) + c.Server.outbox <- NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:])) // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between - // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send - // tranShowAgreement but with the NoServerAgreement field set to 1. + // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send + // TranShowAgreement but with the NoServerAgreement field set to 1. if c.Authorize(accessNoAgreement) { // If client version is nil, then the client uses the 1.2.3 login behavior if c.Version != nil { - c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1})) + c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1})) } } else { - c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement)) + c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement)) } - // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed - if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) { - c.Agreed = true - c.logger = c.logger.With("name", string(c.UserName)) - c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }())) + // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login + // flow and not the 1.5+ flow. + if len(c.UserName) != 0 { + // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as + // part of TranAgreed + c.logger = c.logger.With("Name", string(c.UserName)) + c.logger.Info("Login successful", "clientVersion", "Not sent (probably 1.2.3)") + // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this + // information yet, so we do it in TranAgreed instead for _, t := range c.notifyOthers( - *NewTransaction( - tranNotifyChangeUser, nil, - NewField(fieldUserName, c.UserName), - NewField(fieldUserID, *c.ID), - NewField(fieldUserIconID, c.Icon), - NewField(fieldUserFlags, c.Flags), + NewTransaction( + TranNotifyChangeUser, [2]byte{0, 0}, + NewField(FieldUserName, c.UserName), + NewField(FieldUserID, c.ID[:]), + NewField(FieldUserIconID, c.Icon), + NewField(FieldUserFlags, c.Flags[:]), ), ) { c.Server.outbox <- t } } - c.Server.Stats.LoginCount += 1 + c.Server.mux.Lock() + c.Server.Stats.ConnectionCounter += 1 + if len(s.Clients) > c.Server.Stats.ConnectionPeak { + c.Server.Stats.ConnectionPeak = len(s.Clients) + } + c.Server.mux.Unlock() // Scan for new transactions and handle them as they come in. for scanner.Scan() { - // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the - // scanner re-uses the buffer for subsequent scans. + // Copy the scanner bytes to a new slice to it to avoid a data race when the scanner re-uses the buffer. buf := make([]byte, len(scanner.Bytes())) copy(buf, scanner.Bytes()) @@ -690,26 +708,22 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser return err } - if err := c.handleTransaction(t); err != nil { - c.logger.Errorw("Error handling transaction", "err", err) - } + c.handleTransaction(t) } return nil } -func (s *Server) NewPrivateChat(cc *ClientConn) []byte { - s.mux.Lock() - defer s.mux.Unlock() +func (s *Server) NewPrivateChat(cc *ClientConn) [4]byte { + s.PrivateChatsMu.Lock() + defer s.PrivateChatsMu.Unlock() - randID := make([]byte, 4) - rand.Read(randID) - data := binary.BigEndian.Uint32(randID[:]) + var randID [4]byte + _, _ = rand.Read(randID[:]) - s.PrivateChats[data] = &PrivateChat{ - Subject: "", - ClientConn: make(map[uint16]*ClientConn), + s.PrivateChats[randID] = &PrivateChat{ + ClientConn: make(map[[2]byte]*ClientConn), } - s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc + s.PrivateChats[randID].ClientConn[cc.ID] = cc return randID } @@ -722,14 +736,10 @@ const dlFldrActionNextFile = 3 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error { defer dontPanic(s.Logger) - txBuf := make([]byte, 16) - if _, err := io.ReadFull(rwc, txBuf); err != nil { - return err - } - + // The first 16 bytes contain the file transfer. var t transfer - if _, err := t.Write(txBuf); err != nil { - return err + if _, err := io.CopyN(&t, rwc, 16); err != nil { + return fmt.Errorf("error reading file transfer: %w", err) } defer func() { @@ -737,6 +747,10 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro delete(s.fileTransfers, t.ReferenceNumber) s.mux.Unlock() + // Wait a few seconds before closing the connection: this is a workaround for problems + // observed with Windows clients where the client must initiate close of the TCP connection before + // the server does. This is gross and seems unnecessary. TODO: Revisit? + time.Sleep(3 * time.Second) }() s.mux.Lock() @@ -755,7 +769,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro rLogger := s.Logger.With( "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr, "login", fileTransfer.ClientConn.Account.Login, - "name", string(fileTransfer.ClientConn.UserName), + "Name", string(fileTransfer.ClientConn.UserName), ) fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) @@ -765,455 +779,56 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro switch fileTransfer.Type { case bannerDownload: - if err := s.bannerDownload(rwc); err != nil { - panic(err) - return err + if _, err := io.Copy(rwc, bytes.NewBuffer(s.banner)); err != nil { + return fmt.Errorf("error sending banner: %w", err) } case FileDownload: s.Stats.DownloadCounter += 1 + s.Stats.DownloadsInProgress += 1 + defer func() { + s.Stats.DownloadsInProgress -= 1 + }() - var dataOffset int64 - if fileTransfer.fileResumeData != nil { - dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) - } - - fw, err := newFileWrapper(s.FS, fullPath, 0) - if err != nil { - return err - } - - rLogger.Infow("File download started", "filePath", fullPath) - - // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client - if fileTransfer.options == nil { - // Start by sending flat file object to client - if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil { - return err - } - } - - file, err := fw.dataForkReader() - if err != nil { - return err - } - - br := bufio.NewReader(file) - if _, err := br.Discard(int(dataOffset)); err != nil { - return err - } - - if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil { - return err - } - - // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data - if fileTransfer.fileResumeData == nil { - err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader()) - if err != nil { - return err - } - } - - rFile, err := fw.rsrcForkFile() + err = DownloadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, true) if err != nil { - return nil - } - - if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { - return err + return fmt.Errorf("file download error: %w", err) } case FileUpload: s.Stats.UploadCounter += 1 + s.Stats.UploadsInProgress += 1 + defer func() { s.Stats.UploadsInProgress -= 1 }() - var file *os.File - - // A file upload has three possible cases: - // 1) Upload a new file - // 2) Resume a partially transferred file - // 3) Replace a fully uploaded file - // We have to infer which case applies by inspecting what is already on the filesystem - - // 1) Check for existing file: - _, err = os.Stat(fullPath) - if err == nil { - return errors.New("existing file found at " + fullPath) - } - if errors.Is(err, fs.ErrNotExist) { - // If not found, open or create a new .incomplete file - file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) - if err != nil { - return err - } - } - - f, err := newFileWrapper(s.FS, fullPath, 0) + err = UploadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err - } - - rLogger.Infow("File upload started", "dstFile", fullPath) - - rForkWriter := io.Discard - iForkWriter := io.Discard - if s.Config.PreserveResourceForks { - rForkWriter, err = f.rsrcForkWriter() - if err != nil { - return err - } - - iForkWriter, err = f.infoForkWriter() - if err != nil { - return err - } - } - - if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { - s.Logger.Error(err) - } - - if err := file.Close(); err != nil { - return err + return fmt.Errorf("file upload error: %w", err) } - if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil { - return err - } - - rLogger.Infow("File upload complete", "dstFile", fullPath) case FolderDownload: - // Folder Download flow: - // 1. Get filePath from the transfer - // 2. Iterate over files - // 3. For each fileWrapper: - // Send fileWrapper header to client - // The client can reply in 3 ways: - // - // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed: - // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper - // - // 2. If download of a fileWrapper is to be resumed: - // client sends: - // []byte{0x00, 0x02} // download folder action - // [2]byte // Resume data size - // []byte fileWrapper resume data (see myField_FileResumeData) - // - // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01} - // - // When download is requested (case 2 or 3), server replies with: - // [4]byte - fileWrapper size - // []byte - Flattened File Object - // - // After every fileWrapper download, client could request next fileWrapper with: - // []byte{0x00, 0x03} - // - // This notifies the server to send the next item header - - basePathLen := len(fullPath) - - rLogger.Infow("Start folder download", "path", fullPath) - - nextAction := make([]byte, 2) - if _, err := io.ReadFull(rwc, nextAction); err != nil { - return err - } - - i := 0 - err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error { - s.Stats.DownloadCounter += 1 - i += 1 - - if err != nil { - return err - } - - // skip dot files - if strings.HasPrefix(info.Name(), ".") { - return nil - } - - hlFile, err := newFileWrapper(s.FS, path, 0) - if err != nil { - return err - } - - subPath := path[basePathLen+1:] - rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir()) - - if i == 1 { - return nil - } - - fileHeader := NewFileHeader(subPath, info.IsDir()) - - // Send the fileWrapper header to client - if _, err := rwc.Write(fileHeader.Payload()); err != nil { - s.Logger.Errorf("error sending file header: %v", err) - return err - } - - // Read the client's Next Action request - if _, err := io.ReadFull(rwc, nextAction); err != nil { - return err - } - - rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) - - var dataOffset int64 - - switch nextAction[1] { - case dlFldrActionResumeFile: - // get size of resumeData - resumeDataByteLen := make([]byte, 2) - if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil { - return err - } - - resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen) - resumeDataBytes := make([]byte, resumeDataLen) - if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil { - return err - } - - var frd FileResumeData - if err := frd.UnmarshalBinary(resumeDataBytes); err != nil { - return err - } - dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:])) - case dlFldrActionNextFile: - // client asked to skip this file - return nil - } - - if info.IsDir() { - return nil - } - - rLogger.Infow("File download started", - "fileName", info.Name(), - "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)), - ) - - // Send file size to client - if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil { - s.Logger.Error(err) - return err - } - - // Send ffo bytes to client - if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil { - s.Logger.Error(err) - return err - } - - file, err := s.FS.Open(path) - if err != nil { - return err - } - - // wr := bufio.NewWriterSize(rwc, 1460) - if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil { - return err - } - - if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 { - err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader()) - if err != nil { - return err - } - - rFile, err := hlFile.rsrcForkFile() - if err != nil { - return err - } - - if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { - return err - } - } - - // Read the client's Next Action request. This is always 3, I think? - if _, err := io.ReadFull(rwc, nextAction); err != nil { - return err - } - - return nil - }) + s.Stats.DownloadCounter += 1 + s.Stats.DownloadsInProgress += 1 + defer func() { s.Stats.DownloadsInProgress -= 1 }() + err = DownloadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err + return fmt.Errorf("file upload error: %w", err) } case FolderUpload: - rLogger.Infow( + s.Stats.UploadCounter += 1 + s.Stats.UploadsInProgress += 1 + defer func() { s.Stats.UploadsInProgress -= 1 }() + rLogger.Info( "Folder upload started", "dstPath", fullPath, "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize), "FolderItemCount", fileTransfer.FolderItemCount, ) - // Check if the target folder exists. If not, create it. - if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) { - if err := s.FS.Mkdir(fullPath, 0777); err != nil { - return err - } - } - - // Begin the folder upload flow by sending the "next file action" to client - if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - - fileSize := make([]byte, 4) - - for i := 0; i < fileTransfer.ItemCount(); i++ { - s.Stats.UploadCounter += 1 - - var fu folderUpload - if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil { - return err - } - if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil { - return err - } - if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil { - return err - } - - fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes - - if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil { - return err - } - - rLogger.Infow( - "Folder upload continued", - "FormattedPath", fu.FormattedPath(), - "IsFolder", fmt.Sprintf("%x", fu.IsFolder), - "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), - ) - - if fu.IsFolder == [2]byte{0, 1} { - if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) { - if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil { - return err - } - } - - // Tell client to send next file - if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - } else { - nextAction := dlFldrActionSendFile - - // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. - _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath())) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - return err - } - if err == nil { - nextAction = dlFldrActionNextFile - } - - // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. - incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix)) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - return err - } - if err == nil { - nextAction = dlFldrActionResumeFile - } - - if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil { - return err - } - - switch nextAction { - case dlFldrActionNextFile: - continue - case dlFldrActionResumeFile: - offset := make([]byte, 4) - binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size())) - - file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return err - } - - fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)}) - - b, _ := fileResumeData.BinaryMarshal() - - bs := make([]byte, 2) - binary.BigEndian.PutUint16(bs, uint16(len(b))) - - if _, err := rwc.Write(append(bs, b...)); err != nil { - return err - } - - if _, err := io.ReadFull(rwc, fileSize); err != nil { - return err - } - - if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil { - s.Logger.Error(err) - } - - err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath()) - if err != nil { - return err - } - - case dlFldrActionSendFile: - if _, err := io.ReadFull(rwc, fileSize); err != nil { - return err - } - - filePath := filepath.Join(fullPath, fu.FormattedPath()) - - hlFile, err := newFileWrapper(s.FS, filePath, 0) - if err != nil { - return err - } - - rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize)) - - incWriter, err := hlFile.incFileWriter() - if err != nil { - return err - } - - rForkWriter := io.Discard - iForkWriter := io.Discard - if s.Config.PreserveResourceForks { - iForkWriter, err = hlFile.infoForkWriter() - if err != nil { - return err - } - - rForkWriter, err = hlFile.rsrcForkWriter() - if err != nil { - return err - } - } - if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { - return err - } - - if err := os.Rename(filePath+".incomplete", filePath); err != nil { - return err - } - } - - // Tell client to send next fileWrapper - if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - } + err = UploadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) + if err != nil { + return fmt.Errorf("file upload error: %w", err) } - rLogger.Infof("Folder upload complete") } - return nil }