10 "github.com/go-playground/validator/v10"
27 type contextKey string
29 var contextKeyReq = contextKey("req")
31 type requestCtx struct {
38 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
39 idleCheckInterval = 10 // time in seconds to check for idle users
40 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
43 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
47 Accounts map[string]*Account
49 Clients map[uint16]*ClientConn
50 ThreadedNews *ThreadedNews
51 FileTransfers map[uint32]*FileTransfer
54 Logger *zap.SugaredLogger
55 PrivateChats map[uint32]*PrivateChat
60 FS FileStore // Storage backend to use for File storage
62 outbox chan Transaction
65 flatNewsMux sync.Mutex
69 type PrivateChat struct {
71 ClientConn map[uint16]*ClientConn
74 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
75 s.Logger.Infow("Hotline server started",
77 "API port", fmt.Sprintf(":%v", s.Port),
78 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
85 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
90 s.Logger.Fatal(s.Serve(ctx, ln))
95 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
101 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
109 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
111 conn, err := ln.Accept()
117 defer func() { _ = conn.Close() }()
119 err = s.handleFileTransfer(
120 context.WithValue(ctx, contextKeyReq, requestCtx{
121 remoteAddr: conn.RemoteAddr().String(),
127 s.Logger.Errorw("file transfer error", "reason", err)
133 func (s *Server) sendTransaction(t Transaction) error {
134 requestNum := binary.BigEndian.Uint16(t.Type)
135 clientID, err := byteToInt(*t.clientID)
141 client := s.Clients[uint16(clientID)]
144 return fmt.Errorf("invalid client id %v", *t.clientID)
146 userName := string(client.UserName)
147 login := client.Account.Login
149 handler := TransactionHandlers[requestNum]
151 b, err := t.MarshalBinary()
156 if n, err = client.Connection.Write(b); err != nil {
159 s.Logger.Debugw("Sent Transaction",
162 "IsReply", t.IsReply,
163 "type", handler.Name,
165 "remoteAddr", client.RemoteAddr,
170 func (s *Server) processOutbox() {
174 if err := s.sendTransaction(t); err != nil {
175 s.Logger.Errorw("error sending transaction", "err", err)
181 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
185 conn, err := ln.Accept()
187 s.Logger.Errorw("error accepting connection", "err", err)
189 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
190 remoteAddr: conn.RemoteAddr().String(),
194 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
195 s.Logger.Infow("New client connection established", "RemoteAddr", conn.RemoteAddr())
197 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
199 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
207 agreementFile = "Agreement.txt"
210 // NewServer constructs a new Server from a config dir
211 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
214 Accounts: make(map[string]*Account),
216 Clients: make(map[uint16]*ClientConn),
217 FileTransfers: make(map[uint32]*FileTransfer),
218 PrivateChats: make(map[uint32]*PrivateChat),
219 ConfigDir: configDir,
221 NextGuestID: new(uint16),
222 outbox: make(chan Transaction),
223 Stats: &Stats{StartTime: time.Now()},
224 ThreadedNews: &ThreadedNews{},
230 // generate a new random passID for tracker registration
231 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
235 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
240 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
244 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
248 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
252 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
256 server.Config.FileRoot = filepath.Join(configDir, "Files")
258 *server.NextGuestID = 1
260 if server.Config.EnableTrackerRegistration {
262 "Tracker registration enabled",
263 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
264 "trackers", server.Config.Trackers,
269 tr := &TrackerRegistration{
270 UserCount: server.userCount(),
271 PassID: server.TrackerPassID[:],
272 Name: server.Config.Name,
273 Description: server.Config.Description,
275 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
276 for _, t := range server.Config.Trackers {
277 if err := register(t, tr); err != nil {
278 server.Logger.Errorw("unable to register with tracker %v", "error", err)
280 server.Logger.Infow("Sent Tracker registration", "data", tr)
283 time.Sleep(trackerUpdateFrequency * time.Second)
288 // Start Client Keepalive go routine
289 go server.keepaliveHandler()
294 func (s *Server) userCount() int {
298 return len(s.Clients)
301 func (s *Server) keepaliveHandler() {
303 time.Sleep(idleCheckInterval * time.Second)
306 for _, c := range s.Clients {
307 c.IdleTime += idleCheckInterval
308 if c.IdleTime > userIdleSeconds && !c.Idle {
311 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
312 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
313 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
316 tranNotifyChangeUser,
317 NewField(fieldUserID, *c.ID),
318 NewField(fieldUserFlags, *c.Flags),
319 NewField(fieldUserName, c.UserName),
320 NewField(fieldUserIconID, *c.Icon),
328 func (s *Server) writeThreadedNews() error {
332 out, err := yaml.Marshal(s.ThreadedNews)
336 err = ioutil.WriteFile(
337 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
344 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
348 clientConn := &ClientConn{
351 Flags: &[]byte{0, 0},
357 Transfers: make(map[int][]*FileTransfer),
359 RemoteAddr: remoteAddr,
364 binary.BigEndian.PutUint16(*clientConn.ID, ID)
365 s.Clients[ID] = clientConn
370 // NewUser creates a new user account entry in the server map and config file
371 func (s *Server) NewUser(login, name, password string, access []byte) error {
378 Password: hashAndSalt([]byte(password)),
381 out, err := yaml.Marshal(&account)
385 s.Accounts[login] = &account
387 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
390 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
394 // update renames the user login
395 if login != newLogin {
396 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
400 s.Accounts[newLogin] = s.Accounts[login]
401 delete(s.Accounts, login)
404 account := s.Accounts[newLogin]
405 account.Access = &access
407 account.Password = password
409 out, err := yaml.Marshal(&account)
414 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
421 // DeleteUser deletes the user account
422 func (s *Server) DeleteUser(login string) error {
426 delete(s.Accounts, login)
428 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
431 func (s *Server) connectedUsers() []Field {
435 var connectedUsers []Field
436 for _, c := range sortedClients(s.Clients) {
444 Name: string(c.UserName),
446 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
448 return connectedUsers
451 // loadThreadedNews loads the threaded news data from disk
452 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
453 fh, err := os.Open(threadedNewsPath)
457 decoder := yaml.NewDecoder(fh)
459 return decoder.Decode(s.ThreadedNews)
462 // loadAccounts loads account data from disk
463 func (s *Server) loadAccounts(userDir string) error {
464 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
469 if len(matches) == 0 {
470 return errors.New("no user accounts found in " + userDir)
473 for _, file := range matches {
474 fh, err := s.FS.Open(file)
480 decoder := yaml.NewDecoder(fh)
481 if err := decoder.Decode(&account); err != nil {
485 s.Accounts[account.Login] = &account
490 func (s *Server) loadConfig(path string) error {
491 fh, err := s.FS.Open(path)
496 decoder := yaml.NewDecoder(fh)
497 err = decoder.Decode(s.Config)
502 validate := validator.New()
503 err = validate.Struct(s.Config)
511 minTransactionLen = 22 // minimum length of any transaction
514 // dontPanic recovers and logs panics instead of crashing
515 // TODO: remove this after known issues are fixed
516 func dontPanic(logger *zap.SugaredLogger) {
517 if r := recover(); r != nil {
518 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
519 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
523 // handleNewConnection takes a new net.Conn and performs the initial login sequence
524 func (s *Server) handleNewConnection(ctx context.Context, conn io.ReadWriteCloser, remoteAddr string) error {
525 defer dontPanic(s.Logger)
527 if err := Handshake(conn); err != nil {
531 buf := make([]byte, 1024)
532 // TODO: fix potential short read with io.ReadFull
533 readLen, err := conn.Read(buf)
534 if readLen < minTransactionLen {
541 clientLogin, _, err := ReadTransaction(buf[:readLen])
546 c := s.NewClientConn(conn, remoteAddr)
549 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
550 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
551 *c.Version = clientLogin.GetField(fieldVersion).Data
554 for _, char := range encodedLogin {
555 login += string(rune(255 - uint(char)))
561 // If authentication fails, send error reply and close connection
562 if !c.Authenticate(login, encodedPassword) {
563 t := c.NewErrReply(clientLogin, "Incorrect login.")
564 b, err := t.MarshalBinary()
568 if _, err := conn.Write(b); err != nil {
571 return fmt.Errorf("incorrect login")
574 if clientLogin.GetField(fieldUserName).Data != nil {
575 c.UserName = clientLogin.GetField(fieldUserName).Data
578 if clientLogin.GetField(fieldUserIconID).Data != nil {
579 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
582 c.Account = c.Server.Accounts[login]
584 if c.Authorize(accessDisconUser) {
585 *c.Flags = []byte{0, 2}
588 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
590 c.logger.Infow("Client connection received", "version", fmt.Sprintf("%x", *c.Version))
592 s.outbox <- c.NewReply(clientLogin,
593 NewField(fieldVersion, []byte{0x00, 0xbe}),
594 NewField(fieldCommunityBannerID, []byte{0, 0}),
595 NewField(fieldServerName, []byte(s.Config.Name)),
598 // Send user access privs so client UI knows how to behave
599 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
601 // Show agreement to client
602 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
604 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
605 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
607 c.logger = c.logger.With("name", string(c.UserName))
609 for _, t := range c.notifyOthers(
611 tranNotifyChangeUser, nil,
612 NewField(fieldUserName, c.UserName),
613 NewField(fieldUserID, *c.ID),
614 NewField(fieldUserIconID, *c.Icon),
615 NewField(fieldUserFlags, *c.Flags),
622 c.Server.Stats.LoginCount += 1
624 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
625 tranBuff := make([]byte, 0)
627 // Infinite loop where take action on incoming client requests until the connection is closed
629 buf = make([]byte, readBuffSize)
630 tranBuff = tranBuff[tReadlen:]
632 readLen, err := c.Connection.Read(buf)
636 tranBuff = append(tranBuff, buf[:readLen]...)
638 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
639 // into a slice of transactions
640 var transactions []Transaction
641 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
642 c.logger.Errorw("Error handling transaction", "err", err)
645 // iterate over all the transactions that were parsed from the byte slice and handle them
646 for _, t := range transactions {
647 if err := c.handleTransaction(&t); err != nil {
648 c.logger.Errorw("Error handling transaction", "err", err)
654 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
655 // in the transfer request payload, and the file transfer server will use it to map the request
657 func (s *Server) NewTransactionRef() []byte {
658 transactionRef := make([]byte, 4)
659 rand.Read(transactionRef)
661 return transactionRef
664 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
668 randID := make([]byte, 4)
670 data := binary.BigEndian.Uint32(randID[:])
672 s.PrivateChats[data] = &PrivateChat{
674 ClientConn: make(map[uint16]*ClientConn),
676 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
681 const dlFldrActionSendFile = 1
682 const dlFldrActionResumeFile = 2
683 const dlFldrActionNextFile = 3
685 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
686 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
687 defer dontPanic(s.Logger)
689 txBuf := make([]byte, 16)
690 if _, err := io.ReadFull(rwc, txBuf); err != nil {
695 if _, err := t.Write(txBuf); err != nil {
699 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
702 delete(s.FileTransfers, transferRefNum)
707 fileTransfer, ok := s.FileTransfers[transferRefNum]
710 return errors.New("invalid transaction ID")
713 rLogger := s.Logger.With(
714 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
715 "xferID", transferRefNum,
718 switch fileTransfer.Type {
720 if err := s.bannerDownload(rwc); err != nil {
724 s.Stats.DownloadCounter += 1
726 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
732 if fileTransfer.fileResumeData != nil {
733 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
736 fw, err := newFileWrapper(s.FS, fullFilePath, 0)
741 rLogger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
743 wr := bufio.NewWriterSize(rwc, 1460)
745 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
746 if fileTransfer.options == nil {
747 // Start by sending flat file object to client
748 if _, err := wr.Write(fw.ffo.BinaryMarshal()); err != nil {
753 file, err := fw.dataForkReader()
758 if err := sendFile(wr, file, int(dataOffset)); err != nil {
762 if err := wr.Flush(); err != nil {
766 // if the client requested to resume transfer, do not send the resource fork, or it will be appended into the fileWrapper data
767 if fileTransfer.fileResumeData == nil {
768 err = binary.Write(wr, binary.BigEndian, fw.rsrcForkHeader())
772 if err := wr.Flush(); err != nil {
777 rFile, err := fw.rsrcForkFile()
782 err = sendFile(wr, rFile, int(dataOffset))
787 if err := wr.Flush(); err != nil {
792 s.Stats.UploadCounter += 1
794 destinationFile, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
801 // A file upload has three possible cases:
802 // 1) Upload a new file
803 // 2) Resume a partially transferred file
804 // 3) Replace a fully uploaded file
805 // We have to infer which case applies by inspecting what is already on the filesystem
807 // 1) Check for existing file:
808 _, err = os.Stat(destinationFile)
810 // If found, that means this upload is intended to replace the file
811 if err = os.Remove(destinationFile); err != nil {
814 file, err = os.Create(destinationFile + incompleteFileSuffix)
816 if errors.Is(err, fs.ErrNotExist) {
817 // If not found, open or create a new .incomplete file
818 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
824 f, err := newFileWrapper(s.FS, destinationFile, 0)
829 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
831 rForkWriter := io.Discard
832 iForkWriter := io.Discard
833 if s.Config.PreserveResourceForks {
834 rForkWriter, err = f.rsrcForkWriter()
839 iForkWriter, err = f.infoForkWriter()
845 if err := receiveFile(rwc, file, rForkWriter, iForkWriter); err != nil {
849 if err := file.Close(); err != nil {
853 if err := s.FS.Rename(destinationFile+".incomplete", destinationFile); err != nil {
857 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
859 // Folder Download flow:
860 // 1. Get filePath from the transfer
861 // 2. Iterate over files
862 // 3. For each fileWrapper:
863 // Send fileWrapper header to client
864 // The client can reply in 3 ways:
866 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
867 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
869 // 2. If download of a fileWrapper is to be resumed:
871 // []byte{0x00, 0x02} // download folder action
872 // [2]byte // Resume data size
873 // []byte fileWrapper resume data (see myField_FileResumeData)
875 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
877 // When download is requested (case 2 or 3), server replies with:
878 // [4]byte - fileWrapper size
879 // []byte - Flattened File Object
881 // After every fileWrapper download, client could request next fileWrapper with:
882 // []byte{0x00, 0x03}
884 // This notifies the server to send the next item header
886 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
891 basePathLen := len(fullFilePath)
893 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
895 nextAction := make([]byte, 2)
896 if _, err := io.ReadFull(rwc, nextAction); err != nil {
901 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
902 s.Stats.DownloadCounter += 1
910 if strings.HasPrefix(info.Name(), ".") {
914 hlFile, err := newFileWrapper(s.FS, path, 0)
919 subPath := path[basePathLen+1:]
920 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
926 fileHeader := NewFileHeader(subPath, info.IsDir())
928 // Send the fileWrapper header to client
929 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
930 s.Logger.Errorf("error sending file header: %v", err)
934 // Read the client's Next Action request
935 if _, err := io.ReadFull(rwc, nextAction); err != nil {
939 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
943 switch nextAction[1] {
944 case dlFldrActionResumeFile:
945 // get size of resumeData
946 resumeDataByteLen := make([]byte, 2)
947 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
951 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
952 resumeDataBytes := make([]byte, resumeDataLen)
953 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
957 var frd FileResumeData
958 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
961 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
962 case dlFldrActionNextFile:
963 // client asked to skip this file
971 s.Logger.Infow("File download started",
972 "fileName", info.Name(),
973 "transactionRef", fileTransfer.ReferenceNumber,
974 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
977 // Send file size to client
978 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
983 // Send ffo bytes to client
984 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
989 file, err := s.FS.Open(path)
994 // wr := bufio.NewWriterSize(rwc, 1460)
995 err = sendFile(rwc, file, int(dataOffset))
1000 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1001 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1006 rFile, err := hlFile.rsrcForkFile()
1011 err = sendFile(rwc, rFile, int(dataOffset))
1017 // Read the client's Next Action request. This is always 3, I think?
1018 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1030 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
1036 "Folder upload started",
1037 "transactionRef", fileTransfer.ReferenceNumber,
1039 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
1040 "FolderItemCount", fileTransfer.FolderItemCount,
1043 // Check if the target folder exists. If not, create it.
1044 if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
1045 if err := s.FS.Mkdir(dstPath, 0777); err != nil {
1050 // Begin the folder upload flow by sending the "next file action" to client
1051 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1055 fileSize := make([]byte, 4)
1057 for i := 0; i < fileTransfer.ItemCount(); i++ {
1058 s.Stats.UploadCounter += 1
1061 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1064 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1067 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1071 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1073 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1078 "Folder upload continued",
1079 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
1080 "FormattedPath", fu.FormattedPath(),
1081 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1082 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1085 if fu.IsFolder == [2]byte{0, 1} {
1086 if _, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath())); os.IsNotExist(err) {
1087 if err := os.Mkdir(filepath.Join(dstPath, fu.FormattedPath()), 0777); err != nil {
1092 // Tell client to send next file
1093 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1097 nextAction := dlFldrActionSendFile
1099 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1100 _, err = os.Stat(filepath.Join(dstPath, fu.FormattedPath()))
1101 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1105 nextAction = dlFldrActionNextFile
1108 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1109 incompleteFile, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath()+incompleteFileSuffix))
1110 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1114 nextAction = dlFldrActionResumeFile
1117 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1122 case dlFldrActionNextFile:
1124 case dlFldrActionResumeFile:
1125 offset := make([]byte, 4)
1126 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1128 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1133 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1135 b, _ := fileResumeData.BinaryMarshal()
1137 bs := make([]byte, 2)
1138 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1140 if _, err := rwc.Write(append(bs, b...)); err != nil {
1144 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1148 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard); err != nil {
1152 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1157 case dlFldrActionSendFile:
1158 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1162 filePath := filepath.Join(dstPath, fu.FormattedPath())
1164 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1169 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1171 incWriter, err := hlFile.incFileWriter()
1176 rForkWriter := io.Discard
1177 iForkWriter := io.Discard
1178 if s.Config.PreserveResourceForks {
1179 iForkWriter, err = hlFile.infoForkWriter()
1184 rForkWriter, err = hlFile.rsrcForkWriter()
1189 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter); err != nil {
1192 // _ = newFile.Close()
1193 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1198 // Tell client to send next fileWrapper
1199 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1204 s.Logger.Infof("Folder upload complete")