]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/server.go
Read banner once at startup
[rbdr/mobius] / hotline / server.go
index 3e4ba2f08f90d1f9db317085c0873f82930292ac..b5bb0d515cde11cf2bc6cb013bbc6a04b7ba3aa1 100644 (file)
@@ -2,20 +2,22 @@ package hotline
 
 import (
        "bufio"
+       "bytes"
        "context"
        "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"
        "net"
        "os"
+       "path"
        "path/filepath"
        "strings"
        "sync"
@@ -28,11 +30,16 @@ var contextKeyReq = contextKey("req")
 
 type requestCtx struct {
        remoteAddr string
-       login      string
-       name       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 {
+       NetInterface  string
        Port          int
        Accounts      map[string]*Account
        Agreement     []byte
@@ -42,6 +49,7 @@ type Server struct {
        Config    *Config
        ConfigDir string
        Logger    *zap.SugaredLogger
+       banner    []byte
 
        PrivateChatsMu sync.Mutex
        PrivateChats   map[uint32]*PrivateChat
@@ -85,15 +93,15 @@ type PrivateChat struct {
 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),
+               "API port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port),
+               "Transfer port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1),
        )
 
        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)
                }
@@ -103,10 +111,9 @@ func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFu
 
        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)
-
                }
 
                s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
@@ -210,8 +217,9 @@ const (
 )
 
 // NewServer constructs a new Server from a config dir
-func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
+func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger, fs FileStore) (*Server, error) {
        server := Server{
+               NetInterface:  netInterface,
                Port:          netPort,
                Accounts:      make(map[string]*Account),
                Config:        new(Config),
@@ -224,7 +232,7 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File
                outbox:        make(chan Transaction),
                Stats:         &Stats{Since: time.Now()},
                ThreadedNews:  &ThreadedNews{},
-               FS:            FS,
+               FS:            fs,
                banList:       make(map[string]*time.Time),
        }
 
@@ -259,7 +267,15 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File
                return nil, err
        }
 
-       server.Config.FileRoot = filepath.Join(configDir, "Files")
+       // If the FileRoot is an absolute path, use it, otherwise treat as a relative path to the config dir.
+       if !filepath.IsAbs(server.Config.FileRoot) {
+               server.Config.FileRoot = filepath.Join(configDir, server.Config.FileRoot)
+       }
+
+       server.banner, err = os.ReadFile(filepath.Join(server.ConfigDir, server.Config.BannerFile))
+       if err != nil {
+               return nil, fmt.Errorf("error opening banner: %w", err)
+       }
 
        *server.NextGuestID = 1
 
@@ -274,7 +290,7 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS File
                        for {
                                tr := &TrackerRegistration{
                                        UserCount:   server.userCount(),
-                                       PassID:      server.TrackerPassID[:],
+                                       PassID:      server.TrackerPassID,
                                        Name:        server.Config.Name,
                                        Description: server.Config.Description,
                                }
@@ -315,15 +331,15 @@ func (s *Server) keepaliveHandler() {
                                c.Idle = true
 
                                flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
-                               flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
+                               flagBitmap.SetBit(flagBitmap, UserFlagAway, 1)
                                binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
 
                                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),
                                )
                        }
                }
@@ -339,7 +355,7 @@ func (s *Server) writeBanList() error {
        if err != nil {
                return err
        }
-       err = ioutil.WriteFile(
+       err = os.WriteFile(
                filepath.Join(s.ConfigDir, "Banlist.yaml"),
                out,
                0666,
@@ -376,15 +392,14 @@ func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *Clie
                Server:     s,
                Version:    []byte{},
                AutoReply:  []byte{},
-               transfers:  map[int]map[[4]byte]*FileTransfer{},
                RemoteAddr: remoteAddr,
-       }
-       clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
-               FileDownload:   {},
-               FileUpload:     {},
-               FolderDownload: {},
-               FolderUpload:   {},
-               bannerDownload: {},
+               transfers: map[int]map[[4]byte]*FileTransfer{
+                       FileDownload:   {},
+                       FileUpload:     {},
+                       FolderDownload: {},
+                       FolderUpload:   {},
+                       bannerDownload: {},
+               },
        }
 
        *s.NextGuestID++
@@ -411,9 +426,26 @@ func (s *Server) NewUser(login, name, password string, access accessBitmap) erro
        if err != nil {
                return err
        }
+
+       // 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 err
+       }
+       defer file.Close()
+
+       _, err = file.Write(out)
+       if err != nil {
+               return fmt.Errorf("error writing account file: %w", err)
+       }
+
        s.Accounts[login] = &account
 
