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