]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/server.go
Improve Frogblast client compatibility
[rbdr/mobius] / hotline / server.go
index e5a7b8eb08a4ed8be7c0fce1555e7839264a8587..8d6803b274f411c3a0b1eb4d360a9f9daeccd8b3 100644 (file)
@@ -18,7 +18,6 @@ import (
        "net"
        "os"
        "path/filepath"
-       "runtime/debug"
        "strings"
        "sync"
        "time"
@@ -34,36 +33,37 @@ type requestCtx struct {
        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
-)
-
 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
+var frogblastVersion = []byte{0, 0, 0, 0xb9} // version ID used by the Frogblast 1.2.4 client
 
 type Server struct {
-       Port         int
-       Accounts     map[string]*Account
-       Agreement    []byte
-       Clients      map[uint16]*ClientConn
-       ThreadedNews *ThreadedNews
-
+       Port          int
+       Accounts      map[string]*Account
+       Agreement     []byte
+       Clients       map[uint16]*ClientConn
        fileTransfers map[[4]byte]*FileTransfer
 
-       Config        *Config
-       ConfigDir     string
-       Logger        *zap.SugaredLogger
-       PrivateChats  map[uint32]*PrivateChat
+       Config    *Config
+       ConfigDir string
+       Logger    *zap.SugaredLogger
+
+       PrivateChatsMu sync.Mutex
+       PrivateChats   map[uint32]*PrivateChat
+
        NextGuestID   *uint16
        TrackerPassID [4]byte
-       Stats         *Stats
+
+       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
+
        flatNewsMux sync.Mutex
        FlatNews    []byte
 
@@ -71,6 +71,16 @@ 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
@@ -216,7 +226,7 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File
                Logger:        logger,
                NextGuestID:   new(uint16),
                outbox:        make(chan Transaction),
-               Stats:         &Stats{StartTime: time.Now()},
+               Stats:         &Stats{Since: time.Now()},
                ThreadedNews:  &ThreadedNews{},
                FS:            FS,
                banList:       make(map[string]*time.Time),
@@ -277,7 +287,7 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File
                                        if err := register(t, tr); err != nil {
                                                server.Logger.Errorw("unable to register with tracker %v", "error", err)
                                        }
-                                       server.Logger.Infow("Sent Tracker registration", "data", tr)
+                                       server.Logger.Debugw("Sent Tracker registration", "addr", t)
                                }
 
                                time.Sleep(trackerUpdateFrequency * time.Second)
@@ -308,16 +318,16 @@ func (s *Server) keepaliveHandler() {
                        if c.IdleTime > userIdleSeconds && !c.Idle {
                                c.Idle = true
 
-                               flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
+                               flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
                                flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
-                               binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
+                               binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
 
                                c.sendAll(
                                        tranNotifyChangeUser,
                                        NewField(fieldUserID, *c.ID),
-                                       NewField(fieldUserFlags, *c.Flags),
+                                       NewField(fieldUserFlags, c.Flags),
                                        NewField(fieldUserName, c.UserName),
-                                       NewField(fieldUserIconID, *c.Icon),
+                                       NewField(fieldUserIconID, c.Icon),
                                )
                        }
                }
@@ -342,14 +352,14 @@ func (s *Server) writeBanList() error {
 }
 
 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(
+       err = s.FS.WriteFile(
                filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
                out,
                0666,
@@ -363,12 +373,12 @@ func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *Clie
 
        clientConn := &ClientConn{
                ID:         &[]byte{0, 0},
-               Icon:       &[]byte{0, 0},
-               Flags:      &[]byte{0, 0},
+               Icon:       []byte{0, 0},
+               Flags:      []byte{0, 0},
                UserName:   []byte{},
                Connection: conn,
                Server:     s,
-               Version:    &[]byte{},
+               Version:    []byte{},
                AutoReply:  []byte{},
                transfers:  map[int]map[[4]byte]*FileTransfer{},
                Agreed:     false,
@@ -392,7 +402,7 @@ func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *Clie
 }
 
 // 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()
 
@@ -400,7 +410,7 @@ func (s *Server) NewUser(login, name, password string, access []byte) error {
                Login:    login,
                Name:     name,
                Password: hashAndSalt([]byte(password)),
-               Access:   &access,
+               Access:   access,
        }
        out, err := yaml.Marshal(&account)
        if err != nil {
@@ -411,7 +421,7 @@ func (s *Server) NewUser(login, name, password string, access []byte) error {
        return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
 }
 
-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()
 
@@ -426,7 +436,7 @@ func (s *Server) UpdateUser(login, newLogin, name, password string, access []byt
        }
 
        account := s.Accounts[newLogin]
-       account.Access = &access
+       account.Access = access
        account.Name = name
        account.Password = password
 
@@ -463,8 +473,8 @@ func (s *Server) connectedUsers() []Field {
                }
                user := User{
                        ID:    *c.ID,
-                       Icon:  *c.Icon,
-                       Flags: *c.Flags,
+                       Icon:  c.Icon,
+                       Flags: c.Flags,
                        Name:  string(c.UserName),
                }
                connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
@@ -541,14 +551,6 @@ func (s *Server) loadConfig(path string) error {
        return nil
 }
 
-// dontPanic logs panics instead of crashing
-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()))
-       }
-}
-
 // 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)
@@ -563,9 +565,9 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
 
        scanner.Scan()
 
