]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
Implement GetClientInfoText with per-client file transfer info
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "github.com/go-playground/validator/v10"
11 "go.uber.org/zap"
12 "gopkg.in/yaml.v3"
13 "io"
14 "io/fs"
15 "io/ioutil"
16 "math/big"
17 "math/rand"
18 "net"
19 "os"
20 "path/filepath"
21 "runtime/debug"
22 "strings"
23 "sync"
24 "time"
25 )
26
27 type contextKey string
28
29 var contextKeyReq = contextKey("req")
30
31 type requestCtx struct {
32 remoteAddr string
33 login string
34 name string
35 }
36
37 const (
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
41 )
42
43 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
44
45 type Server struct {
46 Port int
47 Accounts map[string]*Account
48 Agreement []byte
49 Clients map[uint16]*ClientConn
50 ThreadedNews *ThreadedNews
51
52 fileTransfers map[[4]byte]*FileTransfer
53
54 Config *Config
55 ConfigDir string
56 Logger *zap.SugaredLogger
57 PrivateChats map[uint32]*PrivateChat
58 NextGuestID *uint16
59 TrackerPassID [4]byte
60 Stats *Stats
61
62 FS FileStore // Storage backend to use for File storage
63
64 outbox chan Transaction
65 mux sync.Mutex
66
67 flatNewsMux sync.Mutex
68 FlatNews []byte
69 }
70
71 type PrivateChat struct {
72 Subject string
73 ClientConn map[uint16]*ClientConn
74 }
75
76 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
77 s.Logger.Infow("Hotline server started",
78 "version", VERSION,
79 "API port", fmt.Sprintf(":%v", s.Port),
80 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
81 )
82
83 var wg sync.WaitGroup
84
85 wg.Add(1)
86 go func() {
87 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
88 if err != nil {
89 s.Logger.Fatal(err)
90 }
91
92 s.Logger.Fatal(s.Serve(ctx, ln))
93 }()
94
95 wg.Add(1)
96 go func() {
97 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
98 if err != nil {
99 s.Logger.Fatal(err)
100
101 }
102
103 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
104 }()
105
106 wg.Wait()
107
108 return nil
109 }
110
111 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
112 for {
113 conn, err := ln.Accept()
114 if err != nil {
115 return err
116 }
117
118 go func() {
119 defer func() { _ = conn.Close() }()
120
121 err = s.handleFileTransfer(
122 context.WithValue(ctx, contextKeyReq, requestCtx{
123 remoteAddr: conn.RemoteAddr().String(),
124 }),
125 conn,
126 )
127
128 if err != nil {
129 s.Logger.Errorw("file transfer error", "reason", err)
130 }
131 }()
132 }
133 }
134
135 func (s *Server) sendTransaction(t Transaction) error {
136 requestNum := binary.BigEndian.Uint16(t.Type)
137 clientID, err := byteToInt(*t.clientID)
138 if err != nil {
139 return err
140 }
141
142 s.mux.Lock()
143 client := s.Clients[uint16(clientID)]
144 s.mux.Unlock()
145 if client == nil {
146 return fmt.Errorf("invalid client id %v", *t.clientID)
147 }
148 userName := string(client.UserName)
149 login := client.Account.Login
150
151 handler := TransactionHandlers[requestNum]
152
153 b, err := t.MarshalBinary()
154 if err != nil {
155 return err
156 }
157 var n int
158 if n, err = client.Connection.Write(b); err != nil {
159 return err
160 }
161 s.Logger.Debugw("Sent Transaction",
162 "name", userName,
163 "login", login,
164 "IsReply", t.IsReply,
165 "type", handler.Name,
166 "sentBytes", n,
167 "remoteAddr", client.RemoteAddr,
168 )
169 return nil
170 }
171
172 func (s *Server) processOutbox() {
173 for {
174 t := <-s.outbox
175 go func() {
176 if err := s.sendTransaction(t); err != nil {
177 s.Logger.Errorw("error sending transaction", "err", err)
178 }
179 }()
180 }
181 }
182
183 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
184 go s.processOutbox()
185
186 for {
187 conn, err := ln.Accept()
188 if err != nil {
189 s.Logger.Errorw("error accepting connection", "err", err)
190 }
191 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
192 remoteAddr: conn.RemoteAddr().String(),
193 })
194
195 go func() {
196 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
197 s.Logger.Infow("New client connection established", "RemoteAddr", conn.RemoteAddr())
198 if err == io.EOF {
199 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
200 } else {
201 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
202 }
203 }
204 }()
205 }
206 }
207
208 const (
209 agreementFile = "Agreement.txt"
210 )
211
212 // NewServer constructs a new Server from a config dir
213 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
214 server := Server{
215 Port: netPort,
216 Accounts: make(map[string]*Account),
217 Config: new(Config),
218 Clients: make(map[uint16]*ClientConn),
219 fileTransfers: make(map[[4]byte]*FileTransfer),
220 PrivateChats: make(map[uint32]*PrivateChat),
221 ConfigDir: configDir,
222 Logger: logger,
223 NextGuestID: new(uint16),
224 outbox: make(chan Transaction),
225 Stats: &Stats{StartTime: time.Now()},
226 ThreadedNews: &ThreadedNews{},
227 FS: FS,
228 }
229
230 var err error
231
232 // generate a new random passID for tracker registration
233 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
234 return nil, err
235 }
236
237 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
238 if err != nil {
239 return nil, err
240 }
241
242 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
243 return nil, err
244 }
245
246 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
247 return nil, err
248 }
249
250 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
251 return nil, err
252 }
253
254 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
255 return nil, err
256 }
257
258 server.Config.FileRoot = filepath.Join(configDir, "Files")
259
260 *server.NextGuestID = 1
261
262 if server.Config.EnableTrackerRegistration {
263 server.Logger.Infow(
264 "Tracker registration enabled",
265 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
266 "trackers", server.Config.Trackers,
267 )
268
269 go func() {
270 for {
271 tr := &TrackerRegistration{
272 UserCount: server.userCount(),
273 PassID: server.TrackerPassID[:],
274 Name: server.Config.Name,
275 Description: server.Config.Description,
276 }
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)
281 }
282 server.Logger.Infow("Sent Tracker registration", "data", tr)
283 }
284
285 time.Sleep(trackerUpdateFrequency * time.Second)
286 }
287 }()
288 }
289
290 // Start Client Keepalive go routine
291 go server.keepaliveHandler()
292
293 return &server, nil
294 }
295
296 func (s *Server) userCount() int {
297 s.mux.Lock()
298 defer s.mux.Unlock()
299
300 return len(s.Clients)
301 }
302
303 func (s *Server) keepaliveHandler() {
304 for {
305 time.Sleep(idleCheckInterval * time.Second)
306 s.mux.Lock()
307
308 for _, c := range s.Clients {
309 c.IdleTime += idleCheckInterval
310 if c.IdleTime > userIdleSeconds && !c.Idle {
311 c.Idle = true
312
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()))
316
317 c.sendAll(
318 tranNotifyChangeUser,
319 NewField(fieldUserID, *c.ID),
320 NewField(fieldUserFlags, *c.Flags),
321 NewField(fieldUserName, c.UserName),
322 NewField(fieldUserIconID, *c.Icon),
323 )
324 }
325 }
326 s.mux.Unlock()
327 }
328 }
329
330 func (s *Server) writeThreadedNews() error {
331 s.mux.Lock()
332 defer s.mux.Unlock()
333
334 out, err := yaml.Marshal(s.ThreadedNews)
335 if err != nil {
336 return err
337 }
338 err = ioutil.WriteFile(
339 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
340 out,
341 0666,
342 )
343 return err
344 }
345
346 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
347 s.mux.Lock()
348 defer s.mux.Unlock()
349
350 clientConn := &ClientConn{
351 ID: &[]byte{0, 0},
352 Icon: &[]byte{0, 0},
353 Flags: &[]byte{0, 0},
354 UserName: []byte{},
355 Connection: conn,
356 Server: s,
357 Version: &[]byte{},
358 AutoReply: []byte{},
359 transfers: map[int]map[[4]byte]*FileTransfer{},
360 Agreed: false,
361 RemoteAddr: remoteAddr,
362 }
363 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
364 FileDownload: {},
365 FileUpload: {},
366 FolderDownload: {},
367 FolderUpload: {},
368 bannerDownload: {},
369 }
370
371 *s.NextGuestID++
372 ID := *s.NextGuestID
373
374 binary.BigEndian.PutUint16(*clientConn.ID, ID)
375 s.Clients[ID] = clientConn
376
377 return clientConn
378 }
379
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 {
382 s.mux.Lock()
383 defer s.mux.Unlock()
384
385 account := Account{
386 Login: login,
387 Name: name,
388 Password: hashAndSalt([]byte(password)),
389 Access: &access,
390 }
391 out, err := yaml.Marshal(&account)
392 if err != nil {
393 return err
394 }
395 s.Accounts[login] = &account
396
397 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
398 }
399
400 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
401 s.mux.Lock()
402 defer s.mux.Unlock()
403
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"))
407 if err != nil {
408 return err
409 }
410 s.Accounts[newLogin] = s.Accounts[login]
411 delete(s.Accounts, login)
412 }
413
414 account := s.Accounts[newLogin]
415 account.Access = &access
416 account.Name = name
417 account.Password = password
418
419 out, err := yaml.Marshal(&account)
420 if err != nil {
421 return err
422 }
423
424 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
425 return err
426 }
427
428 return nil
429 }
430
431 // DeleteUser deletes the user account
432 func (s *Server) DeleteUser(login string) error {
433 s.mux.Lock()
434 defer s.mux.Unlock()
435
436 delete(s.Accounts, login)
437
438 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
439 }
440
441 func (s *Server) connectedUsers() []Field {
442 s.mux.Lock()
443 defer s.mux.Unlock()
444
445 var connectedUsers []Field
446 for _, c := range sortedClients(s.Clients) {
447 if !c.Agreed {
448 continue
449 }
450 user := User{
451 ID: *c.ID,
452 Icon: *c.Icon,
453 Flags: *c.Flags,
454 Name: string(c.UserName),
455 }
456 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
457 }
458 return connectedUsers
459 }
460
461 // loadThreadedNews loads the threaded news data from disk
462 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
463 fh, err := os.Open(threadedNewsPath)
464 if err != nil {
465 return err
466 }
467 decoder := yaml.NewDecoder(fh)
468
469 return decoder.Decode(s.ThreadedNews)
470 }
471
472 // loadAccounts loads account data from disk
473 func (s *Server) loadAccounts(userDir string) error {
474 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
475 if err != nil {
476 return err
477 }
478
479 if len(matches) == 0 {
480 return errors.New("no user accounts found in " + userDir)
481 }
482
483 for _, file := range matches {
484 fh, err := s.FS.Open(file)
485 if err != nil {
486 return err
487 }
488
489 account := Account{}
490 decoder := yaml.NewDecoder(fh)
491 if err := decoder.Decode(&account); err != nil {
492 return err
493 }
494
495 s.Accounts[account.Login] = &account
496 }
497 return nil
498 }
499
500 func (s *Server) loadConfig(path string) error {
501 fh, err := s.FS.Open(path)
502 if err != nil {
503 return err
504 }
505
506 decoder := yaml.NewDecoder(fh)
507 err = decoder.Decode(s.Config)
508 if err != nil {
509 return err
510 }
511
512 validate := validator.New()
513 err = validate.Struct(s.Config)
514 if err != nil {
515 return err
516 }
517 return nil
518 }
519
520 const (
521 minTransactionLen = 22 // minimum length of any transaction
522 )
523
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()))
530 }
531 }
532
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)
536
537 if err := Handshake(conn); err != nil {
538 return err
539 }
540
541 buf := make([]byte, 1024)
542 // TODO: fix potential short read with io.ReadFull
543 readLen, err := conn.Read(buf)
544 if readLen < minTransactionLen {
545 return err
546 }
547 if err != nil {
548 return err
549 }
550
551 clientLogin, _, err := ReadTransaction(buf[:readLen])
552 if err != nil {
553 return err
554 }
555
556 c := s.NewClientConn(conn, remoteAddr)
557 defer c.Disconnect()
558
559 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
560 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
561 *c.Version = clientLogin.GetField(fieldVersion).Data
562
563 var login string
564 for _, char := range encodedLogin {
565 login += string(rune(255 - uint(char)))
566 }
567 if login == "" {
568 login = GuestAccount
569 }
570
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()
575 if err != nil {
576 return err
577 }
578 if _, err := conn.Write(b); err != nil {
579 return err
580 }
581 return fmt.Errorf("incorrect login")
582 }
583
584 if clientLogin.GetField(fieldUserName).Data != nil {
585 c.UserName = clientLogin.GetField(fieldUserName).Data
586 }
587
588 if clientLogin.GetField(fieldUserIconID).Data != nil {
589 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
590 }
591
592 c.Account = c.Server.Accounts[login]
593
594 if c.Authorize(accessDisconUser) {
595 *c.Flags = []byte{0, 2}
596 }
597
598 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
599
600 c.logger.Infow("Client connection received", "version", fmt.Sprintf("%x", *c.Version))
601
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)),
606 )
607
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))
610
611 // Show agreement to client
612 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
613
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) {
616 c.Agreed = true
617 c.logger = c.logger.With("name", string(c.UserName))
618
619 for _, t := range c.notifyOthers(
620 *NewTransaction(
621 tranNotifyChangeUser, nil,
622 NewField(fieldUserName, c.UserName),
623 NewField(fieldUserID, *c.ID),
624 NewField(fieldUserIconID, *c.Icon),
625 NewField(fieldUserFlags, *c.Flags),
626 ),
627 ) {
628 c.Server.outbox <- t
629 }
630 }
631
632 c.Server.Stats.LoginCount += 1
633
634 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
635 tranBuff := make([]byte, 0)
636 tReadlen := 0
637 // Infinite loop where take action on incoming client requests until the connection is closed
638 for {
639 buf = make([]byte, readBuffSize)
640 tranBuff = tranBuff[tReadlen:]
641
642 readLen, err := c.Connection.Read(buf)
643 if err != nil {
644 return err
645 }
646 tranBuff = append(tranBuff, buf[:readLen]...)
647
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)
653 }
654
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)
659 }
660 }
661 }
662 }
663
664 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
665 s.mux.Lock()
666 defer s.mux.Unlock()
667
668 randID := make([]byte, 4)
669 rand.Read(randID)
670 data := binary.BigEndian.Uint32(randID[:])
671
672 s.PrivateChats[data] = &PrivateChat{
673 Subject: "",
674 ClientConn: make(map[uint16]*ClientConn),
675 }
676 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
677
678 return randID
679 }
680
681 const dlFldrActionSendFile = 1
682 const dlFldrActionResumeFile = 2
683 const dlFldrActionNextFile = 3
684
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)
688
689 txBuf := make([]byte, 16)
690 if _, err := io.ReadFull(rwc, txBuf); err != nil {
691 return err
692 }
693
694 var t transfer
695 if _, err := t.Write(txBuf); err != nil {
696 return err
697 }
698
699 defer func() {
700 s.mux.Lock()
701 delete(s.fileTransfers, t.ReferenceNumber)
702 s.mux.Unlock()
703
704 }()
705
706 s.mux.Lock()
707 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
708 s.mux.Unlock()
709 if !ok {
710 return errors.New("invalid transaction ID")
711 }
712
713 defer func() {
714 fileTransfer.ClientConn.transfersMU.Lock()
715 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
716 fileTransfer.ClientConn.transfersMU.Unlock()
717 }()
718
719 rLogger := s.Logger.With(
720 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
721 "login", fileTransfer.ClientConn.Account.Login,
722 "name", string(fileTransfer.ClientConn.UserName),
723 )
724
725 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
726 if err != nil {
727 return err
728 }
729
730 switch fileTransfer.Type {
731 case bannerDownload:
732 if err := s.bannerDownload(rwc); err != nil {
733 panic(err)
734 return err
735 }
736 case FileDownload:
737 s.Stats.DownloadCounter += 1
738
739 var dataOffset int64
740 if fileTransfer.fileResumeData != nil {
741 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
742 }
743
744 fw, err := newFileWrapper(s.FS, fullPath, 0)
745 if err != nil {
746 return err
747 }
748
749 rLogger.Infow("File download started", "filePath", fullPath)
750
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 {
755 return err
756 }
757 }
758
759 file, err := fw.dataForkReader()
760 if err != nil {
761 return err
762 }
763
764 br := bufio.NewReader(file)
765 if _, err := br.Discard(int(dataOffset)); err != nil {
766 return err
767 }
768
769 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
770 return err
771 }
772
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())
776 if err != nil {
777 return err
778 }
779 }
780
781 rFile, err := fw.rsrcForkFile()
782 if err != nil {
783 return nil
784 }
785
786 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
787 return err
788 }
789
790 case FileUpload:
791 s.Stats.UploadCounter += 1
792
793 var file *os.File
794
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
800
801 // 1) Check for existing file:
802 _, err = os.Stat(fullPath)
803 if err == nil {
804 return errors.New("existing file found at " + fullPath)
805 }
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)
809 if err != nil {
810 return err
811 }
812 }
813
814 f, err := newFileWrapper(s.FS, fullPath, 0)
815 if err != nil {
816 return err
817 }
818
819 rLogger.Infow("File upload started", "dstFile", fullPath)
820
821 rForkWriter := io.Discard
822 iForkWriter := io.Discard
823 if s.Config.PreserveResourceForks {
824 rForkWriter, err = f.rsrcForkWriter()
825 if err != nil {
826 return err
827 }
828
829 iForkWriter, err = f.infoForkWriter()
830 if err != nil {
831 return err
832 }
833 }
834
835 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
836 s.Logger.Error(err)
837 }
838
839 if err := file.Close(); err != nil {
840 return err
841 }
842
843 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
844 return err
845 }
846
847 rLogger.Infow("File upload complete", "dstFile", fullPath)
848 case FolderDownload:
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:
855 //
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
858 //
859 // 2. If download of a fileWrapper is to be resumed:
860 // client sends:
861 // []byte{0x00, 0x02} // download folder action
862 // [2]byte // Resume data size
863 // []byte fileWrapper resume data (see myField_FileResumeData)
864 //
865 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
866 //
867 // When download is requested (case 2 or 3), server replies with:
868 // [4]byte - fileWrapper size
869 // []byte - Flattened File Object
870 //
871 // After every fileWrapper download, client could request next fileWrapper with:
872 // []byte{0x00, 0x03}
873 //
874 // This notifies the server to send the next item header
875
876 basePathLen := len(fullPath)
877
878 rLogger.Infow("Start folder download", "path", fullPath)
879
880 nextAction := make([]byte, 2)
881 if _, err := io.ReadFull(rwc, nextAction); err != nil {
882 return err
883 }
884
885 i := 0
886 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
887 s.Stats.DownloadCounter += 1
888 i += 1
889
890 if err != nil {
891 return err
892 }
893
894 // skip dot files
895 if strings.HasPrefix(info.Name(), ".") {
896 return nil
897 }
898
899 hlFile, err := newFileWrapper(s.FS, path, 0)
900 if err != nil {
901 return err
902 }
903
904 subPath := path[basePathLen+1:]
905 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
906
907 if i == 1 {
908 return nil
909 }
910
911 fileHeader := NewFileHeader(subPath, info.IsDir())
912
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)
916 return err
917 }
918
919 // Read the client's Next Action request
920 if _, err := io.ReadFull(rwc, nextAction); err != nil {
921 return err
922 }
923
924 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
925
926 var dataOffset int64
927
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 {
933 return err
934 }
935
936 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
937 resumeDataBytes := make([]byte, resumeDataLen)
938 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
939 return err
940 }
941
942 var frd FileResumeData
943 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
944 return err
945 }
946 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
947 case dlFldrActionNextFile:
948 // client asked to skip this file
949 return nil
950 }
951
952 if info.IsDir() {
953 return nil
954 }
955
956 rLogger.Infow("File download started",
957 "fileName", info.Name(),
958 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
959 )
960
961 // Send file size to client
962 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
963 s.Logger.Error(err)
964 return err
965 }
966
967 // Send ffo bytes to client
968 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
969 s.Logger.Error(err)
970 return err
971 }
972
973 file, err := s.FS.Open(path)
974 if err != nil {
975 return err
976 }
977
978 // wr := bufio.NewWriterSize(rwc, 1460)
979 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
980 return err
981 }
982
983 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
984 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
985 if err != nil {
986 return err
987 }
988
989 rFile, err := hlFile.rsrcForkFile()
990 if err != nil {
991 return err
992 }
993
994 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
995 return err
996 }
997 }
998
999 // Read the client's Next Action request. This is always 3, I think?
1000 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1001 return err
1002 }
1003
1004 return nil
1005 })
1006
1007 if err != nil {
1008 return err
1009 }
1010
1011 case FolderUpload:
1012 rLogger.Infow(
1013 "Folder upload started",
1014 "dstPath", fullPath,
1015 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1016 "FolderItemCount", fileTransfer.FolderItemCount,
1017 )
1018
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 {
1022 return err
1023 }
1024 }
1025
1026 // Begin the folder upload flow by sending the "next file action" to client
1027 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1028 return err
1029 }
1030
1031 fileSize := make([]byte, 4)
1032
1033 for i := 0; i < fileTransfer.ItemCount(); i++ {
1034 s.Stats.UploadCounter += 1
1035
1036 var fu folderUpload
1037 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1038 return err
1039 }
1040 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1041 return err
1042 }
1043 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1044 return err
1045 }
1046
1047 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1048
1049 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1050 return err
1051 }
1052
1053 rLogger.Infow(
1054 "Folder upload continued",
1055 "FormattedPath", fu.FormattedPath(),
1056 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1057 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1058 )
1059
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 {
1063 return err
1064 }
1065 }
1066
1067 // Tell client to send next file
1068 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1069 return err
1070 }
1071 } else {
1072 nextAction := dlFldrActionSendFile
1073
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) {
1077 return err
1078 }
1079 if err == nil {
1080 nextAction = dlFldrActionNextFile
1081 }
1082
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) {
1086 return err
1087 }
1088 if err == nil {
1089 nextAction = dlFldrActionResumeFile
1090 }
1091
1092 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1093 return err
1094 }
1095
1096 switch nextAction {
1097 case dlFldrActionNextFile:
1098 continue
1099 case dlFldrActionResumeFile:
1100 offset := make([]byte, 4)
1101 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1102
1103 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1104 if err != nil {
1105 return err
1106 }
1107
1108 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1109
1110 b, _ := fileResumeData.BinaryMarshal()
1111
1112 bs := make([]byte, 2)
1113 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1114
1115 if _, err := rwc.Write(append(bs, b...)); err != nil {
1116 return err
1117 }
1118
1119 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1120 return err
1121 }
1122
1123 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1124 s.Logger.Error(err)
1125 }
1126
1127 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1128 if err != nil {
1129 return err
1130 }
1131
1132 case dlFldrActionSendFile:
1133 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1134 return err
1135 }
1136
1137 filePath := filepath.Join(fullPath, fu.FormattedPath())
1138
1139 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1140 if err != nil {
1141 return err
1142 }
1143
1144 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1145
1146 incWriter, err := hlFile.incFileWriter()
1147 if err != nil {
1148 return err
1149 }
1150
1151 rForkWriter := io.Discard
1152 iForkWriter := io.Discard
1153 if s.Config.PreserveResourceForks {
1154 iForkWriter, err = hlFile.infoForkWriter()
1155 if err != nil {
1156 return err
1157 }
1158
1159 rForkWriter, err = hlFile.rsrcForkWriter()
1160 if err != nil {
1161 return err
1162 }
1163 }
1164 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1165 return err
1166 }
1167
1168 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1169 return err
1170 }
1171 }
1172
1173 // Tell client to send next fileWrapper
1174 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1175 return err
1176 }
1177 }
1178 }
1179 rLogger.Infof("Folder upload complete")
1180 }
1181
1182 return nil
1183 }