28 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
29 idleCheckInterval = 10 // time in seconds to check for idle users
30 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
35 Accounts map[string]*Account
37 Clients map[uint16]*ClientConn
39 ThreadedNews *ThreadedNews
40 FileTransfers map[uint32]*FileTransfer
43 Logger *zap.SugaredLogger
44 PrivateChats map[uint32]*PrivateChat
49 APIListener net.Listener
50 FileListener net.Listener
52 // newsReader io.Reader
53 // newsWriter io.WriteCloser
55 outbox chan Transaction
58 flatNewsMux sync.Mutex
61 type PrivateChat struct {
63 ClientConn map[uint16]*ClientConn
66 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
67 s.Logger.Infow("Hotline server started", "version", VERSION)
71 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
74 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
81 func (s *Server) APIPort() int {
82 return s.APIListener.Addr().(*net.TCPAddr).Port
85 func (s *Server) ServeFileTransfers(ln net.Listener) error {
86 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
89 conn, err := ln.Accept()
95 if err := s.handleFileTransfer(conn); err != nil {
96 s.Logger.Errorw("file transfer error", "reason", err)
102 func (s *Server) sendTransaction(t Transaction) error {
103 requestNum := binary.BigEndian.Uint16(t.Type)
104 clientID, err := byteToInt(*t.clientID)
110 client := s.Clients[uint16(clientID)]
113 return fmt.Errorf("invalid client id %v", *t.clientID)
115 userName := string(client.UserName)
116 login := client.Account.Login
118 handler := TransactionHandlers[requestNum]
120 b, err := t.MarshalBinary()
125 if n, err = client.Connection.Write(b); err != nil {
128 s.Logger.Debugw("Sent Transaction",
131 "IsReply", t.IsReply,
132 "type", handler.Name,
134 "remoteAddr", client.Connection.RemoteAddr(),
139 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
140 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
143 conn, err := ln.Accept()
145 s.Logger.Errorw("error accepting connection", "err", err)
152 if err := s.sendTransaction(t); err != nil {
153 s.Logger.Errorw("error sending transaction", "err", err)
159 if err := s.handleNewConnection(conn); err != nil {
161 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
163 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
171 agreementFile = "Agreement.txt"
174 // NewServer constructs a new Server from a config dir
175 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
178 Accounts: make(map[string]*Account),
180 Clients: make(map[uint16]*ClientConn),
181 FileTransfers: make(map[uint32]*FileTransfer),
182 PrivateChats: make(map[uint32]*PrivateChat),
183 ConfigDir: configDir,
185 NextGuestID: new(uint16),
186 outbox: make(chan Transaction),
187 Stats: &Stats{StartTime: time.Now()},
188 ThreadedNews: &ThreadedNews{},
189 TrackerPassID: make([]byte, 4),
192 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
196 server.APIListener = ln
202 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
203 server.FileListener = ln2
208 // generate a new random passID for tracker registration
209 if _, err := rand.Read(server.TrackerPassID); err != nil {
213 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
214 if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
218 if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil {
222 if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil {
226 if err := server.loadConfig(configDir + "config.yaml"); err != nil {
230 if err := server.loadAccounts(configDir + "Users/"); err != nil {
234 server.Config.FileRoot = configDir + "Files/"
236 *server.NextGuestID = 1
238 if server.Config.EnableTrackerRegistration {
241 tr := TrackerRegistration{
242 Port: []byte{0x15, 0x7c},
243 UserCount: server.userCount(),
244 PassID: server.TrackerPassID,
245 Name: server.Config.Name,
246 Description: server.Config.Description,
248 for _, t := range server.Config.Trackers {
249 server.Logger.Infof("Registering with tracker %v", t)
251 if err := register(t, tr); err != nil {
252 server.Logger.Errorw("unable to register with tracker %v", "error", err)
256 time.Sleep(trackerUpdateFrequency * time.Second)
261 // Start Client Keepalive go routine
262 go server.keepaliveHandler()
267 func (s *Server) userCount() int {
271 return len(s.Clients)
274 func (s *Server) keepaliveHandler() {
276 time.Sleep(idleCheckInterval * time.Second)
279 for _, c := range s.Clients {
280 c.IdleTime += idleCheckInterval
281 if c.IdleTime > userIdleSeconds && !c.Idle {
284 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
285 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
286 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
289 tranNotifyChangeUser,
290 NewField(fieldUserID, *c.ID),
291 NewField(fieldUserFlags, *c.Flags),
292 NewField(fieldUserName, c.UserName),
293 NewField(fieldUserIconID, *c.Icon),
301 func (s *Server) writeThreadedNews() error {
305 out, err := yaml.Marshal(s.ThreadedNews)
309 err = ioutil.WriteFile(
310 s.ConfigDir+"ThreadedNews.yaml",
317 func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
321 clientConn := &ClientConn{
324 Flags: &[]byte{0, 0},
330 Transfers: make(map[int][]*FileTransfer),
336 binary.BigEndian.PutUint16(*clientConn.ID, ID)
337 s.Clients[ID] = clientConn
342 // NewUser creates a new user account entry in the server map and config file
343 func (s *Server) NewUser(login, name, password string, access []byte) error {
350 Password: hashAndSalt([]byte(password)),
353 out, err := yaml.Marshal(&account)
357 s.Accounts[login] = &account
359 return FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
362 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
366 fmt.Printf("login: %v, newLogin: %v: ", login, newLogin)
368 // update renames the user login
369 if login != newLogin {
370 err := os.Rename(s.ConfigDir+"Users/"+login+".yaml", s.ConfigDir+"Users/"+newLogin+".yaml")
374 s.Accounts[newLogin] = s.Accounts[login]
375 delete(s.Accounts, login)
378 account := s.Accounts[newLogin]
379 account.Access = &access
381 account.Password = password
383 out, err := yaml.Marshal(&account)
387 if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil {
394 // DeleteUser deletes the user account
395 func (s *Server) DeleteUser(login string) error {
399 delete(s.Accounts, login)
401 return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
404 func (s *Server) connectedUsers() []Field {
408 var connectedUsers []Field
409 for _, c := range sortedClients(s.Clients) {
417 Name: string(c.UserName),
419 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
421 return connectedUsers
424 // loadThreadedNews loads the threaded news data from disk
425 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
426 fh, err := os.Open(threadedNewsPath)
430 decoder := yaml.NewDecoder(fh)
432 return decoder.Decode(s.ThreadedNews)
435 // loadAccounts loads account data from disk
436 func (s *Server) loadAccounts(userDir string) error {
437 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
442 if len(matches) == 0 {
443 return errors.New("no user accounts found in " + userDir)
446 for _, file := range matches {
447 fh, err := FS.Open(file)
453 decoder := yaml.NewDecoder(fh)
454 if err := decoder.Decode(&account); err != nil {
458 s.Accounts[account.Login] = &account
463 func (s *Server) loadConfig(path string) error {
464 fh, err := FS.Open(path)
469 decoder := yaml.NewDecoder(fh)
470 err = decoder.Decode(s.Config)
478 minTransactionLen = 22 // minimum length of any transaction
481 // dontPanic recovers and logs panics instead of crashing
482 // TODO: remove this after known issues are fixed
483 func dontPanic(logger *zap.SugaredLogger) {
484 if r := recover(); r != nil {
485 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
486 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
490 // handleNewConnection takes a new net.Conn and performs the initial login sequence
491 func (s *Server) handleNewConnection(conn net.Conn) error {
492 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
493 if _, err := conn.Read(handshakeBuf); err != nil {
496 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
500 buf := make([]byte, 1024)
501 readLen, err := conn.Read(buf)
502 if readLen < minTransactionLen {
509 clientLogin, _, err := ReadTransaction(buf[:readLen])
514 c := s.NewClientConn(conn)
517 defer dontPanic(s.Logger)
519 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
520 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
521 *c.Version = clientLogin.GetField(fieldVersion).Data
524 for _, char := range encodedLogin {
525 login += string(rune(255 - uint(char)))
531 // If authentication fails, send error reply and close connection
532 if !c.Authenticate(login, encodedPassword) {
533 t := c.NewErrReply(clientLogin, "Incorrect login.")
534 b, err := t.MarshalBinary()
538 if _, err := conn.Write(b); err != nil {
541 return fmt.Errorf("incorrect login")
544 if clientLogin.GetField(fieldUserName).Data != nil {
545 c.UserName = clientLogin.GetField(fieldUserName).Data
548 if clientLogin.GetField(fieldUserIconID).Data != nil {
549 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
552 c.Account = c.Server.Accounts[login]
554 if c.Authorize(accessDisconUser) {
555 *c.Flags = []byte{0, 2}
558 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
560 s.outbox <- c.NewReply(clientLogin,
561 NewField(fieldVersion, []byte{0x00, 0xbe}),
562 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
563 NewField(fieldServerName, []byte(s.Config.Name)),
566 // Send user access privs so client UI knows how to behave
567 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
569 // Show agreement to client
570 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
572 // assume simplified hotline v1.2.3 login flow that does not require agreement
573 if *c.Version == nil {
578 tranNotifyChangeUser, nil,
579 NewField(fieldUserName, c.UserName),
580 NewField(fieldUserID, *c.ID),
581 NewField(fieldUserIconID, *c.Icon),
582 NewField(fieldUserFlags, *c.Flags),
587 c.Server.Stats.LoginCount += 1
589 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
590 tranBuff := make([]byte, 0)
592 // Infinite loop where take action on incoming client requests until the connection is closed
594 buf = make([]byte, readBuffSize)
595 tranBuff = tranBuff[tReadlen:]
597 readLen, err := c.Connection.Read(buf)
601 tranBuff = append(tranBuff, buf[:readLen]...)
603 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
604 // into a slice of transactions
605 var transactions []Transaction
606 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
607 c.Server.Logger.Errorw("Error handling transaction", "err", err)
610 // iterate over all of the transactions that were parsed from the byte slice and handle them
611 for _, t := range transactions {
612 if err := c.handleTransaction(&t); err != nil {
613 c.Server.Logger.Errorw("Error handling transaction", "err", err)
619 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
620 // in the file transfer request payload, and the file transfer server will use it to map the request
622 func (s *Server) NewTransactionRef() []byte {
623 transactionRef := make([]byte, 4)
624 rand.Read(transactionRef)
626 return transactionRef
629 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
633 randID := make([]byte, 4)
635 data := binary.BigEndian.Uint32(randID[:])
637 s.PrivateChats[data] = &PrivateChat{
639 ClientConn: make(map[uint16]*ClientConn),
641 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
646 const dlFldrActionSendFile = 1
647 const dlFldrActionResumeFile = 2
648 const dlFldrActionNextFile = 3
650 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
651 func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
654 if err := conn.Close(); err != nil {
655 s.Logger.Errorw("error closing connection", "error", err)
659 defer dontPanic(s.Logger)
661 txBuf := make([]byte, 16)
662 if _, err := io.ReadFull(conn, txBuf); err != nil {
667 if _, err := t.Write(txBuf); err != nil {
671 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
674 delete(s.FileTransfers, transferRefNum)
679 fileTransfer, ok := s.FileTransfers[transferRefNum]
682 return errors.New("invalid transaction ID")
685 switch fileTransfer.Type {
687 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
693 if fileTransfer.fileResumeData != nil {
694 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
697 ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset)
702 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
704 if fileTransfer.options == nil {
705 // Start by sending flat file object to client
706 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
711 file, err := FS.Open(fullFilePath)
716 sendBuffer := make([]byte, 1048576)
720 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
721 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
729 totalSent += int64(bytesRead)
731 fileTransfer.BytesSent += bytesRead
733 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
738 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
739 tmpFile := destinationFile + ".incomplete"
741 file, err := effectiveFile(destinationFile)
742 if errors.Is(err, fs.ErrNotExist) {
743 file, err = FS.Create(tmpFile)
749 defer func() { _ = file.Close() }()
751 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
753 // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data
754 if err := receiveFile(conn, file, io.Discard); err != nil {
758 if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil {
762 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
764 // Folder Download flow:
765 // 1. Get filePath from the transfer
766 // 2. Iterate over files
768 // Send file header to client
769 // The client can reply in 3 ways:
771 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
772 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
774 // 2. If download of a file is to be resumed:
776 // []byte{0x00, 0x02} // download folder action
777 // [2]byte // Resume data size
778 // []byte file resume data (see myField_FileResumeData)
780 // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01}
782 // When download is requested (case 2 or 3), server replies with:
783 // [4]byte - file size
784 // []byte - Flattened File Object
786 // After every file download, client could request next file with:
787 // []byte{0x00, 0x03}
789 // This notifies the server to send the next item header
791 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
796 basePathLen := len(fullFilePath)
798 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
800 nextAction := make([]byte, 2)
801 if _, err := conn.Read(nextAction); err != nil {
806 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
811 subPath := path[basePathLen+1:]
812 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
818 fileHeader := NewFileHeader(subPath, info.IsDir())
820 // Send the file header to client
821 if _, err := conn.Write(fileHeader.Payload()); err != nil {
822 s.Logger.Errorf("error sending file header: %v", err)
826 // Read the client's Next Action request
827 if _, err := conn.Read(nextAction); err != nil {
831 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
835 switch nextAction[1] {
836 case dlFldrActionResumeFile:
837 // client asked to resume this file
838 var frd FileResumeData
839 // get size of resumeData
840 if _, err := conn.Read(nextAction); err != nil {
844 resumeDataLen := binary.BigEndian.Uint16(nextAction)
845 resumeDataBytes := make([]byte, resumeDataLen)
846 if _, err := conn.Read(resumeDataBytes); err != nil {
850 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
853 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
854 case dlFldrActionNextFile:
855 // client asked to skip this file
863 splitPath := strings.Split(path, "/")
865 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset)
869 s.Logger.Infow("File download started",
870 "fileName", info.Name(),
871 "transactionRef", fileTransfer.ReferenceNumber,
872 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
875 // Send file size to client
876 if _, err := conn.Write(ffo.TransferSize()); err != nil {
881 // Send ffo bytes to client
882 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
887 file, err := FS.Open(path)
892 // // Copy N bytes from file to connection
893 // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
898 sendBuffer := make([]byte, 1048576)
902 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
903 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
911 totalSent += int64(bytesRead)
913 fileTransfer.BytesSent += bytesRead
915 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
920 // TODO: optionally send resource fork header and resource fork data
922 // Read the client's Next Action request. This is always 3, I think?
923 if _, err := conn.Read(nextAction); err != nil {
931 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
936 "Folder upload started",
937 "transactionRef", fileTransfer.ReferenceNumber,
939 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
940 "FolderItemCount", fileTransfer.FolderItemCount,
943 // Check if the target folder exists. If not, create it.
944 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
945 if err := FS.Mkdir(dstPath, 0777); err != nil {
950 // Begin the folder upload flow by sending the "next file action" to client
951 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
955 fileSize := make([]byte, 4)
956 readBuffer := make([]byte, 1024)
958 for i := 0; i < fileTransfer.ItemCount(); i++ {
960 _, err := conn.Read(readBuffer)
964 fu := readFolderUpload(readBuffer)
967 "Folder upload continued",
968 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
969 "FormattedPath", fu.FormattedPath(),
970 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
971 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
974 if fu.IsFolder == [2]byte{0, 1} {
975 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
976 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
981 // Tell client to send next file
982 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
986 nextAction := dlFldrActionSendFile
988 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
989 _, err := os.Stat(dstPath + "/" + fu.FormattedPath())
990 if err != nil && !errors.Is(err, fs.ErrNotExist) {
994 nextAction = dlFldrActionNextFile
997 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
998 inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
999 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1003 nextAction = dlFldrActionResumeFile
1006 fmt.Printf("Next Action: %v\n", nextAction)
1008 if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil {
1013 case dlFldrActionNextFile:
1015 case dlFldrActionResumeFile:
1016 offset := make([]byte, 4)
1017 binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size()))
1019 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1024 fileResumeData := NewFileResumeData([]ForkInfoList{
1025 *NewForkInfoList(offset),
1028 b, _ := fileResumeData.BinaryMarshal()
1030 bs := make([]byte, 2)
1031 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1033 if _, err := conn.Write(append(bs, b...)); err != nil {
1037 if _, err := conn.Read(fileSize); err != nil {
1041 if err := receiveFile(conn, file, ioutil.Discard); err != nil {
1045 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1050 case dlFldrActionSendFile:
1051 if _, err := conn.Read(fileSize); err != nil {
1055 filePath := dstPath + "/" + fu.FormattedPath()
1056 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize))
1058 newFile, err := FS.Create(filePath + ".incomplete")
1063 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
1067 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1072 // Tell client to send next file
1073 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1078 s.Logger.Infof("Folder upload complete")
1084 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1085 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1086 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1087 for _, c := range unsortedClients {
1088 clients = append(clients, c)
1090 sort.Sort(byClientID(clients))