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