25 "golang.org/x/crypto/bcrypt"
30 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
31 idleCheckInterval = 10 // time in seconds to check for idle users
32 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
37 Accounts map[string]*Account
39 Clients map[uint16]*ClientConn
41 ThreadedNews *ThreadedNews
42 FileTransfers map[uint32]*FileTransfer
45 Logger *zap.SugaredLogger
46 PrivateChats map[uint32]*PrivateChat
51 APIListener net.Listener
52 FileListener net.Listener
55 newsWriter io.WriteCloser
57 outbox chan Transaction
60 flatNewsMux sync.Mutex
63 type PrivateChat struct {
65 ClientConn map[uint16]*ClientConn
68 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
69 s.Logger.Infow("Hotline server started", "version", VERSION)
73 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
76 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
83 func (s *Server) APIPort() int {
84 return s.APIListener.Addr().(*net.TCPAddr).Port
87 func (s *Server) ServeFileTransfers(ln net.Listener) error {
88 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
91 conn, err := ln.Accept()
97 if err := s.TransferFile(conn); err != nil {
98 s.Logger.Errorw("file transfer error", "reason", err)
104 func (s *Server) sendTransaction(t Transaction) error {
105 requestNum := binary.BigEndian.Uint16(t.Type)
106 clientID, err := byteToInt(*t.clientID)
112 client := s.Clients[uint16(clientID)]
115 return errors.New("invalid client")
117 userName := string(client.UserName)
118 login := client.Account.Login
120 handler := TransactionHandlers[requestNum]
122 b, err := t.MarshalBinary()
127 if n, err = client.Connection.Write(b); err != nil {
130 s.Logger.Debugw("Sent Transaction",
133 "IsReply", t.IsReply,
134 "type", handler.Name,
136 "remoteAddr", client.Connection.RemoteAddr(),
141 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
142 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
145 conn, err := ln.Accept()
147 s.Logger.Errorw("error accepting connection", "err", err)
154 if err := s.sendTransaction(t); err != nil {
155 s.Logger.Errorw("error sending transaction", "err", err)
161 if err := s.handleNewConnection(conn); err != nil {
163 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
165 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
173 agreementFile = "Agreement.txt"
176 // NewServer constructs a new Server from a config dir
177 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
180 Accounts: make(map[string]*Account),
182 Clients: make(map[uint16]*ClientConn),
183 FileTransfers: make(map[uint32]*FileTransfer),
184 PrivateChats: make(map[uint32]*PrivateChat),
185 ConfigDir: configDir,
187 NextGuestID: new(uint16),
188 outbox: make(chan Transaction),
189 Stats: &Stats{StartTime: time.Now()},
190 ThreadedNews: &ThreadedNews{},
191 TrackerPassID: make([]byte, 4),
194 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
198 server.APIListener = ln
204 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
205 server.FileListener = ln2
210 // generate a new random passID for tracker registration
211 if _, err := rand.Read(server.TrackerPassID); err != nil {
215 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
216 if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
220 if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil {
224 if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil {
228 if err := server.loadConfig(configDir + "config.yaml"); err != nil {
232 if err := server.loadAccounts(configDir + "Users/"); err != nil {
236 server.Config.FileRoot = configDir + "Files/"
238 *server.NextGuestID = 1
240 if server.Config.EnableTrackerRegistration {
243 tr := TrackerRegistration{
244 Port: []byte{0x15, 0x7c},
245 UserCount: server.userCount(),
246 PassID: server.TrackerPassID,
247 Name: server.Config.Name,
248 Description: server.Config.Description,
250 for _, t := range server.Config.Trackers {
251 server.Logger.Infof("Registering with tracker %v", t)
253 if err := register(t, tr); err != nil {
254 server.Logger.Errorw("unable to register with tracker %v", "error", err)
258 time.Sleep(trackerUpdateFrequency * time.Second)
263 // Start Client Keepalive go routine
264 go server.keepaliveHandler()
269 func (s *Server) userCount() int {
273 return len(s.Clients)
276 func (s *Server) keepaliveHandler() {
278 time.Sleep(idleCheckInterval * time.Second)
281 for _, c := range s.Clients {
282 *c.IdleTime += idleCheckInterval
283 if *c.IdleTime > userIdleSeconds && !c.Idle {
286 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
287 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
288 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
291 tranNotifyChangeUser,
292 NewField(fieldUserID, *c.ID),
293 NewField(fieldUserFlags, *c.Flags),
294 NewField(fieldUserName, c.UserName),
295 NewField(fieldUserIconID, *c.Icon),
303 func (s *Server) writeThreadedNews() error {
307 out, err := yaml.Marshal(s.ThreadedNews)
311 err = ioutil.WriteFile(
312 s.ConfigDir+"ThreadedNews.yaml",
319 func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
323 clientConn := &ClientConn{
326 Flags: &[]byte{0, 0},
332 AutoReply: &[]byte{},
333 Transfers: make(map[int][]*FileTransfer),
338 *clientConn.IdleTime = 0
340 binary.BigEndian.PutUint16(*clientConn.ID, ID)
341 s.Clients[ID] = clientConn
346 // NewUser creates a new user account entry in the server map and config file
347 func (s *Server) NewUser(login, name, password string, access []byte) error {
354 Password: hashAndSalt([]byte(password)),
357 out, err := yaml.Marshal(&account)
361 s.Accounts[login] = &account
363 return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
366 // DeleteUser deletes the user account
367 func (s *Server) DeleteUser(login string) error {
371 delete(s.Accounts, login)
373 return os.Remove(s.ConfigDir + "Users/" + login + ".yaml")
376 func (s *Server) connectedUsers() []Field {
380 var connectedUsers []Field
381 for _, c := range s.Clients {
386 Name: string(c.UserName),
388 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
390 return connectedUsers
393 // loadThreadedNews loads the threaded news data from disk
394 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
395 fh, err := os.Open(threadedNewsPath)
399 decoder := yaml.NewDecoder(fh)
400 decoder.SetStrict(true)
402 return decoder.Decode(s.ThreadedNews)
405 // loadAccounts loads account data from disk
406 func (s *Server) loadAccounts(userDir string) error {
407 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
412 if len(matches) == 0 {
413 return errors.New("no user accounts found in " + userDir)
416 for _, file := range matches {
417 fh, err := os.Open(file)
423 decoder := yaml.NewDecoder(fh)
424 decoder.SetStrict(true)
425 if err := decoder.Decode(&account); err != nil {
429 s.Accounts[account.Login] = &account
434 func (s *Server) loadConfig(path string) error {
435 fh, err := os.Open(path)
440 decoder := yaml.NewDecoder(fh)
441 decoder.SetStrict(true)
442 err = decoder.Decode(s.Config)
450 minTransactionLen = 22 // minimum length of any transaction
453 // handleNewConnection takes a new net.Conn and performs the initial login sequence
454 func (s *Server) handleNewConnection(conn net.Conn) error {
455 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
456 if _, err := conn.Read(handshakeBuf); err != nil {
459 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
463 buf := make([]byte, 1024)
464 readLen, err := conn.Read(buf)
465 if readLen < minTransactionLen {
472 clientLogin, _, err := ReadTransaction(buf[:readLen])
477 c := s.NewClientConn(conn)
480 if r := recover(); r != nil {
481 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
482 c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
487 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
488 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
489 *c.Version = clientLogin.GetField(fieldVersion).Data
492 for _, char := range encodedLogin {
493 login += string(rune(255 - uint(char)))
499 // If authentication fails, send error reply and close connection
500 if !c.Authenticate(login, encodedPassword) {
501 t := c.NewErrReply(clientLogin, "Incorrect login.")
502 b, err := t.MarshalBinary()
506 if _, err := conn.Write(b); err != nil {
509 return fmt.Errorf("incorrect login")
512 if clientLogin.GetField(fieldUserName).Data != nil {
513 c.UserName = clientLogin.GetField(fieldUserName).Data
516 if clientLogin.GetField(fieldUserIconID).Data != nil {
517 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
520 c.Account = c.Server.Accounts[login]
522 if c.Authorize(accessDisconUser) {
523 *c.Flags = []byte{0, 2}
526 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
528 s.outbox <- c.NewReply(clientLogin,
529 NewField(fieldVersion, []byte{0x00, 0xbe}),
530 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
531 NewField(fieldServerName, []byte(s.Config.Name)),
534 // Send user access privs so client UI knows how to behave
535 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
537 // Show agreement to client
538 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
540 if _, err := c.notifyNewUserHasJoined(); err != nil {
543 c.Server.Stats.LoginCount += 1
545 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
546 const maxTranSize = 1024000
547 tranBuff := make([]byte, 0)
549 // Infinite loop where take action on incoming client requests until the connection is closed
551 buf = make([]byte, readBuffSize)
552 tranBuff = tranBuff[tReadlen:]
554 readLen, err := c.Connection.Read(buf)
558 tranBuff = append(tranBuff, buf[:readLen]...)
560 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
561 // into a slice of transactions
562 var transactions []Transaction
563 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
564 c.Server.Logger.Errorw("Error handling transaction", "err", err)
567 // iterate over all of the transactions that were parsed from the byte slice and handle them
568 for _, t := range transactions {
569 if err := c.handleTransaction(&t); err != nil {
570 c.Server.Logger.Errorw("Error handling transaction", "err", err)
576 func hashAndSalt(pwd []byte) string {
577 // Use GenerateFromPassword to hash & salt pwd.
578 // MinCost is just an integer constant provided by the bcrypt
579 // package along with DefaultCost & MaxCost.
580 // The cost can be any value you want provided it isn't lower
581 // than the MinCost (4)
582 hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
586 // GenerateFromPassword returns a byte slice so we need to
587 // convert the bytes to a string and return it
591 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
592 // in the file transfer request payload, and the file transfer server will use it to map the request
594 func (s *Server) NewTransactionRef() []byte {
595 transactionRef := make([]byte, 4)
596 rand.Read(transactionRef)
598 return transactionRef
601 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
605 randID := make([]byte, 4)
607 data := binary.BigEndian.Uint32(randID[:])
609 s.PrivateChats[data] = &PrivateChat{
611 ClientConn: make(map[uint16]*ClientConn),
613 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
618 const dlFldrActionSendFile = 1
619 const dlFldrActionResumeFile = 2
620 const dlFldrActionNextFile = 3
622 func (s *Server) TransferFile(conn net.Conn) error {
623 defer func() { _ = conn.Close() }()
625 buf := make([]byte, 1024)
626 if _, err := conn.Read(buf); err != nil {
631 _, err := t.Write(buf[:16])
636 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
637 fileTransfer := s.FileTransfers[transferRefNum]
639 switch fileTransfer.Type {
641 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName))
643 ffo, err := NewFlattenedFileObject(
644 s.Config.FileRoot+string(fileTransfer.FilePath),
645 string(fileTransfer.FileName),
651 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String())
653 // Start by sending flat file object to client
654 if _, err := conn.Write(ffo.Payload()); err != nil {
658 file, err := os.Open(fullFilePath)
663 sendBuffer := make([]byte, 1048576)
666 if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
670 fileTransfer.BytesSent += bytesRead
672 delete(s.FileTransfers, transferRefNum)
674 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
679 if _, err := conn.Read(buf); err != nil {
683 ffo := ReadFlattenedFileObject(buf)
684 payloadLen := len(ffo.Payload())
685 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
687 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
689 "File upload started",
690 "transactionRef", fileTransfer.ReferenceNumber,
691 "RemoteAddr", conn.RemoteAddr().String(),
693 "dstFile", destinationFile,
696 newFile, err := os.Create(destinationFile)
701 defer func() { _ = newFile.Close() }()
703 const buffSize = 1024
705 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
708 receivedBytes := buffSize - payloadLen
711 if (fileSize - receivedBytes) < buffSize {
713 "File upload complete",
714 "transactionRef", fileTransfer.ReferenceNumber,
715 "RemoteAddr", conn.RemoteAddr().String(),
717 "dstFile", destinationFile,
720 if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil {
721 return fmt.Errorf("file transfer failed: %s", err)
726 // Copy N bytes from conn to upload file
727 n, err := io.CopyN(newFile, conn, buffSize)
731 receivedBytes += int(n)
734 // Folder Download flow:
735 // 1. Get filePath from the transfer
736 // 2. Iterate over files
738 // Send file header to client
739 // The client can reply in 3 ways:
741 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
742 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
744 // 2. If download of a file is to be resumed:
746 // []byte{0x00, 0x02} // download folder action
747 // [2]byte // Resume data size
748 // []byte file resume data (see myField_FileResumeData)
750 // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
752 // When download is requested (case 2 or 3), server replies with:
753 // [4]byte - file size
754 // []byte - Flattened File Object
756 // After every file download, client could request next file with:
757 // []byte{0x00, 0x03}
759 // This notifies the server to send the next item header
762 _ = fh.UnmarshalBinary(fileTransfer.FilePath)
763 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+fh.String(), string(fileTransfer.FileName))
765 basePathLen := len(fullFilePath)
767 readBuffer := make([]byte, 1024)
769 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr())
772 _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
774 subPath := path[basePathLen:]
775 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
777 fileHeader := NewFileHeader(subPath, info.IsDir())
783 // Send the file header to client
784 if _, err := conn.Write(fileHeader.Payload()); err != nil {
785 s.Logger.Errorf("error sending file header: %v", err)
789 // Read the client's Next Action request
790 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
791 if _, err := conn.Read(readBuffer); err != nil {
792 s.Logger.Errorf("error reading next action: %v", err)
796 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2]))
802 splitPath := strings.Split(path, "/")
803 //strings.Join(splitPath[:len(splitPath)-1], "/")
805 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), info.Name())
809 s.Logger.Infow("File download started",
810 "fileName", info.Name(),
811 "transactionRef", fileTransfer.ReferenceNumber,
812 "RemoteAddr", conn.RemoteAddr().String(),
813 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
816 // Send file size to client
817 if _, err := conn.Write(ffo.TransferSize()); err != nil {
822 // Send file bytes to client
823 if _, err := conn.Write(ffo.Payload()); err != nil {
828 file, err := os.Open(path)
833 sendBuffer := make([]byte, 1048576)
834 totalBytesSent := len(ffo.Payload())
837 bytesRead, err := file.Read(sendBuffer)
839 // Read the client's Next Action request
840 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
841 if _, err := conn.Read(readBuffer); err != nil {
842 s.Logger.Errorf("error reading next action: %v", err)
848 sentBytes, readErr := conn.Write(sendBuffer[:bytesRead])
849 totalBytesSent += sentBytes
858 dstPath := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
860 "Folder upload started",
861 "transactionRef", fileTransfer.ReferenceNumber,
862 "RemoteAddr", conn.RemoteAddr().String(),
864 "TransferSize", fileTransfer.TransferSize,
865 "FolderItemCount", fileTransfer.FolderItemCount,
868 // Check if the target folder exists. If not, create it.
869 if _, err := os.Stat(dstPath); os.IsNotExist(err) {
870 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
871 if err := os.Mkdir(dstPath, 0777); err != nil {
876 readBuffer := make([]byte, 1024)
878 // Begin the folder upload flow by sending the "next file action" to client
879 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
883 fileSize := make([]byte, 4)
884 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
886 for i := uint16(0); i < itemCount; i++ {
887 if _, err := conn.Read(readBuffer); err != nil {
890 fu := readFolderUpload(readBuffer)
893 "Folder upload continued",
894 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
895 "RemoteAddr", conn.RemoteAddr().String(),
896 "FormattedPath", fu.FormattedPath(),
897 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
898 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount),
901 if bytes.Equal(fu.IsFolder, []byte{0, 1}) {
902 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
903 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
904 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
909 // Tell client to send next file
910 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
915 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
916 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
917 // Send dlFldrAction_SendFile to client to begin transfer
918 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
922 if _, err := conn.Read(fileSize); err != nil {
923 fmt.Println("Error reading:", err.Error()) // TODO: handle
926 s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize)
928 if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil {
932 // Tell client to send next file
933 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
938 // Client sends "MACR" after the file. Read and discard.
939 // TODO: This doesn't seem to be documented. What is this? Maybe resource fork?
940 if _, err := conn.Read(readBuffer); err != nil {
945 s.Logger.Infof("Folder upload complete")
951 func transferFile(conn net.Conn, dst string) error {
952 const buffSize = 1024
953 buf := make([]byte, buffSize)
955 // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes
956 if _, err := conn.Read(buf); err != nil {
959 ffo := ReadFlattenedFileObject(buf)
960 payloadLen := len(ffo.Payload())
961 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
963 newFile, err := os.Create(dst)
967 defer func() { _ = newFile.Close() }()
968 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
971 receivedBytes := buffSize - payloadLen
974 if (fileSize - receivedBytes) < buffSize {
975 _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes))
979 // Copy N bytes from conn to upload file
980 n, err := io.CopyN(newFile, conn, buffSize)
984 receivedBytes += int(n)
990 // 00 02 // PathItemCount
994 // 73 75 62 66 6f 6c 64 65 72 // "subfolder"
998 // 73 75 62 66 6f 6c 64 65 72 2d 74 65 73 74 66 69 6c 65 2d 35 6b // "subfolder-testfile-5k"
999 func readFolderUpload(buf []byte) folderUpload {
1000 dataLen := binary.BigEndian.Uint16(buf[0:2])
1003 DataSize: buf[0:2], // Size of this structure (not including data size element itself)
1005 PathItemCount: buf[4:6],
1006 FileNamePath: buf[6 : dataLen+2],
1012 type folderUpload struct {
1015 PathItemCount []byte
1019 func (fu *folderUpload) FormattedPath() string {
1020 pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount)
1022 var pathSegments []string
1023 pathData := fu.FileNamePath
1025 for i := uint16(0); i < pathItemLen; i++ {
1026 segLen := pathData[2]
1027 pathSegments = append(pathSegments, string(pathData[3:3+segLen]))
1028 pathData = pathData[3+segLen:]
1031 return strings.Join(pathSegments, pathSeparator)
1034 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1035 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1036 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1037 for _, c := range unsortedClients {
1038 clients = append(clients, c)
1040 sort.Sort(byClientID(clients))