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