-       clientLogin, _, err := ReadTransaction(scanner.Bytes())
-       if err != nil {
-               panic(err)
+       var clientLogin Transaction
+       if _, err := clientLogin.Write(scanner.Bytes()); err != nil {
+               return err
        }
 
        c := s.NewClientConn(rwc, remoteAddr)
@@ -598,7 +600,7 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
 
        encodedLogin := clientLogin.GetField(fieldUserLogin).Data
        encodedPassword := clientLogin.GetField(fieldUserPassword).Data
-       *c.Version = clientLogin.GetField(fieldVersion).Data
+       c.Version = clientLogin.GetField(fieldVersion).Data
 
        var login string
        for _, char := range encodedLogin {
@@ -612,7 +614,7 @@ 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.")
+               t := c.NewErrReply(&clientLogin, "Incorrect login.")
                b, err := t.MarshalBinary()
                if err != nil {
                        return err
@@ -621,11 +623,17 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                        return err
                }
 
-               c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", *c.Version))
+               c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
 
                return nil
        }
 
+       if clientLogin.GetField(fieldUserIconID).Data != nil {
+               c.Icon = clientLogin.GetField(fieldUserIconID).Data
+       }
+
+       c.Account = c.Server.Accounts[login]
+
        if clientLogin.GetField(fieldUserName).Data != nil {
                if c.Authorize(accessAnyName) {
                        c.UserName = clientLogin.GetField(fieldUserName).Data
@@ -634,48 +642,54 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                }
        }
 
-       if clientLogin.GetField(fieldUserIconID).Data != nil {
-               *c.Icon = clientLogin.GetField(fieldUserIconID).Data
-       }
-
-       c.Account = c.Server.Accounts[login]
-
        if c.Authorize(accessDisconUser) {
-               *c.Flags = []byte{0, 2}
+               c.Flags = []byte{0, 2}
        }
 
-       s.outbox <- c.NewReply(clientLogin,
+       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))
+       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))
+       }
 
        // 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) {
+       if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) {
                c.Agreed = true
                c.logger = c.logger.With("name", string(c.UserName))
-               c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", *c.Version))
+               c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
 
                for _, t := range c.notifyOthers(
                        *NewTransaction(
                                tranNotifyChangeUser, nil,
                                NewField(fieldUserName, c.UserName),
                                NewField(fieldUserID, *c.ID),
-                               NewField(fieldUserIconID, *c.Icon),
-                               NewField(fieldUserFlags, *c.Flags),
+                               NewField(fieldUserIconID, c.Icon),
+                               NewField(fieldUserFlags, c.Flags),
                        ),
                ) {
                        c.Server.outbox <- t
                }
        }
 
-       c.Server.Stats.LoginCount += 1
+       c.Server.Stats.ConnectionCounter += 1
+       if len(s.Clients) > c.Server.Stats.ConnectionPeak {
+               c.Server.Stats.ConnectionPeak = len(s.Clients)
+       }
 
        // Scan for new transactions and handle them as they come in.
        for scanner.Scan() {
@@ -684,11 +698,12 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                buf := make([]byte, len(scanner.Bytes()))
                copy(buf, scanner.Bytes())
 
-               t, _, err := ReadTransaction(buf)
-               if err != nil {
-                       panic(err)
+               var t Transaction
+               if _, err := t.Write(buf); err != nil {
+                       return err
                }
-               if err := c.handleTransaction(*t); err != nil {
+
+               if err := c.handleTransaction(t); err != nil {
                        c.logger.Errorw("Error handling transaction", "err", err)
                }
        }
@@ -696,15 +711,14 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
 }
 
 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
-       s.mux.Lock()
-       defer s.mux.Unlock()
+       s.PrivateChatsMu.Lock()
+       defer s.PrivateChatsMu.Unlock()
 
        randID := make([]byte, 4)
        rand.Read(randID)
        data := binary.BigEndian.Uint32(randID[:])
 
        s.PrivateChats[data] = &PrivateChat{
-               Subject:    "",
                ClientConn: make(map[uint16]*ClientConn),
        }
        s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
@@ -764,11 +778,12 @@ 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
                }
        case FileDownload:
                s.Stats.DownloadCounter += 1
+               s.Stats.DownloadsInProgress += 1
+               defer func() { s.Stats.DownloadsInProgress -= 1 }()
 
                var dataOffset int64
                if fileTransfer.fileResumeData != nil {
@@ -823,6 +838,8 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
 
        case FileUpload:
                s.Stats.UploadCounter += 1
+               s.Stats.UploadsInProgress += 1
+               defer func() { s.Stats.UploadsInProgress -= 1 }()
 
                var file *os.File
 
@@ -879,7 +896,12 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                }
 
                rLogger.Infow("File upload complete", "dstFile", fullPath)
+
        case FolderDownload:
+               s.Stats.DownloadCounter += 1
+               s.Stats.DownloadsInProgress += 1
+               defer func() { s.Stats.DownloadsInProgress -= 1 }()
+
                // Folder Download flow:
                // 1. Get filePath from the transfer
                // 2. Iterate over files
@@ -1043,6 +1065,9 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                }
 
        case FolderUpload:
+               s.Stats.UploadCounter += 1
+               s.Stats.UploadsInProgress += 1
+               defer func() { s.Stats.UploadsInProgress -= 1 }()
                rLogger.Infow(
                        "Folder upload started",
                        "dstPath", fullPath,