]> git.r.bdr.sh - rbdr/mobius/blame - hotline/server.go
Remove unneeded code
[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
21581958 524func (s *Server) handleNewConnection(ctx context.Context, conn io.ReadWriteCloser, 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}),
9067f234 594 NewField(fieldCommunityBannerID, []byte{0, 0}),
6988a057
JH
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
67db911d
JH
607 c.logger = c.logger.With("name", string(c.UserName))
608
21581958 609 for _, t := range c.notifyOthers(
003a743e
JH
610 *NewTransaction(
611 tranNotifyChangeUser, nil,
612 NewField(fieldUserName, c.UserName),
613 NewField(fieldUserID, *c.ID),
614 NewField(fieldUserIconID, *c.Icon),
615 NewField(fieldUserFlags, *c.Flags),
616 ),
21581958
JH
617 ) {
618 c.Server.outbox <- t
619 }
6988a057 620 }
bd1ce113 621
6988a057
JH
622 c.Server.Stats.LoginCount += 1
623
624 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
6988a057
JH
625 tranBuff := make([]byte, 0)
626 tReadlen := 0
627 // Infinite loop where take action on incoming client requests until the connection is closed
628 for {
629 buf = make([]byte, readBuffSize)
630 tranBuff = tranBuff[tReadlen:]
631
632 readLen, err := c.Connection.Read(buf)
633 if err != nil {
634 return err
635 }
636 tranBuff = append(tranBuff, buf[:readLen]...)
637
638 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
639 // into a slice of transactions
640 var transactions []Transaction
641 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
0fcfa5d5 642 c.logger.Errorw("Error handling transaction", "err", err)
6988a057
JH
643 }
644
7cd900d6 645 // iterate over all the transactions that were parsed from the byte slice and handle them
6988a057
JH
646 for _, t := range transactions {
647 if err := c.handleTransaction(&t); err != nil {
21581958 648 c.logger.Errorw("Error handling transaction", "err", err)
6988a057
JH
649 }
650 }
651 }
652}
653
6988a057 654// NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
7cd900d6 655// in the transfer request payload, and the file transfer server will use it to map the request
6988a057
JH
656// to a transfer
657func (s *Server) NewTransactionRef() []byte {
658 transactionRef := make([]byte, 4)
659 rand.Read(transactionRef)
660
661 return transactionRef
662}
663
664func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
665 s.mux.Lock()
666 defer s.mux.Unlock()
667
668 randID := make([]byte, 4)
669 rand.Read(randID)
670 data := binary.BigEndian.Uint32(randID[:])
671
672 s.PrivateChats[data] = &PrivateChat{
673 Subject: "",
674 ClientConn: make(map[uint16]*ClientConn),
675 }
676 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
677
678 return randID
679}
680
681const dlFldrActionSendFile = 1
682const dlFldrActionResumeFile = 2
683const dlFldrActionNextFile = 3
684
85767504 685// handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
7cd900d6 686func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
37a954c8 687 defer dontPanic(s.Logger)
0a92e50b 688
2e7c03cf 689 txBuf := make([]byte, 16)
7cd900d6 690 if _, err := io.ReadFull(rwc, txBuf); err != nil {
6988a057
JH
691 return err
692 }
693
df2735b2 694 var t transfer
0a92e50b 695 if _, err := t.Write(txBuf); err != nil {
6988a057
JH
696 return err
697 }
698
699 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
0a92e50b
JH
700 defer func() {
701 s.mux.Lock()
702 delete(s.FileTransfers, transferRefNum)
703 s.mux.Unlock()
704 }()
6988a057 705
0a92e50b
JH
706 s.mux.Lock()
707 fileTransfer, ok := s.FileTransfers[transferRefNum]
708 s.mux.Unlock()
709 if !ok {
710 return errors.New("invalid transaction ID")
711 }
16a4ad70 712
7cd900d6
JH
713 rLogger := s.Logger.With(
714 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
715 "xferID", transferRefNum,
716 )
717
6988a057 718 switch fileTransfer.Type {
9067f234
JH
719 case bannerDownload:
720 if err := s.bannerDownload(rwc); err != nil {
721 return err
722 }
6988a057 723 case FileDownload:
23411fc2
JH
724 s.Stats.DownloadCounter += 1
725
92a7e455
JH
726 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
727 if err != nil {
728 return err
729 }
6988a057 730
16a4ad70
JH
731 var dataOffset int64
732 if fileTransfer.fileResumeData != nil {
733 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
734 }
735
7cd900d6 736 fw, err := newFileWrapper(s.FS, fullFilePath, 0)
6988a057
JH
737 if err != nil {
738 return err
739 }
740
7cd900d6 741 rLogger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
6988a057 742
7cd900d6
JH
743 wr := bufio.NewWriterSize(rwc, 1460)
744
745 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
d1cd6664
JH
746 if fileTransfer.options == nil {
747 // Start by sending flat file object to client
7cd900d6 748 if _, err := wr.Write(fw.ffo.BinaryMarshal()); err != nil {
d1cd6664
JH
749 return err
750 }
6988a057
JH
751 }
752
7cd900d6 753 file, err := fw.dataForkReader()
6988a057
JH
754 if err != nil {
755 return err
756 }
757
7cd900d6
JH
758 if err := sendFile(wr, file, int(dataOffset)); err != nil {
759 return err
760 }
761
762 if err := wr.Flush(); err != nil {
763 return err
764 }
765
766 // if the client requested to resume transfer, do not send the resource fork, or it will be appended into the fileWrapper data
767 if fileTransfer.fileResumeData == nil {
768 err = binary.Write(wr, binary.BigEndian, fw.rsrcForkHeader())
16a4ad70
JH
769 if err != nil {
770 return err
771 }
7cd900d6 772 if err := wr.Flush(); err != nil {
6988a057
JH
773 return err
774 }
775 }
7cd900d6
JH
776
777 rFile, err := fw.rsrcForkFile()
778 if err != nil {
779 return nil
780 }
781
782 err = sendFile(wr, rFile, int(dataOffset))
67db911d
JH
783 if err != nil {
784 return err
785 }
7cd900d6
JH
786
787 if err := wr.Flush(); err != nil {
788 return err
789 }
790
6988a057 791 case FileUpload:
23411fc2
JH
792 s.Stats.UploadCounter += 1
793
7cd900d6
JH
794 destinationFile, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
795 if err != nil {
796 return err
797 }
16a4ad70 798
5c14e4c9
JH
799 var file *os.File
800
801 // A file upload has three possible cases:
802 // 1) Upload a new file
803 // 2) Resume a partially transferred file
804 // 3) Replace a fully uploaded file
7cd900d6 805 // We have to infer which case applies by inspecting what is already on the filesystem
5c14e4c9
JH
806
807 // 1) Check for existing file:
7cd900d6 808 _, err = os.Stat(destinationFile)
5c14e4c9
JH
809 if err == nil {
810 // If found, that means this upload is intended to replace the file
811 if err = os.Remove(destinationFile); err != nil {
812 return err
813 }
814 file, err = os.Create(destinationFile + incompleteFileSuffix)
815 }
16a4ad70 816 if errors.Is(err, fs.ErrNotExist) {
7cd900d6 817 // If not found, open or create a new .incomplete file
5c14e4c9 818 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
16a4ad70
JH
819 if err != nil {
820 return err
821 }
6988a057 822 }
16a4ad70 823
7cd900d6
JH
824 f, err := newFileWrapper(s.FS, destinationFile, 0)
825 if err != nil {
826 return err
827 }
828
85767504 829 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
6988a057 830
7cd900d6
JH
831 rForkWriter := io.Discard
832 iForkWriter := io.Discard
833 if s.Config.PreserveResourceForks {
834 rForkWriter, err = f.rsrcForkWriter()
835 if err != nil {
836 return err
837 }
838
839 iForkWriter, err = f.infoForkWriter()
840 if err != nil {
841 return err
842 }
843 }
844
845 if err := receiveFile(rwc, file, rForkWriter, iForkWriter); err != nil {
16a4ad70
JH
846 return err
847 }
848
e00ff8fe
JH
849 if err := file.Close(); err != nil {
850 return err
851 }
67db911d 852
7cd900d6 853 if err := s.FS.Rename(destinationFile+".incomplete", destinationFile); err != nil {
16a4ad70 854 return err
6988a057 855 }
85767504
JH
856
857 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
6988a057
JH
858 case FolderDownload:
859 // Folder Download flow:
df2735b2 860 // 1. Get filePath from the transfer
6988a057 861 // 2. Iterate over files
7cd900d6
JH
862 // 3. For each fileWrapper:
863 // Send fileWrapper header to client
6988a057
JH
864 // The client can reply in 3 ways:
865 //
7cd900d6
JH
866 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
867 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
6988a057 868 //
7cd900d6 869 // 2. If download of a fileWrapper is to be resumed:
6988a057
JH
870 // client sends:
871 // []byte{0x00, 0x02} // download folder action
872 // [2]byte // Resume data size
7cd900d6 873 // []byte fileWrapper resume data (see myField_FileResumeData)
6988a057 874 //
7cd900d6 875 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
6988a057
JH
876 //
877 // When download is requested (case 2 or 3), server replies with:
7cd900d6 878 // [4]byte - fileWrapper size
6988a057
JH
879 // []byte - Flattened File Object
880 //
7cd900d6 881 // After every fileWrapper download, client could request next fileWrapper with:
6988a057
JH
882 // []byte{0x00, 0x03}
883 //
884 // This notifies the server to send the next item header
885
92a7e455
JH
886 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
887 if err != nil {
888 return err
889 }
6988a057
JH
890
891 basePathLen := len(fullFilePath)
892
85767504 893 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
6988a057 894
85767504 895 nextAction := make([]byte, 2)
7cd900d6 896 if _, err := io.ReadFull(rwc, nextAction); err != nil {
85767504
JH
897 return err
898 }
6988a057
JH
899
900 i := 0
85767504 901 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
23411fc2 902 s.Stats.DownloadCounter += 1
7cd900d6 903 i += 1
23411fc2 904
85767504
JH
905 if err != nil {
906 return err
907 }
7cd900d6
JH
908
909 // skip dot files
910 if strings.HasPrefix(info.Name(), ".") {
911 return nil
912 }
913
914 hlFile, err := newFileWrapper(s.FS, path, 0)
915 if err != nil {
916 return err
917 }
918
85767504 919 subPath := path[basePathLen+1:]
6988a057
JH
920 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
921
6988a057
JH
922 if i == 1 {
923 return nil
924 }
925
85767504
JH
926 fileHeader := NewFileHeader(subPath, info.IsDir())
927
7cd900d6
JH
928 // Send the fileWrapper header to client
929 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
6988a057
JH
930 s.Logger.Errorf("error sending file header: %v", err)
931 return err
932 }
933
934 // Read the client's Next Action request
7cd900d6 935 if _, err := io.ReadFull(rwc, nextAction); err != nil {
6988a057
JH
936 return err
937 }
938
85767504 939 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
6988a057 940
16a4ad70
JH
941 var dataOffset int64
942
943 switch nextAction[1] {
944 case dlFldrActionResumeFile:
16a4ad70 945 // get size of resumeData
7cd900d6
JH
946 resumeDataByteLen := make([]byte, 2)
947 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
16a4ad70
JH
948 return err
949 }
950
7cd900d6 951 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
16a4ad70 952 resumeDataBytes := make([]byte, resumeDataLen)
7cd900d6 953 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
16a4ad70
JH
954 return err
955 }
956
7cd900d6 957 var frd FileResumeData
16a4ad70
JH
958 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
959 return err
960 }
961 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
962 case dlFldrActionNextFile:
963 // client asked to skip this file
964 return nil
965 }
966
6988a057
JH
967 if info.IsDir() {
968 return nil
969 }
970
6988a057
JH
971 s.Logger.Infow("File download started",
972 "fileName", info.Name(),
973 "transactionRef", fileTransfer.ReferenceNumber,
7cd900d6 974 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
6988a057
JH
975 )
976
977 // Send file size to client
7cd900d6 978 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
6988a057
JH
979 s.Logger.Error(err)
980 return err
981 }
982
85767504 983 // Send ffo bytes to client
7cd900d6 984 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
6988a057
JH
985 s.Logger.Error(err)
986 return err
987 }
988
b196a50a 989 file, err := s.FS.Open(path)
6988a057
JH
990 if err != nil {
991 return err
992 }
993
7cd900d6
JH
994 // wr := bufio.NewWriterSize(rwc, 1460)
995 err = sendFile(rwc, file, int(dataOffset))
996 if err != nil {
997 return err
998 }
999
1000 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1001 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
16a4ad70 1002 if err != nil {
7cd900d6 1003 return err
16a4ad70 1004 }
16a4ad70 1005
7cd900d6
JH
1006 rFile, err := hlFile.rsrcForkFile()
1007 if err != nil {
1008 return err
1009 }
16a4ad70 1010
7cd900d6
JH
1011 err = sendFile(rwc, rFile, int(dataOffset))
1012 if err != nil {
16a4ad70
JH
1013 return err
1014 }
85767504 1015 }
6988a057 1016
16a4ad70 1017 // Read the client's Next Action request. This is always 3, I think?
7cd900d6 1018 if _, err := io.ReadFull(rwc, nextAction); err != nil {
85767504 1019 return err
6988a057 1020 }
85767504 1021
16a4ad70 1022 return nil
6988a057
JH
1023 })
1024
67db911d
JH
1025 if err != nil {
1026 return err
1027 }
1028
6988a057 1029 case FolderUpload:
92a7e455
JH
1030 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
1031 if err != nil {
1032 return err
1033 }
7cd900d6 1034
6988a057
JH
1035 s.Logger.Infow(
1036 "Folder upload started",
1037 "transactionRef", fileTransfer.ReferenceNumber,
6988a057 1038 "dstPath", dstPath,
92a7e455 1039 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
6988a057
JH
1040 "FolderItemCount", fileTransfer.FolderItemCount,
1041 )
1042
1043 // Check if the target folder exists. If not, create it.
b196a50a
JH
1044 if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
1045 if err := s.FS.Mkdir(dstPath, 0777); err != nil {
16a4ad70 1046 return err
6988a057
JH
1047 }
1048 }
1049
6988a057 1050 // Begin the folder upload flow by sending the "next file action" to client
7cd900d6 1051 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1052 return err
1053 }
1054
1055 fileSize := make([]byte, 4)
16a4ad70
JH
1056
1057 for i := 0; i < fileTransfer.ItemCount(); i++ {
ba29c43b
JH
1058 s.Stats.UploadCounter += 1
1059
1060 var fu folderUpload
7cd900d6 1061 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
ba29c43b
JH
1062 return err
1063 }
7cd900d6 1064 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
ba29c43b
JH
1065 return err
1066 }
7cd900d6 1067 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
ba29c43b
JH
1068 return err
1069 }
ba29c43b 1070
7cd900d6
JH
1071 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1072
1073 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
6988a057
JH
1074 return err
1075 }
6988a057
JH
1076
1077 s.Logger.Infow(
1078 "Folder upload continued",
1079 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
6988a057
JH
1080 "FormattedPath", fu.FormattedPath(),
1081 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
c5d9af5a 1082 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
6988a057
JH
1083 )
1084
c5d9af5a 1085 if fu.IsFolder == [2]byte{0, 1} {
f22acf38
JH
1086 if _, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath())); os.IsNotExist(err) {
1087 if err := os.Mkdir(filepath.Join(dstPath, fu.FormattedPath()), 0777); err != nil {
16a4ad70 1088 return err
6988a057
JH
1089 }
1090 }
1091
1092 // Tell client to send next file
7cd900d6 1093 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1094 return err
1095 }
1096 } else {
16a4ad70
JH
1097 nextAction := dlFldrActionSendFile
1098
1099 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
f22acf38 1100 _, err = os.Stat(filepath.Join(dstPath, fu.FormattedPath()))
16a4ad70 1101 if err != nil && !errors.Is(err, fs.ErrNotExist) {
6988a057
JH
1102 return err
1103 }
16a4ad70
JH
1104 if err == nil {
1105 nextAction = dlFldrActionNextFile
1106 }
6988a057 1107
16a4ad70 1108 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
f22acf38 1109 incompleteFile, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath()+incompleteFileSuffix))
16a4ad70 1110 if err != nil && !errors.Is(err, fs.ErrNotExist) {
85767504 1111 return err
6988a057 1112 }
16a4ad70
JH
1113 if err == nil {
1114 nextAction = dlFldrActionResumeFile
1115 }
6988a057 1116
7cd900d6 1117 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
85767504
JH
1118 return err
1119 }
1120
16a4ad70
JH
1121 switch nextAction {
1122 case dlFldrActionNextFile:
1123 continue
1124 case dlFldrActionResumeFile:
1125 offset := make([]byte, 4)
7cd900d6 1126 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
16a4ad70
JH
1127
1128 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1129 if err != nil {
1130 return err
1131 }
1132
7cd900d6 1133 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
16a4ad70
JH
1134
1135 b, _ := fileResumeData.BinaryMarshal()
1136
1137 bs := make([]byte, 2)
1138 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1139
7cd900d6 1140 if _, err := rwc.Write(append(bs, b...)); err != nil {
16a4ad70
JH
1141 return err
1142 }
1143
7cd900d6 1144 if _, err := io.ReadFull(rwc, fileSize); err != nil {
16a4ad70
JH
1145 return err
1146 }
1147
7cd900d6 1148 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard); err != nil {
16a4ad70
JH
1149 s.Logger.Error(err)
1150 }
1151
1152 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1153 if err != nil {
1154 return err
1155 }
1156
1157 case dlFldrActionSendFile:
7cd900d6 1158 if _, err := io.ReadFull(rwc, fileSize); err != nil {
16a4ad70
JH
1159 return err
1160 }
1161
f22acf38 1162 filePath := filepath.Join(dstPath, fu.FormattedPath())
16a4ad70 1163
7cd900d6 1164 hlFile, err := newFileWrapper(s.FS, filePath, 0)
16a4ad70
JH
1165 if err != nil {
1166 return err
1167 }
1168
7cd900d6
JH
1169 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1170
1171 incWriter, err := hlFile.incFileWriter()
1172 if err != nil {
1173 return err
1174 }
1175
1176 rForkWriter := io.Discard
1177 iForkWriter := io.Discard
1178 if s.Config.PreserveResourceForks {
1179 iForkWriter, err = hlFile.infoForkWriter()
1180 if err != nil {
1181 return err
1182 }
1183
1184 rForkWriter, err = hlFile.rsrcForkWriter()
1185 if err != nil {
1186 return err
1187 }
16a4ad70 1188 }
7cd900d6
JH
1189 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter); err != nil {
1190 return err
1191 }
1192 // _ = newFile.Close()
16a4ad70
JH
1193 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1194 return err
1195 }
6988a057
JH
1196 }
1197
7cd900d6
JH
1198 // Tell client to send next fileWrapper
1199 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1200 return err
1201 }
6988a057
JH
1202 }
1203 }
1204 s.Logger.Infof("Folder upload complete")
1205 }
1206
1207 return nil
1208}