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 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
197 s.Logger.Infow("New client connection established", "RemoteAddr", conn.RemoteAddr())
199 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
201 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
209 agreementFile = "Agreement.txt"
212 // NewServer constructs a new Server from a config dir
213 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
216 Accounts: make(map[string]*Account),
218 Clients: make(map[uint16]*ClientConn),
219 fileTransfers: make(map[[4]byte]*FileTransfer),
220 PrivateChats: make(map[uint32]*PrivateChat),
221 ConfigDir: configDir,
223 NextGuestID: new(uint16),
224 outbox: make(chan Transaction),
225 Stats: &Stats{StartTime: time.Now()},
226 ThreadedNews: &ThreadedNews{},
232 // generate a new random passID for tracker registration
233 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
237 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
242 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
246 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
250 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
254 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
258 server.Config.FileRoot = filepath.Join(configDir, "Files")
260 *server.NextGuestID = 1
262 if server.Config.EnableTrackerRegistration {
264 "Tracker registration enabled",
265 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
266 "trackers", server.Config.Trackers,
271 tr := &TrackerRegistration{
272 UserCount: server.userCount(),
273 PassID: server.TrackerPassID[:],
274 Name: server.Config.Name,
275 Description: server.Config.Description,
277 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
278 for _, t := range server.Config.Trackers {
279 if err := register(t, tr); err != nil {
280 server.Logger.Errorw("unable to register with tracker %v", "error", err)
282 server.Logger.Infow("Sent Tracker registration", "data", tr)
285 time.Sleep(trackerUpdateFrequency * time.Second)
290 // Start Client Keepalive go routine
291 go server.keepaliveHandler()
296 func (s *Server) userCount() int {
300 return len(s.Clients)
303 func (s *Server) keepaliveHandler() {
305 time.Sleep(idleCheckInterval * time.Second)
308 for _, c := range s.Clients {
309 c.IdleTime += idleCheckInterval
310 if c.IdleTime > userIdleSeconds && !c.Idle {
313 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
314 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
315 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
318 tranNotifyChangeUser,
319 NewField(fieldUserID, *c.ID),
320 NewField(fieldUserFlags, *c.Flags),
321 NewField(fieldUserName, c.UserName),
322 NewField(fieldUserIconID, *c.Icon),
330 func (s *Server) writeThreadedNews() error {
334 out, err := yaml.Marshal(s.ThreadedNews)
338 err = ioutil.WriteFile(
339 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
346 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
350 clientConn := &ClientConn{
353 Flags: &[]byte{0, 0},
359 transfers: map[int]map[[4]byte]*FileTransfer{},
361 RemoteAddr: remoteAddr,
363 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
374 binary.BigEndian.PutUint16(*clientConn.ID, ID)
375 s.Clients[ID] = clientConn
380 // NewUser creates a new user account entry in the server map and config file
381 func (s *Server) NewUser(login, name, password string, access []byte) error {
388 Password: hashAndSalt([]byte(password)),
391 out, err := yaml.Marshal(&account)
395 s.Accounts[login] = &account
397 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
400 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
404 // update renames the user login
405 if login != newLogin {
406 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
410 s.Accounts[newLogin] = s.Accounts[login]
411 delete(s.Accounts, login)
414 account := s.Accounts[newLogin]
415 account.Access = &access
417 account.Password = password
419 out, err := yaml.Marshal(&account)
424 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
431 // DeleteUser deletes the user account
432 func (s *Server) DeleteUser(login string) error {
436 delete(s.Accounts, login)
438 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
441 func (s *Server) connectedUsers() []Field {
445 var connectedUsers []Field
446 for _, c := range sortedClients(s.Clients) {
454 Name: string(c.UserName),
456 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
458 return connectedUsers
461 // loadThreadedNews loads the threaded news data from disk
462 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
463 fh, err := os.Open(threadedNewsPath)
467 decoder := yaml.NewDecoder(fh)
469 return decoder.Decode(s.ThreadedNews)
472 // loadAccounts loads account data from disk
473 func (s *Server) loadAccounts(userDir string) error {
474 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
479 if len(matches) == 0 {
480 return errors.New("no user accounts found in " + userDir)
483 for _, file := range matches {
484 fh, err := s.FS.Open(file)
490 decoder := yaml.NewDecoder(fh)
491 if err := decoder.Decode(&account); err != nil {
495 s.Accounts[account.Login] = &account
500 func (s *Server) loadConfig(path string) error {
501 fh, err := s.FS.Open(path)
506 decoder := yaml.NewDecoder(fh)
507 err = decoder.Decode(s.Config)
512 validate := validator.New()
513 err = validate.Struct(s.Config)
521 minTransactionLen = 22 // minimum length of any transaction
524 // dontPanic recovers and logs panics instead of crashing
525 // TODO: remove this after known issues are fixed
526 func dontPanic(logger *zap.SugaredLogger) {
527 if r := recover(); r != nil {
528 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
529 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
533 // handleNewConnection takes a new net.Conn and performs the initial login sequence
534 func (s *Server) handleNewConnection(ctx context.Context, conn io.ReadWriteCloser, remoteAddr string) error {
535 defer dontPanic(s.Logger)
537 if err := Handshake(conn); err != nil {
541 buf := make([]byte, 1024)
542 // TODO: fix potential short read with io.ReadFull
543 readLen, err := conn.Read(buf)
544 if readLen < minTransactionLen {
551 clientLogin, _, err := ReadTransaction(buf[:readLen])
556 c := s.NewClientConn(conn, remoteAddr)
559 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
560 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
561 *c.Version = clientLogin.GetField(fieldVersion).Data
564 for _, char := range encodedLogin {
565 login += string(rune(255 - uint(char)))
571 // If authentication fails, send error reply and close connection
572 if !c.Authenticate(login, encodedPassword) {
573 t := c.NewErrReply(clientLogin, "Incorrect login.")
574 b, err := t.MarshalBinary()
578 if _, err := conn.Write(b); err != nil {
581 return fmt.Errorf("incorrect login")
584 if clientLogin.GetField(fieldUserName).Data != nil {
585 c.UserName = clientLogin.GetField(fieldUserName).Data
588 if clientLogin.GetField(fieldUserIconID).Data != nil {
589 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
592 c.Account = c.Server.Accounts[login]
594 if c.Authorize(accessDisconUser) {
595 *c.Flags = []byte{0, 2}
598 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
600 c.logger.Infow("Client connection received", "version", fmt.Sprintf("%x", *c.Version))
602 s.outbox <- c.NewReply(clientLogin,
603 NewField(fieldVersion, []byte{0x00, 0xbe}),
604 NewField(fieldCommunityBannerID, []byte{0, 0}),
605 NewField(fieldServerName, []byte(s.Config.Name)),
608 // Send user access privs so client UI knows how to behave
609 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
611 // Show agreement to client
612 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
614 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
615 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
617 c.logger = c.logger.With("name", string(c.UserName))
619 for _, t := range c.notifyOthers(
621 tranNotifyChangeUser, nil,
622 NewField(fieldUserName, c.UserName),
623 NewField(fieldUserID, *c.ID),
624 NewField(fieldUserIconID, *c.Icon),
625 NewField(fieldUserFlags, *c.Flags),
632 c.Server.Stats.LoginCount += 1
634 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
635 tranBuff := make([]byte, 0)
637 // Infinite loop where take action on incoming client requests until the connection is closed
639 buf = make([]byte, readBuffSize)
640 tranBuff = tranBuff[tReadlen:]
642 readLen, err := c.Connection.Read(buf)
646 tranBuff = append(tranBuff, buf[:readLen]...)
648 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
649 // into a slice of transactions
650 var transactions []Transaction
651 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
652 c.logger.Errorw("Error handling transaction", "err", err)
655 // iterate over all the transactions that were parsed from the byte slice and handle them
656 for _, t := range transactions {
657 if err := c.handleTransaction(&t); err != nil {
658 c.logger.Errorw("Error handling transaction", "err", err)
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 {
701 delete(s.fileTransfers, t.ReferenceNumber)
707 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
710 return errors.New("invalid transaction ID")
714 fileTransfer.ClientConn.transfersMU.Lock()
715 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
716 fileTransfer.ClientConn.transfersMU.Unlock()
719 rLogger := s.Logger.With(
720 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
721 "login", fileTransfer.ClientConn.Account.Login,
722 "name", string(fileTransfer.ClientConn.UserName),
725 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
730 switch fileTransfer.Type {
732 if err := s.bannerDownload(rwc); err != nil {
737 s.Stats.DownloadCounter += 1
740 if fileTransfer.fileResumeData != nil {
741 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
744 fw, err := newFileWrapper(s.FS, fullPath, 0)
749 rLogger.Infow("File download started", "filePath", fullPath)
751 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
752 if fileTransfer.options == nil {
753 // Start by sending flat file object to client
754 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
759 file, err := fw.dataForkReader()
764 br := bufio.NewReader(file)
765 if _, err := br.Discard(int(dataOffset)); err != nil {
769 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
773 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
774 if fileTransfer.fileResumeData == nil {
775 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
781 rFile, err := fw.rsrcForkFile()
786 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
791 s.Stats.UploadCounter += 1
795 // A file upload has three possible cases:
796 // 1) Upload a new file
797 // 2) Resume a partially transferred file
798 // 3) Replace a fully uploaded file
799 // We have to infer which case applies by inspecting what is already on the filesystem
801 // 1) Check for existing file:
802 _, err = os.Stat(fullPath)
804 return errors.New("existing file found at " + fullPath)
806 if errors.Is(err, fs.ErrNotExist) {
807 // If not found, open or create a new .incomplete file
808 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
814 f, err := newFileWrapper(s.FS, fullPath, 0)
819 rLogger.Infow("File upload started", "dstFile", fullPath)
821 rForkWriter := io.Discard
822 iForkWriter := io.Discard
823 if s.Config.PreserveResourceForks {
824 rForkWriter, err = f.rsrcForkWriter()
829 iForkWriter, err = f.infoForkWriter()
835 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
839 if err := file.Close(); err != nil {
843 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
847 rLogger.Infow("File upload complete", "dstFile", fullPath)
849 // Folder Download flow:
850 // 1. Get filePath from the transfer
851 // 2. Iterate over files
852 // 3. For each fileWrapper:
853 // Send fileWrapper header to client
854 // The client can reply in 3 ways:
856 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
857 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
859 // 2. If download of a fileWrapper is to be resumed:
861 // []byte{0x00, 0x02} // download folder action
862 // [2]byte // Resume data size
863 // []byte fileWrapper resume data (see myField_FileResumeData)
865 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
867 // When download is requested (case 2 or 3), server replies with:
868 // [4]byte - fileWrapper size
869 // []byte - Flattened File Object
871 // After every fileWrapper download, client could request next fileWrapper with:
872 // []byte{0x00, 0x03}
874 // This notifies the server to send the next item header
876 basePathLen := len(fullPath)
878 rLogger.Infow("Start folder download", "path", fullPath)
880 nextAction := make([]byte, 2)
881 if _, err := io.ReadFull(rwc, nextAction); err != nil {
886 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
887 s.Stats.DownloadCounter += 1
895 if strings.HasPrefix(info.Name(), ".") {
899 hlFile, err := newFileWrapper(s.FS, path, 0)
904 subPath := path[basePathLen+1:]
905 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
911 fileHeader := NewFileHeader(subPath, info.IsDir())
913 // Send the fileWrapper header to client
914 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
915 s.Logger.Errorf("error sending file header: %v", err)
919 // Read the client's Next Action request
920 if _, err := io.ReadFull(rwc, nextAction); err != nil {
924 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
928 switch nextAction[1] {
929 case dlFldrActionResumeFile:
930 // get size of resumeData
931 resumeDataByteLen := make([]byte, 2)
932 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
936 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
937 resumeDataBytes := make([]byte, resumeDataLen)
938 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
942 var frd FileResumeData
943 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
946 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
947 case dlFldrActionNextFile:
948 // client asked to skip this file
956 rLogger.Infow("File download started",
957 "fileName", info.Name(),
958 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
961 // Send file size to client
962 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
967 // Send ffo bytes to client
968 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
973 file, err := s.FS.Open(path)
978 // wr := bufio.NewWriterSize(rwc, 1460)
979 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
983 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
984 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
989 rFile, err := hlFile.rsrcForkFile()
994 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
999 // Read the client's Next Action request. This is always 3, I think?
1000 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1013 "Folder upload started",
1014 "dstPath", fullPath,
1015 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1016 "FolderItemCount", fileTransfer.FolderItemCount,
1019 // Check if the target folder exists. If not, create it.
1020 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1021 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1026 // Begin the folder upload flow by sending the "next file action" to client
1027 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1031 fileSize := make([]byte, 4)
1033 for i := 0; i < fileTransfer.ItemCount(); i++ {
1034 s.Stats.UploadCounter += 1
1037 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1040 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1043 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1047 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1049 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1054 "Folder upload continued",
1055 "FormattedPath", fu.FormattedPath(),
1056 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1057 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1060 if fu.IsFolder == [2]byte{0, 1} {
1061 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1062 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1067 // Tell client to send next file
1068 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1072 nextAction := dlFldrActionSendFile
1074 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1075 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1076 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1080 nextAction = dlFldrActionNextFile
1083 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1084 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1085 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1089 nextAction = dlFldrActionResumeFile
1092 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1097 case dlFldrActionNextFile:
1099 case dlFldrActionResumeFile:
1100 offset := make([]byte, 4)
1101 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1103 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1108 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1110 b, _ := fileResumeData.BinaryMarshal()
1112 bs := make([]byte, 2)
1113 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1115 if _, err := rwc.Write(append(bs, b...)); err != nil {
1119 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1123 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1127 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1132 case dlFldrActionSendFile:
1133 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1137 filePath := filepath.Join(fullPath, fu.FormattedPath())
1139 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1144 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1146 incWriter, err := hlFile.incFileWriter()
1151 rForkWriter := io.Discard
1152 iForkWriter := io.Discard
1153 if s.Config.PreserveResourceForks {
1154 iForkWriter, err = hlFile.infoForkWriter()
1159 rForkWriter, err = hlFile.rsrcForkWriter()
1164 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1168 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1173 // Tell client to send next fileWrapper
1174 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1179 rLogger.Infof("Folder upload complete")