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