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