]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
e6322e04193db80676a76f9e9623dde8e80a4c6c
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "context"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "github.com/go-playground/validator/v10"
9 "go.uber.org/zap"
10 "io"
11 "io/fs"
12 "io/ioutil"
13 "math/big"
14 "math/rand"
15 "net"
16 "os"
17 "path"
18 "path/filepath"
19 "runtime/debug"
20 "sort"
21 "strings"
22 "sync"
23 "time"
24
25 "gopkg.in/yaml.v3"
26 )
27
28 const (
29 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
30 idleCheckInterval = 10 // time in seconds to check for idle users
31 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
32 )
33
34 type Server struct {
35 Port int
36 Accounts map[string]*Account
37 Agreement []byte
38 Clients map[uint16]*ClientConn
39 FlatNews []byte
40 ThreadedNews *ThreadedNews
41 FileTransfers map[uint32]*FileTransfer
42 Config *Config
43 ConfigDir string
44 Logger *zap.SugaredLogger
45 PrivateChats map[uint32]*PrivateChat
46 NextGuestID *uint16
47 TrackerPassID []byte
48 Stats *Stats
49
50 APIListener net.Listener
51 FileListener net.Listener
52
53 // newsReader io.Reader
54 // newsWriter io.WriteCloser
55
56 outbox chan Transaction
57
58 mux sync.Mutex
59 flatNewsMux sync.Mutex
60 }
61
62 type PrivateChat struct {
63 Subject string
64 ClientConn map[uint16]*ClientConn
65 }
66
67 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
68 s.Logger.Infow("Hotline server started", "version", VERSION)
69 var wg sync.WaitGroup
70
71 wg.Add(1)
72 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
73
74 wg.Add(1)
75 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
76
77 wg.Wait()
78
79 return nil
80 }
81
82 func (s *Server) APIPort() int {
83 return s.APIListener.Addr().(*net.TCPAddr).Port
84 }
85
86 func (s *Server) ServeFileTransfers(ln net.Listener) error {
87 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
88
89 for {
90 conn, err := ln.Accept()
91 if err != nil {
92 return err
93 }
94
95 go func() {
96 if err := s.handleFileTransfer(conn); err != nil {
97 s.Logger.Errorw("file transfer error", "reason", err)
98 }
99 }()
100 }
101 }
102
103 func (s *Server) sendTransaction(t Transaction) error {
104 requestNum := binary.BigEndian.Uint16(t.Type)
105 clientID, err := byteToInt(*t.clientID)
106 if err != nil {
107 return err
108 }
109
110 s.mux.Lock()
111 client := s.Clients[uint16(clientID)]
112 s.mux.Unlock()
113 if client == nil {
114 return fmt.Errorf("invalid client id %v", *t.clientID)
115 }
116 userName := string(client.UserName)
117 login := client.Account.Login
118
119 handler := TransactionHandlers[requestNum]
120
121 b, err := t.MarshalBinary()
122 if err != nil {
123 return err
124 }
125 var n int
126 if n, err = client.Connection.Write(b); err != nil {
127 return err
128 }
129 s.Logger.Debugw("Sent Transaction",
130 "name", userName,
131 "login", login,
132 "IsReply", t.IsReply,
133 "type", handler.Name,
134 "sentBytes", n,
135 "remoteAddr", client.RemoteAddr,
136 )
137 return nil
138 }
139
140 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
141 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
142
143 for {
144 conn, err := ln.Accept()
145 if err != nil {
146 s.Logger.Errorw("error accepting connection", "err", err)
147 }
148
149 go func() {
150 for {
151 t := <-s.outbox
152 go func() {
153 if err := s.sendTransaction(t); err != nil {
154 s.Logger.Errorw("error sending transaction", "err", err)
155 }
156 }()
157 }
158 }()
159 go func() {
160 if err := s.handleNewConnection(conn, conn.RemoteAddr().String()); err != nil {
161 if err == io.EOF {
162 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
163 } else {
164 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
165 }
166 }
167 }()
168 }
169 }
170
171 const (
172 agreementFile = "Agreement.txt"
173 )
174
175 // NewServer constructs a new Server from a config dir
176 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
177 server := Server{
178 Port: netPort,
179 Accounts: make(map[string]*Account),
180 Config: new(Config),
181 Clients: make(map[uint16]*ClientConn),
182 FileTransfers: make(map[uint32]*FileTransfer),
183 PrivateChats: make(map[uint32]*PrivateChat),
184 ConfigDir: configDir,
185 Logger: logger,
186 NextGuestID: new(uint16),
187 outbox: make(chan Transaction),
188 Stats: &Stats{StartTime: time.Now()},
189 ThreadedNews: &ThreadedNews{},
190 TrackerPassID: make([]byte, 4),
191 }
192
193 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
194 if err != nil {
195 return nil, err
196 }
197 server.APIListener = ln
198
199 if netPort != 0 {
200 netPort += 1
201 }
202
203 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
204 server.FileListener = ln2
205 if err != nil {
206 return nil, err
207 }
208
209 // generate a new random passID for tracker registration
210 if _, err := rand.Read(server.TrackerPassID); err != nil {
211 return nil, err
212 }
213
214 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
215 if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
216 return nil, err
217 }
218
219 if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil {
220 return nil, err
221 }
222
223 if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil {
224 return nil, err
225 }
226
227 if err := server.loadConfig(configDir + "config.yaml"); err != nil {
228 return nil, err
229 }
230
231 if err := server.loadAccounts(configDir + "Users/"); err != nil {
232 return nil, err
233 }
234
235 server.Config.FileRoot = configDir + "Files/"
236
237 *server.NextGuestID = 1
238
239 if server.Config.EnableTrackerRegistration {
240 server.Logger.Infow(
241 "Tracker registration enabled",
242 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
243 "trackers", server.Config.Trackers,
244 )
245
246 go func() {
247 for {
248 tr := &TrackerRegistration{
249 Port: []byte{0x15, 0x7c},
250 UserCount: server.userCount(),
251 PassID: server.TrackerPassID,
252 Name: server.Config.Name,
253 Description: server.Config.Description,
254 }
255 for _, t := range server.Config.Trackers {
256 if err := register(t, tr); err != nil {
257 server.Logger.Errorw("unable to register with tracker %v", "error", err)
258 }
259 server.Logger.Infow("Sent Tracker registration", "data", tr)
260 }
261
262 time.Sleep(trackerUpdateFrequency * time.Second)
263 }
264 }()
265 }
266
267 // Start Client Keepalive go routine
268 go server.keepaliveHandler()
269
270 return &server, nil
271 }
272
273 func (s *Server) userCount() int {
274 s.mux.Lock()
275 defer s.mux.Unlock()
276
277 return len(s.Clients)
278 }
279
280 func (s *Server) keepaliveHandler() {
281 for {
282 time.Sleep(idleCheckInterval * time.Second)
283 s.mux.Lock()
284
285 for _, c := range s.Clients {
286 c.IdleTime += idleCheckInterval
287 if c.IdleTime > userIdleSeconds && !c.Idle {
288 c.Idle = true
289
290 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
291 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
292 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
293
294 c.sendAll(
295 tranNotifyChangeUser,
296 NewField(fieldUserID, *c.ID),
297 NewField(fieldUserFlags, *c.Flags),
298 NewField(fieldUserName, c.UserName),
299 NewField(fieldUserIconID, *c.Icon),
300 )
301 }
302 }
303 s.mux.Unlock()
304 }
305 }
306
307 func (s *Server) writeThreadedNews() error {
308 s.mux.Lock()
309 defer s.mux.Unlock()
310
311 out, err := yaml.Marshal(s.ThreadedNews)
312 if err != nil {
313 return err
314 }
315 err = ioutil.WriteFile(
316 s.ConfigDir+"ThreadedNews.yaml",
317 out,
318 0666,
319 )
320 return err
321 }
322
323 func (s *Server) NewClientConn(conn net.Conn, remoteAddr string) *ClientConn {
324 s.mux.Lock()
325 defer s.mux.Unlock()
326
327 clientConn := &ClientConn{
328 ID: &[]byte{0, 0},
329 Icon: &[]byte{0, 0},
330 Flags: &[]byte{0, 0},
331 UserName: []byte{},
332 Connection: conn,
333 Server: s,
334 Version: &[]byte{},
335 AutoReply: []byte{},
336 Transfers: make(map[int][]*FileTransfer),
337 Agreed: false,
338 RemoteAddr: remoteAddr,
339 }
340 *s.NextGuestID++
341 ID := *s.NextGuestID
342
343 binary.BigEndian.PutUint16(*clientConn.ID, ID)
344 s.Clients[ID] = clientConn
345
346 return clientConn
347 }
348
349 // NewUser creates a new user account entry in the server map and config file
350 func (s *Server) NewUser(login, name, password string, access []byte) error {
351 s.mux.Lock()
352 defer s.mux.Unlock()
353
354 account := Account{
355 Login: login,
356 Name: name,
357 Password: hashAndSalt([]byte(password)),
358 Access: &access,
359 }
360 out, err := yaml.Marshal(&account)
361 if err != nil {
362 return err
363 }
364 s.Accounts[login] = &account
365
366 return FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
367 }
368
369 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
370 s.mux.Lock()
371 defer s.mux.Unlock()
372
373 fmt.Printf("login: %v, newLogin: %v: ", login, newLogin)
374
375 // update renames the user login
376 if login != newLogin {
377 err := os.Rename(s.ConfigDir+"Users/"+login+".yaml", s.ConfigDir+"Users/"+newLogin+".yaml")
378 if err != nil {
379 return err
380 }
381 s.Accounts[newLogin] = s.Accounts[login]
382 delete(s.Accounts, login)
383 }
384
385 account := s.Accounts[newLogin]
386 account.Access = &access
387 account.Name = name
388 account.Password = password
389
390 out, err := yaml.Marshal(&account)
391 if err != nil {
392 return err
393 }
394 if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil {
395 return err
396 }
397
398 return nil
399 }
400
401 // DeleteUser deletes the user account
402 func (s *Server) DeleteUser(login string) error {
403 s.mux.Lock()
404 defer s.mux.Unlock()
405
406 delete(s.Accounts, login)
407
408 return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
409 }
410
411 func (s *Server) connectedUsers() []Field {
412 s.mux.Lock()
413 defer s.mux.Unlock()
414
415 var connectedUsers []Field
416 for _, c := range sortedClients(s.Clients) {
417 if !c.Agreed {
418 continue
419 }
420 user := User{
421 ID: *c.ID,
422 Icon: *c.Icon,
423 Flags: *c.Flags,
424 Name: string(c.UserName),
425 }
426 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
427 }
428 return connectedUsers
429 }
430
431 // loadThreadedNews loads the threaded news data from disk
432 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
433 fh, err := os.Open(threadedNewsPath)
434 if err != nil {
435 return err
436 }
437 decoder := yaml.NewDecoder(fh)
438
439 return decoder.Decode(s.ThreadedNews)
440 }
441
442 // loadAccounts loads account data from disk
443 func (s *Server) loadAccounts(userDir string) error {
444 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
445 if err != nil {
446 return err
447 }
448
449 if len(matches) == 0 {
450 return errors.New("no user accounts found in " + userDir)
451 }
452
453 for _, file := range matches {
454 fh, err := FS.Open(file)
455 if err != nil {
456 return err
457 }
458
459 account := Account{}
460 decoder := yaml.NewDecoder(fh)
461 if err := decoder.Decode(&account); err != nil {
462 return err
463 }
464
465 s.Accounts[account.Login] = &account
466 }
467 return nil
468 }
469
470 func (s *Server) loadConfig(path string) error {
471 fh, err := FS.Open(path)
472 if err != nil {
473 return err
474 }
475
476 decoder := yaml.NewDecoder(fh)
477 err = decoder.Decode(s.Config)
478 if err != nil {
479 return err
480 }
481
482 validate := validator.New()
483 err = validate.Struct(s.Config)
484 if err != nil {
485 return err
486 }
487 return nil
488 }
489
490 const (
491 minTransactionLen = 22 // minimum length of any transaction
492 )
493
494 // dontPanic recovers and logs panics instead of crashing
495 // TODO: remove this after known issues are fixed
496 func dontPanic(logger *zap.SugaredLogger) {
497 if r := recover(); r != nil {
498 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
499 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
500 }
501 }
502
503 // handleNewConnection takes a new net.Conn and performs the initial login sequence
504 func (s *Server) handleNewConnection(conn net.Conn, remoteAddr string) error {
505 defer dontPanic(s.Logger)
506
507 if err := Handshake(conn); err != nil {
508 return err
509 }
510
511 buf := make([]byte, 1024)
512 // TODO: fix potential short read with io.ReadFull
513 readLen, err := conn.Read(buf)
514 if readLen < minTransactionLen {
515 return err
516 }
517 if err != nil {
518 return err
519 }
520
521 clientLogin, _, err := ReadTransaction(buf[:readLen])
522 if err != nil {
523 return err
524 }
525
526 c := s.NewClientConn(conn, remoteAddr)
527 defer c.Disconnect()
528
529 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
530 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
531 *c.Version = clientLogin.GetField(fieldVersion).Data
532
533 var login string
534 for _, char := range encodedLogin {
535 login += string(rune(255 - uint(char)))
536 }
537 if login == "" {
538 login = GuestAccount
539 }
540
541 // If authentication fails, send error reply and close connection
542 if !c.Authenticate(login, encodedPassword) {
543 t := c.NewErrReply(clientLogin, "Incorrect login.")
544 b, err := t.MarshalBinary()
545 if err != nil {
546 return err
547 }
548 if _, err := conn.Write(b); err != nil {
549 return err
550 }
551 return fmt.Errorf("incorrect login")
552 }
553
554 if clientLogin.GetField(fieldUserName).Data != nil {
555 c.UserName = clientLogin.GetField(fieldUserName).Data
556 }
557
558 if clientLogin.GetField(fieldUserIconID).Data != nil {
559 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
560 }
561
562 c.Account = c.Server.Accounts[login]
563
564 if c.Authorize(accessDisconUser) {
565 *c.Flags = []byte{0, 2}
566 }
567
568 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr)
569
570 s.outbox <- c.NewReply(clientLogin,
571 NewField(fieldVersion, []byte{0x00, 0xbe}),
572 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
573 NewField(fieldServerName, []byte(s.Config.Name)),
574 )
575
576 // Send user access privs so client UI knows how to behave
577 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
578
579 // Show agreement to client
580 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
581
582 // assume simplified hotline v1.2.3 login flow that does not require agreement
583 if *c.Version == nil {
584 c.Agreed = true
585
586 c.notifyOthers(
587 *NewTransaction(
588 tranNotifyChangeUser, nil,
589 NewField(fieldUserName, c.UserName),
590 NewField(fieldUserID, *c.ID),
591 NewField(fieldUserIconID, *c.Icon),
592 NewField(fieldUserFlags, *c.Flags),
593 ),
594 )
595 }
596
597 c.Server.Stats.LoginCount += 1
598
599 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
600 tranBuff := make([]byte, 0)
601 tReadlen := 0
602 // Infinite loop where take action on incoming client requests until the connection is closed
603 for {
604 buf = make([]byte, readBuffSize)
605 tranBuff = tranBuff[tReadlen:]
606
607 readLen, err := c.Connection.Read(buf)
608 if err != nil {
609 return err
610 }
611 tranBuff = append(tranBuff, buf[:readLen]...)
612
613 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
614 // into a slice of transactions
615 var transactions []Transaction
616 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
617 c.Server.Logger.Errorw("Error handling transaction", "err", err)
618 }
619
620 // iterate over all of the transactions that were parsed from the byte slice and handle them
621 for _, t := range transactions {
622 if err := c.handleTransaction(&t); err != nil {
623 c.Server.Logger.Errorw("Error handling transaction", "err", err)
624 }
625 }
626 }
627 }
628
629 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
630 // in the file transfer request payload, and the file transfer server will use it to map the request
631 // to a transfer
632 func (s *Server) NewTransactionRef() []byte {
633 transactionRef := make([]byte, 4)
634 rand.Read(transactionRef)
635
636 return transactionRef
637 }
638
639 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
640 s.mux.Lock()
641 defer s.mux.Unlock()
642
643 randID := make([]byte, 4)
644 rand.Read(randID)
645 data := binary.BigEndian.Uint32(randID[:])
646
647 s.PrivateChats[data] = &PrivateChat{
648 Subject: "",
649 ClientConn: make(map[uint16]*ClientConn),
650 }
651 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
652
653 return randID
654 }
655
656 const dlFldrActionSendFile = 1
657 const dlFldrActionResumeFile = 2
658 const dlFldrActionNextFile = 3
659
660 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
661 func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
662 defer func() {
663
664 if err := conn.Close(); err != nil {
665 s.Logger.Errorw("error closing connection", "error", err)
666 }
667 }()
668
669 defer dontPanic(s.Logger)
670
671 txBuf := make([]byte, 16)
672 if _, err := io.ReadFull(conn, txBuf); err != nil {
673 return err
674 }
675
676 var t transfer
677 if _, err := t.Write(txBuf); err != nil {
678 return err
679 }
680
681 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
682 defer func() {
683 s.mux.Lock()
684 delete(s.FileTransfers, transferRefNum)
685 s.mux.Unlock()
686 }()
687
688 s.mux.Lock()
689 fileTransfer, ok := s.FileTransfers[transferRefNum]
690 s.mux.Unlock()
691 if !ok {
692 return errors.New("invalid transaction ID")
693 }
694
695 switch fileTransfer.Type {
696 case FileDownload:
697 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
698 if err != nil {
699 return err
700 }
701
702 var dataOffset int64
703 if fileTransfer.fileResumeData != nil {
704 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
705 }
706
707 ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset)
708 if err != nil {
709 return err
710 }
711
712 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
713
714 if fileTransfer.options == nil {
715 // Start by sending flat file object to client
716 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
717 return err
718 }
719 }
720
721 file, err := FS.Open(fullFilePath)
722 if err != nil {
723 return err
724 }
725
726 sendBuffer := make([]byte, 1048576)
727 var totalSent int64
728 for {
729 var bytesRead int
730 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
731 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
732 return err
733 }
734 break
735 }
736 if err != nil {
737 return err
738 }
739 totalSent += int64(bytesRead)
740
741 fileTransfer.BytesSent += bytesRead
742
743 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
744 return err
745 }
746 }
747 case FileUpload:
748 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
749
750 var file *os.File
751
752 // A file upload has three possible cases:
753 // 1) Upload a new file
754 // 2) Resume a partially transferred file
755 // 3) Replace a fully uploaded file
756 // Unfortunately we have to infer which case applies by inspecting what is already on the file system
757
758 // 1) Check for existing file:
759 _, err := os.Stat(destinationFile)
760 if err == nil {
761 // If found, that means this upload is intended to replace the file
762 if err = os.Remove(destinationFile); err != nil {
763 return err
764 }
765 file, err = os.Create(destinationFile + incompleteFileSuffix)
766 }
767 if errors.Is(err, fs.ErrNotExist) {
768 // If not found, open or create a new incomplete file
769 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
770 if err != nil {
771 return err
772 }
773 }
774
775 defer func() { _ = file.Close() }()
776
777 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
778
779 // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data
780 if err := receiveFile(conn, file, io.Discard); err != nil {
781 return err
782 }
783
784 if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil {
785 return err
786 }
787
788 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
789 case FolderDownload:
790 // Folder Download flow:
791 // 1. Get filePath from the transfer
792 // 2. Iterate over files
793 // 3. For each file:
794 // Send file header to client
795 // The client can reply in 3 ways:
796 //
797 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
798 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
799 //
800 // 2. If download of a file is to be resumed:
801 // client sends:
802 // []byte{0x00, 0x02} // download folder action
803 // [2]byte // Resume data size
804 // []byte file resume data (see myField_FileResumeData)
805 //
806 // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01}
807 //
808 // When download is requested (case 2 or 3), server replies with:
809 // [4]byte - file size
810 // []byte - Flattened File Object
811 //
812 // After every file download, client could request next file with:
813 // []byte{0x00, 0x03}
814 //
815 // This notifies the server to send the next item header
816
817 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
818 if err != nil {
819 return err
820 }
821
822 basePathLen := len(fullFilePath)
823
824 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
825
826 nextAction := make([]byte, 2)
827 if _, err := io.ReadFull(conn, nextAction); err != nil {
828 return err
829 }
830
831 i := 0
832 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
833 if err != nil {
834 return err
835 }
836 i += 1
837 subPath := path[basePathLen+1:]
838 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
839
840 if i == 1 {
841 return nil
842 }
843
844 fileHeader := NewFileHeader(subPath, info.IsDir())
845
846 // Send the file header to client
847 if _, err := conn.Write(fileHeader.Payload()); err != nil {
848 s.Logger.Errorf("error sending file header: %v", err)
849 return err
850 }
851
852 // Read the client's Next Action request
853 if _, err := io.ReadFull(conn, nextAction); err != nil {
854 return err
855 }
856
857 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
858
859 var dataOffset int64
860
861 switch nextAction[1] {
862 case dlFldrActionResumeFile:
863 // client asked to resume this file
864 var frd FileResumeData
865 // get size of resumeData
866 if _, err := io.ReadFull(conn, nextAction); err != nil {
867 return err
868 }
869
870 resumeDataLen := binary.BigEndian.Uint16(nextAction)
871 resumeDataBytes := make([]byte, resumeDataLen)
872 if _, err := io.ReadFull(conn, resumeDataBytes); err != nil {
873 return err
874 }
875
876 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
877 return err
878 }
879 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
880 case dlFldrActionNextFile:
881 // client asked to skip this file
882 return nil
883 }
884
885 if info.IsDir() {
886 return nil
887 }
888
889 splitPath := strings.Split(path, "/")
890
891 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset)
892 if err != nil {
893 return err
894 }
895 s.Logger.Infow("File download started",
896 "fileName", info.Name(),
897 "transactionRef", fileTransfer.ReferenceNumber,
898 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
899 )
900
901 // Send file size to client
902 if _, err := conn.Write(ffo.TransferSize()); err != nil {
903 s.Logger.Error(err)
904 return err
905 }
906
907 // Send ffo bytes to client
908 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
909 s.Logger.Error(err)
910 return err
911 }
912
913 file, err := FS.Open(path)
914 if err != nil {
915 return err
916 }
917
918 // // Copy N bytes from file to connection
919 // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
920 // if err != nil {
921 // return err
922 // }
923 // file.Close()
924 sendBuffer := make([]byte, 1048576)
925 var totalSent int64
926 for {
927 var bytesRead int
928 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
929 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
930 return err
931 }
932 break
933 }
934 if err != nil {
935 panic(err)
936 }
937 totalSent += int64(bytesRead)
938
939 fileTransfer.BytesSent += bytesRead
940
941 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
942 return err
943 }
944 }
945
946 // TODO: optionally send resource fork header and resource fork data
947
948 // Read the client's Next Action request. This is always 3, I think?
949 if _, err := io.ReadFull(conn, nextAction); err != nil {
950 return err
951 }
952
953 return nil
954 })
955
956 case FolderUpload:
957 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
958 if err != nil {
959 return err
960 }
961 s.Logger.Infow(
962 "Folder upload started",
963 "transactionRef", fileTransfer.ReferenceNumber,
964 "dstPath", dstPath,
965 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
966 "FolderItemCount", fileTransfer.FolderItemCount,
967 )
968
969 // Check if the target folder exists. If not, create it.
970 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
971 if err := FS.Mkdir(dstPath, 0777); err != nil {
972 return err
973 }
974 }
975
976 // Begin the folder upload flow by sending the "next file action" to client
977 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
978 return err
979 }
980
981 fileSize := make([]byte, 4)
982 readBuffer := make([]byte, 1024)
983
984 for i := 0; i < fileTransfer.ItemCount(); i++ {
985 // TODO: fix potential short read with io.ReadFull
986 _, err := conn.Read(readBuffer)
987 if err != nil {
988 return err
989 }
990 fu := readFolderUpload(readBuffer)
991
992 s.Logger.Infow(
993 "Folder upload continued",
994 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
995 "FormattedPath", fu.FormattedPath(),
996 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
997 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
998 )
999
1000 if fu.IsFolder == [2]byte{0, 1} {
1001 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
1002 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
1003 return err
1004 }
1005 }
1006
1007 // Tell client to send next file
1008 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1009 return err
1010 }
1011 } else {
1012 nextAction := dlFldrActionSendFile
1013
1014 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1015 _, err := os.Stat(dstPath + "/" + fu.FormattedPath())
1016 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1017 return err
1018 }
1019 if err == nil {
1020 nextAction = dlFldrActionNextFile
1021 }
1022
1023 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1024 inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
1025 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1026 return err
1027 }
1028 if err == nil {
1029 nextAction = dlFldrActionResumeFile
1030 }
1031
1032 fmt.Printf("Next Action: %v\n", nextAction)
1033
1034 if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil {
1035 return err
1036 }
1037
1038 switch nextAction {
1039 case dlFldrActionNextFile:
1040 continue
1041 case dlFldrActionResumeFile:
1042 offset := make([]byte, 4)
1043 binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size()))
1044
1045 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1046 if err != nil {
1047 return err
1048 }
1049
1050 fileResumeData := NewFileResumeData([]ForkInfoList{
1051 *NewForkInfoList(offset),
1052 })
1053
1054 b, _ := fileResumeData.BinaryMarshal()
1055
1056 bs := make([]byte, 2)
1057 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1058
1059 if _, err := conn.Write(append(bs, b...)); err != nil {
1060 return err
1061 }
1062
1063 if _, err := io.ReadFull(conn, fileSize); err != nil {
1064 return err
1065 }
1066
1067 if err := receiveFile(conn, file, ioutil.Discard); err != nil {
1068 s.Logger.Error(err)
1069 }
1070
1071 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1072 if err != nil {
1073 return err
1074 }
1075
1076 case dlFldrActionSendFile:
1077 if _, err := conn.Read(fileSize); err != nil {
1078 return err
1079 }
1080
1081 filePath := dstPath + "/" + fu.FormattedPath()
1082 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize))
1083
1084 newFile, err := FS.Create(filePath + ".incomplete")
1085 if err != nil {
1086 return err
1087 }
1088
1089 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
1090 s.Logger.Error(err)
1091 }
1092 _ = newFile.Close()
1093 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1094 return err
1095 }
1096 }
1097
1098 // Tell client to send next file
1099 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1100 return err
1101 }
1102 }
1103 }
1104 s.Logger.Infof("Folder upload complete")
1105 }
1106
1107 return nil
1108 }
1109
1110 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1111 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1112 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1113 for _, c := range unsortedClients {
1114 clients = append(clients, c)
1115 }
1116 sort.Sort(byClientID(clients))
1117 return clients
1118 }