X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/d005ef04cfaa26943e6dd33807d741577ffb232a..a6216dd89252fa01dc176f98f1e4ecfd3f637566:/hotline/server.go diff --git a/hotline/server.go b/hotline/server.go index f4a2ad4..f2a69ad 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -2,20 +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" - "io/ioutil" + "log" + "log/slog" "math/big" "math/rand" "net" "os" + "path" "path/filepath" "strings" "sync" @@ -28,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 @@ -41,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 @@ -83,33 +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() @@ -135,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) } }() } @@ -172,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) } }() } @@ -184,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) } } }() @@ -210,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), @@ -224,7 +233,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,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, @@ -274,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) @@ -315,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( @@ -339,7 +356,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 +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++ @@ -411,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 { @@ -422,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) } @@ -452,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 { @@ -463,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 } @@ -514,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 @@ -643,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 } @@ -694,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 @@ -729,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 @@ -741,7 +783,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), @@ -806,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 @@ -826,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 } } @@ -898,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 @@ -915,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 { @@ -926,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 @@ -962,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 { @@ -989,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 @@ -1008,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 @@ -1040,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 } @@ -1099,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), @@ -1140,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), @@ -1210,8 +1249,8 @@ 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 { - s.Logger.Error(err) + if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil { + s.Logger.Error(err.Error()) } err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath()) @@ -1231,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 { @@ -1266,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