]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
0677a813a6d48da4a2aaf99fca228d0c1a28c366
[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 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
197
198 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
199 if err == io.EOF {
200 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
201 } else {
202 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
203 }
204 }
205 }()
206 }
207 }
208
209 const (
210 agreementFile = "Agreement.txt"
211 )
212
213 // NewServer constructs a new Server from a config dir
214 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
215 server := Server{
216 Port: netPort,
217 Accounts: make(map[string]*Account),
218 Config: new(Config),
219 Clients: make(map[uint16]*ClientConn),
220 fileTransfers: make(map[[4]byte]*FileTransfer),
221 PrivateChats: make(map[uint32]*PrivateChat),
222 ConfigDir: configDir,
223 Logger: logger,
224 NextGuestID: new(uint16),
225 outbox: make(chan Transaction),
226 Stats: &Stats{StartTime: time.Now()},
227 ThreadedNews: &ThreadedNews{},
228 FS: FS,
229 }
230
231 var err error
232
233 // generate a new random passID for tracker registration
234 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
235 return nil, err
236 }
237
238 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
239 if err != nil {
240 return nil, err
241 }
242
243 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
244 return nil, err
245 }
246
247 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
248 return nil, err
249 }
250
251 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
252 return nil, err
253 }
254
255 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
256 return nil, err
257 }
258
259 server.Config.FileRoot = filepath.Join(configDir, "Files")
260
261 *server.NextGuestID = 1
262
263 if server.Config.EnableTrackerRegistration {
264 server.Logger.Infow(
265 "Tracker registration enabled",
266 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
267 "trackers", server.Config.Trackers,
268 )
269
270 go func() {
271 for {
272 tr := &TrackerRegistration{
273 UserCount: server.userCount(),
274 PassID: server.TrackerPassID[:],
275 Name: server.Config.Name,
276 Description: server.Config.Description,
277 }
278 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
279 for _, t := range server.Config.Trackers {
280 if err := register(t, tr); err != nil {
281 server.Logger.Errorw("unable to register with tracker %v", "error", err)
282 }
283 server.Logger.Infow("Sent Tracker registration", "data", tr)
284 }
285
286 time.Sleep(trackerUpdateFrequency * time.Second)
287 }
288 }()
289 }
290
291 // Start Client Keepalive go routine
292 go server.keepaliveHandler()
293
294 return &server, nil
295 }
296
297 func (s *Server) userCount() int {
298 s.mux.Lock()
299 defer s.mux.Unlock()
300
301 return len(s.Clients)
302 }
303
304 func (s *Server) keepaliveHandler() {
305 for {
306 time.Sleep(idleCheckInterval * time.Second)
307 s.mux.Lock()
308
309 for _, c := range s.Clients {
310 c.IdleTime += idleCheckInterval
311 if c.IdleTime > userIdleSeconds && !c.Idle {
312 c.Idle = true
313
314 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
315 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
316 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
317
318 c.sendAll(
319 tranNotifyChangeUser,
320 NewField(fieldUserID, *c.ID),
321 NewField(fieldUserFlags, *c.Flags),
322 NewField(fieldUserName, c.UserName),
323 NewField(fieldUserIconID, *c.Icon),
324 )
325 }
326 }
327 s.mux.Unlock()
328 }
329 }
330
331 func (s *Server) writeThreadedNews() error {
332 s.mux.Lock()
333 defer s.mux.Unlock()
334
335 out, err := yaml.Marshal(s.ThreadedNews)
336 if err != nil {
337 return err
338 }
339 err = ioutil.WriteFile(
340 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
341 out,
342 0666,
343 )
344 return err
345 }
346
347 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
348 s.mux.Lock()
349 defer s.mux.Unlock()
350
351 clientConn := &ClientConn{
352 ID: &[]byte{0, 0},
353 Icon: &[]byte{0, 0},
354 Flags: &[]byte{0, 0},
355 UserName: []byte{},
356 Connection: conn,
357 Server: s,
358 Version: &[]byte{},
359 AutoReply: []byte{},
360 transfers: map[int]map[[4]byte]*FileTransfer{},
361 Agreed: false,
362 RemoteAddr: remoteAddr,
363 }
364 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
365 FileDownload: {},
366 FileUpload: {},
367 FolderDownload: {},
368 FolderUpload: {},
369 bannerDownload: {},
370 }
371
372 *s.NextGuestID++
373 ID := *s.NextGuestID
374
375 binary.BigEndian.PutUint16(*clientConn.ID, ID)
376 s.Clients[ID] = clientConn
377
378 return clientConn
379 }
380
381 // NewUser creates a new user account entry in the server map and config file
382 func (s *Server) NewUser(login, name, password string, access []byte) error {
383 s.mux.Lock()
384 defer s.mux.Unlock()
385
386 account := Account{
387 Login: login,
388 Name: name,
389 Password: hashAndSalt([]byte(password)),
390 Access: &access,
391 }
392 out, err := yaml.Marshal(&account)
393 if err != nil {
394 return err
395 }
396 s.Accounts[login] = &account
397
398 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
399 }
400
401 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
402 s.mux.Lock()
403 defer s.mux.Unlock()
404
405 // update renames the user login
406 if login != newLogin {
407 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
408 if err != nil {
409 return err
410 }
411 s.Accounts[newLogin] = s.Accounts[login]
412 delete(s.Accounts, login)
413 }
414
415 account := s.Accounts[newLogin]
416 account.Access = &access
417 account.Name = name
418 account.Password = password
419
420 out, err := yaml.Marshal(&account)
421 if err != nil {
422 return err
423 }
424
425 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
426 return err
427 }
428
429 return nil
430 }
431
432 // DeleteUser deletes the user account
433 func (s *Server) DeleteUser(login string) error {
434 s.mux.Lock()
435 defer s.mux.Unlock()
436
437 delete(s.Accounts, login)
438
439 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
440 }
441
442 func (s *Server) connectedUsers() []Field {
443 s.mux.Lock()
444 defer s.mux.Unlock()
445
446 var connectedUsers []Field
447 for _, c := range sortedClients(s.Clients) {
448 if !c.Agreed {
449 continue
450 }
451 user := User{
452 ID: *c.ID,
453 Icon: *c.Icon,
454 Flags: *c.Flags,
455 Name: string(c.UserName),
456 }
457 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
458 }
459 return connectedUsers
460 }
461
462 // loadThreadedNews loads the threaded news data from disk
463 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
464 fh, err := os.Open(threadedNewsPath)
465 if err != nil {
466 return err
467 }
468 decoder := yaml.NewDecoder(fh)
469
470 return decoder.Decode(s.ThreadedNews)
471 }
472
473 // loadAccounts loads account data from disk
474 func (s *Server) loadAccounts(userDir string) error {
475 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
476 if err != nil {
477 return err
478 }
479
480 if len(matches) == 0 {
481 return errors.New("no user accounts found in " + userDir)
482 }
483
484 for _, file := range matches {
485 fh, err := s.FS.Open(file)
486 if err != nil {
487 return err
488 }
489
490 account := Account{}
491 decoder := yaml.NewDecoder(fh)
492 if err := decoder.Decode(&account); err != nil {
493 return err
494 }
495
496 s.Accounts[account.Login] = &account
497 }
498 return nil
499 }
500
501 func (s *Server) loadConfig(path string) error {
502 fh, err := s.FS.Open(path)
503 if err != nil {
504 return err
505 }
506
507 decoder := yaml.NewDecoder(fh)
508 err = decoder.Decode(s.Config)
509 if err != nil {
510 return err
511 }
512
513 validate := validator.New()
514 err = validate.Struct(s.Config)
515 if err != nil {
516 return err
517 }
518 return nil
519 }
520
521 const (
522 minTransactionLen = 22 // minimum length of any transaction
523 )
524
525 // dontPanic recovers and logs panics instead of crashing
526 // TODO: remove this after known issues are fixed
527 func dontPanic(logger *zap.SugaredLogger) {
528 if r := recover(); r != nil {
529 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
530 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
531 }
532 }
533
534 // handleNewConnection takes a new net.Conn and performs the initial login sequence
535 func (s *Server) handleNewConnection(ctx context.Context, conn io.ReadWriteCloser, remoteAddr string) error {
536 defer dontPanic(s.Logger)
537
538 if err := Handshake(conn); err != nil {
539 return err
540 }
541
542 buf := make([]byte, 1024)
543 // TODO: fix potential short read with io.ReadFull
544 readLen, err := conn.Read(buf)
545 if readLen < minTransactionLen {
546 return err
547 }
548 if err != nil {
549 return err
550 }
551
552 clientLogin, _, err := ReadTransaction(buf[:readLen])
553 if err != nil {
554 return err
555 }
556
557 c := s.NewClientConn(conn, remoteAddr)
558 defer c.Disconnect()
559
560 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
561 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
562 *c.Version = clientLogin.GetField(fieldVersion).Data
563
564 var login string
565 for _, char := range encodedLogin {
566 login += string(rune(255 - uint(char)))
567 }
568 if login == "" {
569 login = GuestAccount
570 }
571
572 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
573
574 // If authentication fails, send error reply and close connection
575 if !c.Authenticate(login, encodedPassword) {
576 t := c.NewErrReply(clientLogin, "Incorrect login.")
577 b, err := t.MarshalBinary()
578 if err != nil {
579 return err
580 }
581 if _, err := conn.Write(b); err != nil {
582 return err
583 }
584
585 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", *c.Version))
586
587 return nil
588 }
589
590 if clientLogin.GetField(fieldUserName).Data != nil {
591 c.UserName = clientLogin.GetField(fieldUserName).Data
592 }
593
594 if clientLogin.GetField(fieldUserIconID).Data != nil {
595 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
596 }
597
598 c.Account = c.Server.Accounts[login]
599
600 if c.Authorize(accessDisconUser) {
601 *c.Flags = []byte{0, 2}
602 }
603
604 s.outbox <- c.NewReply(clientLogin,
605 NewField(fieldVersion, []byte{0x00, 0xbe}),
606 NewField(fieldCommunityBannerID, []byte{0, 0}),
607 NewField(fieldServerName, []byte(s.Config.Name)),
608 )
609
610 // Send user access privs so client UI knows how to behave
611 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
612
613 // Show agreement to client
614 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
615
616 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
617 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
618 c.Agreed = true
619 c.logger = c.logger.With("name", string(c.UserName))
620 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", *c.Version))
621
622 for _, t := range c.notifyOthers(
623 *NewTransaction(
624 tranNotifyChangeUser, nil,
625 NewField(fieldUserName, c.UserName),
626 NewField(fieldUserID, *c.ID),
627 NewField(fieldUserIconID, *c.Icon),
628 NewField(fieldUserFlags, *c.Flags),
629 ),
630 ) {
631 c.Server.outbox <- t
632 }
633 }
634
635 c.Server.Stats.LoginCount += 1
636
637 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
638 tranBuff := make([]byte, 0)
639 tReadlen := 0
640 // Infinite loop where take action on incoming client requests until the connection is closed
641 for {
642 buf = make([]byte, readBuffSize)
643 tranBuff = tranBuff[tReadlen:]
644
645 readLen, err := c.Connection.Read(buf)
646 if err != nil {
647 return err
648 }
649 tranBuff = append(tranBuff, buf[:readLen]...)
650
651 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
652 // into a slice of transactions
653 var transactions []Transaction
654 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
655 c.logger.Errorw("Error handling transaction", "err", err)
656 }
657
658 // iterate over all the transactions that were parsed from the byte slice and handle them
659 for _, t := range transactions {
660 if err := c.handleTransaction(&t); err != nil {
661 c.logger.Errorw("Error handling transaction", "err", err)
662 }
663 }
664 }
665 }
666
667 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
668 s.mux.Lock()
669 defer s.mux.Unlock()
670
671 randID := make([]byte, 4)
672 rand.Read(randID)
673 data := binary.BigEndian.Uint32(randID[:])
674
675 s.PrivateChats[data] = &PrivateChat{
676 Subject: "",
677 ClientConn: make(map[uint16]*ClientConn),
678 }
679 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
680
681 return randID
682 }
683
684 const dlFldrActionSendFile = 1
685 const dlFldrActionResumeFile = 2
686 const dlFldrActionNextFile = 3
687
688 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
689 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
690 defer dontPanic(s.Logger)
691
692 txBuf := make([]byte, 16)
693 if _, err := io.ReadFull(rwc, txBuf); err != nil {
694 return err
695 }
696
697 var t transfer
698 if _, err := t.Write(txBuf); err != nil {
699 return err
700 }
701
702 defer func() {
703 s.mux.Lock()
704 delete(s.fileTransfers, t.ReferenceNumber)
705 s.mux.Unlock()
706
707 }()
708
709 s.mux.Lock()
710 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
711 s.mux.Unlock()
712 if !ok {
713 return errors.New("invalid transaction ID")
714 }
715
716 defer func() {
717 fileTransfer.ClientConn.transfersMU.Lock()
718 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
719 fileTransfer.ClientConn.transfersMU.Unlock()
720 }()
721
722 rLogger := s.Logger.With(
723 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
724 "login", fileTransfer.ClientConn.Account.Login,
725 "name", string(fileTransfer.ClientConn.UserName),
726 )
727
728 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
729 if err != nil {
730 return err
731 }
732
733 switch fileTransfer.Type {
734 case bannerDownload:
735 if err := s.bannerDownload(rwc); err != nil {
736 panic(err)
737 return err
738 }
739 case FileDownload:
740 s.Stats.DownloadCounter += 1
741
742 var dataOffset int64
743 if fileTransfer.fileResumeData != nil {
744 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
745 }
746
747 fw, err := newFileWrapper(s.FS, fullPath, 0)
748 if err != nil {
749 return err
750 }
751
752 rLogger.Infow("File download started", "filePath", fullPath)
753
754 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
755 if fileTransfer.options == nil {
756 // Start by sending flat file object to client
757 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
758 return err
759 }
760 }
761
762 file, err := fw.dataForkReader()
763 if err != nil {
764 return err
765 }
766
767 br := bufio.NewReader(file)
768 if _, err := br.Discard(int(dataOffset)); err != nil {
769 return err
770 }
771
772 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
773 return err
774 }
775
776 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
777 if fileTransfer.fileResumeData == nil {
778 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
779 if err != nil {
780 return err
781 }
782 }
783
784 rFile, err := fw.rsrcForkFile()
785 if err != nil {
786 return nil
787 }
788
789 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
790 return err
791 }
792
793 case FileUpload:
794 s.Stats.UploadCounter += 1
795
796 var file *os.File
797
798 // A file upload has three possible cases:
799 // 1) Upload a new file
800 // 2) Resume a partially transferred file
801 // 3) Replace a fully uploaded file
802 // We have to infer which case applies by inspecting what is already on the filesystem
803
804 // 1) Check for existing file:
805 _, err = os.Stat(fullPath)
806 if err == nil {
807 return errors.New("existing file found at " + fullPath)
808 }
809 if errors.Is(err, fs.ErrNotExist) {
810 // If not found, open or create a new .incomplete file
811 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
812 if err != nil {
813 return err
814 }
815 }
816
817 f, err := newFileWrapper(s.FS, fullPath, 0)
818 if err != nil {
819 return err
820 }
821
822 rLogger.Infow("File upload started", "dstFile", fullPath)
823
824 rForkWriter := io.Discard
825 iForkWriter := io.Discard
826 if s.Config.PreserveResourceForks {
827 rForkWriter, err = f.rsrcForkWriter()
828 if err != nil {
829 return err
830 }
831
832 iForkWriter, err = f.infoForkWriter()
833 if err != nil {
834 return err
835 }
836 }
837
838 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
839 s.Logger.Error(err)
840 }
841
842 if err := file.Close(); err != nil {
843 return err
844 }
845
846 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
847 return err
848 }
849
850 rLogger.Infow("File upload complete", "dstFile", fullPath)
851 case FolderDownload:
852 // Folder Download flow:
853 // 1. Get filePath from the transfer
854 // 2. Iterate over files
855 // 3. For each fileWrapper:
856 // Send fileWrapper header to client
857 // The client can reply in 3 ways:
858 //
859 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
860 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
861 //
862 // 2. If download of a fileWrapper is to be resumed:
863 // client sends:
864 // []byte{0x00, 0x02} // download folder action
865 // [2]byte // Resume data size
866 // []byte fileWrapper resume data (see myField_FileResumeData)
867 //
868 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
869 //
870 // When download is requested (case 2 or 3), server replies with:
871 // [4]byte - fileWrapper size
872 // []byte - Flattened File Object
873 //
874 // After every fileWrapper download, client could request next fileWrapper with:
875 // []byte{0x00, 0x03}
876 //
877 // This notifies the server to send the next item header
878
879 basePathLen := len(fullPath)
880
881 rLogger.Infow("Start folder download", "path", fullPath)
882
883 nextAction := make([]byte, 2)
884 if _, err := io.ReadFull(rwc, nextAction); err != nil {
885 return err
886 }
887
888 i := 0
889 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
890 s.Stats.DownloadCounter += 1
891 i += 1
892
893 if err != nil {
894 return err
895 }
896
897 // skip dot files
898 if strings.HasPrefix(info.Name(), ".") {
899 return nil
900 }
901
902 hlFile, err := newFileWrapper(s.FS, path, 0)
903 if err != nil {
904 return err
905 }
906
907 subPath := path[basePathLen+1:]
908 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
909
910 if i == 1 {
911 return nil
912 }
913
914 fileHeader := NewFileHeader(subPath, info.IsDir())
915
916 // Send the fileWrapper header to client
917 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
918 s.Logger.Errorf("error sending file header: %v", err)
919 return err
920 }
921
922 // Read the client's Next Action request
923 if _, err := io.ReadFull(rwc, nextAction); err != nil {
924 return err
925 }
926
927 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
928
929 var dataOffset int64
930
931 switch nextAction[1] {
932 case dlFldrActionResumeFile:
933 // get size of resumeData
934 resumeDataByteLen := make([]byte, 2)
935 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
936 return err
937 }
938
939 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
940 resumeDataBytes := make([]byte, resumeDataLen)
941 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
942 return err
943 }
944
945 var frd FileResumeData
946 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
947 return err
948 }
949 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
950 case dlFldrActionNextFile:
951 // client asked to skip this file
952 return nil
953 }
954
955 if info.IsDir() {
956 return nil
957 }
958
959 rLogger.Infow("File download started",
960 "fileName", info.Name(),
961 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
962 )
963
964 // Send file size to client
965 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
966 s.Logger.Error(err)
967 return err
968 }
969
970 // Send ffo bytes to client
971 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
972 s.Logger.Error(err)
973 return err
974 }
975
976 file, err := s.FS.Open(path)
977 if err != nil {
978 return err
979 }
980
981 // wr := bufio.NewWriterSize(rwc, 1460)
982 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
983 return err
984 }
985
986 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
987 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
988 if err != nil {
989 return err
990 }
991
992 rFile, err := hlFile.rsrcForkFile()
993 if err != nil {
994 return err
995 }
996
997 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
998 return err
999 }
1000 }
1001
1002 // Read the client's Next Action request. This is always 3, I think?
1003 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1004 return err
1005 }
1006
1007 return nil
1008 })
1009
1010 if err != nil {
1011 return err
1012 }
1013
1014 case FolderUpload:
1015 rLogger.Infow(
1016 "Folder upload started",
1017 "dstPath", fullPath,
1018 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1019 "FolderItemCount", fileTransfer.FolderItemCount,
1020 )
1021
1022 // Check if the target folder exists. If not, create it.
1023 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1024 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1025 return err
1026 }
1027 }
1028
1029 // Begin the folder upload flow by sending the "next file action" to client
1030 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1031 return err
1032 }
1033
1034 fileSize := make([]byte, 4)
1035
1036 for i := 0; i < fileTransfer.ItemCount(); i++ {
1037 s.Stats.UploadCounter += 1
1038
1039 var fu folderUpload
1040 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1041 return err
1042 }
1043 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1044 return err
1045 }
1046 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1047 return err
1048 }
1049
1050 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1051
1052 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1053 return err
1054 }
1055
1056 rLogger.Infow(
1057 "Folder upload continued",
1058 "FormattedPath", fu.FormattedPath(),
1059 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1060 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1061 )
1062
1063 if fu.IsFolder == [2]byte{0, 1} {
1064 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1065 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1066 return err
1067 }
1068 }
1069
1070 // Tell client to send next file
1071 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1072 return err
1073 }
1074 } else {
1075 nextAction := dlFldrActionSendFile
1076
1077 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1078 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1079 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1080 return err
1081 }
1082 if err == nil {
1083 nextAction = dlFldrActionNextFile
1084 }
1085
1086 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1087 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1088 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1089 return err
1090 }
1091 if err == nil {
1092 nextAction = dlFldrActionResumeFile
1093 }
1094
1095 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1096 return err
1097 }
1098
1099 switch nextAction {
1100 case dlFldrActionNextFile:
1101 continue
1102 case dlFldrActionResumeFile:
1103 offset := make([]byte, 4)
1104 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1105
1106 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1107 if err != nil {
1108 return err
1109 }
1110
1111 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1112
1113 b, _ := fileResumeData.BinaryMarshal()
1114
1115 bs := make([]byte, 2)
1116 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1117
1118 if _, err := rwc.Write(append(bs, b...)); err != nil {
1119 return err
1120 }
1121
1122 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1123 return err
1124 }
1125
1126 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1127 s.Logger.Error(err)
1128 }
1129
1130 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1131 if err != nil {
1132 return err
1133 }
1134
1135 case dlFldrActionSendFile:
1136 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1137 return err
1138 }
1139
1140 filePath := filepath.Join(fullPath, fu.FormattedPath())
1141
1142 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1143 if err != nil {
1144 return err
1145 }
1146
1147 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1148
1149 incWriter, err := hlFile.incFileWriter()
1150 if err != nil {
1151 return err
1152 }
1153
1154 rForkWriter := io.Discard
1155 iForkWriter := io.Discard
1156 if s.Config.PreserveResourceForks {
1157 iForkWriter, err = hlFile.infoForkWriter()
1158 if err != nil {
1159 return err
1160 }
1161
1162 rForkWriter, err = hlFile.rsrcForkWriter()
1163 if err != nil {
1164 return err
1165 }
1166 }
1167 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1168 return err
1169 }
1170
1171 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1172 return err
1173 }
1174 }
1175
1176 // Tell client to send next fileWrapper
1177 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1178 return err
1179 }
1180 }
1181 }
1182 rLogger.Infof("Folder upload complete")
1183 }
1184
1185 return nil
1186 }