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