X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/2e7c03cf691f453ca2762f44c6945e5b70bc0f51..a2ef262a164fc735b9b8471ac0c8001eea2b9bf6:/hotline/server.go diff --git a/hotline/server.go b/hotline/server.go index 3a58893..0ee2dd7 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -1,89 +1,125 @@ package hotline import ( + "bufio" + "bytes" "context" + "crypto/rand" "encoding/binary" "errors" "fmt" - "go.uber.org/zap" + "github.com/go-playground/validator/v10" + "golang.org/x/text/encoding/charmap" + "gopkg.in/yaml.v3" "io" - "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.v2" ) -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 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 - TrackerPassID []byte - Stats *Stats - - APIListener net.Listener - FileListener net.Listener - - // newsReader io.Reader - // newsWriter io.WriteCloser + 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 + + statsMu sync.Mutex + Stats *Stats + + 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) +func (s *Server) ListenAndServe(ctx context.Context) error { var wg sync.WaitGroup wg.Add(1) - go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }() + go func() { + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port)) + if err != nil { + log.Fatal(err) + } + + log.Fatal(s.Serve(ctx, ln)) + }() wg.Add(1) - go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }() + go func() { + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1)) + if err != nil { + log.Fatal(err) + } + + log.Fatal(s.ServeFileTransfers(ctx, ln)) + }() wg.Wait() return nil } -func (s *Server) APIPort() int { - return s.APIListener.Addr().(*net.TCPAddr).Port -} - -func (s *Server) ServeFileTransfers(ln net.Listener) error { - s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1)) - +func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error { for { conn, err := ln.Accept() if err != nil { @@ -91,75 +127,69 @@ func (s *Server) ServeFileTransfers(ln net.Listener) error { } go func() { - if err := s.TransferFile(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.Connection.RemoteAddr(), - ) + return nil } -func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error { - s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port)) +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); 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) } } }() @@ -171,85 +201,91 @@ const ( ) // NewServer constructs a new Server from a config dir -func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*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{}, - TrackerPassID: make([]byte, 4), + FS: fs, + banList: make(map[string]*time.Time), } - ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort)) - if err != nil { - return nil, err - } - server.APIListener = ln + var err error - if netPort != 0 { - netPort += 1 + // generate a new random passID for tracker registration + if _, err := rand.Read(server.TrackerPassID[:]); err != nil { + return nil, err } - ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort)) - server.FileListener = ln2 + server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile)) if err != nil { return nil, err } - // generate a new random passID for tracker registration - if _, err := rand.Read(server.TrackerPassID); err != nil { + if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil { return nil, err } - server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile) - if server.Agreement, err = os.ReadFile(configDir + agreementFile); 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")) - if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil { - return nil, err - } + _ = loadFromYAMLFile(filepath.Join(configDir, "Banlist.yaml"), &server.banList) - if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil { - return nil, err + 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.Info( + "Tracker registration enabled", + "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency), + "trackers", server.Config.Trackers, + ) + go func() { for { - tr := TrackerRegistration{ - Port: []byte{0x15, 0x7c}, + tr := &TrackerRegistration{ UserCount: server.userCount(), 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 { - server.Logger.Infof("Registering with tracker %v", t) - - 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.Debug("Sent Tracker registration", "addr", t) } time.Sleep(trackerUpdateFrequency * time.Second) @@ -280,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), ) } } @@ -297,65 +332,129 @@ 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) *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 := 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) + } + defer file.Close() + + b, err := yaml.Marshal(account) + if err != nil { + return err + } + + _, 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() - account := Account{ - Login: login, - Name: name, - Password: hashAndSalt([]byte(password)), - Access: &access, + // If the login has changed, rename the account file. + if login != newLogin { + 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 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.Name = name + account.Password = password + out, err := yaml.Marshal(&account) if err != nil { return err } - s.Accounts[login] = &account - return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666) + 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 } // DeleteUser deletes the user account @@ -363,65 +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 os.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) - decoder.SetStrict(true) + 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 := FS.Open(file) - if err != nil { - return err - } - - account := Account{} - decoder := yaml.NewDecoder(fh) - decoder.SetStrict(true) - 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 @@ -430,174 +527,203 @@ func (s *Server) loadAccounts(userDir string) error { } func (s *Server) loadConfig(path string) error { - fh, err := FS.Open(path) + fh, err := s.FS.Open(path) if err != nil { return err } decoder := yaml.NewDecoder(fh) - decoder.SetStrict(true) err = decoder.Decode(s.Config) if err != nil { return err } + + validate := validator.New() + err = validate.Struct(s.Config) + if err != nil { + return err + } return nil } -const ( - minTransactionLen = 22 // minimum length of any transaction -) +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) error { - handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length - if _, err := conn.Read(handshakeBuf); err != nil { - return err - } - if err := Handshake(conn, handshakeBuf[:12]); err != nil { - return err - } +func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error { + defer dontPanic(s.Logger) + + // 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) - 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) + c := s.NewClientConn(rwc, remoteAddr) defer c.Disconnect() - defer func() { - if r := recover(); r != nil { - fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) - c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) - 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", conn.RemoteAddr().String()) + 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)) - - // assume simplified hotline v1.2.3 login flow that does not require agreement - if *c.Version == nil { - c.Agreed = true - if _, err := c.notifyNewUserHasJoined(); err != nil { - return err + 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 } @@ -606,392 +732,103 @@ const dlFldrActionSendFile = 1 const dlFldrActionResumeFile = 2 const dlFldrActionNextFile = 3 -func (s *Server) TransferFile(conn net.Conn) error { - defer func() { _ = conn.Close() }() - - txBuf := make([]byte, 16) - _, err := conn.Read(txBuf) - if err != nil { - return err - } +// handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection +func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error { + defer dontPanic(s.Logger) + // The first 16 bytes contain the file transfer. var t transfer - _, err = t.Write(txBuf) - if 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[:]) - fileTransfer := s.FileTransfers[transferRefNum] - - switch fileTransfer.Type { - case FileDownload: - fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) - if err != nil { - return err - } - - ffo, err := NewFlattenedFileObject( - s.Config.FileRoot, - fileTransfer.FilePath, - fileTransfer.FileName, - ) - if err != nil { - return err - } - - s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String()) + defer func() { + s.mux.Lock() + delete(s.fileTransfers, t.ReferenceNumber) + s.mux.Unlock() - // Start by sending flat file object to client - if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { - return err - } + // 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) + }() - file, err := FS.Open(fullFilePath) - if err != nil { - return err - } + s.mux.Lock() + fileTransfer, ok := s.fileTransfers[t.ReferenceNumber] + s.mux.Unlock() + if !ok { + return errors.New("invalid transaction ID") + } - sendBuffer := make([]byte, 1048576) - for { - var bytesRead int - if bytesRead, err = file.Read(sendBuffer); err == io.EOF { - break - } + defer func() { + fileTransfer.ClientConn.transfersMU.Lock() + delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber) + fileTransfer.ClientConn.transfersMU.Unlock() + }() - fileTransfer.BytesSent += bytesRead + rLogger := s.Logger.With( + "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr, + "login", fileTransfer.ClientConn.Account.Login, + "Name", string(fileTransfer.ClientConn.UserName), + ) - delete(s.FileTransfers, transferRefNum) + fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) + if err != nil { + return err + } - if _, err := conn.Write(sendBuffer[:bytesRead]); 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 FileUpload: - const buffSize = 1460 - - uploadBuf := make([]byte, buffSize) + case FileDownload: + s.Stats.DownloadCounter += 1 + s.Stats.DownloadsInProgress += 1 + defer func() { + s.Stats.DownloadsInProgress -= 1 + }() - _, err := conn.Read(uploadBuf) + err = DownloadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, true) if err != nil { - return err + return fmt.Errorf("file download error: %w", err) } - ffo := ReadFlattenedFileObject(uploadBuf) - payloadLen := len(ffo.BinaryMarshal()) - fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) - - destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) - s.Logger.Infow( - "File upload started", - "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), - "size", fileSize, - "dstFile", destinationFile, - ) + case FileUpload: + s.Stats.UploadCounter += 1 + s.Stats.UploadsInProgress += 1 + defer func() { s.Stats.UploadsInProgress -= 1 }() - newFile, err := os.Create(destinationFile) + err = UploadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err + return fmt.Errorf("file upload error: %w", err) } - defer func() { _ = newFile.Close() }() - - if _, err := newFile.Write(uploadBuf[payloadLen:]); err != nil { - return err - } - receivedBytes := buffSize - payloadLen - - for { - if (fileSize - receivedBytes) < buffSize { - s.Logger.Infow( - "File upload complete", - "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), - "size", fileSize, - "dstFile", destinationFile, - ) - - if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil { - return fmt.Errorf("file transfer failed: %s", err) - } - return nil - } - - // Copy N bytes from conn to upload file - n, err := io.CopyN(newFile, conn, buffSize) - if err != nil { - return err - } - receivedBytes += int(n) - } 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) + 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) } - basePathLen := len(fullFilePath) - - readBuffer := make([]byte, 1024) - - s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr()) - - i := 0 - _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error { - i += 1 - subPath := path[basePathLen:] - s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) - - fileHeader := NewFileHeader(subPath, info.IsDir()) - - if i == 1 { - return nil - } - - // 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 - // TODO: Remove hardcoded behavior and switch behaviors based on the next action send - if _, err := conn.Read(readBuffer); err != nil { - return err - } - - s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2])) - - if info.IsDir() { - return nil - } - - splitPath := strings.Split(path, "/") - - ffo, err := NewFlattenedFileObject( - strings.Join(splitPath[:len(splitPath)-1], "/"), - nil, - []byte(info.Name()), - ) - if err != nil { - return err - } - s.Logger.Infow("File download started", - "fileName", info.Name(), - "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), - "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 file bytes to client - if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { - s.Logger.Error(err) - return err - } - - file, err := FS.Open(path) - if err != nil { - return err - } - - sendBuffer := make([]byte, 1048576) - totalBytesSent := len(ffo.BinaryMarshal()) - - for { - bytesRead, err := file.Read(sendBuffer) - if err == io.EOF { - // Read the client's Next Action request - // TODO: Remove hardcoded behavior and switch behaviors based on the next action send - if _, err := conn.Read(readBuffer); err != nil { - s.Logger.Errorf("error reading next action: %v", err) - return err - } - break - } - - sentBytes, readErr := conn.Write(sendBuffer[:bytesRead]) - totalBytesSent += sentBytes - if readErr != 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, - "RemoteAddr", conn.RemoteAddr().String(), - "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 := FS.Stat(dstPath); os.IsNotExist(err) { - s.Logger.Infow("Creating target path", "dstPath", dstPath) - if err := FS.Mkdir(dstPath, 0777); err != nil { - s.Logger.Error(err) - } - } - - readBuffer := make([]byte, 1024) - - // 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) - itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount) - - for i := uint16(0); i < itemCount; i++ { - if _, err := conn.Read(readBuffer); err != nil { - return err - } - fu := readFolderUpload(readBuffer) - - s.Logger.Infow( - "Folder upload continued", - "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), - "RemoteAddr", conn.RemoteAddr().String(), - "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) { - s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath) - if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil { - s.Logger.Error(err) - } - } - - // Tell client to send next file - if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { - s.Logger.Error(err) - return err - } - } else { - // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. - // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. - // Send dlFldrAction_SendFile to client to begin transfer - if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil { - return err - } - - if _, err := conn.Read(fileSize); err != nil { - fmt.Println("Error reading:", err.Error()) // TODO: handle - } - - s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize) - - if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil { - s.Logger.Error(err) - } - - // Tell client to send next file - if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { - s.Logger.Error(err) - return err - } - - // Client sends "MACR" after the file. Read and discard. - // TODO: This doesn't seem to be documented. What is this? Maybe resource fork? - if _, err := conn.Read(readBuffer); err != nil { - return err - } - } - } - s.Logger.Infof("Folder upload complete") - } - - return nil -} - -func transferFile(conn net.Conn, dst string) error { - const buffSize = 1024 - buf := make([]byte, buffSize) - - // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes - if _, err := conn.Read(buf); err != nil { - return err - } - ffo := ReadFlattenedFileObject(buf) - payloadLen := len(ffo.BinaryMarshal()) - fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) - - newFile, err := os.Create(dst) - if err != nil { - return err - } - defer func() { _ = newFile.Close() }() - if _, err := newFile.Write(buf[payloadLen:]); err != nil { - return err - } - receivedBytes := buffSize - payloadLen - - for { - if (fileSize - receivedBytes) < buffSize { - _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)) - return err - } - - // Copy N bytes from conn to upload file - n, err := io.CopyN(newFile, conn, buffSize) + err = UploadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err + return fmt.Errorf("file upload error: %w", err) } - receivedBytes += int(n) } -} - -// 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 + return nil }