11 "github.com/go-playground/validator/v10"
12 "golang.org/x/text/encoding/charmap"
27 type contextKey string
29 var contextKeyReq = contextKey("req")
31 type requestCtx struct {
35 // Converts bytes from Mac Roman encoding to UTF-8
36 var txtDecoder = charmap.Macintosh.NewDecoder()
38 // Converts bytes from UTF-8 to Mac Roman encoding
39 var txtEncoder = charmap.Macintosh.NewEncoder()
44 Accounts map[string]*Account
47 Clients map[[2]byte]*ClientConn
48 fileTransfers map[[4]byte]*FileTransfer
55 PrivateChatsMu sync.Mutex
56 PrivateChats map[[4]byte]*PrivateChat
58 nextClientID atomic.Uint32
64 FS FileStore // Storage backend to use for File storage
66 outbox chan Transaction
69 threadedNewsMux sync.Mutex
70 ThreadedNews *ThreadedNews
72 flatNewsMux sync.Mutex
76 banList map[string]*time.Time
79 func (s *Server) CurrentStats() Stats {
81 defer s.statsMu.Unlock()
84 stats.CurrentlyConnected = len(s.Clients)
89 type PrivateChat struct {
91 ClientConn map[[2]byte]*ClientConn
94 func (s *Server) ListenAndServe(ctx context.Context) error {
99 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port))
104 log.Fatal(s.Serve(ctx, ln))
109 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1))
114 log.Fatal(s.ServeFileTransfers(ctx, ln))
122 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
124 conn, err := ln.Accept()
130 defer func() { _ = conn.Close() }()
132 err = s.handleFileTransfer(
133 context.WithValue(ctx, contextKeyReq, requestCtx{remoteAddr: conn.RemoteAddr().String()}),
138 s.Logger.Error("file transfer error", "reason", err)
144 func (s *Server) sendTransaction(t Transaction) error {
146 client, ok := s.Clients[t.clientID]
149 if !ok || client == nil {
153 _, err := io.Copy(client.Connection, &t)
155 return fmt.Errorf("failed to send transaction to client %v: %v", t.clientID, err)
161 func (s *Server) processOutbox() {
165 if err := s.sendTransaction(t); err != nil {
166 s.Logger.Error("error sending transaction", "err", err)
172 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
176 conn, err := ln.Accept()
178 s.Logger.Error("error accepting connection", "err", err)
180 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
181 remoteAddr: conn.RemoteAddr().String(),
185 s.Logger.Info("Connection established", "RemoteAddr", conn.RemoteAddr())
188 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
190 s.Logger.Info("Client disconnected", "RemoteAddr", conn.RemoteAddr())
192 s.Logger.Error("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
200 agreementFile = "Agreement.txt"
203 // NewServer constructs a new Server from a config dir
204 // TODO: move config file reads out of this function
205 func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, fs FileStore) (*Server, error) {
207 NetInterface: netInterface,
209 Accounts: make(map[string]*Account),
211 Clients: make(map[[2]byte]*ClientConn),
212 fileTransfers: make(map[[4]byte]*FileTransfer),
213 PrivateChats: make(map[[4]byte]*PrivateChat),
214 ConfigDir: configDir,
216 outbox: make(chan Transaction),
217 Stats: &Stats{Since: time.Now()},
218 ThreadedNews: &ThreadedNews{},
220 banList: make(map[string]*time.Time),
225 // generate a new random passID for tracker registration
226 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
230 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
235 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
239 // try to load the ban list, but ignore errors as this file may not be present or may be empty
240 //_ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
242 _ = loadFromYAMLFile(filepath.Join(configDir, "Banlist.yaml"), &server.banList)
244 err = loadFromYAMLFile(filepath.Join(configDir, "ThreadedNews.yaml"), &server.ThreadedNews)
246 return nil, fmt.Errorf("error loading threaded news: %w", err)
249 err = server.loadConfig(filepath.Join(configDir, "config.yaml"))
251 return nil, fmt.Errorf("error loading config: %w", err)
254 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
258 // If the FileRoot is an absolute path, use it, otherwise treat as a relative path to the config dir.
259 if !filepath.IsAbs(server.Config.FileRoot) {
260 server.Config.FileRoot = filepath.Join(configDir, server.Config.FileRoot)
263 server.banner, err = os.ReadFile(filepath.Join(server.ConfigDir, server.Config.BannerFile))
265 return nil, fmt.Errorf("error opening banner: %w", err)
268 if server.Config.EnableTrackerRegistration {
270 "Tracker registration enabled",
271 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
272 "trackers", server.Config.Trackers,
277 tr := &TrackerRegistration{
278 UserCount: server.userCount(),
279 PassID: server.TrackerPassID,
280 Name: server.Config.Name,
281 Description: server.Config.Description,
283 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
284 for _, t := range server.Config.Trackers {
285 if err := register(&RealDialer{}, t, tr); err != nil {
286 server.Logger.Error("unable to register with tracker %v", "error", err)
288 server.Logger.Debug("Sent Tracker registration", "addr", t)
291 time.Sleep(trackerUpdateFrequency * time.Second)
296 // Start Client Keepalive go routine
297 go server.keepaliveHandler()
302 func (s *Server) userCount() int {
306 return len(s.Clients)
309 func (s *Server) keepaliveHandler() {
311 time.Sleep(idleCheckInterval * time.Second)
314 for _, c := range s.Clients {
315 c.IdleTime += idleCheckInterval
316 if c.IdleTime > userIdleSeconds && !c.Idle {
320 c.Flags.Set(UserFlagAway, 1)
323 TranNotifyChangeUser,
324 NewField(FieldUserID, c.ID[:]),
325 NewField(FieldUserFlags, c.Flags[:]),
326 NewField(FieldUserName, c.UserName),
327 NewField(FieldUserIconID, c.Icon),
335 func (s *Server) writeBanList() error {
337 defer s.banListMU.Unlock()
339 out, err := yaml.Marshal(s.banList)
344 filepath.Join(s.ConfigDir, "Banlist.yaml"),
351 func (s *Server) writeThreadedNews() error {
352 s.threadedNewsMux.Lock()
353 defer s.threadedNewsMux.Unlock()
355 out, err := yaml.Marshal(s.ThreadedNews)
359 err = s.FS.WriteFile(
360 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
367 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
371 clientConn := &ClientConn{
372 Icon: []byte{0, 0}, // TODO: make array type
375 RemoteAddr: remoteAddr,
376 transfers: map[int]map[[4]byte]*FileTransfer{
385 s.nextClientID.Add(1)
387 binary.BigEndian.PutUint16(clientConn.ID[:], uint16(s.nextClientID.Load()))
388 s.Clients[clientConn.ID] = clientConn
393 // NewUser creates a new user account entry in the server map and config file
394 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
398 account := NewAccount(login, name, password, access)
400 // Create account file, returning an error if one already exists.
401 file, err := os.OpenFile(
402 filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"),
403 os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644,
406 return fmt.Errorf("error creating account file: %w", err)
410 b, err := yaml.Marshal(account)
415 _, err = file.Write(b)
417 return fmt.Errorf("error writing account file: %w", err)
420 s.Accounts[login] = account
425 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
429 // If the login has changed, rename the account file.
430 if login != newLogin {
432 filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"),
433 filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"),
436 return fmt.Errorf("error renaming account file: %w", err)
438 s.Accounts[newLogin] = s.Accounts[login]
439 s.Accounts[newLogin].Login = newLogin
440 delete(s.Accounts, login)
443 account := s.Accounts[newLogin]
444 account.Access = access
446 account.Password = password
448 out, err := yaml.Marshal(&account)
453 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
454 return fmt.Errorf("error writing account file: %w", err)
460 // DeleteUser deletes the user account
461 func (s *Server) DeleteUser(login string) error {
465 err := s.FS.Remove(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"))
470 delete(s.Accounts, login)
475 func (s *Server) connectedUsers() []Field {
477 //defer s.mux.Unlock()
479 var connectedUsers []Field
480 for _, c := range sortedClients(s.Clients) {
481 b, err := io.ReadAll(&User{
485 Name: string(c.UserName),
490 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, b))
492 return connectedUsers
495 // loadFromYAMLFile loads data from a YAML file into the provided data structure.
496 func loadFromYAMLFile(path string, data interface{}) error {
497 fh, err := os.Open(path)
503 decoder := yaml.NewDecoder(fh)
504 return decoder.Decode(data)
507 // loadAccounts loads account data from disk
508 func (s *Server) loadAccounts(userDir string) error {
509 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
514 if len(matches) == 0 {
515 return fmt.Errorf("no accounts found in directory: %s", userDir)
518 for _, file := range matches {
520 if err = loadFromYAMLFile(file, &account); err != nil {
521 return fmt.Errorf("error loading account %s: %w", file, err)
524 s.Accounts[account.Login] = &account
529 func (s *Server) loadConfig(path string) error {
530 fh, err := s.FS.Open(path)
535 decoder := yaml.NewDecoder(fh)
536 err = decoder.Decode(s.Config)
541 validate := validator.New()
542 err = validate.Struct(s.Config)
549 func sendBanMessage(rwc io.Writer, message string) {
553 NewField(FieldData, []byte(message)),
554 NewField(FieldChatOptions, []byte{0, 0}),
556 _, _ = io.Copy(rwc, &t)
557 time.Sleep(1 * time.Second)
560 // handleNewConnection takes a new net.Conn and performs the initial login sequence
561 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
562 defer dontPanic(s.Logger)
564 // Check if remoteAddr is present in the ban list
565 ipAddr := strings.Split(remoteAddr, ":")[0]
566 if banUntil, ok := s.banList[ipAddr]; ok {
569 sendBanMessage(rwc, "You are permanently banned on this server")
570 s.Logger.Debug("Disconnecting permanently banned IP", "remoteAddr", ipAddr)
575 if time.Now().Before(*banUntil) {
576 sendBanMessage(rwc, "You are temporarily banned on this server")
577 s.Logger.Debug("Disconnecting temporarily banned IP", "remoteAddr", ipAddr)
582 if err := performHandshake(rwc); err != nil {
583 return fmt.Errorf("error performing handshake: %w", err)
586 // Create a new scanner for parsing incoming bytes into transaction tokens
587 scanner := bufio.NewScanner(rwc)
588 scanner.Split(transactionScanner)
592 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
593 // scanner re-uses the buffer for subsequent scans.
594 buf := make([]byte, len(scanner.Bytes()))
595 copy(buf, scanner.Bytes())
597 var clientLogin Transaction
598 if _, err := clientLogin.Write(buf); err != nil {
599 return fmt.Errorf("error writing login transaction: %w", err)
602 c := s.NewClientConn(rwc, remoteAddr)
605 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
606 c.Version = clientLogin.GetField(FieldVersion).Data
608 login := string(encodeString(clientLogin.GetField(FieldUserLogin).Data))
613 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
615 // If authentication fails, send error reply and close connection
616 if !c.Authenticate(login, encodedPassword) {
617 t := c.NewErrReply(&clientLogin, "Incorrect login.")[0]
619 _, err := io.Copy(rwc, &t)
624 c.logger.Info("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
629 if clientLogin.GetField(FieldUserIconID).Data != nil {
630 c.Icon = clientLogin.GetField(FieldUserIconID).Data
634 c.Account = c.Server.Accounts[login]
637 if clientLogin.GetField(FieldUserName).Data != nil {
638 if c.Authorize(accessAnyName) {
639 c.UserName = clientLogin.GetField(FieldUserName).Data
641 c.UserName = []byte(c.Account.Name)
645 if c.Authorize(accessDisconUser) {
646 c.Flags.Set(UserFlagAdmin, 1)
649 s.outbox <- c.NewReply(&clientLogin,
650 NewField(FieldVersion, []byte{0x00, 0xbe}),
651 NewField(FieldCommunityBannerID, []byte{0, 0}),
652 NewField(FieldServerName, []byte(s.Config.Name)),
655 // Send user access privs so client UI knows how to behave
656 c.Server.outbox <- NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
658 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
659 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
660 // TranShowAgreement but with the NoServerAgreement field set to 1.
661 if c.Authorize(accessNoAgreement) {
662 // If client version is nil, then the client uses the 1.2.3 login behavior
663 if c.Version != nil {
664 c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
667 c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
670 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
671 // flow and not the 1.5+ flow.
672 if len(c.UserName) != 0 {
673 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
674 // part of TranAgreed
675 c.logger = c.logger.With("Name", string(c.UserName))
676 c.logger.Info("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
678 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
679 // information yet, so we do it in TranAgreed instead
680 for _, t := range c.notifyOthers(
682 TranNotifyChangeUser, [2]byte{0, 0},
683 NewField(FieldUserName, c.UserName),
684 NewField(FieldUserID, c.ID[:]),
685 NewField(FieldUserIconID, c.Icon),
686 NewField(FieldUserFlags, c.Flags[:]),
694 c.Server.Stats.ConnectionCounter += 1
695 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
696 c.Server.Stats.ConnectionPeak = len(s.Clients)
698 c.Server.mux.Unlock()
700 // Scan for new transactions and handle them as they come in.
702 // Copy the scanner bytes to a new slice to it to avoid a data race when the scanner re-uses the buffer.
703 buf := make([]byte, len(scanner.Bytes()))
704 copy(buf, scanner.Bytes())
707 if _, err := t.Write(buf); err != nil {
711 c.handleTransaction(t)
716 func (s *Server) NewPrivateChat(cc *ClientConn) [4]byte {
717 s.PrivateChatsMu.Lock()
718 defer s.PrivateChatsMu.Unlock()
721 _, _ = rand.Read(randID[:])
723 s.PrivateChats[randID] = &PrivateChat{
724 ClientConn: make(map[[2]byte]*ClientConn),
726 s.PrivateChats[randID].ClientConn[cc.ID] = cc
731 const dlFldrActionSendFile = 1
732 const dlFldrActionResumeFile = 2
733 const dlFldrActionNextFile = 3
735 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
736 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
737 defer dontPanic(s.Logger)
739 // The first 16 bytes contain the file transfer.
741 if _, err := io.CopyN(&t, rwc, 16); err != nil {
742 return fmt.Errorf("error reading file transfer: %w", err)
747 delete(s.fileTransfers, t.ReferenceNumber)
750 // Wait a few seconds before closing the connection: this is a workaround for problems
751 // observed with Windows clients where the client must initiate close of the TCP connection before
752 // the server does. This is gross and seems unnecessary. TODO: Revisit?
753 time.Sleep(3 * time.Second)
757 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
760 return errors.New("invalid transaction ID")
764 fileTransfer.ClientConn.transfersMU.Lock()
765 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
766 fileTransfer.ClientConn.transfersMU.Unlock()
769 rLogger := s.Logger.With(
770 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
771 "login", fileTransfer.ClientConn.Account.Login,
772 "Name", string(fileTransfer.ClientConn.UserName),
775 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
780 switch fileTransfer.Type {
782 if _, err := io.Copy(rwc, bytes.NewBuffer(s.banner)); err != nil {
783 return fmt.Errorf("error sending banner: %w", err)
786 s.Stats.DownloadCounter += 1
787 s.Stats.DownloadsInProgress += 1
789 s.Stats.DownloadsInProgress -= 1
792 err = DownloadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, true)
794 return fmt.Errorf("file download error: %w", err)
798 s.Stats.UploadCounter += 1
799 s.Stats.UploadsInProgress += 1
800 defer func() { s.Stats.UploadsInProgress -= 1 }()
802 err = UploadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks)
804 return fmt.Errorf("file upload error: %w", err)
808 s.Stats.DownloadCounter += 1
809 s.Stats.DownloadsInProgress += 1
810 defer func() { s.Stats.DownloadsInProgress -= 1 }()
812 err = DownloadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks)
814 return fmt.Errorf("file upload error: %w", err)
818 s.Stats.UploadCounter += 1
819 s.Stats.UploadsInProgress += 1
820 defer func() { s.Stats.UploadsInProgress -= 1 }()
822 "Folder upload started",
824 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
825 "FolderItemCount", fileTransfer.FolderItemCount,
828 err = UploadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks)
830 return fmt.Errorf("file upload error: %w", err)