]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
Add missing error handling and logging (#109)
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "bufio"
5 "context"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "github.com/go-playground/validator/v10"
10 "go.uber.org/zap"
11 "gopkg.in/yaml.v3"
12 "io"
13 "io/fs"
14 "math/big"
15 "math/rand"
16 "net"
17 "os"
18 "path/filepath"
19 "strings"
20 "sync"
21 "time"
22 )
23
24 type contextKey string
25
26 var contextKeyReq = contextKey("req")
27
28 type requestCtx struct {
29 remoteAddr string
30 }
31
32 type Server struct {
33 Port int
34 Accounts map[string]*Account
35 Agreement []byte
36 Clients map[uint16]*ClientConn
37 fileTransfers map[[4]byte]*FileTransfer
38
39 Config *Config
40 ConfigDir string
41 Logger *zap.SugaredLogger
42
43 PrivateChatsMu sync.Mutex
44 PrivateChats map[uint32]*PrivateChat
45
46 NextGuestID *uint16
47 TrackerPassID [4]byte
48
49 StatsMu sync.Mutex
50 Stats *Stats
51
52 FS FileStore // Storage backend to use for File storage
53
54 outbox chan Transaction
55 mux sync.Mutex
56
57 threadedNewsMux sync.Mutex
58 ThreadedNews *ThreadedNews
59
60 flatNewsMux sync.Mutex
61 FlatNews []byte
62
63 banListMU sync.Mutex
64 banList map[string]*time.Time
65 }
66
67 func (s *Server) CurrentStats() Stats {
68 s.StatsMu.Lock()
69 defer s.StatsMu.Unlock()
70
71 stats := s.Stats
72 stats.CurrentlyConnected = len(s.Clients)
73
74 return *stats
75 }
76
77 type PrivateChat struct {
78 Subject string
79 ClientConn map[uint16]*ClientConn
80 }
81
82 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
83 s.Logger.Infow("Hotline server started",
84 "version", VERSION,
85 "API port", fmt.Sprintf(":%v", s.Port),
86 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
87 )
88
89 var wg sync.WaitGroup
90
91 wg.Add(1)
92 go func() {
93 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
94 if err != nil {
95 s.Logger.Fatal(err)
96 }
97
98 s.Logger.Fatal(s.Serve(ctx, ln))
99 }()
100
101 wg.Add(1)
102 go func() {
103 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
104 if err != nil {
105 s.Logger.Fatal(err)
106 }
107
108 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
109 }()
110
111 wg.Wait()
112
113 return nil
114 }
115
116 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
117 for {
118 conn, err := ln.Accept()
119 if err != nil {
120 return err
121 }
122
123 go func() {
124 defer func() { _ = conn.Close() }()
125
126 err = s.handleFileTransfer(
127 context.WithValue(ctx, contextKeyReq, requestCtx{
128 remoteAddr: conn.RemoteAddr().String(),
129 }),
130 conn,
131 )
132
133 if err != nil {
134 s.Logger.Errorw("file transfer error", "reason", err)
135 }
136 }()
137 }
138 }
139
140 func (s *Server) sendTransaction(t Transaction) error {
141 clientID, err := byteToInt(*t.clientID)
142 if err != nil {
143 return err
144 }
145
146 s.mux.Lock()
147 client := s.Clients[uint16(clientID)]
148 s.mux.Unlock()
149 if client == nil {
150 return fmt.Errorf("invalid client id %v", *t.clientID)
151 }
152
153 b, err := t.MarshalBinary()
154 if err != nil {
155 return err
156 }
157
158 _, err = client.Connection.Write(b)
159 if err != nil {
160 return err
161 }
162
163 return nil
164 }
165
166 func (s *Server) processOutbox() {
167 for {
168 t := <-s.outbox
169 go func() {
170 if err := s.sendTransaction(t); err != nil {
171 s.Logger.Errorw("error sending transaction", "err", err)
172 }
173 }()
174 }
175 }
176
177 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
178 go s.processOutbox()
179
180 for {
181 conn, err := ln.Accept()
182 if err != nil {
183 s.Logger.Errorw("error accepting connection", "err", err)
184 }
185 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
186 remoteAddr: conn.RemoteAddr().String(),
187 })
188
189 go func() {
190 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
191
192 defer conn.Close()
193 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
194 if err == io.EOF {
195 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
196 } else {
197 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
198 }
199 }
200 }()
201 }
202 }
203
204 const (
205 agreementFile = "Agreement.txt"
206 )
207
208 // NewServer constructs a new Server from a config dir
209 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, fs FileStore) (*Server, error) {
210 server := Server{
211 Port: netPort,
212 Accounts: make(map[string]*Account),
213 Config: new(Config),
214 Clients: make(map[uint16]*ClientConn),
215 fileTransfers: make(map[[4]byte]*FileTransfer),
216 PrivateChats: make(map[uint32]*PrivateChat),
217 ConfigDir: configDir,
218 Logger: logger,
219 NextGuestID: new(uint16),
220 outbox: make(chan Transaction),
221 Stats: &Stats{Since: time.Now()},
222 ThreadedNews: &ThreadedNews{},
223 FS: fs,
224 banList: make(map[string]*time.Time),
225 }
226
227 var err error
228
229 // generate a new random passID for tracker registration
230 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
231 return nil, err
232 }
233
234 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
235 if err != nil {
236 return nil, err
237 }
238
239 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
240 return nil, err
241 }
242
243 // try to load the ban list, but ignore errors as this file may not be present or may be empty
244 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
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.Debugw("Sent Tracker registration", "addr", t)
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) writeBanList() error {
331 s.banListMU.Lock()
332 defer s.banListMU.Unlock()
333
334 out, err := yaml.Marshal(s.banList)
335 if err != nil {
336 return err
337 }
338 err = os.WriteFile(
339 filepath.Join(s.ConfigDir, "Banlist.yaml"),
340 out,
341 0666,
342 )
343 return err
344 }
345
346 func (s *Server) writeThreadedNews() error {
347 s.threadedNewsMux.Lock()
348 defer s.threadedNewsMux.Unlock()
349
350 out, err := yaml.Marshal(s.ThreadedNews)
351 if err != nil {
352 return err
353 }
354 err = s.FS.WriteFile(
355 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
356 out,
357 0666,
358 )
359 return err
360 }
361
362 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
363 s.mux.Lock()
364 defer s.mux.Unlock()
365
366 clientConn := &ClientConn{
367 ID: &[]byte{0, 0},
368 Icon: []byte{0, 0},
369 Flags: []byte{0, 0},
370 UserName: []byte{},
371 Connection: conn,
372 Server: s,
373 Version: []byte{},
374 AutoReply: []byte{},
375 transfers: map[int]map[[4]byte]*FileTransfer{},
376 RemoteAddr: remoteAddr,
377 }
378 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
379 FileDownload: {},
380 FileUpload: {},
381 FolderDownload: {},
382 FolderUpload: {},
383 bannerDownload: {},
384 }
385
386 *s.NextGuestID++
387 ID := *s.NextGuestID
388
389 binary.BigEndian.PutUint16(*clientConn.ID, ID)
390 s.Clients[ID] = clientConn
391
392 return clientConn
393 }
394
395 // NewUser creates a new user account entry in the server map and config file
396 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
397 s.mux.Lock()
398 defer s.mux.Unlock()
399
400 account := Account{
401 Login: login,
402 Name: name,
403 Password: hashAndSalt([]byte(password)),
404 Access: access,
405 }
406 out, err := yaml.Marshal(&account)
407 if err != nil {
408 return err
409 }
410 s.Accounts[login] = &account
411
412 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
413 }
414
415 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
416 s.mux.Lock()
417 defer s.mux.Unlock()
418
419 // update renames the user login
420 if login != newLogin {
421 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
422 if err != nil {
423 return err
424 }
425 s.Accounts[newLogin] = s.Accounts[login]
426 delete(s.Accounts, login)
427 }
428
429 account := s.Accounts[newLogin]
430 account.Access = access
431 account.Name = name
432 account.Password = password
433
434 out, err := yaml.Marshal(&account)
435 if err != nil {
436 return err
437 }
438
439 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
440 return err
441 }
442
443 return nil
444 }
445
446 // DeleteUser deletes the user account
447 func (s *Server) DeleteUser(login string) error {
448 s.mux.Lock()
449 defer s.mux.Unlock()
450
451 delete(s.Accounts, login)
452
453 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
454 }
455
456 func (s *Server) connectedUsers() []Field {
457 s.mux.Lock()
458 defer s.mux.Unlock()
459
460 var connectedUsers []Field
461 for _, c := range sortedClients(s.Clients) {
462 user := User{
463 ID: *c.ID,
464 Icon: c.Icon,
465 Flags: c.Flags,
466 Name: string(c.UserName),
467 }
468 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, user.Payload()))
469 }
470 return connectedUsers
471 }
472
473 func (s *Server) loadBanList(path string) error {
474 fh, err := os.Open(path)
475 if err != nil {
476 return err
477 }
478 decoder := yaml.NewDecoder(fh)
479
480 return decoder.Decode(s.banList)
481 }
482
483 // loadThreadedNews loads the threaded news data from disk
484 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
485 fh, err := os.Open(threadedNewsPath)
486 if err != nil {
487 return err
488 }
489 decoder := yaml.NewDecoder(fh)
490
491 return decoder.Decode(s.ThreadedNews)
492 }
493
494 // loadAccounts loads account data from disk
495 func (s *Server) loadAccounts(userDir string) error {
496 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
497 if err != nil {
498 return err
499 }
500
501 if len(matches) == 0 {
502 return errors.New("no user accounts found in " + userDir)
503 }
504
505 for _, file := range matches {
506 fh, err := s.FS.Open(file)
507 if err != nil {
508 return err
509 }
510
511 account := Account{}
512 decoder := yaml.NewDecoder(fh)
513 if err := decoder.Decode(&account); err != nil {
514 return err
515 }
516
517 s.Accounts[account.Login] = &account
518 }
519 return nil
520 }
521
522 func (s *Server) loadConfig(path string) error {
523 fh, err := s.FS.Open(path)
524 if err != nil {
525 return err
526 }
527
528 decoder := yaml.NewDecoder(fh)
529 err = decoder.Decode(s.Config)
530 if err != nil {
531 return err
532 }
533
534 validate := validator.New()
535 err = validate.Struct(s.Config)
536 if err != nil {
537 return err
538 }
539 return nil
540 }
541
542 // handleNewConnection takes a new net.Conn and performs the initial login sequence
543 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
544 defer dontPanic(s.Logger)
545
546 if err := Handshake(rwc); err != nil {
547 return err
548 }
549
550 // Create a new scanner for parsing incoming bytes into transaction tokens
551 scanner := bufio.NewScanner(rwc)
552 scanner.Split(transactionScanner)
553
554 scanner.Scan()
555
556 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
557 // scanner re-uses the buffer for subsequent scans.
558 buf := make([]byte, len(scanner.Bytes()))
559 copy(buf, scanner.Bytes())
560
561 var clientLogin Transaction
562 if _, err := clientLogin.Write(buf); err != nil {
563 return err
564 }
565
566 // check if remoteAddr is present in the ban list
567 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
568 // permaban
569 if banUntil == nil {
570 t := NewTransaction(
571 TranServerMsg,
572 &[]byte{0, 0},
573 NewField(FieldData, []byte("You are permanently banned on this server")),
574 NewField(FieldChatOptions, []byte{0, 0}),
575 )
576
577 b, err := t.MarshalBinary()
578 if err != nil {
579 return err
580 }
581
582 _, err = rwc.Write(b)
583 if err != nil {
584 return err
585 }
586
587 time.Sleep(1 * time.Second)
588 return nil
589 }
590
591 // temporary ban
592 if time.Now().Before(*banUntil) {
593 t := NewTransaction(
594 TranServerMsg,
595 &[]byte{0, 0},
596 NewField(FieldData, []byte("You are temporarily banned on this server")),
597 NewField(FieldChatOptions, []byte{0, 0}),
598 )
599 b, err := t.MarshalBinary()
600 if err != nil {
601 return err
602 }
603
604 _, err = rwc.Write(b)
605 if err != nil {
606 return err
607 }
608
609 time.Sleep(1 * time.Second)
610 return nil
611 }
612 }
613
614 c := s.NewClientConn(rwc, remoteAddr)
615 defer c.Disconnect()
616
617 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
618 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
619 c.Version = clientLogin.GetField(FieldVersion).Data
620
621 var login string
622 for _, char := range encodedLogin {
623 login += string(rune(255 - uint(char)))
624 }
625 if login == "" {
626 login = GuestAccount
627 }
628
629 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
630
631 // If authentication fails, send error reply and close connection
632 if !c.Authenticate(login, encodedPassword) {
633 t := c.NewErrReply(&clientLogin, "Incorrect login.")
634 b, err := t.MarshalBinary()
635 if err != nil {
636 return err
637 }
638 if _, err := rwc.Write(b); err != nil {
639 return err
640 }
641
642 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
643
644 return nil
645 }
646
647 if clientLogin.GetField(FieldUserIconID).Data != nil {
648 c.Icon = clientLogin.GetField(FieldUserIconID).Data
649 }
650
651 c.Account = c.Server.Accounts[login]
652
653 if clientLogin.GetField(FieldUserName).Data != nil {
654 if c.Authorize(accessAnyName) {
655 c.UserName = clientLogin.GetField(FieldUserName).Data
656 } else {
657 c.UserName = []byte(c.Account.Name)
658 }
659 }
660
661 if c.Authorize(accessDisconUser) {
662 c.Flags = []byte{0, 2}
663 }
664
665 s.outbox <- c.NewReply(&clientLogin,
666 NewField(FieldVersion, []byte{0x00, 0xbe}),
667 NewField(FieldCommunityBannerID, []byte{0, 0}),
668 NewField(FieldServerName, []byte(s.Config.Name)),
669 )
670
671 // Send user access privs so client UI knows how to behave
672 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
673
674 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
675 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
676 // TranShowAgreement but with the NoServerAgreement field set to 1.
677 if c.Authorize(accessNoAgreement) {
678 // If client version is nil, then the client uses the 1.2.3 login behavior
679 if c.Version != nil {
680 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
681 }
682 } else {
683 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
684 }
685
686 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
687 // flow and not the 1.5+ flow.
688 if len(c.UserName) != 0 {
689 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
690 // part of TranAgreed
691 c.logger = c.logger.With("name", string(c.UserName))
692
693 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
694
695 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
696 // information yet, so we do it in TranAgreed instead
697 for _, t := range c.notifyOthers(
698 *NewTransaction(
699 TranNotifyChangeUser, nil,
700 NewField(FieldUserName, c.UserName),
701 NewField(FieldUserID, *c.ID),
702 NewField(FieldUserIconID, c.Icon),
703 NewField(FieldUserFlags, c.Flags),
704 ),
705 ) {
706 c.Server.outbox <- t
707 }
708 }
709
710 c.Server.Stats.ConnectionCounter += 1
711 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
712 c.Server.Stats.ConnectionPeak = len(s.Clients)
713 }
714
715 // Scan for new transactions and handle them as they come in.
716 for scanner.Scan() {
717 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
718 // scanner re-uses the buffer for subsequent scans.
719 buf := make([]byte, len(scanner.Bytes()))
720 copy(buf, scanner.Bytes())
721
722 var t Transaction
723 if _, err := t.Write(buf); err != nil {
724 return err
725 }
726
727 if err := c.handleTransaction(t); err != nil {
728 c.logger.Errorw("Error handling transaction", "err", err)
729 }
730 }
731 return nil
732 }
733
734 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
735 s.PrivateChatsMu.Lock()
736 defer s.PrivateChatsMu.Unlock()
737
738 randID := make([]byte, 4)
739 rand.Read(randID)
740 data := binary.BigEndian.Uint32(randID)
741
742 s.PrivateChats[data] = &PrivateChat{
743 ClientConn: make(map[uint16]*ClientConn),
744 }
745 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
746
747 return randID
748 }
749
750 const dlFldrActionSendFile = 1
751 const dlFldrActionResumeFile = 2
752 const dlFldrActionNextFile = 3
753
754 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
755 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
756 defer dontPanic(s.Logger)
757
758 txBuf := make([]byte, 16)
759 if _, err := io.ReadFull(rwc, txBuf); err != nil {
760 return err
761 }
762
763 var t transfer
764 if _, err := t.Write(txBuf); err != nil {
765 return err
766 }
767
768 defer func() {
769 s.mux.Lock()
770 delete(s.fileTransfers, t.ReferenceNumber)
771 s.mux.Unlock()
772
773 // Wait a few seconds before closing the connection: this is a workaround for problems
774 // observed with Windows clients where the client must initiate close of the TCP connection before
775 // the server does. This is gross and seems unnecessary. TODO: Revisit?
776 time.Sleep(3 * time.Second)
777 }()
778
779 s.mux.Lock()
780 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
781 s.mux.Unlock()
782 if !ok {
783 return errors.New("invalid transaction ID")
784 }
785
786 defer func() {
787 fileTransfer.ClientConn.transfersMU.Lock()
788 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
789 fileTransfer.ClientConn.transfersMU.Unlock()
790 }()
791
792 rLogger := s.Logger.With(
793 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
794 "login", fileTransfer.ClientConn.Account.Login,
795 "name", string(fileTransfer.ClientConn.UserName),
796 )
797
798 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
799 if err != nil {
800 return err
801 }
802
803 switch fileTransfer.Type {
804 case bannerDownload:
805 if err := s.bannerDownload(rwc); err != nil {
806 return err
807 }
808 case FileDownload:
809 s.Stats.DownloadCounter += 1
810 s.Stats.DownloadsInProgress += 1
811 defer func() {
812 s.Stats.DownloadsInProgress -= 1
813 }()
814
815 var dataOffset int64
816 if fileTransfer.fileResumeData != nil {
817 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
818 }
819
820 fw, err := newFileWrapper(s.FS, fullPath, 0)
821 if err != nil {
822 return err
823 }
824
825 rLogger.Infow("File download started", "filePath", fullPath)
826
827 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
828 if fileTransfer.options == nil {
829 // Start by sending flat file object to client
830 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
831 return err
832 }
833 }
834
835 file, err := fw.dataForkReader()
836 if err != nil {
837 return err
838 }
839
840 br := bufio.NewReader(file)
841 if _, err := br.Discard(int(dataOffset)); err != nil {
842 return err
843 }
844
845 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
846 return err
847 }
848
849 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
850 if fileTransfer.fileResumeData == nil {
851 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
852 if err != nil {
853 return err
854 }
855 }
856
857 rFile, err := fw.rsrcForkFile()
858 if err != nil {
859 return nil
860 }
861
862 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
863 return err
864 }
865
866 case FileUpload:
867 s.Stats.UploadCounter += 1
868 s.Stats.UploadsInProgress += 1
869 defer func() { s.Stats.UploadsInProgress -= 1 }()
870
871 var file *os.File
872
873 // A file upload has three possible cases:
874 // 1) Upload a new file
875 // 2) Resume a partially transferred file
876 // 3) Replace a fully uploaded file
877 // We have to infer which case applies by inspecting what is already on the filesystem
878
879 // 1) Check for existing file:
880 _, err = os.Stat(fullPath)
881 if err == nil {
882 return errors.New("existing file found at " + fullPath)
883 }
884 if errors.Is(err, fs.ErrNotExist) {
885 // If not found, open or create a new .incomplete file
886 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
887 if err != nil {
888 return err
889 }
890 }
891
892 f, err := newFileWrapper(s.FS, fullPath, 0)
893 if err != nil {
894 return err
895 }
896
897 rLogger.Infow("File upload started", "dstFile", fullPath)
898
899 rForkWriter := io.Discard
900 iForkWriter := io.Discard
901 if s.Config.PreserveResourceForks {
902 rForkWriter, err = f.rsrcForkWriter()
903 if err != nil {
904 return err
905 }
906
907 iForkWriter, err = f.infoForkWriter()
908 if err != nil {
909 return err
910 }
911 }
912
913 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
914 s.Logger.Error(err)
915 }
916
917 if err := file.Close(); err != nil {
918 return err
919 }
920
921 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
922 return err
923 }
924
925 rLogger.Infow("File upload complete", "dstFile", fullPath)
926
927 case FolderDownload:
928 s.Stats.DownloadCounter += 1
929 s.Stats.DownloadsInProgress += 1
930 defer func() { s.Stats.DownloadsInProgress -= 1 }()
931
932 // Folder Download flow:
933 // 1. Get filePath from the transfer
934 // 2. Iterate over files
935 // 3. For each fileWrapper:
936 // Send fileWrapper header to client
937 // The client can reply in 3 ways:
938 //
939 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
940 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
941 //
942 // 2. If download of a fileWrapper is to be resumed:
943 // client sends:
944 // []byte{0x00, 0x02} // download folder action
945 // [2]byte // Resume data size
946 // []byte fileWrapper resume data (see myField_FileResumeData)
947 //
948 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
949 //
950 // When download is requested (case 2 or 3), server replies with:
951 // [4]byte - fileWrapper size
952 // []byte - Flattened File Object
953 //
954 // After every fileWrapper download, client could request next fileWrapper with:
955 // []byte{0x00, 0x03}
956 //
957 // This notifies the server to send the next item header
958
959 basePathLen := len(fullPath)
960
961 rLogger.Infow("Start folder download", "path", fullPath)
962
963 nextAction := make([]byte, 2)
964 if _, err := io.ReadFull(rwc, nextAction); err != nil {
965 return err
966 }
967
968 i := 0
969 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
970 s.Stats.DownloadCounter += 1
971 i += 1
972
973 if err != nil {
974 return err
975 }
976
977 // skip dot files
978 if strings.HasPrefix(info.Name(), ".") {
979 return nil
980 }
981
982 hlFile, err := newFileWrapper(s.FS, path, 0)
983 if err != nil {
984 return err
985 }
986
987 subPath := path[basePathLen+1:]
988 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
989
990 if i == 1 {
991 return nil
992 }
993
994 fileHeader := NewFileHeader(subPath, info.IsDir())
995
996 // Send the fileWrapper header to client
997 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
998 s.Logger.Errorf("error sending file header: %v", err)
999 return err
1000 }
1001
1002 // Read the client's Next Action request
1003 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1004 return err
1005 }
1006
1007 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1008
1009 var dataOffset int64
1010
1011 switch nextAction[1] {
1012 case dlFldrActionResumeFile:
1013 // get size of resumeData
1014 resumeDataByteLen := make([]byte, 2)
1015 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1016 return err
1017 }
1018
1019 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1020 resumeDataBytes := make([]byte, resumeDataLen)
1021 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1022 return err
1023 }
1024
1025 var frd FileResumeData
1026 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1027 return err
1028 }
1029 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1030 case dlFldrActionNextFile:
1031 // client asked to skip this file
1032 return nil
1033 }
1034
1035 if info.IsDir() {
1036 return nil
1037 }
1038
1039 rLogger.Infow("File download started",
1040 "fileName", info.Name(),
1041 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1042 )
1043
1044 // Send file size to client
1045 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1046 s.Logger.Error(err)
1047 return err
1048 }
1049
1050 // Send ffo bytes to client
1051 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1052 s.Logger.Error(err)
1053 return err
1054 }
1055
1056 file, err := s.FS.Open(path)
1057 if err != nil {
1058 return err
1059 }
1060
1061 // wr := bufio.NewWriterSize(rwc, 1460)
1062 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1063 return err
1064 }
1065
1066 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1067 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1068 if err != nil {
1069 return err
1070 }
1071
1072 rFile, err := hlFile.rsrcForkFile()
1073 if err != nil {
1074 return err
1075 }
1076
1077 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1078 return err
1079 }
1080 }
1081
1082 // Read the client's Next Action request. This is always 3, I think?
1083 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1084 return err
1085 }
1086
1087 return nil
1088 })
1089
1090 if err != nil {
1091 return err
1092 }
1093
1094 case FolderUpload:
1095 s.Stats.UploadCounter += 1
1096 s.Stats.UploadsInProgress += 1
1097 defer func() { s.Stats.UploadsInProgress -= 1 }()
1098 rLogger.Infow(
1099 "Folder upload started",
1100 "dstPath", fullPath,
1101 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1102 "FolderItemCount", fileTransfer.FolderItemCount,
1103 )
1104
1105 // Check if the target folder exists. If not, create it.
1106 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1107 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1108 return err
1109 }
1110 }
1111
1112 // Begin the folder upload flow by sending the "next file action" to client
1113 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1114 return err
1115 }
1116
1117 fileSize := make([]byte, 4)
1118
1119 for i := 0; i < fileTransfer.ItemCount(); i++ {
1120 s.Stats.UploadCounter += 1
1121
1122 var fu folderUpload
1123 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1124 return err
1125 }
1126 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1127 return err
1128 }
1129 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1130 return err
1131 }
1132
1133 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1134
1135 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1136 return err
1137 }
1138
1139 rLogger.Infow(
1140 "Folder upload continued",
1141 "FormattedPath", fu.FormattedPath(),
1142 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1143 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1144 )
1145
1146 if fu.IsFolder == [2]byte{0, 1} {
1147 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1148 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1149 return err
1150 }
1151 }
1152
1153 // Tell client to send next file
1154 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1155 return err
1156 }
1157 } else {
1158 nextAction := dlFldrActionSendFile
1159
1160 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1161 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1162 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1163 return err
1164 }
1165 if err == nil {
1166 nextAction = dlFldrActionNextFile
1167 }
1168
1169 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1170 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1171 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1172 return err
1173 }
1174 if err == nil {
1175 nextAction = dlFldrActionResumeFile
1176 }
1177
1178 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1179 return err
1180 }
1181
1182 switch nextAction {
1183 case dlFldrActionNextFile:
1184 continue
1185 case dlFldrActionResumeFile:
1186 offset := make([]byte, 4)
1187 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1188
1189 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1190 if err != nil {
1191 return err
1192 }
1193
1194 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1195
1196 b, _ := fileResumeData.BinaryMarshal()
1197
1198 bs := make([]byte, 2)
1199 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1200
1201 if _, err := rwc.Write(append(bs, b...)); err != nil {
1202 return err
1203 }
1204
1205 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1206 return err
1207 }
1208
1209 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1210 s.Logger.Error(err)
1211 }
1212
1213 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1214 if err != nil {
1215 return err
1216 }
1217
1218 case dlFldrActionSendFile:
1219 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1220 return err
1221 }
1222
1223 filePath := filepath.Join(fullPath, fu.FormattedPath())
1224
1225 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1226 if err != nil {
1227 return err
1228 }
1229
1230 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1231
1232 incWriter, err := hlFile.incFileWriter()
1233 if err != nil {
1234 return err
1235 }
1236
1237 rForkWriter := io.Discard
1238 iForkWriter := io.Discard
1239 if s.Config.PreserveResourceForks {
1240 iForkWriter, err = hlFile.infoForkWriter()
1241 if err != nil {
1242 return err
1243 }
1244
1245 rForkWriter, err = hlFile.rsrcForkWriter()
1246 if err != nil {
1247 return err
1248 }
1249 }
1250 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1251 return err
1252 }
1253
1254 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1255 return err
1256 }
1257 }
1258
1259 // Tell client to send next fileWrapper
1260 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1261 return err
1262 }
1263 }
1264 }
1265 rLogger.Infof("Folder upload complete")
1266 }
1267
1268 return nil
1269 }