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