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 net.Conn, 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{0x00, 0x01}),
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) {
608 c.logger = c.logger.With("name", string(c.UserName))
612 tranNotifyChangeUser, nil,
613 NewField(fieldUserName, c.UserName),
614 NewField(fieldUserID, *c.ID),
615 NewField(fieldUserIconID, *c.Icon),
616 NewField(fieldUserFlags, *c.Flags),
621 c.Server.Stats.LoginCount += 1
623 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
624 tranBuff := make([]byte, 0)
626 // Infinite loop where take action on incoming client requests until the connection is closed
628 buf = make([]byte, readBuffSize)
629 tranBuff = tranBuff[tReadlen:]
631 readLen, err := c.Connection.Read(buf)
635 tranBuff = append(tranBuff, buf[:readLen]...)
637 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
638 // into a slice of transactions
639 var transactions []Transaction
640 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
641 c.logger.Errorw("Error handling transaction", "err", err)
644 // iterate over all the transactions that were parsed from the byte slice and handle them
645 for _, t := range transactions {
646 if err := c.handleTransaction(&t); err != nil {
647 c.Server.Logger.Errorw("Error handling transaction", "err", err)
653 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
654 // in the transfer request payload, and the file transfer server will use it to map the request
656 func (s *Server) NewTransactionRef() []byte {
657 transactionRef := make([]byte, 4)
658 rand.Read(transactionRef)
660 return transactionRef
663 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
667 randID := make([]byte, 4)
669 data := binary.BigEndian.Uint32(randID[:])
671 s.PrivateChats[data] = &PrivateChat{
673 ClientConn: make(map[uint16]*ClientConn),
675 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
680 const dlFldrActionSendFile = 1
681 const dlFldrActionResumeFile = 2
682 const dlFldrActionNextFile = 3
684 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
685 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
686 defer dontPanic(s.Logger)
688 txBuf := make([]byte, 16)
689 if _, err := io.ReadFull(rwc, txBuf); err != nil {
694 if _, err := t.Write(txBuf); err != nil {
698 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
701 delete(s.FileTransfers, transferRefNum)
706 fileTransfer, ok := s.FileTransfers[transferRefNum]
709 return errors.New("invalid transaction ID")
712 rLogger := s.Logger.With(
713 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
714 "xferID", transferRefNum,
717 switch fileTransfer.Type {
719 s.Stats.DownloadCounter += 1
721 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
727 if fileTransfer.fileResumeData != nil {
728 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
731 fw, err := newFileWrapper(s.FS, fullFilePath, 0)
736 rLogger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
738 wr := bufio.NewWriterSize(rwc, 1460)
740 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
741 if fileTransfer.options == nil {
742 // Start by sending flat file object to client
743 if _, err := wr.Write(fw.ffo.BinaryMarshal()); err != nil {
748 file, err := fw.dataForkReader()
753 if err := sendFile(wr, file, int(dataOffset)); err != nil {
757 if err := wr.Flush(); err != nil {
761 // if the client requested to resume transfer, do not send the resource fork, or it will be appended into the fileWrapper data
762 if fileTransfer.fileResumeData == nil {
763 err = binary.Write(wr, binary.BigEndian, fw.rsrcForkHeader())
767 if err := wr.Flush(); err != nil {
772 rFile, err := fw.rsrcForkFile()
777 err = sendFile(wr, rFile, int(dataOffset))
782 if err := wr.Flush(); err != nil {
787 s.Stats.UploadCounter += 1
789 destinationFile, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
796 // A file upload has three possible cases:
797 // 1) Upload a new file
798 // 2) Resume a partially transferred file
799 // 3) Replace a fully uploaded file
800 // We have to infer which case applies by inspecting what is already on the filesystem
802 // 1) Check for existing file:
803 _, err = os.Stat(destinationFile)
805 // If found, that means this upload is intended to replace the file
806 if err = os.Remove(destinationFile); err != nil {
809 file, err = os.Create(destinationFile + incompleteFileSuffix)
811 if errors.Is(err, fs.ErrNotExist) {
812 // If not found, open or create a new .incomplete file
813 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
819 f, err := newFileWrapper(s.FS, destinationFile, 0)
824 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
826 rForkWriter := io.Discard
827 iForkWriter := io.Discard
828 if s.Config.PreserveResourceForks {
829 rForkWriter, err = f.rsrcForkWriter()
834 iForkWriter, err = f.infoForkWriter()
840 if err := receiveFile(rwc, file, rForkWriter, iForkWriter); err != nil {
844 if err := file.Close(); err != nil {
848 if err := s.FS.Rename(destinationFile+".incomplete", destinationFile); err != nil {
852 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
854 // Folder Download flow:
855 // 1. Get filePath from the transfer
856 // 2. Iterate over files
857 // 3. For each fileWrapper:
858 // Send fileWrapper header to client
859 // The client can reply in 3 ways:
861 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
862 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
864 // 2. If download of a fileWrapper is to be resumed:
866 // []byte{0x00, 0x02} // download folder action
867 // [2]byte // Resume data size
868 // []byte fileWrapper resume data (see myField_FileResumeData)
870 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
872 // When download is requested (case 2 or 3), server replies with:
873 // [4]byte - fileWrapper size
874 // []byte - Flattened File Object
876 // After every fileWrapper download, client could request next fileWrapper with:
877 // []byte{0x00, 0x03}
879 // This notifies the server to send the next item header
881 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
886 basePathLen := len(fullFilePath)
888 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
890 nextAction := make([]byte, 2)
891 if _, err := io.ReadFull(rwc, nextAction); err != nil {
896 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
897 s.Stats.DownloadCounter += 1
905 if strings.HasPrefix(info.Name(), ".") {
909 hlFile, err := newFileWrapper(s.FS, path, 0)
914 subPath := path[basePathLen+1:]
915 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
921 fileHeader := NewFileHeader(subPath, info.IsDir())
923 // Send the fileWrapper header to client
924 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
925 s.Logger.Errorf("error sending file header: %v", err)
929 // Read the client's Next Action request
930 if _, err := io.ReadFull(rwc, nextAction); err != nil {
934 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
938 switch nextAction[1] {
939 case dlFldrActionResumeFile:
940 // get size of resumeData
941 resumeDataByteLen := make([]byte, 2)
942 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
946 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
947 resumeDataBytes := make([]byte, resumeDataLen)
948 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
952 var frd FileResumeData
953 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
956 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
957 case dlFldrActionNextFile:
958 // client asked to skip this file
966 s.Logger.Infow("File download started",
967 "fileName", info.Name(),
968 "transactionRef", fileTransfer.ReferenceNumber,
969 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
972 // Send file size to client
973 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
978 // Send ffo bytes to client
979 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
984 file, err := s.FS.Open(path)
989 // wr := bufio.NewWriterSize(rwc, 1460)
990 err = sendFile(rwc, file, int(dataOffset))
995 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
996 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1001 rFile, err := hlFile.rsrcForkFile()
1006 err = sendFile(rwc, rFile, int(dataOffset))
1012 // Read the client's Next Action request. This is always 3, I think?
1013 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1025 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
1031 "Folder upload started",
1032 "transactionRef", fileTransfer.ReferenceNumber,
1034 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
1035 "FolderItemCount", fileTransfer.FolderItemCount,
1038 // Check if the target folder exists. If not, create it.
1039 if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
1040 if err := s.FS.Mkdir(dstPath, 0777); err != nil {
1045 // Begin the folder upload flow by sending the "next file action" to client
1046 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1050 fileSize := make([]byte, 4)
1052 for i := 0; i < fileTransfer.ItemCount(); i++ {
1053 s.Stats.UploadCounter += 1
1056 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1059 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1062 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1066 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1068 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1073 "Folder upload continued",
1074 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
1075 "FormattedPath", fu.FormattedPath(),
1076 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1077 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1080 if fu.IsFolder == [2]byte{0, 1} {
1081 if _, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath())); os.IsNotExist(err) {
1082 if err := os.Mkdir(filepath.Join(dstPath, fu.FormattedPath()), 0777); err != nil {
1087 // Tell client to send next file
1088 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1092 nextAction := dlFldrActionSendFile
1094 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1095 _, err = os.Stat(filepath.Join(dstPath, fu.FormattedPath()))
1096 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1100 nextAction = dlFldrActionNextFile
1103 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1104 incompleteFile, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath()+incompleteFileSuffix))
1105 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1109 nextAction = dlFldrActionResumeFile
1112 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1117 case dlFldrActionNextFile:
1119 case dlFldrActionResumeFile:
1120 offset := make([]byte, 4)
1121 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1123 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1128 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1130 b, _ := fileResumeData.BinaryMarshal()
1132 bs := make([]byte, 2)
1133 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1135 if _, err := rwc.Write(append(bs, b...)); err != nil {
1139 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1143 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard); err != nil {
1147 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1152 case dlFldrActionSendFile:
1153 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1157 filePath := filepath.Join(dstPath, fu.FormattedPath())
1159 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1164 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1166 incWriter, err := hlFile.incFileWriter()
1171 rForkWriter := io.Discard
1172 iForkWriter := io.Discard
1173 if s.Config.PreserveResourceForks {
1174 iForkWriter, err = hlFile.infoForkWriter()
1179 rForkWriter, err = hlFile.rsrcForkWriter()
1184 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter); err != nil {
1187 // _ = newFile.Close()
1188 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1193 // Tell client to send next fileWrapper
1194 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1199 s.Logger.Infof("Folder upload complete")