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