9 "github.com/go-playground/validator/v10"
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
35 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
39 Accounts map[string]*Account
41 Clients map[uint16]*ClientConn
43 ThreadedNews *ThreadedNews
44 FileTransfers map[uint32]*FileTransfer
47 Logger *zap.SugaredLogger
48 PrivateChats map[uint32]*PrivateChat
55 // newsReader io.Reader
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",
72 "API port", fmt.Sprintf(":%v", s.Port),
73 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
80 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
85 s.Logger.Fatal(s.Serve(ctx, cancelRoot, ln))
90 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
96 s.Logger.Fatal(s.ServeFileTransfers(ln))
104 func (s *Server) ServeFileTransfers(ln net.Listener) error {
106 conn, err := ln.Accept()
112 if err := s.handleFileTransfer(conn); err != nil {
113 s.Logger.Errorw("file transfer error", "reason", err)
119 func (s *Server) sendTransaction(t Transaction) error {
120 requestNum := binary.BigEndian.Uint16(t.Type)
121 clientID, err := byteToInt(*t.clientID)
127 client := s.Clients[uint16(clientID)]
130 return fmt.Errorf("invalid client id %v", *t.clientID)
132 userName := string(client.UserName)
133 login := client.Account.Login
135 handler := TransactionHandlers[requestNum]
137 b, err := t.MarshalBinary()
142 if n, err = client.Connection.Write(b); err != nil {
145 s.Logger.Debugw("Sent Transaction",
148 "IsReply", t.IsReply,
149 "type", handler.Name,
151 "remoteAddr", client.RemoteAddr,
156 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
159 conn, err := ln.Accept()
161 s.Logger.Errorw("error accepting connection", "err", err)
168 if err := s.sendTransaction(t); err != nil {
169 s.Logger.Errorw("error sending transaction", "err", err)
175 if err := s.handleNewConnection(conn, conn.RemoteAddr().String()); err != nil {
177 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
179 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
187 agreementFile = "Agreement.txt"
190 // NewServer constructs a new Server from a config dir
191 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
194 Accounts: make(map[string]*Account),
196 Clients: make(map[uint16]*ClientConn),
197 FileTransfers: make(map[uint32]*FileTransfer),
198 PrivateChats: make(map[uint32]*PrivateChat),
199 ConfigDir: configDir,
201 NextGuestID: new(uint16),
202 outbox: make(chan Transaction),
203 Stats: &Stats{StartTime: time.Now()},
204 ThreadedNews: &ThreadedNews{},
210 // generate a new random passID for tracker registration
211 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
215 server.Agreement, err = os.ReadFile(configDir + agreementFile)
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 {
242 "Tracker registration enabled",
243 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
244 "trackers", server.Config.Trackers,
249 tr := &TrackerRegistration{
250 UserCount: server.userCount(),
251 PassID: server.TrackerPassID[:],
252 Name: server.Config.Name,
253 Description: server.Config.Description,
255 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
256 for _, t := range server.Config.Trackers {
257 if err := register(t, tr); err != nil {
258 server.Logger.Errorw("unable to register with tracker %v", "error", err)
260 server.Logger.Infow("Sent Tracker registration", "data", tr)
263 time.Sleep(trackerUpdateFrequency * time.Second)
268 // Start Client Keepalive go routine
269 go server.keepaliveHandler()
274 func (s *Server) userCount() int {
278 return len(s.Clients)
281 func (s *Server) keepaliveHandler() {
283 time.Sleep(idleCheckInterval * time.Second)
286 for _, c := range s.Clients {
287 c.IdleTime += idleCheckInterval
288 if c.IdleTime > userIdleSeconds && !c.Idle {
291 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
292 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
293 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
296 tranNotifyChangeUser,
297 NewField(fieldUserID, *c.ID),
298 NewField(fieldUserFlags, *c.Flags),
299 NewField(fieldUserName, c.UserName),
300 NewField(fieldUserIconID, *c.Icon),
308 func (s *Server) writeThreadedNews() error {
312 out, err := yaml.Marshal(s.ThreadedNews)
316 err = ioutil.WriteFile(
317 s.ConfigDir+"ThreadedNews.yaml",
324 func (s *Server) NewClientConn(conn net.Conn, remoteAddr string) *ClientConn {
328 clientConn := &ClientConn{
331 Flags: &[]byte{0, 0},
337 Transfers: make(map[int][]*FileTransfer),
339 RemoteAddr: remoteAddr,
344 binary.BigEndian.PutUint16(*clientConn.ID, ID)
345 s.Clients[ID] = clientConn
350 // NewUser creates a new user account entry in the server map and config file
351 func (s *Server) NewUser(login, name, password string, access []byte) error {
358 Password: hashAndSalt([]byte(password)),
361 out, err := yaml.Marshal(&account)
365 s.Accounts[login] = &account
367 return s.FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
370 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
374 // update renames the user login
375 if login != newLogin {
376 err := os.Rename(s.ConfigDir+"Users/"+login+".yaml", s.ConfigDir+"Users/"+newLogin+".yaml")
380 s.Accounts[newLogin] = s.Accounts[login]
381 delete(s.Accounts, login)
384 account := s.Accounts[newLogin]
385 account.Access = &access
387 account.Password = password
389 out, err := yaml.Marshal(&account)
393 if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil {
400 // DeleteUser deletes the user account
401 func (s *Server) DeleteUser(login string) error {
405 delete(s.Accounts, login)
407 return s.FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
410 func (s *Server) connectedUsers() []Field {
414 var connectedUsers []Field
415 for _, c := range sortedClients(s.Clients) {
423 Name: string(c.UserName),
425 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
427 return connectedUsers
430 // loadThreadedNews loads the threaded news data from disk
431 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
432 fh, err := os.Open(threadedNewsPath)
436 decoder := yaml.NewDecoder(fh)
438 return decoder.Decode(s.ThreadedNews)
441 // loadAccounts loads account data from disk
442 func (s *Server) loadAccounts(userDir string) error {
443 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
448 if len(matches) == 0 {
449 return errors.New("no user accounts found in " + userDir)
452 for _, file := range matches {
453 fh, err := s.FS.Open(file)
459 decoder := yaml.NewDecoder(fh)
460 if err := decoder.Decode(&account); err != nil {
464 s.Accounts[account.Login] = &account
469 func (s *Server) loadConfig(path string) error {
470 fh, err := s.FS.Open(path)
475 decoder := yaml.NewDecoder(fh)
476 err = decoder.Decode(s.Config)
481 validate := validator.New()
482 err = validate.Struct(s.Config)
490 minTransactionLen = 22 // minimum length of any transaction
493 // dontPanic recovers and logs panics instead of crashing
494 // TODO: remove this after known issues are fixed
495 func dontPanic(logger *zap.SugaredLogger) {
496 if r := recover(); r != nil {
497 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
498 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
502 // handleNewConnection takes a new net.Conn and performs the initial login sequence
503 func (s *Server) handleNewConnection(conn net.Conn, remoteAddr string) error {
504 defer dontPanic(s.Logger)
506 if err := Handshake(conn); err != nil {
510 buf := make([]byte, 1024)
511 // TODO: fix potential short read with io.ReadFull
512 readLen, err := conn.Read(buf)
513 if readLen < minTransactionLen {
520 clientLogin, _, err := ReadTransaction(buf[:readLen])
525 c := s.NewClientConn(conn, remoteAddr)
528 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
529 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
530 *c.Version = clientLogin.GetField(fieldVersion).Data
533 for _, char := range encodedLogin {
534 login += string(rune(255 - uint(char)))
540 // If authentication fails, send error reply and close connection
541 if !c.Authenticate(login, encodedPassword) {
542 t := c.NewErrReply(clientLogin, "Incorrect login.")
543 b, err := t.MarshalBinary()
547 if _, err := conn.Write(b); err != nil {
550 return fmt.Errorf("incorrect login")
553 if clientLogin.GetField(fieldUserName).Data != nil {
554 c.UserName = clientLogin.GetField(fieldUserName).Data
557 if clientLogin.GetField(fieldUserIconID).Data != nil {
558 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
561 c.Account = c.Server.Accounts[login]
563 if c.Authorize(accessDisconUser) {
564 *c.Flags = []byte{0, 2}
567 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr)
569 s.outbox <- c.NewReply(clientLogin,
570 NewField(fieldVersion, []byte{0x00, 0xbe}),
571 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
572 NewField(fieldServerName, []byte(s.Config.Name)),
575 // Send user access privs so client UI knows how to behave
576 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
578 // Show agreement to client
579 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
581 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
582 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
587 tranNotifyChangeUser, nil,
588 NewField(fieldUserName, c.UserName),
589 NewField(fieldUserID, *c.ID),
590 NewField(fieldUserIconID, *c.Icon),
591 NewField(fieldUserFlags, *c.Flags),
596 c.Server.Stats.LoginCount += 1
598 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
599 tranBuff := make([]byte, 0)
601 // Infinite loop where take action on incoming client requests until the connection is closed
603 buf = make([]byte, readBuffSize)
604 tranBuff = tranBuff[tReadlen:]
606 readLen, err := c.Connection.Read(buf)
610 tranBuff = append(tranBuff, buf[:readLen]...)
612 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
613 // into a slice of transactions
614 var transactions []Transaction
615 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
616 c.Server.Logger.Errorw("Error handling transaction", "err", err)
619 // iterate over all of the transactions that were parsed from the byte slice and handle them
620 for _, t := range transactions {
621 if err := c.handleTransaction(&t); err != nil {
622 c.Server.Logger.Errorw("Error handling transaction", "err", err)
628 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
629 // in the file transfer request payload, and the file transfer server will use it to map the request
631 func (s *Server) NewTransactionRef() []byte {
632 transactionRef := make([]byte, 4)
633 rand.Read(transactionRef)
635 return transactionRef
638 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
642 randID := make([]byte, 4)
644 data := binary.BigEndian.Uint32(randID[:])
646 s.PrivateChats[data] = &PrivateChat{
648 ClientConn: make(map[uint16]*ClientConn),
650 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
655 const dlFldrActionSendFile = 1
656 const dlFldrActionResumeFile = 2
657 const dlFldrActionNextFile = 3
659 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
660 func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
663 if err := conn.Close(); err != nil {
664 s.Logger.Errorw("error closing connection", "error", err)
668 defer dontPanic(s.Logger)
670 txBuf := make([]byte, 16)
671 if _, err := io.ReadFull(conn, txBuf); err != nil {
676 if _, err := t.Write(txBuf); err != nil {
680 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
683 delete(s.FileTransfers, transferRefNum)
688 fileTransfer, ok := s.FileTransfers[transferRefNum]
691 return errors.New("invalid transaction ID")
694 switch fileTransfer.Type {
696 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
702 if fileTransfer.fileResumeData != nil {
703 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
706 ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset)
711 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
713 if fileTransfer.options == nil {
714 // Start by sending flat file object to client
715 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
720 file, err := s.FS.Open(fullFilePath)
725 sendBuffer := make([]byte, 1048576)
729 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
730 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
738 totalSent += int64(bytesRead)
740 fileTransfer.BytesSent += bytesRead
742 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
747 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
751 // A file upload has three possible cases:
752 // 1) Upload a new file
753 // 2) Resume a partially transferred file
754 // 3) Replace a fully uploaded file
755 // Unfortunately we have to infer which case applies by inspecting what is already on the file system
757 // 1) Check for existing file:
758 _, err := os.Stat(destinationFile)
760 // If found, that means this upload is intended to replace the file
761 if err = os.Remove(destinationFile); err != nil {
764 file, err = os.Create(destinationFile + incompleteFileSuffix)
766 if errors.Is(err, fs.ErrNotExist) {
767 // If not found, open or create a new incomplete file
768 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
774 defer func() { _ = file.Close() }()
776 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
778 // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data
779 if err := receiveFile(conn, file, io.Discard); err != nil {
783 if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil {
787 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
789 // Folder Download flow:
790 // 1. Get filePath from the transfer
791 // 2. Iterate over files
793 // Send file header to client
794 // The client can reply in 3 ways:
796 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
797 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
799 // 2. If download of a file is to be resumed:
801 // []byte{0x00, 0x02} // download folder action
802 // [2]byte // Resume data size
803 // []byte file resume data (see myField_FileResumeData)
805 // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01}
807 // When download is requested (case 2 or 3), server replies with:
808 // [4]byte - file size
809 // []byte - Flattened File Object
811 // After every file download, client could request next file with:
812 // []byte{0x00, 0x03}
814 // This notifies the server to send the next item header
816 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
821 basePathLen := len(fullFilePath)
823 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
825 nextAction := make([]byte, 2)
826 if _, err := io.ReadFull(conn, nextAction); err != nil {
831 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
836 subPath := path[basePathLen+1:]
837 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
843 fileHeader := NewFileHeader(subPath, info.IsDir())
845 // Send the file header to client
846 if _, err := conn.Write(fileHeader.Payload()); err != nil {
847 s.Logger.Errorf("error sending file header: %v", err)
851 // Read the client's Next Action request
852 if _, err := io.ReadFull(conn, nextAction); err != nil {
856 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
860 switch nextAction[1] {
861 case dlFldrActionResumeFile:
862 // client asked to resume this file
863 var frd FileResumeData
864 // get size of resumeData
865 if _, err := io.ReadFull(conn, nextAction); err != nil {
869 resumeDataLen := binary.BigEndian.Uint16(nextAction)
870 resumeDataBytes := make([]byte, resumeDataLen)
871 if _, err := io.ReadFull(conn, resumeDataBytes); err != nil {
875 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
878 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
879 case dlFldrActionNextFile:
880 // client asked to skip this file
888 splitPath := strings.Split(path, "/")
890 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset)
894 s.Logger.Infow("File download started",
895 "fileName", info.Name(),
896 "transactionRef", fileTransfer.ReferenceNumber,
897 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
900 // Send file size to client
901 if _, err := conn.Write(ffo.TransferSize()); err != nil {
906 // Send ffo bytes to client
907 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
912 file, err := s.FS.Open(path)
917 // // Copy N bytes from file to connection
918 // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
923 sendBuffer := make([]byte, 1048576)
927 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
928 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
936 totalSent += int64(bytesRead)
938 fileTransfer.BytesSent += bytesRead
940 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
945 // TODO: optionally send resource fork header and resource fork data
947 // Read the client's Next Action request. This is always 3, I think?
948 if _, err := io.ReadFull(conn, nextAction); err != nil {
956 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
961 "Folder upload started",
962 "transactionRef", fileTransfer.ReferenceNumber,
964 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
965 "FolderItemCount", fileTransfer.FolderItemCount,
968 // Check if the target folder exists. If not, create it.
969 if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
970 if err := s.FS.Mkdir(dstPath, 0777); err != nil {
975 // Begin the folder upload flow by sending the "next file action" to client
976 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
980 fileSize := make([]byte, 4)
982 for i := 0; i < fileTransfer.ItemCount(); i++ {
983 s.Stats.UploadCounter += 1
986 if _, err := io.ReadFull(conn, fu.DataSize[:]); err != nil {
990 if _, err := io.ReadFull(conn, fu.IsFolder[:]); err != nil {
993 if _, err := io.ReadFull(conn, fu.PathItemCount[:]); err != nil {
996 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4)
998 if _, err := io.ReadFull(conn, fu.FileNamePath); err != nil {
1003 "Folder upload continued",
1004 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
1005 "FormattedPath", fu.FormattedPath(),
1006 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1007 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1010 if fu.IsFolder == [2]byte{0, 1} {
1011 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
1012 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
1017 // Tell client to send next file
1018 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1022 nextAction := dlFldrActionSendFile
1024 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1025 _, err := os.Stat(dstPath + "/" + fu.FormattedPath())
1026 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1030 nextAction = dlFldrActionNextFile
1033 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1034 inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
1035 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1039 nextAction = dlFldrActionResumeFile
1042 fmt.Printf("Next Action: %v\n", nextAction)
1044 if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil {
1049 case dlFldrActionNextFile:
1051 case dlFldrActionResumeFile:
1052 offset := make([]byte, 4)
1053 binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size()))
1055 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1060 fileResumeData := NewFileResumeData([]ForkInfoList{
1061 *NewForkInfoList(offset),
1064 b, _ := fileResumeData.BinaryMarshal()
1066 bs := make([]byte, 2)
1067 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1069 if _, err := conn.Write(append(bs, b...)); err != nil {
1073 if _, err := io.ReadFull(conn, fileSize); err != nil {
1077 if err := receiveFile(conn, file, ioutil.Discard); err != nil {
1081 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1086 case dlFldrActionSendFile:
1087 if _, err := io.ReadFull(conn, fileSize); err != nil {
1091 filePath := dstPath + "/" + fu.FormattedPath()
1092 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize))
1094 newFile, err := s.FS.Create(filePath + ".incomplete")
1099 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
1103 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1108 // Tell client to send next file
1109 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1114 s.Logger.Infof("Folder upload complete")
1120 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1121 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1122 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1123 for _, c := range unsortedClients {
1124 clients = append(clients, c)
1126 sort.Sort(byClientID(clients))