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 banList map[string]*time.Time
74 type PrivateChat struct {
76 ClientConn map[uint16]*ClientConn
79 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
80 s.Logger.Infow("Hotline server started",
82 "API port", fmt.Sprintf(":%v", s.Port),
83 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
90 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
95 s.Logger.Fatal(s.Serve(ctx, ln))
100 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
106 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
114 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
116 conn, err := ln.Accept()
122 defer func() { _ = conn.Close() }()
124 err = s.handleFileTransfer(
125 context.WithValue(ctx, contextKeyReq, requestCtx{
126 remoteAddr: conn.RemoteAddr().String(),
132 s.Logger.Errorw("file transfer error", "reason", err)
138 func (s *Server) sendTransaction(t Transaction) error {
139 clientID, err := byteToInt(*t.clientID)
145 client := s.Clients[uint16(clientID)]
147 return fmt.Errorf("invalid client id %v", *t.clientID)
152 b, err := t.MarshalBinary()
157 if _, err := client.Connection.Write(b); err != nil {
164 func (s *Server) processOutbox() {
168 if err := s.sendTransaction(t); err != nil {
169 s.Logger.Errorw("error sending transaction", "err", err)
175 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
179 conn, err := ln.Accept()
181 s.Logger.Errorw("error accepting connection", "err", err)
183 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
184 remoteAddr: conn.RemoteAddr().String(),
188 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
191 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
193 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
195 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
203 agreementFile = "Agreement.txt"
206 // NewServer constructs a new Server from a config dir
207 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
210 Accounts: make(map[string]*Account),
212 Clients: make(map[uint16]*ClientConn),
213 fileTransfers: make(map[[4]byte]*FileTransfer),
214 PrivateChats: make(map[uint32]*PrivateChat),
215 ConfigDir: configDir,
217 NextGuestID: new(uint16),
218 outbox: make(chan Transaction),
219 Stats: &Stats{StartTime: time.Now()},
220 ThreadedNews: &ThreadedNews{},
222 banList: make(map[string]*time.Time),
227 // generate a new random passID for tracker registration
228 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
232 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
237 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
241 // try to load the ban list, but ignore errors as this file may not be present or may be empty
242 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
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) writeBanList() error {
330 defer s.banListMU.Unlock()
332 out, err := yaml.Marshal(s.banList)
336 err = ioutil.WriteFile(
337 filepath.Join(s.ConfigDir, "Banlist.yaml"),
344 func (s *Server) writeThreadedNews() error {
348 out, err := yaml.Marshal(s.ThreadedNews)
352 err = ioutil.WriteFile(
353 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
360 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
364 clientConn := &ClientConn{
373 transfers: map[int]map[[4]byte]*FileTransfer{},
375 RemoteAddr: remoteAddr,
377 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
388 binary.BigEndian.PutUint16(*clientConn.ID, ID)
389 s.Clients[ID] = clientConn
394 // NewUser creates a new user account entry in the server map and config file
395 func (s *Server) NewUser(login, name, password string, access []byte) error {
402 Password: hashAndSalt([]byte(password)),
405 out, err := yaml.Marshal(&account)
409 s.Accounts[login] = &account
411 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
414 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
418 // update renames the user login
419 if login != newLogin {
420 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
424 s.Accounts[newLogin] = s.Accounts[login]
425 delete(s.Accounts, login)
428 account := s.Accounts[newLogin]
429 account.Access = &access
431 account.Password = password
433 out, err := yaml.Marshal(&account)
438 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
445 // DeleteUser deletes the user account
446 func (s *Server) DeleteUser(login string) error {
450 delete(s.Accounts, login)
452 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
455 func (s *Server) connectedUsers() []Field {
459 var connectedUsers []Field
460 for _, c := range sortedClients(s.Clients) {
468 Name: string(c.UserName),
470 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
472 return connectedUsers
475 func (s *Server) loadBanList(path string) error {
476 fh, err := os.Open(path)
480 decoder := yaml.NewDecoder(fh)
482 return decoder.Decode(s.banList)
485 // loadThreadedNews loads the threaded news data from disk
486 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
487 fh, err := os.Open(threadedNewsPath)
491 decoder := yaml.NewDecoder(fh)
493 return decoder.Decode(s.ThreadedNews)
496 // loadAccounts loads account data from disk
497 func (s *Server) loadAccounts(userDir string) error {
498 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
503 if len(matches) == 0 {
504 return errors.New("no user accounts found in " + userDir)
507 for _, file := range matches {
508 fh, err := s.FS.Open(file)
514 decoder := yaml.NewDecoder(fh)
515 if err := decoder.Decode(&account); err != nil {
519 s.Accounts[account.Login] = &account
524 func (s *Server) loadConfig(path string) error {
525 fh, err := s.FS.Open(path)
530 decoder := yaml.NewDecoder(fh)
531 err = decoder.Decode(s.Config)
536 validate := validator.New()
537 err = validate.Struct(s.Config)
544 // dontPanic logs panics instead of crashing
545 func dontPanic(logger *zap.SugaredLogger) {
546 if r := recover(); r != nil {
547 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
548 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
552 // handleNewConnection takes a new net.Conn and performs the initial login sequence
553 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
554 defer dontPanic(s.Logger)
556 if err := Handshake(rwc); err != nil {
560 // Create a new scanner for parsing incoming bytes into transaction tokens
561 scanner := bufio.NewScanner(rwc)
562 scanner.Split(transactionScanner)
566 clientLogin, _, err := ReadTransaction(scanner.Bytes())
571 c := s.NewClientConn(rwc, remoteAddr)
573 // check if remoteAddr is present in the ban list
574 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
577 s.outbox <- *NewTransaction(
580 NewField(fieldData, []byte("You are permanently banned on this server")),
581 NewField(fieldChatOptions, []byte{0, 0}),
583 time.Sleep(1 * time.Second)
585 } else if time.Now().Before(*banUntil) {
586 s.outbox <- *NewTransaction(
589 NewField(fieldData, []byte("You are temporarily banned on this server")),
590 NewField(fieldChatOptions, []byte{0, 0}),
592 time.Sleep(1 * time.Second)
599 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
600 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
601 c.Version = clientLogin.GetField(fieldVersion).Data
604 for _, char := range encodedLogin {
605 login += string(rune(255 - uint(char)))
611 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
613 // If authentication fails, send error reply and close connection
614 if !c.Authenticate(login, encodedPassword) {
615 t := c.NewErrReply(clientLogin, "Incorrect login.")
616 b, err := t.MarshalBinary()
620 if _, err := rwc.Write(b); err != nil {
624 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
629 if clientLogin.GetField(fieldUserIconID).Data != nil {
630 c.Icon = clientLogin.GetField(fieldUserIconID).Data
633 c.Account = c.Server.Accounts[login]
635 if clientLogin.GetField(fieldUserName).Data != nil {
636 if c.Authorize(accessAnyName) {
637 c.UserName = clientLogin.GetField(fieldUserName).Data
639 c.UserName = []byte(c.Account.Name)
643 if c.Authorize(accessDisconUser) {
644 c.Flags = []byte{0, 2}
647 s.outbox <- c.NewReply(clientLogin,
648 NewField(fieldVersion, []byte{0x00, 0xbe}),
649 NewField(fieldCommunityBannerID, []byte{0, 0}),
650 NewField(fieldServerName, []byte(s.Config.Name)),
653 // Send user access privs so client UI knows how to behave
654 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
656 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
657 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
658 // tranShowAgreement but with the NoServerAgreement field set to 1.
659 if c.Authorize(accessNoAgreement) {
660 // If client version is nil, then the client uses the 1.2.3 login behavior
661 if c.Version != nil {
662 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
665 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
668 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
669 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) {
671 c.logger = c.logger.With("name", string(c.UserName))
672 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", c.Version))
674 for _, t := range c.notifyOthers(
676 tranNotifyChangeUser, nil,
677 NewField(fieldUserName, c.UserName),
678 NewField(fieldUserID, *c.ID),
679 NewField(fieldUserIconID, c.Icon),
680 NewField(fieldUserFlags, c.Flags),
687 c.Server.Stats.LoginCount += 1
689 // Scan for new transactions and handle them as they come in.
691 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
692 // scanner re-uses the buffer for subsequent scans.
693 buf := make([]byte, len(scanner.Bytes()))
694 copy(buf, scanner.Bytes())
696 t, _, err := ReadTransaction(buf)
700 if err := c.handleTransaction(*t); err != nil {
701 c.logger.Errorw("Error handling transaction", "err", err)
707 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
711 randID := make([]byte, 4)
713 data := binary.BigEndian.Uint32(randID[:])
715 s.PrivateChats[data] = &PrivateChat{
717 ClientConn: make(map[uint16]*ClientConn),
719 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
724 const dlFldrActionSendFile = 1
725 const dlFldrActionResumeFile = 2
726 const dlFldrActionNextFile = 3
728 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
729 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
730 defer dontPanic(s.Logger)
732 txBuf := make([]byte, 16)
733 if _, err := io.ReadFull(rwc, txBuf); err != nil {
738 if _, err := t.Write(txBuf); err != nil {
744 delete(s.fileTransfers, t.ReferenceNumber)
750 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
753 return errors.New("invalid transaction ID")
757 fileTransfer.ClientConn.transfersMU.Lock()
758 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
759 fileTransfer.ClientConn.transfersMU.Unlock()
762 rLogger := s.Logger.With(
763 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
764 "login", fileTransfer.ClientConn.Account.Login,
765 "name", string(fileTransfer.ClientConn.UserName),
768 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
773 switch fileTransfer.Type {
775 if err := s.bannerDownload(rwc); err != nil {
780 s.Stats.DownloadCounter += 1
783 if fileTransfer.fileResumeData != nil {
784 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
787 fw, err := newFileWrapper(s.FS, fullPath, 0)
792 rLogger.Infow("File download started", "filePath", fullPath)
794 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
795 if fileTransfer.options == nil {
796 // Start by sending flat file object to client
797 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
802 file, err := fw.dataForkReader()
807 br := bufio.NewReader(file)
808 if _, err := br.Discard(int(dataOffset)); err != nil {
812 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
816 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
817 if fileTransfer.fileResumeData == nil {
818 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
824 rFile, err := fw.rsrcForkFile()
829 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
834 s.Stats.UploadCounter += 1
838 // A file upload has three possible cases:
839 // 1) Upload a new file
840 // 2) Resume a partially transferred file
841 // 3) Replace a fully uploaded file
842 // We have to infer which case applies by inspecting what is already on the filesystem
844 // 1) Check for existing file:
845 _, err = os.Stat(fullPath)
847 return errors.New("existing file found at " + fullPath)
849 if errors.Is(err, fs.ErrNotExist) {
850 // If not found, open or create a new .incomplete file
851 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
857 f, err := newFileWrapper(s.FS, fullPath, 0)
862 rLogger.Infow("File upload started", "dstFile", fullPath)
864 rForkWriter := io.Discard
865 iForkWriter := io.Discard
866 if s.Config.PreserveResourceForks {
867 rForkWriter, err = f.rsrcForkWriter()
872 iForkWriter, err = f.infoForkWriter()
878 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
882 if err := file.Close(); err != nil {
886 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
890 rLogger.Infow("File upload complete", "dstFile", fullPath)
892 // Folder Download flow:
893 // 1. Get filePath from the transfer
894 // 2. Iterate over files
895 // 3. For each fileWrapper:
896 // Send fileWrapper header to client
897 // The client can reply in 3 ways:
899 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
900 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
902 // 2. If download of a fileWrapper is to be resumed:
904 // []byte{0x00, 0x02} // download folder action
905 // [2]byte // Resume data size
906 // []byte fileWrapper resume data (see myField_FileResumeData)
908 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
910 // When download is requested (case 2 or 3), server replies with:
911 // [4]byte - fileWrapper size
912 // []byte - Flattened File Object
914 // After every fileWrapper download, client could request next fileWrapper with:
915 // []byte{0x00, 0x03}
917 // This notifies the server to send the next item header
919 basePathLen := len(fullPath)
921 rLogger.Infow("Start folder download", "path", fullPath)
923 nextAction := make([]byte, 2)
924 if _, err := io.ReadFull(rwc, nextAction); err != nil {
929 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
930 s.Stats.DownloadCounter += 1
938 if strings.HasPrefix(info.Name(), ".") {
942 hlFile, err := newFileWrapper(s.FS, path, 0)
947 subPath := path[basePathLen+1:]
948 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
954 fileHeader := NewFileHeader(subPath, info.IsDir())
956 // Send the fileWrapper header to client
957 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
958 s.Logger.Errorf("error sending file header: %v", err)
962 // Read the client's Next Action request
963 if _, err := io.ReadFull(rwc, nextAction); err != nil {
967 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
971 switch nextAction[1] {
972 case dlFldrActionResumeFile:
973 // get size of resumeData
974 resumeDataByteLen := make([]byte, 2)
975 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
979 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
980 resumeDataBytes := make([]byte, resumeDataLen)
981 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
985 var frd FileResumeData
986 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
989 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
990 case dlFldrActionNextFile:
991 // client asked to skip this file
999 rLogger.Infow("File download started",
1000 "fileName", info.Name(),
1001 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1004 // Send file size to client
1005 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1010 // Send ffo bytes to client
1011 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1016 file, err := s.FS.Open(path)
1021 // wr := bufio.NewWriterSize(rwc, 1460)
1022 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1026 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1027 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1032 rFile, err := hlFile.rsrcForkFile()
1037 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1042 // Read the client's Next Action request. This is always 3, I think?
1043 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1056 "Folder upload started",
1057 "dstPath", fullPath,
1058 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1059 "FolderItemCount", fileTransfer.FolderItemCount,
1062 // Check if the target folder exists. If not, create it.
1063 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1064 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1069 // Begin the folder upload flow by sending the "next file action" to client
1070 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1074 fileSize := make([]byte, 4)
1076 for i := 0; i < fileTransfer.ItemCount(); i++ {
1077 s.Stats.UploadCounter += 1
1080 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1083 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1086 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1090 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1092 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1097 "Folder upload continued",
1098 "FormattedPath", fu.FormattedPath(),
1099 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1100 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1103 if fu.IsFolder == [2]byte{0, 1} {
1104 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1105 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1110 // Tell client to send next file
1111 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1115 nextAction := dlFldrActionSendFile
1117 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1118 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1119 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1123 nextAction = dlFldrActionNextFile
1126 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1127 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1128 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1132 nextAction = dlFldrActionResumeFile
1135 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1140 case dlFldrActionNextFile:
1142 case dlFldrActionResumeFile:
1143 offset := make([]byte, 4)
1144 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1146 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1151 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1153 b, _ := fileResumeData.BinaryMarshal()
1155 bs := make([]byte, 2)
1156 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1158 if _, err := rwc.Write(append(bs, b...)); err != nil {
1162 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1166 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1170 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1175 case dlFldrActionSendFile:
1176 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1180 filePath := filepath.Join(fullPath, fu.FormattedPath())
1182 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1187 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1189 incWriter, err := hlFile.incFileWriter()
1194 rForkWriter := io.Discard
1195 iForkWriter := io.Discard
1196 if s.Config.PreserveResourceForks {
1197 iForkWriter, err = hlFile.infoForkWriter()
1202 rForkWriter, err = hlFile.rsrcForkWriter()
1207 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1211 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1216 // Tell client to send next fileWrapper
1217 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1222 rLogger.Infof("Folder upload complete")