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