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