X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/b196a50a44a5c72fc43df39fce4407d05ec8863b..a2ef262a164fc735b9b8471ac0c8001eea2b9bf6:/hotline/server.go diff --git a/hotline/server.go b/hotline/server.go index 33888e0..0ee2dd7 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -1,99 +1,117 @@ package hotline 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" - "runtime/debug" - "sort" "strings" "sync" + "sync/atomic" "time" - - "gopkg.in/yaml.v3" ) -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 -) +type contextKey string -var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client +var contextKeyReq = contextKey("req") + +type requestCtx struct { + remoteAddr string +} + +// Converts bytes from Mac Roman encoding to UTF-8 +var txtDecoder = charmap.Macintosh.NewDecoder() + +// 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 - FlatNews []byte - ThreadedNews *ThreadedNews - FileTransfers map[uint32]*FileTransfer - Config *Config - ConfigDir string - Logger *zap.SugaredLogger - PrivateChats map[uint32]*PrivateChat - NextGuestID *uint16 + 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 *slog.Logger + banner []byte + + PrivateChatsMu sync.Mutex + PrivateChats map[[4]byte]*PrivateChat + + nextClientID atomic.Uint32 TrackerPassID [4]byte - Stats *Stats - FS FileStore + statsMu sync.Mutex + Stats *Stats - // newsReader io.Reader - // newsWriter io.WriteCloser + FS FileStore // Storage backend to use for File storage outbox chan Transaction + mux sync.Mutex + + threadedNewsMux sync.Mutex + ThreadedNews *ThreadedNews - mux sync.Mutex flatNewsMux sync.Mutex + FlatNews []byte + + banListMU sync.Mutex + 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, cancelRoot, 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(ln)) + log.Fatal(s.ServeFileTransfers(ctx, ln)) }() wg.Wait() @@ -101,7 +119,7 @@ func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFu return nil } -func (s *Server) ServeFileTransfers(ln net.Listener) error { +func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error { for { conn, err := ln.Accept() if err != nil { @@ -109,74 +127,69 @@ func (s *Server) ServeFileTransfers(ln net.Listener) error { } go func() { - if err := s.handleFileTransfer(conn); err != nil { - s.Logger.Errorw("file transfer error", "reason", err) + defer func() { _ = conn.Close() }() + + err = s.handleFileTransfer( + context.WithValue(ctx, contextKeyReq, requestCtx{remoteAddr: conn.RemoteAddr().String()}), + conn, + ) + + if err != nil { + s.Logger.Error("file transfer error", "reason", err) } }() } } func (s *Server) sendTransaction(t Transaction) error { - requestNum := binary.BigEndian.Uint16(t.Type) - clientID, err := byteToInt(*t.clientID) - if err != nil { - return err - } - s.mux.Lock() - client := s.Clients[uint16(clientID)] + client, ok := s.Clients[t.clientID] s.mux.Unlock() - if client == nil { - return fmt.Errorf("invalid client id %v", *t.clientID) - } - userName := string(client.UserName) - login := client.Account.Login - handler := TransactionHandlers[requestNum] + if !ok || client == nil { + return nil + } - b, err := t.MarshalBinary() + _, err := io.Copy(client.Connection, &t) if err != nil { - return err - } - var n int - if n, err = client.Connection.Write(b); err != nil { - return err + return fmt.Errorf("failed to send transaction to client %v: %v", t.clientID, err) } - s.Logger.Debugw("Sent Transaction", - "name", userName, - "login", login, - "IsReply", t.IsReply, - "type", handler.Name, - "sentBytes", n, - "remoteAddr", client.RemoteAddr, - ) + return nil } -func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error { +func (s *Server) processOutbox() { + for { + t := <-s.outbox + go func() { + if err := s.sendTransaction(t); err != nil { + s.Logger.Error("error sending transaction", "err", err) + } + }() + } +} + +func (s *Server) Serve(ctx context.Context, ln net.Listener) error { + go s.processOutbox() 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() { - for { - t := <-s.outbox - go func() { - if err := s.sendTransaction(t); err != nil { - s.Logger.Errorw("error sending transaction", "err", err) - } - }() - } - }() - go func() { - if err := s.handleNewConnection(conn, conn.RemoteAddr().String()); err != nil { + 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) } } }() @@ -188,21 +201,23 @@ const ( ) // NewServer constructs a new Server from a config dir -func NewServer(configDir, netInterface 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), - FileTransfers: make(map[uint32]*FileTransfer), - PrivateChats: make(map[uint32]*PrivateChat), + Clients: make(map[[2]byte]*ClientConn), + fileTransfers: make(map[[4]byte]*FileTransfer), + 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), } var err error @@ -212,33 +227,46 @@ func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredL return nil, err } - server.Agreement, err = os.ReadFile(configDir + agreementFile) + server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile)) if err != nil { return nil, err } - if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil { + if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil { return nil, err } - if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil { - return nil, err + // 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")) + + _ = 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(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(configDir + "Users/"); err != nil { + if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil { return nil, err } - server.Config.FileRoot = 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, @@ -248,16 +276,16 @@ func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredL 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.Infow("Sent Tracker registration", "data", tr) + server.Logger.Debug("Sent Tracker registration", "addr", t) } time.Sleep(trackerUpdateFrequency * time.Second) @@ -288,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), ) } } @@ -305,84 +332,116 @@ func (s *Server) keepaliveHandler() { } } +func (s *Server) writeBanList() error { + s.banListMU.Lock() + defer s.banListMU.Unlock() + + out, err := yaml.Marshal(s.banList) + if err != nil { + return err + } + err = os.WriteFile( + filepath.Join(s.ConfigDir, "Banlist.yaml"), + out, + 0666, + ) + return err +} + func (s *Server) writeThreadedNews() error { - s.mux.Lock() - defer s.mux.Unlock() + s.threadedNewsMux.Lock() + defer s.threadedNewsMux.Unlock() out, err := yaml.Marshal(s.ThreadedNews) if err != nil { return err } - err = ioutil.WriteFile( - s.ConfigDir+"ThreadedNews.yaml", + err = s.FS.WriteFile( + filepath.Join(s.ConfigDir, "ThreadedNews.yaml"), out, 0666, ) return err } -func (s *Server) NewClientConn(conn net.Conn, remoteAddr string) *ClientConn { +func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn { s.mux.Lock() 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: make(map[int][]*FileTransfer), - Agreed: false, RemoteAddr: remoteAddr, + transfers: map[int]map[[4]byte]*FileTransfer{ + FileDownload: {}, + FileUpload: {}, + FolderDownload: {}, + FolderUpload: {}, + bannerDownload: {}, + }, } - *s.NextGuestID++ - ID := *s.NextGuestID - binary.BigEndian.PutUint16(*clientConn.ID, ID) - s.Clients[ID] = clientConn + s.nextClientID.Add(1) + + binary.BigEndian.PutUint16(clientConn.ID[:], uint16(s.nextClientID.Load())) + s.Clients[clientConn.ID] = clientConn return clientConn } // NewUser creates a new user account entry in the server map and config file -func (s *Server) NewUser(login, name, password string, access []byte) error { +func (s *Server) NewUser(login, name, password string, access accessBitmap) error { 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(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 []byte) error { +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(s.ConfigDir+"Users/"+login+".yaml", 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) } account := s.Accounts[newLogin] - account.Access = &access + account.Access = access account.Name = name account.Password = password @@ -390,8 +449,9 @@ func (s *Server) UpdateUser(login, newLogin, name, password string, access []byt if err != nil { return err } - if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil { - return err + + if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil { + return fmt.Errorf("error writing account file: %w", err) } return nil @@ -402,63 +462,63 @@ 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(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, - Icon: *c.Icon, - Flags: *c.Flags, + b, err := io.ReadAll(&User{ + ID: c.ID, + Icon: c.Icon, + 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 } -// loadThreadedNews loads the threaded news data from disk -func (s *Server) loadThreadedNews(threadedNewsPath string) error { - fh, err := os.Open(threadedNewsPath) +// 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) + defer fh.Close() - return decoder.Decode(s.ThreadedNews) + decoder := yaml.NewDecoder(fh) + return decoder.Decode(data) } // loadAccounts loads account data from disk func (s *Server) loadAccounts(userDir string) error { - matches, err := filepath.Glob(path.Join(userDir, "*.yaml")) + matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml")) if err != nil { return err } 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 @@ -486,168 +546,184 @@ func (s *Server) loadConfig(path string) error { return nil } -const ( - minTransactionLen = 22 // minimum length of any transaction -) - -// dontPanic recovers and logs panics instead of crashing -// TODO: remove this after known issues are fixed -func dontPanic(logger *zap.SugaredLogger) { - if r := recover(); r != nil { - fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) - logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) - } +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(conn net.Conn, remoteAddr string) error { +func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error { defer dontPanic(s.Logger) - if err := Handshake(conn); 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 + } - buf := make([]byte, 1024) - // TODO: fix potential short read with io.ReadFull - readLen, err := conn.Read(buf) - if readLen < minTransactionLen { - return err + // 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 != nil { - return err + + if err := performHandshake(rwc); err != nil { + return fmt.Errorf("error performing handshake: %w", err) } - clientLogin, _, err := ReadTransaction(buf[:readLen]) - if err != nil { - return err + // Create a new scanner for parsing incoming bytes into transaction tokens + scanner := bufio.NewScanner(rwc) + scanner.Split(transactionScanner) + + 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(buf); err != nil { + return fmt.Errorf("error writing login transaction: %w", err) } - c := s.NewClientConn(conn, remoteAddr) + c := s.NewClientConn(rwc, remoteAddr) 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 } + c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login) + // 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 := conn.Write(b); err != nil { - return err - } - return fmt.Errorf("incorrect login") - } - if clientLogin.GetField(fieldUserName).Data != nil { - c.UserName = clientLogin.GetField(fieldUserName).Data + 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 c.Authorize(accessDisconUser) { - *c.Flags = []byte{0, 2} + if clientLogin.GetField(FieldUserName).Data != nil { + if c.Authorize(accessAnyName) { + c.UserName = clientLogin.GetField(FieldUserName).Data + } else { + c.UserName = []byte(c.Account.Name) + } } - s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr) + if c.Authorize(accessDisconUser) { + c.Flags.Set(UserFlagAdmin, 1) + } - s.outbox <- c.NewReply(clientLogin, - NewField(fieldVersion, []byte{0x00, 0xbe}), - NewField(fieldCommunityBannerID, []byte{0x00, 0x01}), - NewField(fieldServerName, []byte(s.Config.Name)), + s.outbox <- c.NewReply(&clientLogin, + 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)) - - // Show agreement to client - 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.notifyOthers( - *NewTransaction( - tranNotifyChangeUser, nil, - NewField(fieldUserName, c.UserName), - NewField(fieldUserID, *c.ID), - NewField(fieldUserIconID, *c.Icon), - NewField(fieldUserFlags, *c.Flags), + 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. + 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})) + } + } else { + c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement)) + } + + // 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, [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() - const readBuffSize = 1024000 // 1KB - TODO: what should this be? - tranBuff := make([]byte, 0) - tReadlen := 0 - // Infinite loop where take action on incoming client requests until the connection is closed - for { - buf = make([]byte, readBuffSize) - tranBuff = tranBuff[tReadlen:] + // Scan for new transactions and handle them as they come in. + for scanner.Scan() { + // 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()) - readLen, err := c.Connection.Read(buf) - if err != nil { + var t Transaction + if _, err := t.Write(buf); err != nil { return err } - tranBuff = append(tranBuff, buf[:readLen]...) - - // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them - // into a slice of transactions - var transactions []Transaction - if transactions, tReadlen, err = readTransactions(tranBuff); err != nil { - c.Server.Logger.Errorw("Error handling transaction", "err", err) - } - // iterate over all of the transactions that were parsed from the byte slice and handle them - for _, t := range transactions { - if err := c.handleTransaction(&t); err != nil { - c.Server.Logger.Errorw("Error handling transaction", "err", err) - } - } + c.handleTransaction(t) } + return nil } -// NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID -// in the file transfer request payload, and the file transfer server will use it to map the request -// to a transfer -func (s *Server) NewTransactionRef() []byte { - transactionRef := make([]byte, 4) - rand.Read(transactionRef) - - return transactionRef -} - -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 } @@ -657,461 +733,102 @@ const dlFldrActionResumeFile = 2 const dlFldrActionNextFile = 3 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection -func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error { - defer func() { - - if err := conn.Close(); err != nil { - s.Logger.Errorw("error closing connection", "error", err) - } - }() - +func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error { defer dontPanic(s.Logger) - txBuf := make([]byte, 16) - if _, err := io.ReadFull(conn, 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) } - transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:]) defer func() { s.mux.Lock() - delete(s.FileTransfers, transferRefNum) + 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() - fileTransfer, ok := s.FileTransfers[transferRefNum] + fileTransfer, ok := s.fileTransfers[t.ReferenceNumber] s.mux.Unlock() if !ok { return errors.New("invalid transaction ID") } - switch fileTransfer.Type { - case FileDownload: - fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) - if err != nil { - return err - } - - var dataOffset int64 - if fileTransfer.fileResumeData != nil { - dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) - } + defer func() { + fileTransfer.ClientConn.transfersMU.Lock() + delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber) + fileTransfer.ClientConn.transfersMU.Unlock() + }() - ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset) - if err != nil { - return err - } + rLogger := s.Logger.With( + "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr, + "login", fileTransfer.ClientConn.Account.Login, + "Name", string(fileTransfer.ClientConn.UserName), + ) - s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber) + fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) + if err != nil { + return err + } - if fileTransfer.options == nil { - // Start by sending flat file object to client - if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { - return err - } + switch fileTransfer.Type { + case bannerDownload: + 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 + }() - file, err := s.FS.Open(fullFilePath) + err = DownloadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, true) if err != nil { - return err + return fmt.Errorf("file download error: %w", err) } - sendBuffer := make([]byte, 1048576) - var totalSent int64 - for { - var bytesRead int - if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF { - if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { - return err - } - break - } - if err != nil { - return err - } - totalSent += int64(bytesRead) - - fileTransfer.BytesSent += bytesRead - - if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { - return err - } - } case FileUpload: - destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) - - 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 - // Unfortunately we have to infer which case applies by inspecting what is already on the file system - - // 1) Check for existing file: - _, err := os.Stat(destinationFile) - if err == nil { - // If found, that means this upload is intended to replace the file - if err = os.Remove(destinationFile); err != nil { - return err - } - file, err = os.Create(destinationFile + incompleteFileSuffix) - } - if errors.Is(err, fs.ErrNotExist) { - // If not found, open or create a new incomplete file - file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) - if err != nil { - return err - } - } - - defer func() { _ = file.Close() }() - - s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) + s.Stats.UploadCounter += 1 + s.Stats.UploadsInProgress += 1 + defer func() { s.Stats.UploadsInProgress -= 1 }() - // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data - if err := receiveFile(conn, file, io.Discard); err != nil { - return err - } - - if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil { - return err - } - - s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) - case FolderDownload: - // Folder Download flow: - // 1. Get filePath from the transfer - // 2. Iterate over files - // 3. For each file: - // Send file header to client - // The client can reply in 3 ways: - // - // 1. If type is an odd number (unknown type?), or file download for the current file is completed: - // client sends []byte{0x00, 0x03} to tell the server to continue to the next file - // - // 2. If download of a file is to be resumed: - // client sends: - // []byte{0x00, 0x02} // download folder action - // [2]byte // Resume data size - // []byte file resume data (see myField_FileResumeData) - // - // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01} - // - // When download is requested (case 2 or 3), server replies with: - // [4]byte - file size - // []byte - Flattened File Object - // - // After every file download, client could request next file with: - // []byte{0x00, 0x03} - // - // This notifies the server to send the next item header - - fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) + err = UploadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err + return fmt.Errorf("file upload error: %w", err) } - basePathLen := len(fullFilePath) - - s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber) + case FolderDownload: + s.Stats.DownloadCounter += 1 + s.Stats.DownloadsInProgress += 1 + defer func() { s.Stats.DownloadsInProgress -= 1 }() - nextAction := make([]byte, 2) - if _, err := io.ReadFull(conn, nextAction); err != nil { - return err + err = DownloadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) + if err != nil { + return fmt.Errorf("file upload error: %w", err) } - i := 0 - err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - i += 1 - subPath := path[basePathLen+1:] - s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) - - if i == 1 { - return nil - } - - fileHeader := NewFileHeader(subPath, info.IsDir()) - - // Send the file header to client - if _, err := conn.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(conn, nextAction); err != nil { - return err - } - - s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) - - var dataOffset int64 - - switch nextAction[1] { - case dlFldrActionResumeFile: - // client asked to resume this file - var frd FileResumeData - // get size of resumeData - if _, err := io.ReadFull(conn, nextAction); err != nil { - return err - } - - resumeDataLen := binary.BigEndian.Uint16(nextAction) - resumeDataBytes := make([]byte, resumeDataLen) - if _, err := io.ReadFull(conn, resumeDataBytes); err != nil { - return err - } - - 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 - } - - splitPath := strings.Split(path, "/") - - ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset) - if err != nil { - return err - } - s.Logger.Infow("File download started", - "fileName", info.Name(), - "transactionRef", fileTransfer.ReferenceNumber, - "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()), - ) - - // Send file size to client - if _, err := conn.Write(ffo.TransferSize()); err != nil { - s.Logger.Error(err) - return err - } - - // Send ffo bytes to client - if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { - s.Logger.Error(err) - return err - } - - file, err := s.FS.Open(path) - if err != nil { - return err - } - - // // Copy N bytes from file to connection - // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:]))) - // if err != nil { - // return err - // } - // file.Close() - sendBuffer := make([]byte, 1048576) - var totalSent int64 - for { - var bytesRead int - if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF { - if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { - return err - } - break - } - if err != nil { - panic(err) - } - totalSent += int64(bytesRead) - - fileTransfer.BytesSent += bytesRead - - if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { - return err - } - } - - // TODO: optionally send resource fork header and resource fork data - - // Read the client's Next Action request. This is always 3, I think? - if _, err := io.ReadFull(conn, nextAction); err != nil { - return err - } - - return nil - }) - case FolderUpload: - dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) - if err != nil { - return err - } - s.Logger.Infow( + s.Stats.UploadCounter += 1 + s.Stats.UploadsInProgress += 1 + defer func() { s.Stats.UploadsInProgress -= 1 }() + rLogger.Info( "Folder upload started", - "transactionRef", fileTransfer.ReferenceNumber, - "dstPath", dstPath, - "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize), + "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(dstPath); os.IsNotExist(err) { - if err := s.FS.Mkdir(dstPath, 0777); err != nil { - return err - } - } - - // Begin the folder upload flow by sending the "next file action" to client - if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - - fileSize := make([]byte, 4) - readBuffer := make([]byte, 1024) - - for i := 0; i < fileTransfer.ItemCount(); i++ { - // TODO: fix potential short read with io.ReadFull - _, err := conn.Read(readBuffer) - if err != nil { - return err - } - fu := readFolderUpload(readBuffer) - - s.Logger.Infow( - "Folder upload continued", - "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), - "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(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) { - if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil { - return err - } - } - - // Tell client to send next file - if _, err := conn.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(dstPath + "/" + 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. - inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - return err - } - if err == nil { - nextAction = dlFldrActionResumeFile - } - - fmt.Printf("Next Action: %v\n", nextAction) - - if _, err := conn.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(inccompleteFile.Size())) - - file, err := os.OpenFile(dstPath+"/"+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 := conn.Write(append(bs, b...)); err != nil { - return err - } - - if _, err := io.ReadFull(conn, fileSize); err != nil { - return err - } - - if err := receiveFile(conn, file, ioutil.Discard); err != nil { - s.Logger.Error(err) - } - - err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath()) - if err != nil { - return err - } - - case dlFldrActionSendFile: - if _, err := conn.Read(fileSize); err != nil { - return err - } - - filePath := dstPath + "/" + fu.FormattedPath() - s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize)) - - newFile, err := s.FS.Create(filePath + ".incomplete") - if err != nil { - return err - } - - if err := receiveFile(conn, newFile, ioutil.Discard); err != nil { - s.Logger.Error(err) - } - _ = newFile.Close() - if err := os.Rename(filePath+".incomplete", filePath); err != nil { - return err - } - } - - // Tell client to send next file - if _, err := conn.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) } - s.Logger.Infof("Folder upload complete") } - return nil } - -// sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values. -// The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work. -func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) { - for _, c := range unsortedClients { - clients = append(clients, c) - } - sort.Sort(byClientID(clients)) - return clients -}