]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
Fix and refactor file transfers to handle resource forks
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "context"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "go.uber.org/zap"
9 "io"
10 "io/ioutil"
11 "math/big"
12 "math/rand"
13 "net"
14 "os"
15 "path"
16 "path/filepath"
17 "runtime/debug"
18 "sort"
19 "strings"
20 "sync"
21 "time"
22
23 "gopkg.in/yaml.v2"
24 )
25
26 const (
27 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
28 idleCheckInterval = 10 // time in seconds to check for idle users
29 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
30 )
31
32 type Server struct {
33 Port int
34 Accounts map[string]*Account
35 Agreement []byte
36 Clients map[uint16]*ClientConn
37 FlatNews []byte
38 ThreadedNews *ThreadedNews
39 FileTransfers map[uint32]*FileTransfer
40 Config *Config
41 ConfigDir string
42 Logger *zap.SugaredLogger
43 PrivateChats map[uint32]*PrivateChat
44 NextGuestID *uint16
45 TrackerPassID []byte
46 Stats *Stats
47
48 APIListener net.Listener
49 FileListener net.Listener
50
51 // newsReader io.Reader
52 // newsWriter io.WriteCloser
53
54 outbox chan Transaction
55
56 mux sync.Mutex
57 flatNewsMux sync.Mutex
58 }
59
60 type PrivateChat struct {
61 Subject string
62 ClientConn map[uint16]*ClientConn
63 }
64
65 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
66 s.Logger.Infow("Hotline server started", "version", VERSION)
67 var wg sync.WaitGroup
68
69 wg.Add(1)
70 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
71
72 wg.Add(1)
73 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
74
75 wg.Wait()
76
77 return nil
78 }
79
80 func (s *Server) APIPort() int {
81 return s.APIListener.Addr().(*net.TCPAddr).Port
82 }
83
84 func (s *Server) ServeFileTransfers(ln net.Listener) error {
85 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
86
87 for {
88 conn, err := ln.Accept()
89 if err != nil {
90 return err
91 }
92
93 go func() {
94 if err := s.handleFileTransfer(conn); err != nil {
95 s.Logger.Errorw("file transfer error", "reason", err)
96 }
97 }()
98 }
99 }
100
101 func (s *Server) sendTransaction(t Transaction) error {
102 requestNum := binary.BigEndian.Uint16(t.Type)
103 clientID, err := byteToInt(*t.clientID)
104 if err != nil {
105 return err
106 }
107
108 s.mux.Lock()
109 client := s.Clients[uint16(clientID)]
110 s.mux.Unlock()
111 if client == nil {
112 return fmt.Errorf("invalid client id %v", *t.clientID)
113 }
114 userName := string(client.UserName)
115 login := client.Account.Login
116
117 handler := TransactionHandlers[requestNum]
118
119 b, err := t.MarshalBinary()
120 if err != nil {
121 return err
122 }
123 var n int
124 if n, err = client.Connection.Write(b); err != nil {
125 return err
126 }
127 s.Logger.Debugw("Sent Transaction",
128 "name", userName,
129 "login", login,
130 "IsReply", t.IsReply,
131 "type", handler.Name,
132 "sentBytes", n,
133 "remoteAddr", client.Connection.RemoteAddr(),
134 )
135 return nil
136 }
137
138 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
139 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
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); 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 TrackerPassID: make([]byte, 4),
189 }
190
191 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
192 if err != nil {
193 return nil, err
194 }
195 server.APIListener = ln
196
197 if netPort != 0 {
198 netPort += 1
199 }
200
201 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
202 server.FileListener = ln2
203 if err != nil {
204 return nil, err
205 }
206
207 // generate a new random passID for tracker registration
208 if _, err := rand.Read(server.TrackerPassID); err != nil {
209 return nil, err
210 }
211
212 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
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 go func() {
239 for {
240 tr := TrackerRegistration{
241 Port: []byte{0x15, 0x7c},
242 UserCount: server.userCount(),
243 PassID: server.TrackerPassID,
244 Name: server.Config.Name,
245 Description: server.Config.Description,
246 }
247 for _, t := range server.Config.Trackers {
248 server.Logger.Infof("Registering with tracker %v", t)
249
250 if err := register(t, tr); err != nil {
251 server.Logger.Errorw("unable to register with tracker %v", "error", err)
252 }
253 }
254
255 time.Sleep(trackerUpdateFrequency * time.Second)
256 }
257 }()
258 }
259
260 // Start Client Keepalive go routine
261 go server.keepaliveHandler()
262
263 return &server, nil
264 }
265
266 func (s *Server) userCount() int {
267 s.mux.Lock()
268 defer s.mux.Unlock()
269
270 return len(s.Clients)
271 }
272
273 func (s *Server) keepaliveHandler() {
274 for {
275 time.Sleep(idleCheckInterval * time.Second)
276 s.mux.Lock()
277
278 for _, c := range s.Clients {
279 c.IdleTime += idleCheckInterval
280 if c.IdleTime > userIdleSeconds && !c.Idle {
281 c.Idle = true
282
283 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
284 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
285 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
286
287 c.sendAll(
288 tranNotifyChangeUser,
289 NewField(fieldUserID, *c.ID),
290 NewField(fieldUserFlags, *c.Flags),
291 NewField(fieldUserName, c.UserName),
292 NewField(fieldUserIconID, *c.Icon),
293 )
294 }
295 }
296 s.mux.Unlock()
297 }
298 }
299
300 func (s *Server) writeThreadedNews() error {
301 s.mux.Lock()
302 defer s.mux.Unlock()
303
304 out, err := yaml.Marshal(s.ThreadedNews)
305 if err != nil {
306 return err
307 }
308 err = ioutil.WriteFile(
309 s.ConfigDir+"ThreadedNews.yaml",
310 out,
311 0666,
312 )
313 return err
314 }
315
316 func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
317 s.mux.Lock()
318 defer s.mux.Unlock()
319
320 clientConn := &ClientConn{
321 ID: &[]byte{0, 0},
322 Icon: &[]byte{0, 0},
323 Flags: &[]byte{0, 0},
324 UserName: []byte{},
325 Connection: conn,
326 Server: s,
327 Version: &[]byte{},
328 AutoReply: []byte{},
329 Transfers: make(map[int][]*FileTransfer),
330 Agreed: false,
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 ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
359 }
360
361 // DeleteUser deletes the user account
362 func (s *Server) DeleteUser(login string) error {
363 s.mux.Lock()
364 defer s.mux.Unlock()
365
366 delete(s.Accounts, login)
367
368 return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
369 }
370
371 func (s *Server) connectedUsers() []Field {
372 s.mux.Lock()
373 defer s.mux.Unlock()
374
375 var connectedUsers []Field
376 for _, c := range sortedClients(s.Clients) {
377 if !c.Agreed {
378 continue
379 }
380 user := User{
381 ID: *c.ID,
382 Icon: *c.Icon,
383 Flags: *c.Flags,
384 Name: string(c.UserName),
385 }
386 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
387 }
388 return connectedUsers
389 }
390
391 // loadThreadedNews loads the threaded news data from disk
392 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
393 fh, err := os.Open(threadedNewsPath)
394 if err != nil {
395 return err
396 }
397 decoder := yaml.NewDecoder(fh)
398 decoder.SetStrict(true)
399
400 return decoder.Decode(s.ThreadedNews)
401 }
402
403 // loadAccounts loads account data from disk
404 func (s *Server) loadAccounts(userDir string) error {
405 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
406 if err != nil {
407 return err
408 }
409
410 if len(matches) == 0 {
411 return errors.New("no user accounts found in " + userDir)
412 }
413
414 for _, file := range matches {
415 fh, err := FS.Open(file)
416 if err != nil {
417 return err
418 }
419
420 account := Account{}
421 decoder := yaml.NewDecoder(fh)
422 decoder.SetStrict(true)
423 if err := decoder.Decode(&account); err != nil {
424 return err
425 }
426
427 s.Accounts[account.Login] = &account
428 }
429 return nil
430 }
431
432 func (s *Server) loadConfig(path string) error {
433 fh, err := FS.Open(path)
434 if err != nil {
435 return err
436 }
437
438 decoder := yaml.NewDecoder(fh)
439 decoder.SetStrict(true)
440 err = decoder.Decode(s.Config)
441 if err != nil {
442 return err
443 }
444 return nil
445 }
446
447 const (
448 minTransactionLen = 22 // minimum length of any transaction
449 )
450
451 // handleNewConnection takes a new net.Conn and performs the initial login sequence
452 func (s *Server) handleNewConnection(conn net.Conn) error {
453 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
454 if _, err := conn.Read(handshakeBuf); err != nil {
455 return err
456 }
457 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
458 return err
459 }
460
461 buf := make([]byte, 1024)
462 readLen, err := conn.Read(buf)
463 if readLen < minTransactionLen {
464 return err
465 }
466 if err != nil {
467 return err
468 }
469
470 clientLogin, _, err := ReadTransaction(buf[:readLen])
471 if err != nil {
472 return err
473 }
474
475 c := s.NewClientConn(conn)
476 defer c.Disconnect()
477 defer func() {
478 if r := recover(); r != nil {
479 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
480 c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
481 c.Disconnect()
482 }
483 }()
484
485 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
486 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
487 *c.Version = clientLogin.GetField(fieldVersion).Data
488
489 var login string
490 for _, char := range encodedLogin {
491 login += string(rune(255 - uint(char)))
492 }
493 if login == "" {
494 login = GuestAccount
495 }
496
497 // If authentication fails, send error reply and close connection
498 if !c.Authenticate(login, encodedPassword) {
499 t := c.NewErrReply(clientLogin, "Incorrect login.")
500 b, err := t.MarshalBinary()
501 if err != nil {
502 return err
503 }
504 if _, err := conn.Write(b); err != nil {
505 return err
506 }
507 return fmt.Errorf("incorrect login")
508 }
509
510 if clientLogin.GetField(fieldUserName).Data != nil {
511 c.UserName = clientLogin.GetField(fieldUserName).Data
512 }
513
514 if clientLogin.GetField(fieldUserIconID).Data != nil {
515 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
516 }
517
518 c.Account = c.Server.Accounts[login]
519
520 if c.Authorize(accessDisconUser) {
521 *c.Flags = []byte{0, 2}
522 }
523
524 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
525
526 s.outbox <- c.NewReply(clientLogin,
527 NewField(fieldVersion, []byte{0x00, 0xbe}),
528 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
529 NewField(fieldServerName, []byte(s.Config.Name)),
530 )
531
532 // Send user access privs so client UI knows how to behave
533 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
534
535 // Show agreement to client
536 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
537
538 // assume simplified hotline v1.2.3 login flow that does not require agreement
539 if *c.Version == nil {
540 c.Agreed = true
541
542 c.notifyOthers(
543 *NewTransaction(
544 tranNotifyChangeUser, nil,
545 NewField(fieldUserName, c.UserName),
546 NewField(fieldUserID, *c.ID),
547 NewField(fieldUserIconID, *c.Icon),
548 NewField(fieldUserFlags, *c.Flags),
549 ),
550 )
551 }
552
553 c.Server.Stats.LoginCount += 1
554
555 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
556 tranBuff := make([]byte, 0)
557 tReadlen := 0
558 // Infinite loop where take action on incoming client requests until the connection is closed
559 for {
560 buf = make([]byte, readBuffSize)
561 tranBuff = tranBuff[tReadlen:]
562
563 readLen, err := c.Connection.Read(buf)
564 if err != nil {
565 return err
566 }
567 tranBuff = append(tranBuff, buf[:readLen]...)
568
569 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
570 // into a slice of transactions
571 var transactions []Transaction
572 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
573 c.Server.Logger.Errorw("Error handling transaction", "err", err)
574 }
575
576 // iterate over all of the transactions that were parsed from the byte slice and handle them
577 for _, t := range transactions {
578 if err := c.handleTransaction(&t); err != nil {
579 c.Server.Logger.Errorw("Error handling transaction", "err", err)
580 }
581 }
582 }
583 }
584
585 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
586 // in the file transfer request payload, and the file transfer server will use it to map the request
587 // to a transfer
588 func (s *Server) NewTransactionRef() []byte {
589 transactionRef := make([]byte, 4)
590 rand.Read(transactionRef)
591
592 return transactionRef
593 }
594
595 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
596 s.mux.Lock()
597 defer s.mux.Unlock()
598
599 randID := make([]byte, 4)
600 rand.Read(randID)
601 data := binary.BigEndian.Uint32(randID[:])
602
603 s.PrivateChats[data] = &PrivateChat{
604 Subject: "",
605 ClientConn: make(map[uint16]*ClientConn),
606 }
607 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
608
609 return randID
610 }
611
612 const dlFldrActionSendFile = 1
613 const dlFldrActionResumeFile = 2
614 const dlFldrActionNextFile = 3
615
616 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
617 func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
618 defer func() {
619 if err := conn.Close(); err != nil {
620 s.Logger.Errorw("error closing connection", "error", err)
621 }
622 }()
623
624 txBuf := make([]byte, 16)
625 _, err := conn.Read(txBuf)
626 if err != nil {
627 return err
628 }
629
630 var t transfer
631 _, err = t.Write(txBuf)
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, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
642 if err != nil {
643 return err
644 }
645
646 ffo, err := NewFlattenedFileObject(
647 s.Config.FileRoot,
648 fileTransfer.FilePath,
649 fileTransfer.FileName,
650 )
651 if err != nil {
652 return err
653 }
654
655 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
656
657 // Start by sending flat file object to client
658 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
659 return err
660 }
661
662 file, err := FS.Open(fullFilePath)
663 if err != nil {
664 return err
665 }
666
667 sendBuffer := make([]byte, 1048576)
668 for {
669 var bytesRead int
670 if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
671 break
672 }
673
674 fileTransfer.BytesSent += bytesRead
675
676 delete(s.FileTransfers, transferRefNum)
677
678 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
679 return err
680 }
681 }
682 case FileUpload:
683 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
684 newFile, err := FS.Create(destinationFile)
685 if err != nil {
686 return err
687 }
688 defer func() { _ = newFile.Close() }()
689
690 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
691
692 if err := receiveFile(conn, newFile, nil); err != nil {
693 s.Logger.Errorw("file upload error", "error", err)
694 }
695
696 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
697 case FolderDownload:
698 // Folder Download flow:
699 // 1. Get filePath from the transfer
700 // 2. Iterate over files
701 // 3. For each file:
702 // Send file header to client
703 // The client can reply in 3 ways:
704 //
705 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
706 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
707 //
708 // 2. If download of a file is to be resumed:
709 // client sends:
710 // []byte{0x00, 0x02} // download folder action
711 // [2]byte // Resume data size
712 // []byte file resume data (see myField_FileResumeData)
713 //
714 // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
715 //
716 // When download is requested (case 2 or 3), server replies with:
717 // [4]byte - file size
718 // []byte - Flattened File Object
719 //
720 // After every file download, client could request next file with:
721 // []byte{0x00, 0x03}
722 //
723 // This notifies the server to send the next item header
724
725 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
726 if err != nil {
727 return err
728 }
729
730 basePathLen := len(fullFilePath)
731
732 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
733
734 nextAction := make([]byte, 2)
735 if _, err := conn.Read(nextAction); err != nil {
736 return err
737 }
738
739 i := 0
740 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
741 if err != nil {
742 return err
743 }
744 i += 1
745 subPath := path[basePathLen+1:]
746 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
747
748 if i == 1 {
749 return nil
750 }
751
752 fileHeader := NewFileHeader(subPath, info.IsDir())
753
754 // Send the file header to client
755 if _, err := conn.Write(fileHeader.Payload()); err != nil {
756 s.Logger.Errorf("error sending file header: %v", err)
757 return err
758 }
759
760 // Read the client's Next Action request
761 if _, err := conn.Read(nextAction); err != nil {
762 return err
763 }
764 if nextAction[1] == 3 {
765 return nil
766 }
767
768 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
769
770 if info.IsDir() {
771 return nil
772 }
773
774 splitPath := strings.Split(path, "/")
775
776 ffo, err := NewFlattenedFileObject(
777 strings.Join(splitPath[:len(splitPath)-1], "/"),
778 nil,
779 []byte(info.Name()),
780 )
781 if err != nil {
782 return err
783 }
784 s.Logger.Infow("File download started",
785 "fileName", info.Name(),
786 "transactionRef", fileTransfer.ReferenceNumber,
787 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
788 )
789
790 // Send file size to client
791 if _, err := conn.Write(ffo.TransferSize()); err != nil {
792 s.Logger.Error(err)
793 return err
794 }
795
796 // Send ffo bytes to client
797 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
798 s.Logger.Error(err)
799 return err
800 }
801
802 file, err := FS.Open(path)
803 if err != nil {
804 return err
805 }
806
807 // Copy N bytes from file to connection
808 _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
809 if err != nil {
810 return err
811 }
812 file.Close()
813
814 // TODO: optionally send resource fork header and resource fork data
815
816 // Read the client's Next Action request
817 if _, err := conn.Read(nextAction); err != nil {
818 return err
819 }
820 // TODO: switch behavior based on possible next action
821
822 return err
823 })
824
825 case FolderUpload:
826 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
827 if err != nil {
828 return err
829 }
830 s.Logger.Infow(
831 "Folder upload started",
832 "transactionRef", fileTransfer.ReferenceNumber,
833 "dstPath", dstPath,
834 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
835 "FolderItemCount", fileTransfer.FolderItemCount,
836 )
837
838 // Check if the target folder exists. If not, create it.
839 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
840 s.Logger.Infow("Creating target path", "dstPath", dstPath)
841 if err := FS.Mkdir(dstPath, 0777); err != nil {
842 s.Logger.Error(err)
843 }
844 }
845
846 // Begin the folder upload flow by sending the "next file action" to client
847 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
848 return err
849 }
850
851 fileSize := make([]byte, 4)
852 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
853
854 readBuffer := make([]byte, 1024)
855 for i := uint16(0); i < itemCount; i++ {
856 _, err := conn.Read(readBuffer)
857 if err != nil {
858 return err
859 }
860 fu := readFolderUpload(readBuffer)
861
862 s.Logger.Infow(
863 "Folder upload continued",
864 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
865 "FormattedPath", fu.FormattedPath(),
866 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
867 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
868 )
869
870 if fu.IsFolder == [2]byte{0, 1} {
871 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
872 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
873 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
874 s.Logger.Error(err)
875 }
876 }
877
878 // Tell client to send next file
879 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
880 s.Logger.Error(err)
881 return err
882 }
883 } else {
884 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
885 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
886 // Send dlFldrAction_SendFile to client to begin transfer
887 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
888 return err
889 }
890
891 if _, err := conn.Read(fileSize); err != nil {
892 return err
893 }
894
895 filePath := dstPath + "/" + fu.FormattedPath()
896 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", itemCount, "fileSize", binary.BigEndian.Uint32(fileSize))
897
898 newFile, err := FS.Create(filePath)
899 if err != nil {
900 return err
901 }
902
903 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
904 s.Logger.Error(err)
905 }
906 _ = newFile.Close()
907
908 // Tell client to send next file
909 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
910 s.Logger.Error(err)
911 return err
912 }
913
914 }
915 }
916 s.Logger.Infof("Folder upload complete")
917 }
918
919 return nil
920 }
921
922 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
923 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
924 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
925 for _, c := range unsortedClients {
926 clients = append(clients, c)
927 }
928 sort.Sort(byClientID(clients))
929 return clients
930 }