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