10 "github.com/go-playground/validator/v10"
26 type contextKey string
28 var contextKeyReq = contextKey("req")
30 type requestCtx struct {
37 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
38 idleCheckInterval = 10 // time in seconds to check for idle users
39 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
42 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
46 Accounts map[string]*Account
48 Clients map[uint16]*ClientConn
49 fileTransfers map[[4]byte]*FileTransfer
53 Logger *zap.SugaredLogger
55 PrivateChatsMu sync.Mutex
56 PrivateChats map[uint32]*PrivateChat
64 FS FileStore // Storage backend to use for File storage
66 outbox chan Transaction
69 threadedNewsMux sync.Mutex
70 ThreadedNews *ThreadedNews
72 flatNewsMux sync.Mutex
76 banList map[string]*time.Time
79 func (s *Server) CurrentStats() Stats {
81 defer s.StatsMu.Unlock()
84 stats.CurrentlyConnected = len(s.Clients)
89 type PrivateChat struct {
91 ClientConn map[uint16]*ClientConn
94 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
95 s.Logger.Infow("Hotline server started",
97 "API port", fmt.Sprintf(":%v", s.Port),
98 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
101 var wg sync.WaitGroup
105 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
110 s.Logger.Fatal(s.Serve(ctx, ln))
115 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
121 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
129 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
131 conn, err := ln.Accept()
137 defer func() { _ = conn.Close() }()
139 err = s.handleFileTransfer(
140 context.WithValue(ctx, contextKeyReq, requestCtx{
141 remoteAddr: conn.RemoteAddr().String(),
147 s.Logger.Errorw("file transfer error", "reason", err)
153 func (s *Server) sendTransaction(t Transaction) error {
154 clientID, err := byteToInt(*t.clientID)
160 client := s.Clients[uint16(clientID)]
162 return fmt.Errorf("invalid client id %v", *t.clientID)
167 b, err := t.MarshalBinary()
172 if _, err := client.Connection.Write(b); err != nil {
179 func (s *Server) processOutbox() {
183 if err := s.sendTransaction(t); err != nil {
184 s.Logger.Errorw("error sending transaction", "err", err)
190 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
194 conn, err := ln.Accept()
196 s.Logger.Errorw("error accepting connection", "err", err)
198 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
199 remoteAddr: conn.RemoteAddr().String(),
203 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
206 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
208 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
210 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
218 agreementFile = "Agreement.txt"
221 // NewServer constructs a new Server from a config dir
222 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
225 Accounts: make(map[string]*Account),
227 Clients: make(map[uint16]*ClientConn),
228 fileTransfers: make(map[[4]byte]*FileTransfer),
229 PrivateChats: make(map[uint32]*PrivateChat),
230 ConfigDir: configDir,
232 NextGuestID: new(uint16),
233 outbox: make(chan Transaction),
234 Stats: &Stats{Since: time.Now()},
235 ThreadedNews: &ThreadedNews{},
237 banList: make(map[string]*time.Time),
242 // generate a new random passID for tracker registration
243 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
247 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
252 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
256 // try to load the ban list, but ignore errors as this file may not be present or may be empty
257 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
259 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
263 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
267 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
271 server.Config.FileRoot = filepath.Join(configDir, "Files")
273 *server.NextGuestID = 1
275 if server.Config.EnableTrackerRegistration {
277 "Tracker registration enabled",
278 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
279 "trackers", server.Config.Trackers,
284 tr := &TrackerRegistration{
285 UserCount: server.userCount(),
286 PassID: server.TrackerPassID[:],
287 Name: server.Config.Name,
288 Description: server.Config.Description,
290 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
291 for _, t := range server.Config.Trackers {
292 if err := register(t, tr); err != nil {
293 server.Logger.Errorw("unable to register with tracker %v", "error", err)
295 server.Logger.Debugw("Sent Tracker registration", "addr", t)
298 time.Sleep(trackerUpdateFrequency * time.Second)
303 // Start Client Keepalive go routine
304 go server.keepaliveHandler()
309 func (s *Server) userCount() int {
313 return len(s.Clients)
316 func (s *Server) keepaliveHandler() {
318 time.Sleep(idleCheckInterval * time.Second)
321 for _, c := range s.Clients {
322 c.IdleTime += idleCheckInterval
323 if c.IdleTime > userIdleSeconds && !c.Idle {
326 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
327 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
328 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
331 tranNotifyChangeUser,
332 NewField(fieldUserID, *c.ID),
333 NewField(fieldUserFlags, c.Flags),
334 NewField(fieldUserName, c.UserName),
335 NewField(fieldUserIconID, c.Icon),
343 func (s *Server) writeBanList() error {
345 defer s.banListMU.Unlock()
347 out, err := yaml.Marshal(s.banList)
351 err = ioutil.WriteFile(
352 filepath.Join(s.ConfigDir, "Banlist.yaml"),
359 func (s *Server) writeThreadedNews() error {
360 s.threadedNewsMux.Lock()
361 defer s.threadedNewsMux.Unlock()
363 out, err := yaml.Marshal(s.ThreadedNews)
367 err = s.FS.WriteFile(
368 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
375 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
379 clientConn := &ClientConn{
388 transfers: map[int]map[[4]byte]*FileTransfer{},
390 RemoteAddr: remoteAddr,
392 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
403 binary.BigEndian.PutUint16(*clientConn.ID, ID)
404 s.Clients[ID] = clientConn
409 // NewUser creates a new user account entry in the server map and config file
410 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
417 Password: hashAndSalt([]byte(password)),
420 out, err := yaml.Marshal(&account)
424 s.Accounts[login] = &account
426 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
429 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
433 // update renames the user login
434 if login != newLogin {
435 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
439 s.Accounts[newLogin] = s.Accounts[login]
440 delete(s.Accounts, login)
443 account := s.Accounts[newLogin]
444 account.Access = access
446 account.Password = password
448 out, err := yaml.Marshal(&account)
453 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
460 // DeleteUser deletes the user account
461 func (s *Server) DeleteUser(login string) error {
465 delete(s.Accounts, login)
467 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
470 func (s *Server) connectedUsers() []Field {
474 var connectedUsers []Field
475 for _, c := range sortedClients(s.Clients) {
483 Name: string(c.UserName),
485 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
487 return connectedUsers
490 func (s *Server) loadBanList(path string) error {
491 fh, err := os.Open(path)
495 decoder := yaml.NewDecoder(fh)
497 return decoder.Decode(s.banList)
500 // loadThreadedNews loads the threaded news data from disk
501 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
502 fh, err := os.Open(threadedNewsPath)
506 decoder := yaml.NewDecoder(fh)
508 return decoder.Decode(s.ThreadedNews)
511 // loadAccounts loads account data from disk
512 func (s *Server) loadAccounts(userDir string) error {
513 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
518 if len(matches) == 0 {
519 return errors.New("no user accounts found in " + userDir)
522 for _, file := range matches {
523 fh, err := s.FS.Open(file)
529 decoder := yaml.NewDecoder(fh)
530 if err := decoder.Decode(&account); err != nil {
534 s.Accounts[account.Login] = &account
539 func (s *Server) loadConfig(path string) error {
540 fh, err := s.FS.Open(path)
545 decoder := yaml.NewDecoder(fh)
546 err = decoder.Decode(s.Config)
551 validate := validator.New()
552 err = validate.Struct(s.Config)
559 // handleNewConnection takes a new net.Conn and performs the initial login sequence
560 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
561 defer dontPanic(s.Logger)
563 if err := Handshake(rwc); err != nil {
567 // Create a new scanner for parsing incoming bytes into transaction tokens
568 scanner := bufio.NewScanner(rwc)
569 scanner.Split(transactionScanner)
573 var clientLogin Transaction
574 if _, err := clientLogin.Write(scanner.Bytes()); err != nil {
578 c := s.NewClientConn(rwc, remoteAddr)
580 // check if remoteAddr is present in the ban list
581 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
584 s.outbox <- *NewTransaction(
587 NewField(fieldData, []byte("You are permanently banned on this server")),
588 NewField(fieldChatOptions, []byte{0, 0}),
590 time.Sleep(1 * time.Second)
592 } else if time.Now().Before(*banUntil) {
593 s.outbox <- *NewTransaction(
596 NewField(fieldData, []byte("You are temporarily banned on this server")),
597 NewField(fieldChatOptions, []byte{0, 0}),
599 time.Sleep(1 * time.Second)
606 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
607 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
608 c.Version = clientLogin.GetField(fieldVersion).Data
611 for _, char := range encodedLogin {
612 login += string(rune(255 - uint(char)))
618 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
620 // If authentication fails, send error reply and close connection
621 if !c.Authenticate(login, encodedPassword) {
622 t := c.NewErrReply(&clientLogin, "Incorrect login.")
623 b, err := t.MarshalBinary()
627 if _, err := rwc.Write(b); err != nil {
631 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
636 if clientLogin.GetField(fieldUserIconID).Data != nil {
637 c.Icon = clientLogin.GetField(fieldUserIconID).Data
640 c.Account = c.Server.Accounts[login]
642 if clientLogin.GetField(fieldUserName).Data != nil {
643 if c.Authorize(accessAnyName) {
644 c.UserName = clientLogin.GetField(fieldUserName).Data
646 c.UserName = []byte(c.Account.Name)
650 if c.Authorize(accessDisconUser) {
651 c.Flags = []byte{0, 2}
654 s.outbox <- c.NewReply(&clientLogin,
655 NewField(fieldVersion, []byte{0x00, 0xbe}),
656 NewField(fieldCommunityBannerID, []byte{0, 0}),
657 NewField(fieldServerName, []byte(s.Config.Name)),
660 // Send user access privs so client UI knows how to behave
661 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
663 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
664 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
665 // tranShowAgreement but with the NoServerAgreement field set to 1.
666 if c.Authorize(accessNoAgreement) {
667 // If client version is nil, then the client uses the 1.2.3 login behavior
668 if c.Version != nil {
669 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
672 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
675 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
676 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) {
678 c.logger = c.logger.With("name", string(c.UserName))
679 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
681 for _, t := range c.notifyOthers(
683 tranNotifyChangeUser, nil,
684 NewField(fieldUserName, c.UserName),
685 NewField(fieldUserID, *c.ID),
686 NewField(fieldUserIconID, c.Icon),
687 NewField(fieldUserFlags, c.Flags),
694 c.Server.Stats.ConnectionCounter += 1
695 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
696 c.Server.Stats.ConnectionPeak = len(s.Clients)
699 // Scan for new transactions and handle them as they come in.
701 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
702 // scanner re-uses the buffer for subsequent scans.
703 buf := make([]byte, len(scanner.Bytes()))
704 copy(buf, scanner.Bytes())
707 if _, err := t.Write(buf); err != nil {
711 if err := c.handleTransaction(t); err != nil {
712 c.logger.Errorw("Error handling transaction", "err", err)
718 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
719 s.PrivateChatsMu.Lock()
720 defer s.PrivateChatsMu.Unlock()
722 randID := make([]byte, 4)
724 data := binary.BigEndian.Uint32(randID[:])
726 s.PrivateChats[data] = &PrivateChat{
727 ClientConn: make(map[uint16]*ClientConn),
729 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
734 const dlFldrActionSendFile = 1
735 const dlFldrActionResumeFile = 2
736 const dlFldrActionNextFile = 3
738 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
739 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
740 defer dontPanic(s.Logger)
742 txBuf := make([]byte, 16)
743 if _, err := io.ReadFull(rwc, txBuf); err != nil {
748 if _, err := t.Write(txBuf); err != nil {
754 delete(s.fileTransfers, t.ReferenceNumber)
760 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
763 return errors.New("invalid transaction ID")
767 fileTransfer.ClientConn.transfersMU.Lock()
768 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
769 fileTransfer.ClientConn.transfersMU.Unlock()
772 rLogger := s.Logger.With(
773 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
774 "login", fileTransfer.ClientConn.Account.Login,
775 "name", string(fileTransfer.ClientConn.UserName),
778 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
783 switch fileTransfer.Type {
785 if err := s.bannerDownload(rwc); err != nil {
789 s.Stats.DownloadCounter += 1
790 s.Stats.DownloadsInProgress += 1
791 defer func() { s.Stats.DownloadsInProgress -= 1 }()
794 if fileTransfer.fileResumeData != nil {
795 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
798 fw, err := newFileWrapper(s.FS, fullPath, 0)
803 rLogger.Infow("File download started", "filePath", fullPath)
805 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
806 if fileTransfer.options == nil {
807 // Start by sending flat file object to client
808 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
813 file, err := fw.dataForkReader()
818 br := bufio.NewReader(file)
819 if _, err := br.Discard(int(dataOffset)); err != nil {
823 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
827 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
828 if fileTransfer.fileResumeData == nil {
829 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
835 rFile, err := fw.rsrcForkFile()
840 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
845 s.Stats.UploadCounter += 1
846 s.Stats.UploadsInProgress += 1
847 defer func() { s.Stats.UploadsInProgress -= 1 }()
851 // A file upload has three possible cases:
852 // 1) Upload a new file
853 // 2) Resume a partially transferred file
854 // 3) Replace a fully uploaded file
855 // We have to infer which case applies by inspecting what is already on the filesystem
857 // 1) Check for existing file:
858 _, err = os.Stat(fullPath)
860 return errors.New("existing file found at " + fullPath)
862 if errors.Is(err, fs.ErrNotExist) {
863 // If not found, open or create a new .incomplete file
864 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
870 f, err := newFileWrapper(s.FS, fullPath, 0)
875 rLogger.Infow("File upload started", "dstFile", fullPath)
877 rForkWriter := io.Discard
878 iForkWriter := io.Discard
879 if s.Config.PreserveResourceForks {
880 rForkWriter, err = f.rsrcForkWriter()
885 iForkWriter, err = f.infoForkWriter()
891 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
895 if err := file.Close(); err != nil {
899 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
903 rLogger.Infow("File upload complete", "dstFile", fullPath)
906 s.Stats.DownloadCounter += 1
907 s.Stats.DownloadsInProgress += 1
908 defer func() { s.Stats.DownloadsInProgress -= 1 }()
910 // Folder Download flow:
911 // 1. Get filePath from the transfer
912 // 2. Iterate over files
913 // 3. For each fileWrapper:
914 // Send fileWrapper header to client
915 // The client can reply in 3 ways:
917 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
918 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
920 // 2. If download of a fileWrapper is to be resumed:
922 // []byte{0x00, 0x02} // download folder action
923 // [2]byte // Resume data size
924 // []byte fileWrapper resume data (see myField_FileResumeData)
926 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
928 // When download is requested (case 2 or 3), server replies with:
929 // [4]byte - fileWrapper size
930 // []byte - Flattened File Object
932 // After every fileWrapper download, client could request next fileWrapper with:
933 // []byte{0x00, 0x03}
935 // This notifies the server to send the next item header
937 basePathLen := len(fullPath)
939 rLogger.Infow("Start folder download", "path", fullPath)
941 nextAction := make([]byte, 2)
942 if _, err := io.ReadFull(rwc, nextAction); err != nil {
947 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
948 s.Stats.DownloadCounter += 1
956 if strings.HasPrefix(info.Name(), ".") {
960 hlFile, err := newFileWrapper(s.FS, path, 0)
965 subPath := path[basePathLen+1:]
966 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
972 fileHeader := NewFileHeader(subPath, info.IsDir())
974 // Send the fileWrapper header to client
975 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
976 s.Logger.Errorf("error sending file header: %v", err)
980 // Read the client's Next Action request
981 if _, err := io.ReadFull(rwc, nextAction); err != nil {
985 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
989 switch nextAction[1] {
990 case dlFldrActionResumeFile:
991 // get size of resumeData
992 resumeDataByteLen := make([]byte, 2)
993 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
997 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
998 resumeDataBytes := make([]byte, resumeDataLen)
999 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1003 var frd FileResumeData
1004 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1007 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1008 case dlFldrActionNextFile:
1009 // client asked to skip this file
1017 rLogger.Infow("File download started",
1018 "fileName", info.Name(),
1019 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1022 // Send file size to client
1023 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1028 // Send ffo bytes to client
1029 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1034 file, err := s.FS.Open(path)
1039 // wr := bufio.NewWriterSize(rwc, 1460)
1040 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1044 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1045 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1050 rFile, err := hlFile.rsrcForkFile()
1055 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1060 // Read the client's Next Action request. This is always 3, I think?
1061 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1073 s.Stats.UploadCounter += 1
1074 s.Stats.UploadsInProgress += 1
1075 defer func() { s.Stats.UploadsInProgress -= 1 }()
1077 "Folder upload started",
1078 "dstPath", fullPath,
1079 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1080 "FolderItemCount", fileTransfer.FolderItemCount,
1083 // Check if the target folder exists. If not, create it.
1084 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1085 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1090 // Begin the folder upload flow by sending the "next file action" to client
1091 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1095 fileSize := make([]byte, 4)
1097 for i := 0; i < fileTransfer.ItemCount(); i++ {
1098 s.Stats.UploadCounter += 1
1101 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1104 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1107 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1111 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1113 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1118 "Folder upload continued",
1119 "FormattedPath", fu.FormattedPath(),
1120 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1121 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1124 if fu.IsFolder == [2]byte{0, 1} {
1125 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1126 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1131 // Tell client to send next file
1132 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1136 nextAction := dlFldrActionSendFile
1138 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1139 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1140 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1144 nextAction = dlFldrActionNextFile
1147 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1148 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1149 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1153 nextAction = dlFldrActionResumeFile
1156 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1161 case dlFldrActionNextFile:
1163 case dlFldrActionResumeFile:
1164 offset := make([]byte, 4)
1165 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1167 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1172 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1174 b, _ := fileResumeData.BinaryMarshal()
1176 bs := make([]byte, 2)
1177 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1179 if _, err := rwc.Write(append(bs, b...)); err != nil {
1183 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1187 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1191 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1196 case dlFldrActionSendFile:
1197 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1201 filePath := filepath.Join(fullPath, fu.FormattedPath())
1203 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1208 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1210 incWriter, err := hlFile.incFileWriter()
1215 rForkWriter := io.Discard
1216 iForkWriter := io.Discard
1217 if s.Config.PreserveResourceForks {
1218 iForkWriter, err = hlFile.infoForkWriter()
1223 rForkWriter, err = hlFile.rsrcForkWriter()
1228 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1232 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1237 // Tell client to send next fileWrapper
1238 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1243 rLogger.Infof("Folder upload complete")