-       return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
+       return nil
 }
 
 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
@@ -422,11 +454,12 @@ func (s *Server) UpdateUser(login, newLogin, name, password string, access acces
 
        // update renames the user login
        if login != newLogin {
-               err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
+               err := os.Rename(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"))
                if err != nil {
-                       return err
+                       return fmt.Errorf("unable to rename account: %w", err)
                }
                s.Accounts[newLogin] = s.Accounts[login]
+               s.Accounts[newLogin].Login = newLogin
                delete(s.Accounts, login)
        }
 
@@ -452,9 +485,14 @@ func (s *Server) DeleteUser(login string) error {
        s.mux.Lock()
        defer s.mux.Unlock()
 
+       err := s.FS.Remove(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"))
+       if err != nil {
+               return err
+       }
+
        delete(s.Accounts, login)
 
-       return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
+       return nil
 }
 
 func (s *Server) connectedUsers() []Field {
@@ -463,13 +501,16 @@ func (s *Server) connectedUsers() []Field {
 
        var connectedUsers []Field
        for _, c := range sortedClients(s.Clients) {
-               user := User{
+               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
 }
@@ -514,8 +555,8 @@ func (s *Server) loadAccounts(userDir string) error {
 
                account := Account{}
                decoder := yaml.NewDecoder(fh)
-               if err := decoder.Decode(&account); err != nil {
-                       return err
+               if err = decoder.Decode(&account); err != nil {
+                       return fmt.Errorf("error loading account %s: %w", file, err)
                }
 
                s.Accounts[account.Login] = &account
@@ -567,37 +608,60 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                return err
        }
 
-       c := s.NewClientConn(rwc, remoteAddr)
-
        // check if remoteAddr is present in the ban list
        if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
                // permaban
                if banUntil == nil {
-                       s.outbox <- *NewTransaction(
-                               tranServerMsg,
-                               c.ID,
-                               NewField(fieldData, []byte("You are permanently banned on this server")),
-                               NewField(fieldChatOptions, []byte{0, 0}),
+                       t := NewTransaction(
+                               TranServerMsg,
+                               &[]byte{0, 0},
+                               NewField(FieldData, []byte("You are permanently banned on this server")),
+                               NewField(FieldChatOptions, []byte{0, 0}),
                        )
+
+                       b, err := t.MarshalBinary()
+                       if err != nil {
+                               return err
+                       }
+
+                       _, err = rwc.Write(b)
+                       if err != nil {
+                               return err
+                       }
+
                        time.Sleep(1 * time.Second)
                        return nil
-               } else if time.Now().Before(*banUntil) {
-                       s.outbox <- *NewTransaction(
-                               tranServerMsg,
-                               c.ID,
-                               NewField(fieldData, []byte("You are temporarily banned on this server")),
-                               NewField(fieldChatOptions, []byte{0, 0}),
+               }
+
+               // temporary ban
+               if time.Now().Before(*banUntil) {
+                       t := NewTransaction(
+                               TranServerMsg,
+                               &[]byte{0, 0},
+                               NewField(FieldData, []byte("You are temporarily banned on this server")),
+                               NewField(FieldChatOptions, []byte{0, 0}),
                        )
+                       b, err := t.MarshalBinary()
+                       if err != nil {
+                               return err
+                       }
+
+                       _, err = rwc.Write(b)
+                       if err != nil {
+                               return err
+                       }
+
                        time.Sleep(1 * time.Second)
                        return nil
                }
-
        }
+
+       c := s.NewClientConn(rwc, remoteAddr)
        defer c.Disconnect()
 
-       encodedLogin := clientLogin.GetField(fieldUserLogin).Data
-       encodedPassword := clientLogin.GetField(fieldUserPassword).Data
-       c.Version = clientLogin.GetField(fieldVersion).Data
+       encodedLogin := clientLogin.GetField(FieldUserLogin).Data
+       encodedPassword := clientLogin.GetField(FieldUserPassword).Data
+       c.Version = clientLogin.GetField(FieldVersion).Data
 
        var login string
        for _, char := range encodedLogin {
@@ -625,15 +689,15 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                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.Account = c.Server.Accounts[login]
 
-       if clientLogin.GetField(fieldUserName).Data != nil {
+       if clientLogin.GetField(FieldUserName).Data != nil {
                if c.Authorize(accessAnyName) {
-                       c.UserName = clientLogin.GetField(fieldUserName).Data
+                       c.UserName = clientLogin.GetField(FieldUserName).Data
                } else {
                        c.UserName = []byte(c.Account.Name)
                }
@@ -644,44 +708,44 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
        }
 
        s.outbox <- c.NewReply(&clientLogin,
-               NewField(fieldVersion, []byte{0x00, 0xbe}),
-               NewField(fieldCommunityBannerID, []byte{0, 0}),
-               NewField(fieldServerName, []byte(s.Config.Name)),
+               NewField(FieldVersion, []byte{0x00, 0xbe}),
+               NewField(FieldCommunityBannerID, []byte{0, 0}),
+               NewField(FieldServerName, []byte(s.Config.Name)),
        )
 
        // Send user access privs so client UI knows how to behave
-       c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
+       c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
 
        // Accounts with accessNoAgreement do not receive the server agreement on login.  The behavior is different between
-       // client versions.  For 1.2.3 client, we do not send tranShowAgreement.  For other client versions, we send
-       // tranShowAgreement but with the NoServerAgreement field set to 1.
+       // client versions.  For 1.2.3 client, we do not send TranShowAgreement.  For other client versions, we send
+       // TranShowAgreement but with the NoServerAgreement field set to 1.
        if c.Authorize(accessNoAgreement) {
                // If client version is nil, then the client uses the 1.2.3 login behavior
                if c.Version != nil {
-                       c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
+                       c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
                }
        } else {
-               c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
+               c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
        }
 
        // 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
+               // part of TranAgreed
                c.logger = c.logger.With("name", string(c.UserName))
 
                c.logger.Infow("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
+               // information yet, so we do it in TranAgreed instead
                for _, t := range c.notifyOthers(
                        *NewTransaction(
-                               tranNotifyChangeUser, nil,
-                               NewField(fieldUserName, c.UserName),
-                               NewField(fieldUserID, *c.ID),
-                               NewField(fieldUserIconID, c.Icon),
-                               NewField(fieldUserFlags, c.Flags),
+                               TranNotifyChangeUser, nil,
+                               NewField(FieldUserName, c.UserName),
+                               NewField(FieldUserID, *c.ID),
+                               NewField(FieldUserIconID, c.Icon),
+                               NewField(FieldUserFlags, c.Flags),
                        ),
                ) {
                        c.Server.outbox <- t
@@ -718,7 +782,7 @@ func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
 
        randID := make([]byte, 4)
        rand.Read(randID)
-       data := binary.BigEndian.Uint32(randID[:])
+       data := binary.BigEndian.Uint32(randID)
 
        s.PrivateChats[data] = &PrivateChat{
                ClientConn: make(map[uint16]*ClientConn),
@@ -783,8 +847,8 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
 
        switch fileTransfer.Type {
        case bannerDownload:
-               if err := s.bannerDownload(rwc); err != nil {
-                       return err
+               if _, err := io.Copy(rwc, bytes.NewBuffer(s.banner)); err != nil {
+                       return fmt.Errorf("error sending banner: %w", err)
                }
        case FileDownload:
                s.Stats.DownloadCounter += 1
@@ -807,8 +871,8 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
 
                // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
                if fileTransfer.options == nil {
-                       // Start by sending flat file object to client
-                       if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
+                       _, err = io.Copy(rwc, fw.ffo)
+                       if err != nil {
                                return err
                        }
                }
@@ -973,11 +1037,8 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                        }
 
                        fileHeader := NewFileHeader(subPath, info.IsDir())
-
-                       // Send the fileWrapper header to client
-                       if _, err := rwc.Write(fileHeader.Payload()); err != nil {
-                               s.Logger.Errorf("error sending file header: %v", err)
-                               return err
+                       if _, err := io.Copy(rwc, &fileHeader); err != nil {
+                               return fmt.Errorf("error sending file header: %w", err)
                        }
 
                        // Read the client's Next Action request
@@ -1029,8 +1090,8 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                        }
 
                        // Send ffo bytes to client
-                       if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
-                               s.Logger.Error(err)
+                       _, err = io.Copy(rwc, hlFile.ffo)
+                       if err != nil {
                                return err
                        }
 
@@ -1187,7 +1248,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                                return err
                                        }
 
-                                       if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
+                                       if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
                                                s.Logger.Error(err)
                                        }