27 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
28 idleCheckInterval = 10 // time in seconds to check for idle users
29 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
34 Accounts map[string]*Account
36 Clients map[uint16]*ClientConn
38 ThreadedNews *ThreadedNews
39 FileTransfers map[uint32]*FileTransfer
42 Logger *zap.SugaredLogger
43 PrivateChats map[uint32]*PrivateChat
48 APIListener net.Listener
49 FileListener net.Listener
51 // newsReader io.Reader
52 // newsWriter io.WriteCloser
54 outbox chan Transaction
57 flatNewsMux sync.Mutex
60 type PrivateChat struct {
62 ClientConn map[uint16]*ClientConn
65 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
66 s.Logger.Infow("Hotline server started", "version", VERSION)
70 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
73 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
80 func (s *Server) APIPort() int {
81 return s.APIListener.Addr().(*net.TCPAddr).Port
84 func (s *Server) ServeFileTransfers(ln net.Listener) error {
85 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
88 conn, err := ln.Accept()
94 if err := s.handleFileTransfer(conn); err != nil {
95 s.Logger.Errorw("file transfer error", "reason", err)
101 func (s *Server) sendTransaction(t Transaction) error {
102 requestNum := binary.BigEndian.Uint16(t.Type)
103 clientID, err := byteToInt(*t.clientID)
109 client := s.Clients[uint16(clientID)]
112 return fmt.Errorf("invalid client id %v", *t.clientID)
114 userName := string(client.UserName)
115 login := client.Account.Login
117 handler := TransactionHandlers[requestNum]
119 b, err := t.MarshalBinary()
124 if n, err = client.Connection.Write(b); err != nil {
127 s.Logger.Debugw("Sent Transaction",
130 "IsReply", t.IsReply,
131 "type", handler.Name,
133 "remoteAddr", client.Connection.RemoteAddr(),
138 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
139 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
142 conn, err := ln.Accept()
144 s.Logger.Errorw("error accepting connection", "err", err)
151 if err := s.sendTransaction(t); err != nil {
152 s.Logger.Errorw("error sending transaction", "err", err)
158 if err := s.handleNewConnection(conn); err != nil {
160 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
162 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
170 agreementFile = "Agreement.txt"
173 // NewServer constructs a new Server from a config dir
174 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
177 Accounts: make(map[string]*Account),
179 Clients: make(map[uint16]*ClientConn),
180 FileTransfers: make(map[uint32]*FileTransfer),
181 PrivateChats: make(map[uint32]*PrivateChat),
182 ConfigDir: configDir,
184 NextGuestID: new(uint16),
185 outbox: make(chan Transaction),
186 Stats: &Stats{StartTime: time.Now()},
187 ThreadedNews: &ThreadedNews{},
188 TrackerPassID: make([]byte, 4),
191 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
195 server.APIListener = ln
201 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
202 server.FileListener = ln2
207 // generate a new random passID for tracker registration
208 if _, err := rand.Read(server.TrackerPassID); err != nil {
212 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
213 if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
217 if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil {
221 if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil {
225 if err := server.loadConfig(configDir + "config.yaml"); err != nil {
229 if err := server.loadAccounts(configDir + "Users/"); err != nil {
233 server.Config.FileRoot = configDir + "Files/"
235 *server.NextGuestID = 1
237 if server.Config.EnableTrackerRegistration {
240 tr := TrackerRegistration{
241 Port: []byte{0x15, 0x7c},
242 UserCount: server.userCount(),
243 PassID: server.TrackerPassID,
244 Name: server.Config.Name,
245 Description: server.Config.Description,
247 for _, t := range server.Config.Trackers {
248 server.Logger.Infof("Registering with tracker %v", t)
250 if err := register(t, tr); err != nil {
251 server.Logger.Errorw("unable to register with tracker %v", "error", err)
255 time.Sleep(trackerUpdateFrequency * time.Second)
260 // Start Client Keepalive go routine
261 go server.keepaliveHandler()
266 func (s *Server) userCount() int {
270 return len(s.Clients)
273 func (s *Server) keepaliveHandler() {
275 time.Sleep(idleCheckInterval * time.Second)
278 for _, c := range s.Clients {
279 c.IdleTime += idleCheckInterval
280 if c.IdleTime > userIdleSeconds && !c.Idle {
283 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
284 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
285 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
288 tranNotifyChangeUser,
289 NewField(fieldUserID, *c.ID),
290 NewField(fieldUserFlags, *c.Flags),
291 NewField(fieldUserName, c.UserName),
292 NewField(fieldUserIconID, *c.Icon),
300 func (s *Server) writeThreadedNews() error {
304 out, err := yaml.Marshal(s.ThreadedNews)
308 err = ioutil.WriteFile(
309 s.ConfigDir+"ThreadedNews.yaml",
316 func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
320 clientConn := &ClientConn{
323 Flags: &[]byte{0, 0},
329 Transfers: make(map[int][]*FileTransfer),
335 binary.BigEndian.PutUint16(*clientConn.ID, ID)
336 s.Clients[ID] = clientConn
341 // NewUser creates a new user account entry in the server map and config file
342 func (s *Server) NewUser(login, name, password string, access []byte) error {
349 Password: hashAndSalt([]byte(password)),
352 out, err := yaml.Marshal(&account)
356 s.Accounts[login] = &account
358 return FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
361 // DeleteUser deletes the user account
362 func (s *Server) DeleteUser(login string) error {
366 delete(s.Accounts, login)
368 return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
371 func (s *Server) connectedUsers() []Field {
375 var connectedUsers []Field
376 for _, c := range sortedClients(s.Clients) {
384 Name: string(c.UserName),
386 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
388 return connectedUsers
391 // loadThreadedNews loads the threaded news data from disk
392 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
393 fh, err := os.Open(threadedNewsPath)
397 decoder := yaml.NewDecoder(fh)
399 return decoder.Decode(s.ThreadedNews)
402 // loadAccounts loads account data from disk
403 func (s *Server) loadAccounts(userDir string) error {
404 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
409 if len(matches) == 0 {
410 return errors.New("no user accounts found in " + userDir)
413 for _, file := range matches {
414 fh, err := FS.Open(file)
420 decoder := yaml.NewDecoder(fh)
421 if err := decoder.Decode(&account); err != nil {
425 s.Accounts[account.Login] = &account
430 func (s *Server) loadConfig(path string) error {
431 fh, err := FS.Open(path)
436 decoder := yaml.NewDecoder(fh)
437 err = decoder.Decode(s.Config)
445 minTransactionLen = 22 // minimum length of any transaction
448 // handleNewConnection takes a new net.Conn and performs the initial login sequence
449 func (s *Server) handleNewConnection(conn net.Conn) error {
450 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
451 if _, err := conn.Read(handshakeBuf); err != nil {
454 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
458 buf := make([]byte, 1024)
459 readLen, err := conn.Read(buf)
460 if readLen < minTransactionLen {
467 clientLogin, _, err := ReadTransaction(buf[:readLen])
472 c := s.NewClientConn(conn)
475 if r := recover(); r != nil {
476 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
477 c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
482 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
483 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
484 *c.Version = clientLogin.GetField(fieldVersion).Data
487 for _, char := range encodedLogin {
488 login += string(rune(255 - uint(char)))
494 // If authentication fails, send error reply and close connection
495 if !c.Authenticate(login, encodedPassword) {
496 t := c.NewErrReply(clientLogin, "Incorrect login.")
497 b, err := t.MarshalBinary()
501 if _, err := conn.Write(b); err != nil {
504 return fmt.Errorf("incorrect login")
507 if clientLogin.GetField(fieldUserName).Data != nil {
508 c.UserName = clientLogin.GetField(fieldUserName).Data
511 if clientLogin.GetField(fieldUserIconID).Data != nil {
512 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
515 c.Account = c.Server.Accounts[login]
517 if c.Authorize(accessDisconUser) {
518 *c.Flags = []byte{0, 2}
521 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
523 s.outbox <- c.NewReply(clientLogin,
524 NewField(fieldVersion, []byte{0x00, 0xbe}),
525 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
526 NewField(fieldServerName, []byte(s.Config.Name)),
529 // Send user access privs so client UI knows how to behave
530 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
532 // Show agreement to client
533 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
535 // assume simplified hotline v1.2.3 login flow that does not require agreement
536 if *c.Version == nil {
541 tranNotifyChangeUser, nil,
542 NewField(fieldUserName, c.UserName),
543 NewField(fieldUserID, *c.ID),
544 NewField(fieldUserIconID, *c.Icon),
545 NewField(fieldUserFlags, *c.Flags),
550 c.Server.Stats.LoginCount += 1
552 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
553 tranBuff := make([]byte, 0)
555 // Infinite loop where take action on incoming client requests until the connection is closed
557 buf = make([]byte, readBuffSize)
558 tranBuff = tranBuff[tReadlen:]
560 readLen, err := c.Connection.Read(buf)
564 tranBuff = append(tranBuff, buf[:readLen]...)
566 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
567 // into a slice of transactions
568 var transactions []Transaction
569 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
570 c.Server.Logger.Errorw("Error handling transaction", "err", err)
573 // iterate over all of the transactions that were parsed from the byte slice and handle them
574 for _, t := range transactions {
575 if err := c.handleTransaction(&t); err != nil {
576 c.Server.Logger.Errorw("Error handling transaction", "err", err)
582 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
583 // in the file transfer request payload, and the file transfer server will use it to map the request
585 func (s *Server) NewTransactionRef() []byte {
586 transactionRef := make([]byte, 4)
587 rand.Read(transactionRef)
589 return transactionRef
592 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
596 randID := make([]byte, 4)
598 data := binary.BigEndian.Uint32(randID[:])
600 s.PrivateChats[data] = &PrivateChat{
602 ClientConn: make(map[uint16]*ClientConn),
604 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
609 const dlFldrActionSendFile = 1
610 const dlFldrActionResumeFile = 2
611 const dlFldrActionNextFile = 3
613 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
614 func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
616 if err := conn.Close(); err != nil {
617 s.Logger.Errorw("error closing connection", "error", err)
621 txBuf := make([]byte, 16)
622 _, err := conn.Read(txBuf)
628 _, err = t.Write(txBuf)
633 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
634 fileTransfer := s.FileTransfers[transferRefNum]
636 switch fileTransfer.Type {
638 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
643 ffo, err := NewFlattenedFileObject(
645 fileTransfer.FilePath,
646 fileTransfer.FileName,
652 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
654 // Start by sending flat file object to client
655 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
659 file, err := FS.Open(fullFilePath)
664 sendBuffer := make([]byte, 1048576)
667 if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
671 fileTransfer.BytesSent += bytesRead
673 delete(s.FileTransfers, transferRefNum)
675 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
680 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
681 newFile, err := FS.Create(destinationFile)
685 defer func() { _ = newFile.Close() }()
687 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
689 if err := receiveFile(conn, newFile, nil); err != nil {
690 s.Logger.Errorw("file upload error", "error", err)
693 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
695 // Folder Download flow:
696 // 1. Get filePath from the transfer
697 // 2. Iterate over files
699 // Send file header to client
700 // The client can reply in 3 ways:
702 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
703 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
705 // 2. If download of a file is to be resumed:
707 // []byte{0x00, 0x02} // download folder action
708 // [2]byte // Resume data size
709 // []byte file resume data (see myField_FileResumeData)
711 // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
713 // When download is requested (case 2 or 3), server replies with:
714 // [4]byte - file size
715 // []byte - Flattened File Object
717 // After every file download, client could request next file with:
718 // []byte{0x00, 0x03}
720 // This notifies the server to send the next item header
722 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
727 basePathLen := len(fullFilePath)
729 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
731 nextAction := make([]byte, 2)
732 if _, err := conn.Read(nextAction); err != nil {
737 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
742 subPath := path[basePathLen+1:]
743 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
749 fileHeader := NewFileHeader(subPath, info.IsDir())
751 // Send the file header to client
752 if _, err := conn.Write(fileHeader.Payload()); err != nil {
753 s.Logger.Errorf("error sending file header: %v", err)
757 // Read the client's Next Action request
758 if _, err := conn.Read(nextAction); err != nil {
761 if nextAction[1] == 3 {
765 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
771 splitPath := strings.Split(path, "/")
773 ffo, err := NewFlattenedFileObject(
774 strings.Join(splitPath[:len(splitPath)-1], "/"),
781 s.Logger.Infow("File download started",
782 "fileName", info.Name(),
783 "transactionRef", fileTransfer.ReferenceNumber,
784 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
787 // Send file size to client
788 if _, err := conn.Write(ffo.TransferSize()); err != nil {
793 // Send ffo bytes to client
794 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
799 file, err := FS.Open(path)
804 // Copy N bytes from file to connection
805 _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
811 // TODO: optionally send resource fork header and resource fork data
813 // Read the client's Next Action request
814 if _, err := conn.Read(nextAction); err != nil {
817 // TODO: switch behavior based on possible next action
823 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
828 "Folder upload started",
829 "transactionRef", fileTransfer.ReferenceNumber,
831 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
832 "FolderItemCount", fileTransfer.FolderItemCount,
835 // Check if the target folder exists. If not, create it.
836 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
837 s.Logger.Infow("Creating target path", "dstPath", dstPath)
838 if err := FS.Mkdir(dstPath, 0777); err != nil {
843 // Begin the folder upload flow by sending the "next file action" to client
844 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
848 fileSize := make([]byte, 4)
849 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
851 readBuffer := make([]byte, 1024)
852 for i := uint16(0); i < itemCount; i++ {
853 _, err := conn.Read(readBuffer)
857 fu := readFolderUpload(readBuffer)
860 "Folder upload continued",
861 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
862 "FormattedPath", fu.FormattedPath(),
863 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
864 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
867 if fu.IsFolder == [2]byte{0, 1} {
868 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
869 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
870 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
875 // Tell client to send next file
876 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
881 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
882 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
883 // Send dlFldrAction_SendFile to client to begin transfer
884 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
888 if _, err := conn.Read(fileSize); err != nil {
892 filePath := dstPath + "/" + fu.FormattedPath()
893 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", itemCount, "fileSize", binary.BigEndian.Uint32(fileSize))
895 newFile, err := FS.Create(filePath)
900 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
905 // Tell client to send next file
906 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
913 s.Logger.Infof("Folder upload complete")
919 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
920 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
921 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
922 for _, c := range unsortedClients {
923 clients = append(clients, c)
925 sort.Sort(byClientID(clients))