]> git.r.bdr.sh - rbdr/mobius/blame - hotline/server.go
Backfill tests and clean up
[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
365 fmt.Printf("login: %v, newLogin: %v: ", login, newLogin)
366
367 // update renames the user login
368 if login != newLogin {
369 err := os.Rename(s.ConfigDir+"Users/"+login+".yaml", s.ConfigDir+"Users/"+newLogin+".yaml")
370 if err != nil {
371 return err
372 }
373 s.Accounts[newLogin] = s.Accounts[login]
374 delete(s.Accounts, login)
375 }
376
377 account := s.Accounts[newLogin]
378 account.Access = &access
379 account.Name = name
380 account.Password = password
381
382 out, err := yaml.Marshal(&account)
383 if err != nil {
384 return err
385 }
386 if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil {
387 return err
388 }
389
390 return nil
391}
392
6988a057
JH
393// DeleteUser deletes the user account
394func (s *Server) DeleteUser(login string) error {
395 s.mux.Lock()
396 defer s.mux.Unlock()
397
398 delete(s.Accounts, login)
399
003a743e 400 return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
6988a057
JH
401}
402
403func (s *Server) connectedUsers() []Field {
404 s.mux.Lock()
405 defer s.mux.Unlock()
406
407 var connectedUsers []Field
c7e932c0 408 for _, c := range sortedClients(s.Clients) {
aebc4d36 409 if !c.Agreed {
bd1ce113
JH
410 continue
411 }
6988a057
JH
412 user := User{
413 ID: *c.ID,
414 Icon: *c.Icon,
415 Flags: *c.Flags,
72dd37f1 416 Name: string(c.UserName),
6988a057
JH
417 }
418 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
419 }
420 return connectedUsers
421}
422
423// loadThreadedNews loads the threaded news data from disk
424func (s *Server) loadThreadedNews(threadedNewsPath string) error {
425 fh, err := os.Open(threadedNewsPath)
426 if err != nil {
427 return err
428 }
429 decoder := yaml.NewDecoder(fh)
6988a057
JH
430
431 return decoder.Decode(s.ThreadedNews)
432}
433
434// loadAccounts loads account data from disk
435func (s *Server) loadAccounts(userDir string) error {
436 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
437 if err != nil {
438 return err
439 }
440
441 if len(matches) == 0 {
442 return errors.New("no user accounts found in " + userDir)
443 }
444
445 for _, file := range matches {
d492c46d 446 fh, err := FS.Open(file)
6988a057
JH
447 if err != nil {
448 return err
449 }
450
451 account := Account{}
452 decoder := yaml.NewDecoder(fh)
6988a057
JH
453 if err := decoder.Decode(&account); err != nil {
454 return err
455 }
456
457 s.Accounts[account.Login] = &account
458 }
459 return nil
460}
461
462func (s *Server) loadConfig(path string) error {
d492c46d 463 fh, err := FS.Open(path)
6988a057
JH
464 if err != nil {
465 return err
466 }
467
468 decoder := yaml.NewDecoder(fh)
6988a057
JH
469 err = decoder.Decode(s.Config)
470 if err != nil {
471 return err
472 }
041c2df6
JH
473
474 validate := validator.New()
475 err = validate.Struct(s.Config)
476 if err != nil {
477 return err
478 }
6988a057
JH
479 return nil
480}
481
482const (
483 minTransactionLen = 22 // minimum length of any transaction
484)
485
37a954c8
JH
486// dontPanic recovers and logs panics instead of crashing
487// TODO: remove this after known issues are fixed
488func dontPanic(logger *zap.SugaredLogger) {
489 if r := recover(); r != nil {
490 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
491 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
492 }
493}
494
6988a057 495// handleNewConnection takes a new net.Conn and performs the initial login sequence
d4c152a4 496func (s *Server) handleNewConnection(conn net.Conn, remoteAddr string) error {
c4208f86
JH
497 defer dontPanic(s.Logger)
498
d4c152a4 499 if err := Handshake(conn); err != nil {
6988a057
JH
500 return err
501 }
502
503 buf := make([]byte, 1024)
c4208f86 504 // TODO: fix potential short read with io.ReadFull
6988a057
JH
505 readLen, err := conn.Read(buf)
506 if readLen < minTransactionLen {
507 return err
508 }
509 if err != nil {
510 return err
511 }
512
513 clientLogin, _, err := ReadTransaction(buf[:readLen])
514 if err != nil {
515 return err
516 }
517
d4c152a4 518 c := s.NewClientConn(conn, remoteAddr)
6988a057 519 defer c.Disconnect()
6988a057
JH
520
521 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
522 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
523 *c.Version = clientLogin.GetField(fieldVersion).Data
524
525 var login string
526 for _, char := range encodedLogin {
527 login += string(rune(255 - uint(char)))
528 }
529 if login == "" {
530 login = GuestAccount
531 }
532
533 // If authentication fails, send error reply and close connection
534 if !c.Authenticate(login, encodedPassword) {
72dd37f1
JH
535 t := c.NewErrReply(clientLogin, "Incorrect login.")
536 b, err := t.MarshalBinary()
537 if err != nil {
538 return err
539 }
540 if _, err := conn.Write(b); err != nil {
6988a057
JH
541 return err
542 }
543 return fmt.Errorf("incorrect login")
544 }
545
6988a057 546 if clientLogin.GetField(fieldUserName).Data != nil {
72dd37f1 547 c.UserName = clientLogin.GetField(fieldUserName).Data
6988a057
JH
548 }
549
550 if clientLogin.GetField(fieldUserIconID).Data != nil {
551 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
552 }
553
554 c.Account = c.Server.Accounts[login]
555
556 if c.Authorize(accessDisconUser) {
557 *c.Flags = []byte{0, 2}
558 }
559
d4c152a4 560 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr)
6988a057
JH
561
562 s.outbox <- c.NewReply(clientLogin,
563 NewField(fieldVersion, []byte{0x00, 0xbe}),
564 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
565 NewField(fieldServerName, []byte(s.Config.Name)),
566 )
567
568 // Send user access privs so client UI knows how to behave
569 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
570
571 // Show agreement to client
572 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
573
bd1ce113
JH
574 // assume simplified hotline v1.2.3 login flow that does not require agreement
575 if *c.Version == nil {
576 c.Agreed = true
003a743e
JH
577
578 c.notifyOthers(
579 *NewTransaction(
580 tranNotifyChangeUser, nil,
581 NewField(fieldUserName, c.UserName),
582 NewField(fieldUserID, *c.ID),
583 NewField(fieldUserIconID, *c.Icon),
584 NewField(fieldUserFlags, *c.Flags),
585 ),
586 )
6988a057 587 }
bd1ce113 588
6988a057
JH
589 c.Server.Stats.LoginCount += 1
590
591 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
6988a057
JH
592 tranBuff := make([]byte, 0)
593 tReadlen := 0
594 // Infinite loop where take action on incoming client requests until the connection is closed
595 for {
596 buf = make([]byte, readBuffSize)
597 tranBuff = tranBuff[tReadlen:]
598
599 readLen, err := c.Connection.Read(buf)
600 if err != nil {
601 return err
602 }
603 tranBuff = append(tranBuff, buf[:readLen]...)
604
605 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
606 // into a slice of transactions
607 var transactions []Transaction
608 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
609 c.Server.Logger.Errorw("Error handling transaction", "err", err)
610 }
611
612 // iterate over all of the transactions that were parsed from the byte slice and handle them
613 for _, t := range transactions {
614 if err := c.handleTransaction(&t); err != nil {
615 c.Server.Logger.Errorw("Error handling transaction", "err", err)
616 }
617 }
618 }
619}
620
6988a057
JH
621// NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
622// in the file transfer request payload, and the file transfer server will use it to map the request
623// to a transfer
624func (s *Server) NewTransactionRef() []byte {
625 transactionRef := make([]byte, 4)
626 rand.Read(transactionRef)
627
628 return transactionRef
629}
630
631func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
632 s.mux.Lock()
633 defer s.mux.Unlock()
634
635 randID := make([]byte, 4)
636 rand.Read(randID)
637 data := binary.BigEndian.Uint32(randID[:])
638
639 s.PrivateChats[data] = &PrivateChat{
640 Subject: "",
641 ClientConn: make(map[uint16]*ClientConn),
642 }
643 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
644
645 return randID
646}
647
648const dlFldrActionSendFile = 1
649const dlFldrActionResumeFile = 2
650const dlFldrActionNextFile = 3
651
85767504
JH
652// handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
653func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
654 defer func() {
0a92e50b 655
85767504
JH
656 if err := conn.Close(); err != nil {
657 s.Logger.Errorw("error closing connection", "error", err)
658 }
659 }()
6988a057 660
37a954c8 661 defer dontPanic(s.Logger)
0a92e50b 662
2e7c03cf 663 txBuf := make([]byte, 16)
0a92e50b 664 if _, err := io.ReadFull(conn, txBuf); err != nil {
6988a057
JH
665 return err
666 }
667
df2735b2 668 var t transfer
0a92e50b 669 if _, err := t.Write(txBuf); err != nil {
6988a057
JH
670 return err
671 }
672
673 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
0a92e50b
JH
674 defer func() {
675 s.mux.Lock()
676 delete(s.FileTransfers, transferRefNum)
677 s.mux.Unlock()
678 }()
6988a057 679
0a92e50b
JH
680 s.mux.Lock()
681 fileTransfer, ok := s.FileTransfers[transferRefNum]
682 s.mux.Unlock()
683 if !ok {
684 return errors.New("invalid transaction ID")
685 }
16a4ad70 686
6988a057
JH
687 switch fileTransfer.Type {
688 case FileDownload:
92a7e455
JH
689 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
690 if err != nil {
691 return err
692 }
6988a057 693
16a4ad70
JH
694 var dataOffset int64
695 if fileTransfer.fileResumeData != nil {
696 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
697 }
698
699 ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset)
6988a057
JH
700 if err != nil {
701 return err
702 }
703
85767504 704 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
6988a057 705
d1cd6664
JH
706 if fileTransfer.options == nil {
707 // Start by sending flat file object to client
708 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
709 return err
710 }
6988a057
JH
711 }
712
92a7e455 713 file, err := FS.Open(fullFilePath)
6988a057
JH
714 if err != nil {
715 return err
716 }
717
718 sendBuffer := make([]byte, 1048576)
16a4ad70 719 var totalSent int64
6988a057
JH
720 for {
721 var bytesRead int
16a4ad70
JH
722 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
723 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
724 return err
725 }
6988a057
JH
726 break
727 }
16a4ad70
JH
728 if err != nil {
729 return err
730 }
731 totalSent += int64(bytesRead)
6988a057
JH
732
733 fileTransfer.BytesSent += bytesRead
734
6988a057
JH
735 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
736 return err
737 }
738 }
739 case FileUpload:
6988a057 740 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
16a4ad70 741
5c14e4c9
JH
742 var file *os.File
743
744 // A file upload has three possible cases:
745 // 1) Upload a new file
746 // 2) Resume a partially transferred file
747 // 3) Replace a fully uploaded file
748 // Unfortunately we have to infer which case applies by inspecting what is already on the file system
749
750 // 1) Check for existing file:
751 _, err := os.Stat(destinationFile)
752 if err == nil {
753 // If found, that means this upload is intended to replace the file
754 if err = os.Remove(destinationFile); err != nil {
755 return err
756 }
757 file, err = os.Create(destinationFile + incompleteFileSuffix)
758 }
16a4ad70 759 if errors.Is(err, fs.ErrNotExist) {
5c14e4c9
JH
760 // If not found, open or create a new incomplete file
761 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
16a4ad70
JH
762 if err != nil {
763 return err
764 }
6988a057 765 }
16a4ad70
JH
766
767 defer func() { _ = file.Close() }()
6988a057 768
85767504 769 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
6988a057 770
16a4ad70
JH
771 // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data
772 if err := receiveFile(conn, file, io.Discard); err != nil {
773 return err
774 }
775
776 if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil {
777 return err
6988a057 778 }
85767504
JH
779
780 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
6988a057
JH
781 case FolderDownload:
782 // Folder Download flow:
df2735b2 783 // 1. Get filePath from the transfer
6988a057
JH
784 // 2. Iterate over files
785 // 3. For each file:
786 // Send file header to client
787 // The client can reply in 3 ways:
788 //
789 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
790 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
791 //
792 // 2. If download of a file is to be resumed:
793 // client sends:
794 // []byte{0x00, 0x02} // download folder action
795 // [2]byte // Resume data size
796 // []byte file resume data (see myField_FileResumeData)
797 //
16a4ad70 798 // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01}
6988a057
JH
799 //
800 // When download is requested (case 2 or 3), server replies with:
801 // [4]byte - file size
802 // []byte - Flattened File Object
803 //
804 // After every file download, client could request next file with:
805 // []byte{0x00, 0x03}
806 //
807 // This notifies the server to send the next item header
808
92a7e455
JH
809 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
810 if err != nil {
811 return err
812 }
6988a057
JH
813
814 basePathLen := len(fullFilePath)
815
85767504 816 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
6988a057 817
85767504 818 nextAction := make([]byte, 2)
c4208f86 819 if _, err := io.ReadFull(conn, nextAction); err != nil {
85767504
JH
820 return err
821 }
6988a057
JH
822
823 i := 0
85767504
JH
824 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
825 if err != nil {
826 return err
827 }
6988a057 828 i += 1
85767504 829 subPath := path[basePathLen+1:]
6988a057
JH
830 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
831
6988a057
JH
832 if i == 1 {
833 return nil
834 }
835
85767504
JH
836 fileHeader := NewFileHeader(subPath, info.IsDir())
837
6988a057
JH
838 // Send the file header to client
839 if _, err := conn.Write(fileHeader.Payload()); err != nil {
840 s.Logger.Errorf("error sending file header: %v", err)
841 return err
842 }
843
844 // Read the client's Next Action request
c4208f86 845 if _, err := io.ReadFull(conn, nextAction); err != nil {
6988a057
JH
846 return err
847 }
848
85767504 849 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
6988a057 850
16a4ad70
JH
851 var dataOffset int64
852
853 switch nextAction[1] {
854 case dlFldrActionResumeFile:
855 // client asked to resume this file
856 var frd FileResumeData
857 // get size of resumeData
c4208f86 858 if _, err := io.ReadFull(conn, nextAction); err != nil {
16a4ad70
JH
859 return err
860 }
861
862 resumeDataLen := binary.BigEndian.Uint16(nextAction)
863 resumeDataBytes := make([]byte, resumeDataLen)
c4208f86 864 if _, err := io.ReadFull(conn, resumeDataBytes); err != nil {
16a4ad70
JH
865 return err
866 }
867
868 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
869 return err
870 }
871 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
872 case dlFldrActionNextFile:
873 // client asked to skip this file
874 return nil
875 }
876
6988a057
JH
877 if info.IsDir() {
878 return nil
879 }
880
881 splitPath := strings.Split(path, "/")
6988a057 882
16a4ad70 883 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset)
6988a057
JH
884 if err != nil {
885 return err
886 }
887 s.Logger.Infow("File download started",
888 "fileName", info.Name(),
889 "transactionRef", fileTransfer.ReferenceNumber,
6988a057
JH
890 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
891 )
892
893 // Send file size to client
894 if _, err := conn.Write(ffo.TransferSize()); err != nil {
895 s.Logger.Error(err)
896 return err
897 }
898
85767504 899 // Send ffo bytes to client
c5d9af5a 900 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
6988a057
JH
901 s.Logger.Error(err)
902 return err
903 }
904
d492c46d 905 file, err := FS.Open(path)
6988a057
JH
906 if err != nil {
907 return err
908 }
909
16a4ad70
JH
910 // // Copy N bytes from file to connection
911 // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
912 // if err != nil {
913 // return err
914 // }
915 // file.Close()
916 sendBuffer := make([]byte, 1048576)
917 var totalSent int64
918 for {
919 var bytesRead int
920 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
921 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
922 return err
923 }
924 break
925 }
926 if err != nil {
927 panic(err)
928 }
929 totalSent += int64(bytesRead)
930
931 fileTransfer.BytesSent += bytesRead
932
933 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
934 return err
935 }
85767504 936 }
6988a057 937
85767504 938 // TODO: optionally send resource fork header and resource fork data
6988a057 939
16a4ad70 940 // Read the client's Next Action request. This is always 3, I think?
c4208f86 941 if _, err := io.ReadFull(conn, nextAction); err != nil {
85767504 942 return err
6988a057 943 }
85767504 944
16a4ad70 945 return nil
6988a057
JH
946 })
947
948 case FolderUpload:
92a7e455
JH
949 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
950 if err != nil {
951 return err
952 }
6988a057
JH
953 s.Logger.Infow(
954 "Folder upload started",
955 "transactionRef", fileTransfer.ReferenceNumber,
6988a057 956 "dstPath", dstPath,
92a7e455 957 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
6988a057
JH
958 "FolderItemCount", fileTransfer.FolderItemCount,
959 )
960
961 // Check if the target folder exists. If not, create it.
92a7e455 962 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
92a7e455 963 if err := FS.Mkdir(dstPath, 0777); err != nil {
16a4ad70 964 return err
6988a057
JH
965 }
966 }
967
6988a057
JH
968 // Begin the folder upload flow by sending the "next file action" to client
969 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
970 return err
971 }
972
973 fileSize := make([]byte, 4)
85767504 974 readBuffer := make([]byte, 1024)
16a4ad70
JH
975
976 for i := 0; i < fileTransfer.ItemCount(); i++ {
c4208f86 977 // TODO: fix potential short read with io.ReadFull
85767504
JH
978 _, err := conn.Read(readBuffer)
979 if err != nil {
6988a057
JH
980 return err
981 }
982 fu := readFolderUpload(readBuffer)
983
984 s.Logger.Infow(
985 "Folder upload continued",
986 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
6988a057
JH
987 "FormattedPath", fu.FormattedPath(),
988 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
c5d9af5a 989 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
6988a057
JH
990 )
991
c5d9af5a 992 if fu.IsFolder == [2]byte{0, 1} {
6988a057 993 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
6988a057 994 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
16a4ad70 995 return err
6988a057
JH
996 }
997 }
998
999 // Tell client to send next file
1000 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1001 return err
1002 }
1003 } else {
16a4ad70
JH
1004 nextAction := dlFldrActionSendFile
1005
1006 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1007 _, err := os.Stat(dstPath + "/" + fu.FormattedPath())
1008 if err != nil && !errors.Is(err, fs.ErrNotExist) {
6988a057
JH
1009 return err
1010 }
16a4ad70
JH
1011 if err == nil {
1012 nextAction = dlFldrActionNextFile
1013 }
6988a057 1014
16a4ad70
JH
1015 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1016 inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
1017 if err != nil && !errors.Is(err, fs.ErrNotExist) {
85767504 1018 return err
6988a057 1019 }
16a4ad70
JH
1020 if err == nil {
1021 nextAction = dlFldrActionResumeFile
1022 }
6988a057 1023
16a4ad70 1024 fmt.Printf("Next Action: %v\n", nextAction)
6988a057 1025
16a4ad70 1026 if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil {
85767504
JH
1027 return err
1028 }
1029
16a4ad70
JH
1030 switch nextAction {
1031 case dlFldrActionNextFile:
1032 continue
1033 case dlFldrActionResumeFile:
1034 offset := make([]byte, 4)
1035 binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size()))
1036
1037 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1038 if err != nil {
1039 return err
1040 }
1041
1042 fileResumeData := NewFileResumeData([]ForkInfoList{
1043 *NewForkInfoList(offset),
1044 })
1045
1046 b, _ := fileResumeData.BinaryMarshal()
1047
1048 bs := make([]byte, 2)
1049 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1050
1051 if _, err := conn.Write(append(bs, b...)); err != nil {
1052 return err
1053 }
1054
c4208f86 1055 if _, err := io.ReadFull(conn, fileSize); err != nil {
16a4ad70
JH
1056 return err
1057 }
1058
1059 if err := receiveFile(conn, file, ioutil.Discard); err != nil {
1060 s.Logger.Error(err)
1061 }
1062
1063 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1064 if err != nil {
1065 return err
1066 }
1067
1068 case dlFldrActionSendFile:
1069 if _, err := conn.Read(fileSize); err != nil {
1070 return err
1071 }
1072
1073 filePath := dstPath + "/" + fu.FormattedPath()
1074 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize))
1075
1076 newFile, err := FS.Create(filePath + ".incomplete")
1077 if err != nil {
1078 return err
1079 }
1080
1081 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
1082 s.Logger.Error(err)
1083 }
1084 _ = newFile.Close()
1085 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1086 return err
1087 }
6988a057
JH
1088 }
1089
1090 // Tell client to send next file
1091 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1092 return err
1093 }
6988a057
JH
1094 }
1095 }
1096 s.Logger.Infof("Folder upload complete")
1097 }
1098
1099 return nil
1100}
1101
6988a057
JH
1102// sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1103// The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1104func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1105 for _, c := range unsortedClients {
1106 clients = append(clients, c)
1107 }
1108 sort.Sort(byClientID(clients))
1109 return clients
1110}