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