]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/server.go
Replace zap logger with slog
[rbdr/mobius] / hotline / server.go
index 500087a96159b171626b23198e978181c5b2ecc1..f2a69ad735b31c4bcd0884b13ca49c99dd3bd525 100644 (file)
@@ -2,19 +2,23 @@ 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"
+       "log"
+       "log/slog"
        "math/big"
        "math/rand"
        "net"
        "os"
+       "path"
        "path/filepath"
        "strings"
        "sync"
@@ -27,11 +31,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
@@ -40,7 +49,8 @@ type Server struct {
 
        Config    *Config
        ConfigDir string
-       Logger    *zap.SugaredLogger
+       Logger    *slog.Logger
+       banner    []byte
 
        PrivateChatsMu sync.Mutex
        PrivateChats   map[uint32]*PrivateChat
@@ -82,32 +92,32 @@ type PrivateChat struct {
 }
 
 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
-       s.Logger.Infow("Hotline server started",
+       s.Logger.Info("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)
+                       log.Fatal(err)
                }
 
-               s.Logger.Fatal(s.Serve(ctx, ln))
+               log.Fatal(s.Serve(ctx, ln))
        }()
 
        wg.Add(1)
        go func() {
-               ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
+               ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1))
                if err != nil {
-                       s.Logger.Fatal(err)
+                       log.Fatal(err)
                }
 
-               s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
+               log.Fatal(s.ServeFileTransfers(ctx, ln))
        }()
 
        wg.Wait()
@@ -133,7 +143,7 @@ func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error
                        )
 
                        if err != nil {
-                               s.Logger.Errorw("file transfer error", "reason", err)
+                               s.Logger.Error("file transfer error", "reason", err)
                        }
                }()
        }
@@ -170,7 +180,7 @@ func (s *Server) processOutbox() {
                t := <-s.outbox
                go func() {
                        if err := s.sendTransaction(t); err != nil {
-                               s.Logger.Errorw("error sending transaction", "err", err)
+                               s.Logger.Error("error sending transaction", "err", err)
                        }
                }()
        }
@@ -182,21 +192,21 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
        for {
                conn, err := ln.Accept()
                if err != nil {
-                       s.Logger.Errorw("error accepting connection", "err", err)
+                       s.Logger.Error("error accepting connection", "err", err)
                }
                connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
                        remoteAddr: conn.RemoteAddr().String(),
                })
 
                go func() {
-                       s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
+                       s.Logger.Info("Connection established", "RemoteAddr", conn.RemoteAddr())
 
                        defer conn.Close()
                        if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
                                if err == io.EOF {
-                                       s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
+                                       s.Logger.Info("Client disconnected", "RemoteAddr", conn.RemoteAddr())
                                } else {
-                                       s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
+                                       s.Logger.Error("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
                                }
                        }
                }()
@@ -208,8 +218,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 *slog.Logger, fs FileStore) (*Server, error) {
        server := Server{
+               NetInterface:  netInterface,
                Port:          netPort,
                Accounts:      make(map[string]*Account),
                Config:        new(Config),
@@ -257,12 +268,20 @@ 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
 
        if server.Config.EnableTrackerRegistration {
-               server.Logger.Infow(
+               server.Logger.Info(
                        "Tracker registration enabled",
                        "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
                        "trackers", server.Config.Trackers,
@@ -272,16 +291,16 @@ func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, fs File
                        for {
                                tr := &TrackerRegistration{
                                        UserCount:   server.userCount(),
-                                       PassID:      server.TrackerPassID[:],
+                                       PassID:      server.TrackerPassID,
                                        Name:        server.Config.Name,
                                        Description: server.Config.Description,
                                }
                                binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
                                for _, t := range server.Config.Trackers {
                                        if err := register(t, tr); err != nil {
-                                               server.Logger.Errorw("unable to register with tracker %v", "error", err)
+                                               server.Logger.Error("unable to register with tracker %v", "error", err)
                                        }
-                                       server.Logger.Debugw("Sent Tracker registration", "addr", t)
+                                       server.Logger.Debug("Sent Tracker registration", "addr", t)
                                }
 
                                time.Sleep(trackerUpdateFrequency * time.Second)
@@ -313,7 +332,7 @@ 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(
@@ -374,15 +393,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++
@@ -409,9 +427,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 {
@@ -420,11 +455,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)
        }
 
@@ -450,9 +486,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 {
@@ -461,13 +502,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
 }
@@ -512,8 +556,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
@@ -641,7 +685,7 @@ 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.Info("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
 
                return nil
        }
@@ -692,7 +736,7 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                // part of TranAgreed
                c.logger = c.logger.With("name", string(c.UserName))
 
-               c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
+               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
@@ -727,7 +771,7 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser
                }
 
                if err := c.handleTransaction(t); err != nil {
-                       c.logger.Errorw("Error handling transaction", "err", err)
+                       c.logger.Error("Error handling transaction", "err", err)
                }
        }
        return nil
@@ -804,8 +848,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
@@ -824,12 +868,12 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                        return err
                }
 
-               rLogger.Infow("File download started", "filePath", fullPath)
+               rLogger.Info("File download started", "filePath", fullPath)
 
                // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
                if fileTransfer.options == nil {
-                       // Start by sending flat file object to client
-                       if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
+                       _, err = io.Copy(rwc, fw.ffo)
+                       if err != nil {
                                return err
                        }
                }
@@ -896,7 +940,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                        return err
                }
 
-               rLogger.Infow("File upload started", "dstFile", fullPath)
+               rLogger.Info("File upload started", "dstFile", fullPath)
 
                rForkWriter := io.Discard
                iForkWriter := io.Discard
@@ -913,7 +957,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                }
 
                if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
-                       s.Logger.Error(err)
+                       s.Logger.Error(err.Error())
                }
 
                if err := file.Close(); err != nil {
@@ -924,7 +968,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                        return err
                }
 
