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
38 Accounts map[string]*Account
40 Clients map[uint16]*ClientConn
42 ThreadedNews *ThreadedNews
43 FileTransfers map[uint32]*FileTransfer
46 Logger *zap.SugaredLogger
47 PrivateChats map[uint32]*PrivateChat
52 APIListener net.Listener
53 FileListener net.Listener
56 newsWriter io.WriteCloser
58 outbox chan Transaction
61 flatNewsMux sync.Mutex
64 type PrivateChat struct {
66 ClientConn map[uint16]*ClientConn
69 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
70 s.Logger.Infow("Hotline server started", "version", VERSION)
74 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
77 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
84 func (s *Server) APIPort() int {
85 return s.APIListener.Addr().(*net.TCPAddr).Port
88 func (s *Server) ServeFileTransfers(ln net.Listener) error {
89 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
92 conn, err := ln.Accept()
98 if err := s.TransferFile(conn); err != nil {
99 s.Logger.Errorw("file transfer error", "reason", err)
105 func (s *Server) sendTransaction(t Transaction) error {
106 requestNum := binary.BigEndian.Uint16(t.Type)
107 clientID, err := byteToInt(*t.clientID)
113 client := s.Clients[uint16(clientID)]
116 return errors.New("invalid client")
118 userName := string(*client.UserName)
119 login := client.Account.Login
121 handler := TransactionHandlers[requestNum]
124 if n, err = client.Connection.Write(t.Payload()); 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"
171 messageBoardFile = "MessageBoard.txt"
172 threadedNewsFile = "ThreadedNews.yaml"
175 // NewServer constructs a new Server from a config dir
176 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
179 Accounts: make(map[string]*Account),
181 Clients: make(map[uint16]*ClientConn),
182 FileTransfers: make(map[uint32]*FileTransfer),
183 PrivateChats: make(map[uint32]*PrivateChat),
184 ConfigDir: configDir,
186 NextGuestID: new(uint16),
187 outbox: make(chan Transaction),
188 Stats: &Stats{StartTime: time.Now()},
189 ThreadedNews: &ThreadedNews{},
190 TrackerPassID: make([]byte, 4),
193 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
197 server.APIListener = ln
203 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
204 server.FileListener = ln2
209 // generate a new random passID for tracker registration
210 if _, err := rand.Read(server.TrackerPassID); err != nil {
214 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
215 if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
219 if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil {
223 if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil {
227 if err := server.loadConfig(configDir + "config.yaml"); err != nil {
231 if err := server.loadAccounts(configDir + "Users/"); err != nil {
235 server.Config.FileRoot = configDir + "Files/"
237 *server.NextGuestID = 1
239 if server.Config.EnableTrackerRegistration {
242 tr := TrackerRegistration{
243 Port: []byte{0x15, 0x7c},
244 UserCount: server.userCount(),
245 PassID: server.TrackerPassID,
246 Name: server.Config.Name,
247 Description: server.Config.Description,
249 for _, t := range server.Config.Trackers {
250 server.Logger.Infof("Registering with tracker %v", t)
252 if err := register(t, tr); err != nil {
253 server.Logger.Errorw("unable to register with tracker %v", "error", err)
257 time.Sleep(trackerUpdateFrequency * time.Second)
262 // Start Client Keepalive go routine
263 go server.keepaliveHandler()
268 func (s *Server) userCount() int {
272 return len(s.Clients)
275 func (s *Server) keepaliveHandler() {
277 time.Sleep(idleCheckInterval * time.Second)
280 for _, c := range s.Clients {
281 *c.IdleTime += idleCheckInterval
282 if *c.IdleTime > userIdleSeconds && !c.Idle {
285 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
286 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
287 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
290 tranNotifyChangeUser,
291 NewField(fieldUserID, *c.ID),
292 NewField(fieldUserFlags, *c.Flags),
293 NewField(fieldUserName, *c.UserName),
294 NewField(fieldUserIconID, *c.Icon),
302 func (s *Server) writeThreadedNews() error {
306 out, err := yaml.Marshal(s.ThreadedNews)
310 err = ioutil.WriteFile(
311 s.ConfigDir+"ThreadedNews.yaml",
318 func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
322 clientConn := &ClientConn{
325 Flags: &[]byte{0, 0},
331 AutoReply: &[]byte{},
332 Transfers: make(map[int][]*FileTransfer),
337 *clientConn.IdleTime = 0
339 binary.BigEndian.PutUint16(*clientConn.ID, ID)
340 s.Clients[ID] = clientConn
345 // NewUser creates a new user account entry in the server map and config file
346 func (s *Server) NewUser(login, name, password string, access []byte) error {
353 Password: hashAndSalt([]byte(password)),
356 out, err := yaml.Marshal(&account)
360 s.Accounts[login] = &account
362 return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
365 // DeleteUser deletes the user account
366 func (s *Server) DeleteUser(login string) error {
370 delete(s.Accounts, login)
372 return os.Remove(s.ConfigDir + "Users/" + login + ".yaml")
375 func (s *Server) connectedUsers() []Field {
379 var connectedUsers []Field
380 for _, c := range s.Clients {
385 Name: string(*c.UserName),
387 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
389 return connectedUsers
392 // loadThreadedNews loads the threaded news data from disk
393 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
394 fh, err := os.Open(threadedNewsPath)
398 decoder := yaml.NewDecoder(fh)
399 decoder.SetStrict(true)
401 return decoder.Decode(s.ThreadedNews)
404 // loadAccounts loads account data from disk
405 func (s *Server) loadAccounts(userDir string) error {
406 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
411 if len(matches) == 0 {
412 return errors.New("no user accounts found in " + userDir)
415 for _, file := range matches {
416 fh, err := os.Open(file)
422 decoder := yaml.NewDecoder(fh)
423 decoder.SetStrict(true)
424 if err := decoder.Decode(&account); err != nil {
428 s.Accounts[account.Login] = &account
433 func (s *Server) loadConfig(path string) error {
434 fh, err := os.Open(path)
439 decoder := yaml.NewDecoder(fh)
440 decoder.SetStrict(true)
441 err = decoder.Decode(s.Config)
449 minTransactionLen = 22 // minimum length of any transaction
452 // handleNewConnection takes a new net.Conn and performs the initial login sequence
453 func (s *Server) handleNewConnection(conn net.Conn) error {
454 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
455 if _, err := conn.Read(handshakeBuf); err != nil {
458 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
462 buf := make([]byte, 1024)
463 readLen, err := conn.Read(buf)
464 if readLen < minTransactionLen {
471 clientLogin, _, err := ReadTransaction(buf[:readLen])
476 c := s.NewClientConn(conn)
479 if r := recover(); r != nil {
480 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
481 c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
486 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
487 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
488 *c.Version = clientLogin.GetField(fieldVersion).Data
491 for _, char := range encodedLogin {
492 login += string(rune(255 - uint(char)))
498 // If authentication fails, send error reply and close connection
499 if !c.Authenticate(login, encodedPassword) {
500 rep := c.NewErrReply(clientLogin, "Incorrect login.")
501 if _, err := conn.Write(rep.Payload()); err != nil {
504 return fmt.Errorf("incorrect login")
507 // Hotline 1.2.3 client does not send fieldVersion
508 // Nostalgia client sends ""
509 //if string(*c.Version) == "" {
510 // *c.UserName = clientLogin.GetField(fieldUserName).Data
511 // *c.Icon = clientLogin.GetField(fieldUserIconID).Data
514 if clientLogin.GetField(fieldUserName).Data != nil {
515 *c.UserName = clientLogin.GetField(fieldUserName).Data
518 if clientLogin.GetField(fieldUserIconID).Data != nil {
519 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
522 c.Account = c.Server.Accounts[login]
524 if c.Authorize(accessDisconUser) {
525 *c.Flags = []byte{0, 2}
528 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
530 s.outbox <- c.NewReply(clientLogin,
531 NewField(fieldVersion, []byte{0x00, 0xbe}),
532 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
533 NewField(fieldServerName, []byte(s.Config.Name)),
536 // Send user access privs so client UI knows how to behave
537 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
539 // Show agreement to client
540 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
542 // The Hotline ClientConn v1.2.3 has a different login sequence than 1.9.2
543 if string(*c.Version) == "" {
544 if _, err := c.notifyNewUserHasJoined(); err != nil {
549 if _, err := c.notifyNewUserHasJoined(); err != nil {
552 c.Server.Stats.LoginCount += 1
554 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
555 const maxTranSize = 1024000
556 tranBuff := make([]byte, 0)
558 // Infinite loop where take action on incoming client requests until the connection is closed
560 buf = make([]byte, readBuffSize)
561 tranBuff = tranBuff[tReadlen:]
563 readLen, err := c.Connection.Read(buf)
567 tranBuff = append(tranBuff, buf[:readLen]...)
569 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
570 // into a slice of transactions
571 var transactions []Transaction
572 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
573 c.Server.Logger.Errorw("Error handling transaction", "err", err)
576 // iterate over all of the transactions that were parsed from the byte slice and handle them
577 for _, t := range transactions {
578 if err := c.handleTransaction(&t); err != nil {
579 c.Server.Logger.Errorw("Error handling transaction", "err", err)
585 func hashAndSalt(pwd []byte) string {
586 // Use GenerateFromPassword to hash & salt pwd.
587 // MinCost is just an integer constant provided by the bcrypt
588 // package along with DefaultCost & MaxCost.
589 // The cost can be any value you want provided it isn't lower
590 // than the MinCost (4)
591 hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
595 // GenerateFromPassword returns a byte slice so we need to
596 // convert the bytes to a string and return it
600 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
601 // in the file transfer request payload, and the file transfer server will use it to map the request
603 func (s *Server) NewTransactionRef() []byte {
604 transactionRef := make([]byte, 4)
605 rand.Read(transactionRef)
607 return transactionRef
610 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
614 randID := make([]byte, 4)
616 data := binary.BigEndian.Uint32(randID[:])
618 s.PrivateChats[data] = &PrivateChat{
620 ClientConn: make(map[uint16]*ClientConn),
622 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
627 const dlFldrActionSendFile = 1
628 const dlFldrActionResumeFile = 2
629 const dlFldrActionNextFile = 3
631 func (s *Server) TransferFile(conn net.Conn) error {
632 defer func() { _ = conn.Close() }()
634 buf := make([]byte, 1024)
635 if _, err := conn.Read(buf); err != nil {
639 t, err := NewReadTransfer(buf)
644 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
645 fileTransfer := s.FileTransfers[transferRefNum]
647 switch fileTransfer.Type {
649 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName))
651 ffo, err := NewFlattenedFileObject(
652 s.Config.FileRoot+string(fileTransfer.FilePath),
653 string(fileTransfer.FileName),
659 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String())
661 // Start by sending flat file object to client
662 if _, err := conn.Write(ffo.Payload()); err != nil {
666 file, err := os.Open(fullFilePath)
671 sendBuffer := make([]byte, 1048576)
674 if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
678 fileTransfer.BytesSent += bytesRead
680 delete(s.FileTransfers, transferRefNum)
682 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
687 if _, err := conn.Read(buf); err != nil {
691 ffo := ReadFlattenedFileObject(buf)
692 payloadLen := len(ffo.Payload())
693 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
695 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
697 "File upload started",
698 "transactionRef", fileTransfer.ReferenceNumber,
699 "RemoteAddr", conn.RemoteAddr().String(),
701 "dstFile", destinationFile,
704 newFile, err := os.Create(destinationFile)
709 defer func() { _ = newFile.Close() }()
711 const buffSize = 1024
713 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
716 receivedBytes := buffSize - payloadLen
719 if (fileSize - receivedBytes) < buffSize {
721 "File upload complete",
722 "transactionRef", fileTransfer.ReferenceNumber,
723 "RemoteAddr", conn.RemoteAddr().String(),
725 "dstFile", destinationFile,
728 if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil {
729 return fmt.Errorf("file transfer failed: %s", err)
734 // Copy N bytes from conn to upload file
735 n, err := io.CopyN(newFile, conn, buffSize)
739 receivedBytes += int(n)
742 // Folder Download flow:
743 // 1. Get filePath from the Transfer
744 // 2. Iterate over files
746 // Send file header to client
747 // The client can reply in 3 ways:
749 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
750 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
752 // 2. If download of a file is to be resumed:
754 // []byte{0x00, 0x02} // download folder action
755 // [2]byte // Resume data size
756 // []byte file resume data (see myField_FileResumeData)
758 // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
760 // When download is requested (case 2 or 3), server replies with:
761 // [4]byte - file size
762 // []byte - Flattened File Object
764 // After every file download, client could request next file with:
765 // []byte{0x00, 0x03}
767 // This notifies the server to send the next item header
769 fh := NewFilePath(fileTransfer.FilePath)
770 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+fh.String(), string(fileTransfer.FileName))
772 basePathLen := len(fullFilePath)
774 readBuffer := make([]byte, 1024)
776 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr())
779 _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
781 subPath := path[basePathLen-2:]
782 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
784 fileHeader := NewFileHeader(subPath, info.IsDir())
790 // Send the file header to client
791 if _, err := conn.Write(fileHeader.Payload()); err != nil {
792 s.Logger.Errorf("error sending file header: %v", err)
796 // Read the client's Next Action request
797 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
798 if _, err := conn.Read(readBuffer); err != nil {
799 s.Logger.Errorf("error reading next action: %v", err)
803 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2]))
809 splitPath := strings.Split(path, "/")
810 //strings.Join(splitPath[:len(splitPath)-1], "/")
812 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), info.Name())
816 s.Logger.Infow("File download started",
817 "fileName", info.Name(),
818 "transactionRef", fileTransfer.ReferenceNumber,
819 "RemoteAddr", conn.RemoteAddr().String(),
820 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
823 // Send file size to client
824 if _, err := conn.Write(ffo.TransferSize()); err != nil {
829 // Send file bytes to client
830 if _, err := conn.Write(ffo.Payload()); err != nil {
835 file, err := os.Open(path)
840 sendBuffer := make([]byte, 1048576)
841 totalBytesSent := len(ffo.Payload())
844 bytesRead, err := file.Read(sendBuffer)
846 // Read the client's Next Action request
847 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
848 if _, err := conn.Read(readBuffer); err != nil {
849 s.Logger.Errorf("error reading next action: %v", err)
855 sentBytes, readErr := conn.Write(sendBuffer[:bytesRead])
856 totalBytesSent += sentBytes
865 dstPath := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
867 "Folder upload started",
868 "transactionRef", fileTransfer.ReferenceNumber,
869 "RemoteAddr", conn.RemoteAddr().String(),
871 "TransferSize", fileTransfer.TransferSize,
872 "FolderItemCount", fileTransfer.FolderItemCount,
875 // Check if the target folder exists. If not, create it.
876 if _, err := os.Stat(dstPath); os.IsNotExist(err) {
877 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
878 if err := os.Mkdir(dstPath, 0777); err != nil {
883 readBuffer := make([]byte, 1024)
885 // Begin the folder upload flow by sending the "next file action" to client
886 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
890 fileSize := make([]byte, 4)
891 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
893 for i := uint16(0); i < itemCount; i++ {
894 if _, err := conn.Read(readBuffer); err != nil {
897 fu := readFolderUpload(readBuffer)
900 "Folder upload continued",
901 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
902 "RemoteAddr", conn.RemoteAddr().String(),
903 "FormattedPath", fu.FormattedPath(),
904 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
905 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount),
908 if bytes.Equal(fu.IsFolder, []byte{0, 1}) {
909 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
910 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
911 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
916 // Tell client to send next file
917 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
922 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
923 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
924 // Send dlFldrAction_SendFile to client to begin transfer
925 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
929 if _, err := conn.Read(fileSize); err != nil {
930 fmt.Println("Error reading:", err.Error()) // TODO: handle
933 s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize)
935 if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil {
939 // Tell client to send next file
940 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
945 // Client sends "MACR" after the file. Read and discard.
946 // TODO: This doesn't seem to be documented. What is this? Maybe resource fork?
947 if _, err := conn.Read(readBuffer); err != nil {
952 s.Logger.Infof("Folder upload complete")
958 func transferFile(conn net.Conn, dst string) error {
959 const buffSize = 1024
960 buf := make([]byte, buffSize)
962 // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes
963 if _, err := conn.Read(buf); err != nil {
966 ffo := ReadFlattenedFileObject(buf)
967 payloadLen := len(ffo.Payload())
968 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
970 newFile, err := os.Create(dst)
974 defer func() { _ = newFile.Close() }()
975 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
978 receivedBytes := buffSize - payloadLen
981 if (fileSize - receivedBytes) < buffSize {
982 _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes))
986 // Copy N bytes from conn to upload file
987 n, err := io.CopyN(newFile, conn, buffSize)
991 receivedBytes += int(n)
997 // 00 02 // PathItemCount
1001 // 73 75 62 66 6f 6c 64 65 72 // "subfolder"
1005 // 73 75 62 66 6f 6c 64 65 72 2d 74 65 73 74 66 69 6c 65 2d 35 6b // "subfolder-testfile-5k"
1006 func readFolderUpload(buf []byte) folderUpload {
1007 dataLen := binary.BigEndian.Uint16(buf[0:2])
1010 DataSize: buf[0:2], // Size of this structure (not including data size element itself)
1012 PathItemCount: buf[4:6],
1013 FileNamePath: buf[6 : dataLen+2],
1019 type folderUpload struct {
1022 PathItemCount []byte
1026 func (fu *folderUpload) FormattedPath() string {
1027 pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount)
1029 var pathSegments []string
1030 pathData := fu.FileNamePath
1032 for i := uint16(0); i < pathItemLen; i++ {
1033 segLen := pathData[2]
1034 pathSegments = append(pathSegments, string(pathData[3:3+segLen]))
1035 pathData = pathData[3+segLen:]
1038 return strings.Join(pathSegments, pathSeparator)
1041 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1042 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1043 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1044 for _, c := range unsortedClients {
1045 clients = append(clients, c)
1047 sort.Sort(byClientID(clients))