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
52 fileTransfers map[[4]byte]*FileTransfer
56 Logger *zap.SugaredLogger
57 PrivateChats map[uint32]*PrivateChat
62 FS FileStore // Storage backend to use for File storage
64 outbox chan Transaction
67 flatNewsMux sync.Mutex
71 type PrivateChat struct {
73 ClientConn map[uint16]*ClientConn
76 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
77 s.Logger.Infow("Hotline server started",
79 "API port", fmt.Sprintf(":%v", s.Port),
80 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
87 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
92 s.Logger.Fatal(s.Serve(ctx, ln))
97 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
103 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
111 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
113 conn, err := ln.Accept()
119 defer func() { _ = conn.Close() }()
121 err = s.handleFileTransfer(
122 context.WithValue(ctx, contextKeyReq, requestCtx{
123 remoteAddr: conn.RemoteAddr().String(),
129 s.Logger.Errorw("file transfer error", "reason", err)
135 func (s *Server) sendTransaction(t Transaction) error {
136 requestNum := binary.BigEndian.Uint16(t.Type)
137 clientID, err := byteToInt(*t.clientID)
143 client := s.Clients[uint16(clientID)]
146 return fmt.Errorf("invalid client id %v", *t.clientID)
148 userName := string(client.UserName)
149 login := client.Account.Login
151 handler := TransactionHandlers[requestNum]
153 b, err := t.MarshalBinary()
158 if n, err = client.Connection.Write(b); err != nil {
161 s.Logger.Debugw("Sent Transaction",
164 "IsReply", t.IsReply,
165 "type", handler.Name,
167 "remoteAddr", client.RemoteAddr,
172 func (s *Server) processOutbox() {
176 if err := s.sendTransaction(t); err != nil {
177 s.Logger.Errorw("error sending transaction", "err", err)
183 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
187 conn, err := ln.Accept()
189 s.Logger.Errorw("error accepting connection", "err", err)
191 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
192 remoteAddr: conn.RemoteAddr().String(),
196 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
198 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
200 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
202 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
210 agreementFile = "Agreement.txt"
213 // NewServer constructs a new Server from a config dir
214 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
217 Accounts: make(map[string]*Account),
219 Clients: make(map[uint16]*ClientConn),
220 fileTransfers: make(map[[4]byte]*FileTransfer),
221 PrivateChats: make(map[uint32]*PrivateChat),
222 ConfigDir: configDir,
224 NextGuestID: new(uint16),
225 outbox: make(chan Transaction),
226 Stats: &Stats{StartTime: time.Now()},
227 ThreadedNews: &ThreadedNews{},
233 // generate a new random passID for tracker registration
234 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
238 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
243 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
247 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
251 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
255 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
259 server.Config.FileRoot = filepath.Join(configDir, "Files")
261 *server.NextGuestID = 1
263 if server.Config.EnableTrackerRegistration {
265 "Tracker registration enabled",
266 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
267 "trackers", server.Config.Trackers,
272 tr := &TrackerRegistration{
273 UserCount: server.userCount(),
274 PassID: server.TrackerPassID[:],
275 Name: server.Config.Name,
276 Description: server.Config.Description,
278 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
279 for _, t := range server.Config.Trackers {
280 if err := register(t, tr); err != nil {
281 server.Logger.Errorw("unable to register with tracker %v", "error", err)
283 server.Logger.Infow("Sent Tracker registration", "data", tr)
286 time.Sleep(trackerUpdateFrequency * time.Second)
291 // Start Client Keepalive go routine
292 go server.keepaliveHandler()
297 func (s *Server) userCount() int {
301 return len(s.Clients)
304 func (s *Server) keepaliveHandler() {
306 time.Sleep(idleCheckInterval * time.Second)
309 for _, c := range s.Clients {
310 c.IdleTime += idleCheckInterval
311 if c.IdleTime > userIdleSeconds && !c.Idle {
314 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
315 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
316 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
319 tranNotifyChangeUser,
320 NewField(fieldUserID, *c.ID),
321 NewField(fieldUserFlags, *c.Flags),
322 NewField(fieldUserName, c.UserName),
323 NewField(fieldUserIconID, *c.Icon),
331 func (s *Server) writeThreadedNews() error {
335 out, err := yaml.Marshal(s.ThreadedNews)
339 err = ioutil.WriteFile(
340 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
347 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
351 clientConn := &ClientConn{
354 Flags: &[]byte{0, 0},
360 transfers: map[int]map[[4]byte]*FileTransfer{},
362 RemoteAddr: remoteAddr,
364 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
375 binary.BigEndian.PutUint16(*clientConn.ID, ID)
376 s.Clients[ID] = clientConn
381 // NewUser creates a new user account entry in the server map and config file
382 func (s *Server) NewUser(login, name, password string, access []byte) error {
389 Password: hashAndSalt([]byte(password)),
392 out, err := yaml.Marshal(&account)
396 s.Accounts[login] = &account
398 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
401 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
405 // update renames the user login
406 if login != newLogin {
407 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
411 s.Accounts[newLogin] = s.Accounts[login]
412 delete(s.Accounts, login)
415 account := s.Accounts[newLogin]
416 account.Access = &access
418 account.Password = password
420 out, err := yaml.Marshal(&account)
425 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
432 // DeleteUser deletes the user account
433 func (s *Server) DeleteUser(login string) error {
437 delete(s.Accounts, login)
439 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
442 func (s *Server) connectedUsers() []Field {
446 var connectedUsers []Field
447 for _, c := range sortedClients(s.Clients) {
455 Name: string(c.UserName),
457 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
459 return connectedUsers
462 // loadThreadedNews loads the threaded news data from disk
463 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
464 fh, err := os.Open(threadedNewsPath)
468 decoder := yaml.NewDecoder(fh)
470 return decoder.Decode(s.ThreadedNews)
473 // loadAccounts loads account data from disk
474 func (s *Server) loadAccounts(userDir string) error {
475 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
480 if len(matches) == 0 {
481 return errors.New("no user accounts found in " + userDir)
484 for _, file := range matches {
485 fh, err := s.FS.Open(file)
491 decoder := yaml.NewDecoder(fh)
492 if err := decoder.Decode(&account); err != nil {
496 s.Accounts[account.Login] = &account
501 func (s *Server) loadConfig(path string) error {
502 fh, err := s.FS.Open(path)
507 decoder := yaml.NewDecoder(fh)
508 err = decoder.Decode(s.Config)
513 validate := validator.New()
514 err = validate.Struct(s.Config)
522 minTransactionLen = 22 // minimum length of any transaction
525 // dontPanic recovers and logs panics instead of crashing
526 // TODO: remove this after known issues are fixed
527 func dontPanic(logger *zap.SugaredLogger) {
528 if r := recover(); r != nil {
529 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
530 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
534 // handleNewConnection takes a new net.Conn and performs the initial login sequence
535 func (s *Server) handleNewConnection(ctx context.Context, conn io.ReadWriteCloser, remoteAddr string) error {
536 defer dontPanic(s.Logger)
538 if err := Handshake(conn); err != nil {
542 buf := make([]byte, 1024)
543 // TODO: fix potential short read with io.ReadFull
544 readLen, err := conn.Read(buf)
545 if readLen < minTransactionLen {
552 clientLogin, _, err := ReadTransaction(buf[:readLen])
557 c := s.NewClientConn(conn, remoteAddr)
560 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
561 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
562 *c.Version = clientLogin.GetField(fieldVersion).Data
565 for _, char := range encodedLogin {
566 login += string(rune(255 - uint(char)))
572 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
574 // If authentication fails, send error reply and close connection
575 if !c.Authenticate(login, encodedPassword) {
576 t := c.NewErrReply(clientLogin, "Incorrect login.")
577 b, err := t.MarshalBinary()
581 if _, err := conn.Write(b); err != nil {
585 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", *c.Version))
590 if clientLogin.GetField(fieldUserName).Data != nil {
591 c.UserName = clientLogin.GetField(fieldUserName).Data
594 if clientLogin.GetField(fieldUserIconID).Data != nil {
595 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
598 c.Account = c.Server.Accounts[login]
600 if c.Authorize(accessDisconUser) {
601 *c.Flags = []byte{0, 2}
604 s.outbox <- c.NewReply(clientLogin,
605 NewField(fieldVersion, []byte{0x00, 0xbe}),
606 NewField(fieldCommunityBannerID, []byte{0, 0}),
607 NewField(fieldServerName, []byte(s.Config.Name)),
610 // Send user access privs so client UI knows how to behave
611 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
613 // Show agreement to client
614 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
616 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
617 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
619 c.logger = c.logger.With("name", string(c.UserName))
620 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", *c.Version))
622 for _, t := range c.notifyOthers(
624 tranNotifyChangeUser, nil,
625 NewField(fieldUserName, c.UserName),
626 NewField(fieldUserID, *c.ID),
627 NewField(fieldUserIconID, *c.Icon),
628 NewField(fieldUserFlags, *c.Flags),
635 c.Server.Stats.LoginCount += 1
637 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
638 tranBuff := make([]byte, 0)
640 // Infinite loop where take action on incoming client requests until the connection is closed
642 buf = make([]byte, readBuffSize)
643 tranBuff = tranBuff[tReadlen:]
645 readLen, err := c.Connection.Read(buf)
649 tranBuff = append(tranBuff, buf[:readLen]...)
651 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
652 // into a slice of transactions
653 var transactions []Transaction
654 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
655 c.logger.Errorw("Error handling transaction", "err", err)
658 // iterate over all the transactions that were parsed from the byte slice and handle them
659 for _, t := range transactions {
660 if err := c.handleTransaction(&t); err != nil {
661 c.logger.Errorw("Error handling transaction", "err", err)
667 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
671 randID := make([]byte, 4)
673 data := binary.BigEndian.Uint32(randID[:])
675 s.PrivateChats[data] = &PrivateChat{
677 ClientConn: make(map[uint16]*ClientConn),
679 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
684 const dlFldrActionSendFile = 1
685 const dlFldrActionResumeFile = 2
686 const dlFldrActionNextFile = 3
688 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
689 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
690 defer dontPanic(s.Logger)
692 txBuf := make([]byte, 16)
693 if _, err := io.ReadFull(rwc, txBuf); err != nil {
698 if _, err := t.Write(txBuf); err != nil {
704 delete(s.fileTransfers, t.ReferenceNumber)
710 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
713 return errors.New("invalid transaction ID")
717 fileTransfer.ClientConn.transfersMU.Lock()
718 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
719 fileTransfer.ClientConn.transfersMU.Unlock()
722 rLogger := s.Logger.With(
723 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
724 "login", fileTransfer.ClientConn.Account.Login,
725 "name", string(fileTransfer.ClientConn.UserName),
728 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
733 switch fileTransfer.Type {
735 if err := s.bannerDownload(rwc); err != nil {
740 s.Stats.DownloadCounter += 1
743 if fileTransfer.fileResumeData != nil {
744 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
747 fw, err := newFileWrapper(s.FS, fullPath, 0)
752 rLogger.Infow("File download started", "filePath", fullPath)
754 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
755 if fileTransfer.options == nil {
756 // Start by sending flat file object to client
757 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
762 file, err := fw.dataForkReader()
767 br := bufio.NewReader(file)
768 if _, err := br.Discard(int(dataOffset)); err != nil {
772 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
776 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
777 if fileTransfer.fileResumeData == nil {
778 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
784 rFile, err := fw.rsrcForkFile()
789 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
794 s.Stats.UploadCounter += 1
798 // A file upload has three possible cases:
799 // 1) Upload a new file
800 // 2) Resume a partially transferred file
801 // 3) Replace a fully uploaded file
802 // We have to infer which case applies by inspecting what is already on the filesystem
804 // 1) Check for existing file:
805 _, err = os.Stat(fullPath)
807 return errors.New("existing file found at " + fullPath)
809 if errors.Is(err, fs.ErrNotExist) {
810 // If not found, open or create a new .incomplete file
811 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
817 f, err := newFileWrapper(s.FS, fullPath, 0)
822 rLogger.Infow("File upload started", "dstFile", fullPath)
824 rForkWriter := io.Discard
825 iForkWriter := io.Discard
826 if s.Config.PreserveResourceForks {
827 rForkWriter, err = f.rsrcForkWriter()
832 iForkWriter, err = f.infoForkWriter()
838 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
842 if err := file.Close(); err != nil {
846 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
850 rLogger.Infow("File upload complete", "dstFile", fullPath)
852 // Folder Download flow:
853 // 1. Get filePath from the transfer
854 // 2. Iterate over files
855 // 3. For each fileWrapper:
856 // Send fileWrapper header to client
857 // The client can reply in 3 ways:
859 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
860 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
862 // 2. If download of a fileWrapper is to be resumed:
864 // []byte{0x00, 0x02} // download folder action
865 // [2]byte // Resume data size
866 // []byte fileWrapper resume data (see myField_FileResumeData)
868 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
870 // When download is requested (case 2 or 3), server replies with:
871 // [4]byte - fileWrapper size
872 // []byte - Flattened File Object
874 // After every fileWrapper download, client could request next fileWrapper with:
875 // []byte{0x00, 0x03}
877 // This notifies the server to send the next item header
879 basePathLen := len(fullPath)
881 rLogger.Infow("Start folder download", "path", fullPath)
883 nextAction := make([]byte, 2)
884 if _, err := io.ReadFull(rwc, nextAction); err != nil {
889 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
890 s.Stats.DownloadCounter += 1
898 if strings.HasPrefix(info.Name(), ".") {
902 hlFile, err := newFileWrapper(s.FS, path, 0)
907 subPath := path[basePathLen+1:]
908 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
914 fileHeader := NewFileHeader(subPath, info.IsDir())
916 // Send the fileWrapper header to client
917 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
918 s.Logger.Errorf("error sending file header: %v", err)
922 // Read the client's Next Action request
923 if _, err := io.ReadFull(rwc, nextAction); err != nil {
927 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
931 switch nextAction[1] {
932 case dlFldrActionResumeFile:
933 // get size of resumeData
934 resumeDataByteLen := make([]byte, 2)
935 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
939 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
940 resumeDataBytes := make([]byte, resumeDataLen)
941 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
945 var frd FileResumeData
946 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
949 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
950 case dlFldrActionNextFile:
951 // client asked to skip this file
959 rLogger.Infow("File download started",
960 "fileName", info.Name(),
961 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
964 // Send file size to client
965 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
970 // Send ffo bytes to client
971 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
976 file, err := s.FS.Open(path)
981 // wr := bufio.NewWriterSize(rwc, 1460)
982 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
986 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
987 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
992 rFile, err := hlFile.rsrcForkFile()
997 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1002 // Read the client's Next Action request. This is always 3, I think?
1003 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1016 "Folder upload started",
1017 "dstPath", fullPath,
1018 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1019 "FolderItemCount", fileTransfer.FolderItemCount,
1022 // Check if the target folder exists. If not, create it.
1023 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1024 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1029 // Begin the folder upload flow by sending the "next file action" to client
1030 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1034 fileSize := make([]byte, 4)
1036 for i := 0; i < fileTransfer.ItemCount(); i++ {
1037 s.Stats.UploadCounter += 1
1040 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1043 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1046 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1050 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1052 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1057 "Folder upload continued",
1058 "FormattedPath", fu.FormattedPath(),
1059 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1060 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1063 if fu.IsFolder == [2]byte{0, 1} {
1064 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1065 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1070 // Tell client to send next file
1071 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1075 nextAction := dlFldrActionSendFile
1077 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1078 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1079 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1083 nextAction = dlFldrActionNextFile
1086 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1087 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1088 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1092 nextAction = dlFldrActionResumeFile
1095 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1100 case dlFldrActionNextFile:
1102 case dlFldrActionResumeFile:
1103 offset := make([]byte, 4)
1104 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1106 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1111 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1113 b, _ := fileResumeData.BinaryMarshal()
1115 bs := make([]byte, 2)
1116 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1118 if _, err := rwc.Write(append(bs, b...)); err != nil {
1122 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1126 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1130 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1135 case dlFldrActionSendFile:
1136 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1140 filePath := filepath.Join(fullPath, fu.FormattedPath())
1142 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1147 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1149 incWriter, err := hlFile.incFileWriter()
1154 rForkWriter := io.Discard
1155 iForkWriter := io.Discard
1156 if s.Config.PreserveResourceForks {
1157 iForkWriter, err = hlFile.infoForkWriter()
1162 rForkWriter, err = hlFile.rsrcForkWriter()
1167 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1171 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1176 // Tell client to send next fileWrapper
1177 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1182 rLogger.Infof("Folder upload complete")