-               rLogger.Infow("File upload complete", "dstFile", fullPath)
+               rLogger.Info("File upload complete", "dstFile", fullPath)
 
        case FolderDownload:
                s.Stats.DownloadCounter += 1
@@ -960,7 +1004,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
 
                basePathLen := len(fullPath)
 
-               rLogger.Infow("Start folder download", "path", fullPath)
+               rLogger.Info("Start folder download", "path", fullPath)
 
                nextAction := make([]byte, 2)
                if _, err := io.ReadFull(rwc, nextAction); err != nil {
@@ -987,18 +1031,15 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                        }
 
                        subPath := path[basePathLen+1:]
-                       rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
+                       rLogger.Debug("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
 
                        if i == 1 {
                                return nil
                        }
 
                        fileHeader := NewFileHeader(subPath, info.IsDir())
-
-                       // Send the fileWrapper header to client
-                       if _, err := rwc.Write(fileHeader.Payload()); err != nil {
-                               s.Logger.Errorf("error sending file header: %v", err)
-                               return err
+                       if _, err := io.Copy(rwc, &fileHeader); err != nil {
+                               return fmt.Errorf("error sending file header: %w", err)
                        }
 
                        // Read the client's Next Action request
@@ -1006,7 +1047,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                return err
                        }
 
-                       rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
+                       rLogger.Debug("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
 
                        var dataOffset int64
 
@@ -1038,20 +1079,20 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                return nil
                        }
 
-                       rLogger.Infow("File download started",
+                       rLogger.Info("File download started",
                                "fileName", info.Name(),
                                "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
                        )
 
                        // Send file size to client
                        if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
-                               s.Logger.Error(err)
+                               s.Logger.Error(err.Error())
                                return err
                        }
 
                        // 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
                        }
 
@@ -1097,7 +1138,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                s.Stats.UploadCounter += 1
                s.Stats.UploadsInProgress += 1
                defer func() { s.Stats.UploadsInProgress -= 1 }()
-               rLogger.Infow(
+               rLogger.Info(
                        "Folder upload started",
                        "dstPath", fullPath,
                        "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
@@ -1138,7 +1179,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                return err
                        }
 
-                       rLogger.Infow(
+                       rLogger.Info(
                                "Folder upload continued",
                                "FormattedPath", fu.FormattedPath(),
                                "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
@@ -1209,7 +1250,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                        }
 
                                        if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
-                                               s.Logger.Error(err)
+                                               s.Logger.Error(err.Error())
                                        }
 
                                        err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
@@ -1229,7 +1270,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                                return err
                                        }
 
-                                       rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
+                                       rLogger.Info("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
 
                                        incWriter, err := hlFile.incFileWriter()
                                        if err != nil {
@@ -1264,7 +1305,7 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro
                                }
                        }
                }
-               rLogger.Infof("Folder upload complete")
+               rLogger.Info("Folder upload complete")
        }
 
        return nil