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