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 clientID, err := byteToInt(*t.clientID)
142 client := s.Clients[uint16(clientID)]
144 return fmt.Errorf("invalid client id %v", *t.clientID)
149 b, err := t.MarshalBinary()
154 if _, err := client.Connection.Write(b); err != nil {
161 func (s *Server) processOutbox() {
165 if err := s.sendTransaction(t); err != nil {
166 s.Logger.Errorw("error sending transaction", "err", err)
172 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
176 conn, err := ln.Accept()
178 s.Logger.Errorw("error accepting connection", "err", err)
180 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
181 remoteAddr: conn.RemoteAddr().String(),
185 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
187 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
189 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
191 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
199 agreementFile = "Agreement.txt"
202 // NewServer constructs a new Server from a config dir
203 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
206 Accounts: make(map[string]*Account),
208 Clients: make(map[uint16]*ClientConn),
209 fileTransfers: make(map[[4]byte]*FileTransfer),
210 PrivateChats: make(map[uint32]*PrivateChat),
211 ConfigDir: configDir,
213 NextGuestID: new(uint16),
214 outbox: make(chan Transaction),
215 Stats: &Stats{StartTime: time.Now()},
216 ThreadedNews: &ThreadedNews{},
222 // generate a new random passID for tracker registration
223 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
227 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
232 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
236 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
240 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
244 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
248 server.Config.FileRoot = filepath.Join(configDir, "Files")
250 *server.NextGuestID = 1
252 if server.Config.EnableTrackerRegistration {
254 "Tracker registration enabled",
255 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
256 "trackers", server.Config.Trackers,
261 tr := &TrackerRegistration{
262 UserCount: server.userCount(),
263 PassID: server.TrackerPassID[:],
264 Name: server.Config.Name,
265 Description: server.Config.Description,
267 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
268 for _, t := range server.Config.Trackers {
269 if err := register(t, tr); err != nil {
270 server.Logger.Errorw("unable to register with tracker %v", "error", err)
272 server.Logger.Infow("Sent Tracker registration", "data", tr)
275 time.Sleep(trackerUpdateFrequency * time.Second)
280 // Start Client Keepalive go routine
281 go server.keepaliveHandler()
286 func (s *Server) userCount() int {
290 return len(s.Clients)
293 func (s *Server) keepaliveHandler() {
295 time.Sleep(idleCheckInterval * time.Second)
298 for _, c := range s.Clients {
299 c.IdleTime += idleCheckInterval
300 if c.IdleTime > userIdleSeconds && !c.Idle {
303 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
304 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
305 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
308 tranNotifyChangeUser,
309 NewField(fieldUserID, *c.ID),
310 NewField(fieldUserFlags, *c.Flags),
311 NewField(fieldUserName, c.UserName),
312 NewField(fieldUserIconID, *c.Icon),
320 func (s *Server) writeThreadedNews() error {
324 out, err := yaml.Marshal(s.ThreadedNews)
328 err = ioutil.WriteFile(
329 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
336 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
340 clientConn := &ClientConn{
343 Flags: &[]byte{0, 0},
349 transfers: map[int]map[[4]byte]*FileTransfer{},
351 RemoteAddr: remoteAddr,
353 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
364 binary.BigEndian.PutUint16(*clientConn.ID, ID)
365 s.Clients[ID] = clientConn
370 // NewUser creates a new user account entry in the server map and config file
371 func (s *Server) NewUser(login, name, password string, access []byte) error {
378 Password: hashAndSalt([]byte(password)),
381 out, err := yaml.Marshal(&account)
385 s.Accounts[login] = &account
387 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
390 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
394 // update renames the user login
395 if login != newLogin {
396 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
400 s.Accounts[newLogin] = s.Accounts[login]
401 delete(s.Accounts, login)
404 account := s.Accounts[newLogin]
405 account.Access = &access
407 account.Password = password
409 out, err := yaml.Marshal(&account)
414 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
421 // DeleteUser deletes the user account
422 func (s *Server) DeleteUser(login string) error {
426 delete(s.Accounts, login)
428 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
431 func (s *Server) connectedUsers() []Field {
435 var connectedUsers []Field
436 for _, c := range sortedClients(s.Clients) {
444 Name: string(c.UserName),
446 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
448 return connectedUsers
451 // loadThreadedNews loads the threaded news data from disk
452 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
453 fh, err := os.Open(threadedNewsPath)
457 decoder := yaml.NewDecoder(fh)
459 return decoder.Decode(s.ThreadedNews)
462 // loadAccounts loads account data from disk
463 func (s *Server) loadAccounts(userDir string) error {
464 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
469 if len(matches) == 0 {
470 return errors.New("no user accounts found in " + userDir)
473 for _, file := range matches {
474 fh, err := s.FS.Open(file)
480 decoder := yaml.NewDecoder(fh)
481 if err := decoder.Decode(&account); err != nil {
485 s.Accounts[account.Login] = &account
490 func (s *Server) loadConfig(path string) error {
491 fh, err := s.FS.Open(path)
496 decoder := yaml.NewDecoder(fh)
497 err = decoder.Decode(s.Config)
502 validate := validator.New()
503 err = validate.Struct(s.Config)
510 // dontPanic logs panics instead of crashing
511 func dontPanic(logger *zap.SugaredLogger) {
512 if r := recover(); r != nil {
513 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
514 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
518 // handleNewConnection takes a new net.Conn and performs the initial login sequence
519 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
520 defer dontPanic(s.Logger)
522 if err := Handshake(rwc); err != nil {
526 // Create a new scanner for parsing incoming bytes into transaction tokens
527 scanner := bufio.NewScanner(rwc)
528 scanner.Split(transactionScanner)
532 clientLogin, _, err := ReadTransaction(scanner.Bytes())
537 c := s.NewClientConn(rwc, remoteAddr)
540 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
541 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
542 *c.Version = clientLogin.GetField(fieldVersion).Data
545 for _, char := range encodedLogin {
546 login += string(rune(255 - uint(char)))
552 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
554 // If authentication fails, send error reply and close connection
555 if !c.Authenticate(login, encodedPassword) {
556 t := c.NewErrReply(clientLogin, "Incorrect login.")
557 b, err := t.MarshalBinary()
561 if _, err := rwc.Write(b); err != nil {
565 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", *c.Version))
570 if clientLogin.GetField(fieldUserName).Data != nil {
571 c.UserName = clientLogin.GetField(fieldUserName).Data
574 if clientLogin.GetField(fieldUserIconID).Data != nil {
575 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
578 c.Account = c.Server.Accounts[login]
580 if c.Authorize(accessDisconUser) {
581 *c.Flags = []byte{0, 2}
584 s.outbox <- c.NewReply(clientLogin,
585 NewField(fieldVersion, []byte{0x00, 0xbe}),
586 NewField(fieldCommunityBannerID, []byte{0, 0}),
587 NewField(fieldServerName, []byte(s.Config.Name)),
590 // Send user access privs so client UI knows how to behave
591 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
593 // Show agreement to client
594 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
596 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
597 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
599 c.logger = c.logger.With("name", string(c.UserName))
600 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", *c.Version))
602 for _, t := range c.notifyOthers(
604 tranNotifyChangeUser, nil,
605 NewField(fieldUserName, c.UserName),
606 NewField(fieldUserID, *c.ID),
607 NewField(fieldUserIconID, *c.Icon),
608 NewField(fieldUserFlags, *c.Flags),
615 c.Server.Stats.LoginCount += 1
617 // Scan for new transactions and handle them as they come in.
619 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
620 // scanner re-uses the buffer for subsequent scans.
621 buf := make([]byte, len(scanner.Bytes()))
622 copy(buf, scanner.Bytes())
624 t, _, err := ReadTransaction(buf)
628 if err := c.handleTransaction(*t); err != nil {
629 c.logger.Errorw("Error handling transaction", "err", err)
635 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
639 randID := make([]byte, 4)
641 data := binary.BigEndian.Uint32(randID[:])
643 s.PrivateChats[data] = &PrivateChat{
645 ClientConn: make(map[uint16]*ClientConn),
647 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
652 const dlFldrActionSendFile = 1
653 const dlFldrActionResumeFile = 2
654 const dlFldrActionNextFile = 3
656 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
657 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
658 defer dontPanic(s.Logger)
660 txBuf := make([]byte, 16)
661 if _, err := io.ReadFull(rwc, txBuf); err != nil {
666 if _, err := t.Write(txBuf); err != nil {
672 delete(s.fileTransfers, t.ReferenceNumber)
678 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
681 return errors.New("invalid transaction ID")
685 fileTransfer.ClientConn.transfersMU.Lock()
686 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
687 fileTransfer.ClientConn.transfersMU.Unlock()
690 rLogger := s.Logger.With(
691 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
692 "login", fileTransfer.ClientConn.Account.Login,
693 "name", string(fileTransfer.ClientConn.UserName),
696 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
701 switch fileTransfer.Type {
703 if err := s.bannerDownload(rwc); err != nil {
708 s.Stats.DownloadCounter += 1
711 if fileTransfer.fileResumeData != nil {
712 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
715 fw, err := newFileWrapper(s.FS, fullPath, 0)
720 rLogger.Infow("File download started", "filePath", fullPath)
722 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
723 if fileTransfer.options == nil {
724 // Start by sending flat file object to client
725 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
730 file, err := fw.dataForkReader()
735 br := bufio.NewReader(file)
736 if _, err := br.Discard(int(dataOffset)); err != nil {
740 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
744 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
745 if fileTransfer.fileResumeData == nil {
746 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
752 rFile, err := fw.rsrcForkFile()
757 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
762 s.Stats.UploadCounter += 1
766 // A file upload has three possible cases:
767 // 1) Upload a new file
768 // 2) Resume a partially transferred file
769 // 3) Replace a fully uploaded file
770 // We have to infer which case applies by inspecting what is already on the filesystem
772 // 1) Check for existing file:
773 _, err = os.Stat(fullPath)
775 return errors.New("existing file found at " + fullPath)
777 if errors.Is(err, fs.ErrNotExist) {
778 // If not found, open or create a new .incomplete file
779 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
785 f, err := newFileWrapper(s.FS, fullPath, 0)
790 rLogger.Infow("File upload started", "dstFile", fullPath)
792 rForkWriter := io.Discard
793 iForkWriter := io.Discard
794 if s.Config.PreserveResourceForks {
795 rForkWriter, err = f.rsrcForkWriter()
800 iForkWriter, err = f.infoForkWriter()
806 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
810 if err := file.Close(); err != nil {
814 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
818 rLogger.Infow("File upload complete", "dstFile", fullPath)
820 // Folder Download flow:
821 // 1. Get filePath from the transfer
822 // 2. Iterate over files
823 // 3. For each fileWrapper:
824 // Send fileWrapper header to client
825 // The client can reply in 3 ways:
827 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
828 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
830 // 2. If download of a fileWrapper is to be resumed:
832 // []byte{0x00, 0x02} // download folder action
833 // [2]byte // Resume data size
834 // []byte fileWrapper resume data (see myField_FileResumeData)
836 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
838 // When download is requested (case 2 or 3), server replies with:
839 // [4]byte - fileWrapper size
840 // []byte - Flattened File Object
842 // After every fileWrapper download, client could request next fileWrapper with:
843 // []byte{0x00, 0x03}
845 // This notifies the server to send the next item header
847 basePathLen := len(fullPath)
849 rLogger.Infow("Start folder download", "path", fullPath)
851 nextAction := make([]byte, 2)
852 if _, err := io.ReadFull(rwc, nextAction); err != nil {
857 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
858 s.Stats.DownloadCounter += 1
866 if strings.HasPrefix(info.Name(), ".") {
870 hlFile, err := newFileWrapper(s.FS, path, 0)
875 subPath := path[basePathLen+1:]
876 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
882 fileHeader := NewFileHeader(subPath, info.IsDir())
884 // Send the fileWrapper header to client
885 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
886 s.Logger.Errorf("error sending file header: %v", err)
890 // Read the client's Next Action request
891 if _, err := io.ReadFull(rwc, nextAction); err != nil {
895 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
899 switch nextAction[1] {
900 case dlFldrActionResumeFile:
901 // get size of resumeData
902 resumeDataByteLen := make([]byte, 2)
903 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
907 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
908 resumeDataBytes := make([]byte, resumeDataLen)
909 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
913 var frd FileResumeData
914 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
917 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
918 case dlFldrActionNextFile:
919 // client asked to skip this file
927 rLogger.Infow("File download started",
928 "fileName", info.Name(),
929 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
932 // Send file size to client
933 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
938 // Send ffo bytes to client
939 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
944 file, err := s.FS.Open(path)
949 // wr := bufio.NewWriterSize(rwc, 1460)
950 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
954 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
955 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
960 rFile, err := hlFile.rsrcForkFile()
965 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
970 // Read the client's Next Action request. This is always 3, I think?
971 if _, err := io.ReadFull(rwc, nextAction); err != nil {
984 "Folder upload started",
986 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
987 "FolderItemCount", fileTransfer.FolderItemCount,
990 // Check if the target folder exists. If not, create it.
991 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
992 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
997 // Begin the folder upload flow by sending the "next file action" to client
998 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1002 fileSize := make([]byte, 4)
1004 for i := 0; i < fileTransfer.ItemCount(); i++ {
1005 s.Stats.UploadCounter += 1
1008 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1011 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1014 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1018 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1020 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1025 "Folder upload continued",
1026 "FormattedPath", fu.FormattedPath(),
1027 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1028 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1031 if fu.IsFolder == [2]byte{0, 1} {
1032 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1033 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1038 // Tell client to send next file
1039 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1043 nextAction := dlFldrActionSendFile
1045 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1046 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1047 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1051 nextAction = dlFldrActionNextFile
1054 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1055 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1056 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1060 nextAction = dlFldrActionResumeFile
1063 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1068 case dlFldrActionNextFile:
1070 case dlFldrActionResumeFile:
1071 offset := make([]byte, 4)
1072 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1074 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1079 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1081 b, _ := fileResumeData.BinaryMarshal()
1083 bs := make([]byte, 2)
1084 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1086 if _, err := rwc.Write(append(bs, b...)); err != nil {
1090 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1094 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1098 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1103 case dlFldrActionSendFile:
1104 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1108 filePath := filepath.Join(fullPath, fu.FormattedPath())
1110 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1115 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1117 incWriter, err := hlFile.incFileWriter()
1122 rForkWriter := io.Discard
1123 iForkWriter := io.Discard
1124 if s.Config.PreserveResourceForks {
1125 iForkWriter, err = hlFile.infoForkWriter()
1130 rForkWriter, err = hlFile.rsrcForkWriter()
1135 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1139 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1144 // Tell client to send next fileWrapper
1145 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1150 rLogger.Infof("Folder upload complete")