]>
Commit | Line | Data |
---|---|---|
6988a057 JH |
1 | package hotline |
2 | ||
3 | import ( | |
6988a057 JH |
4 | "context" |
5 | "encoding/binary" | |
6 | "errors" | |
7 | "fmt" | |
8 | "go.uber.org/zap" | |
9 | "io" | |
16a4ad70 | 10 | "io/fs" |
6988a057 | 11 | "io/ioutil" |
6988a057 JH |
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 | ||
0197c3f5 | 24 | "gopkg.in/yaml.v3" |
6988a057 JH |
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 { | |
6988a057 JH |
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 | ||
aebc4d36 JH |
52 | // newsReader io.Reader |
53 | // newsWriter io.WriteCloser | |
6988a057 JH |
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() { | |
85767504 | 95 | if err := s.handleFileTransfer(conn); err != nil { |
6988a057 JH |
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 { | |
bd1ce113 | 113 | return fmt.Errorf("invalid client id %v", *t.clientID) |
6988a057 | 114 | } |
72dd37f1 | 115 | userName := string(client.UserName) |
6988a057 JH |
116 | login := client.Account.Login |
117 | ||
118 | handler := TransactionHandlers[requestNum] | |
119 | ||
72dd37f1 JH |
120 | b, err := t.MarshalBinary() |
121 | if err != nil { | |
122 | return err | |
123 | } | |
6988a057 | 124 | var n int |
72dd37f1 | 125 | if n, err = client.Connection.Write(b); err != nil { |
6988a057 JH |
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 ( | |
c7e932c0 | 171 | agreementFile = "Agreement.txt" |
6988a057 JH |
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 | go func() { | |
240 | for { | |
241 | tr := TrackerRegistration{ | |
242 | Port: []byte{0x15, 0x7c}, | |
243 | UserCount: server.userCount(), | |
244 | PassID: server.TrackerPassID, | |
245 | Name: server.Config.Name, | |
246 | Description: server.Config.Description, | |
247 | } | |
248 | for _, t := range server.Config.Trackers { | |
249 | server.Logger.Infof("Registering with tracker %v", t) | |
250 | ||
251 | if err := register(t, tr); err != nil { | |
252 | server.Logger.Errorw("unable to register with tracker %v", "error", err) | |
253 | } | |
254 | } | |
255 | ||
256 | time.Sleep(trackerUpdateFrequency * time.Second) | |
257 | } | |
258 | }() | |
259 | } | |
260 | ||
261 | // Start Client Keepalive go routine | |
262 | go server.keepaliveHandler() | |
263 | ||
264 | return &server, nil | |
265 | } | |
266 | ||
267 | func (s *Server) userCount() int { | |
268 | s.mux.Lock() | |
269 | defer s.mux.Unlock() | |
270 | ||
271 | return len(s.Clients) | |
272 | } | |
273 | ||
274 | func (s *Server) keepaliveHandler() { | |
275 | for { | |
276 | time.Sleep(idleCheckInterval * time.Second) | |
277 | s.mux.Lock() | |
278 | ||
279 | for _, c := range s.Clients { | |
61c272e1 JH |
280 | c.IdleTime += idleCheckInterval |
281 | if c.IdleTime > userIdleSeconds && !c.Idle { | |
6988a057 JH |
282 | c.Idle = true |
283 | ||
284 | flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags))) | |
285 | flagBitmap.SetBit(flagBitmap, userFlagAway, 1) | |
286 | binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64())) | |
287 | ||
288 | c.sendAll( | |
289 | tranNotifyChangeUser, | |
290 | NewField(fieldUserID, *c.ID), | |
291 | NewField(fieldUserFlags, *c.Flags), | |
72dd37f1 | 292 | NewField(fieldUserName, c.UserName), |
6988a057 JH |
293 | NewField(fieldUserIconID, *c.Icon), |
294 | ) | |
295 | } | |
296 | } | |
297 | s.mux.Unlock() | |
298 | } | |
299 | } | |
300 | ||
301 | func (s *Server) writeThreadedNews() error { | |
302 | s.mux.Lock() | |
303 | defer s.mux.Unlock() | |
304 | ||
305 | out, err := yaml.Marshal(s.ThreadedNews) | |
306 | if err != nil { | |
307 | return err | |
308 | } | |
309 | err = ioutil.WriteFile( | |
310 | s.ConfigDir+"ThreadedNews.yaml", | |
311 | out, | |
312 | 0666, | |
313 | ) | |
314 | return err | |
315 | } | |
316 | ||
317 | func (s *Server) NewClientConn(conn net.Conn) *ClientConn { | |
318 | s.mux.Lock() | |
319 | defer s.mux.Unlock() | |
320 | ||
321 | clientConn := &ClientConn{ | |
322 | ID: &[]byte{0, 0}, | |
323 | Icon: &[]byte{0, 0}, | |
324 | Flags: &[]byte{0, 0}, | |
72dd37f1 | 325 | UserName: []byte{}, |
6988a057 JH |
326 | Connection: conn, |
327 | Server: s, | |
328 | Version: &[]byte{}, | |
aebc4d36 | 329 | AutoReply: []byte{}, |
6988a057 | 330 | Transfers: make(map[int][]*FileTransfer), |
bd1ce113 | 331 | Agreed: false, |
6988a057 JH |
332 | } |
333 | *s.NextGuestID++ | |
334 | ID := *s.NextGuestID | |
335 | ||
6988a057 JH |
336 | binary.BigEndian.PutUint16(*clientConn.ID, ID) |
337 | s.Clients[ID] = clientConn | |
338 | ||
339 | return clientConn | |
340 | } | |
341 | ||
342 | // NewUser creates a new user account entry in the server map and config file | |
343 | func (s *Server) NewUser(login, name, password string, access []byte) error { | |
344 | s.mux.Lock() | |
345 | defer s.mux.Unlock() | |
346 | ||
347 | account := Account{ | |
348 | Login: login, | |
349 | Name: name, | |
350 | Password: hashAndSalt([]byte(password)), | |
351 | Access: &access, | |
352 | } | |
353 | out, err := yaml.Marshal(&account) | |
354 | if err != nil { | |
355 | return err | |
356 | } | |
357 | s.Accounts[login] = &account | |
358 | ||
481631f6 | 359 | return FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666) |
6988a057 JH |
360 | } |
361 | ||
362 | // DeleteUser deletes the user account | |
363 | func (s *Server) DeleteUser(login string) error { | |
364 | s.mux.Lock() | |
365 | defer s.mux.Unlock() | |
366 | ||
367 | delete(s.Accounts, login) | |
368 | ||
003a743e | 369 | return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml") |
6988a057 JH |
370 | } |
371 | ||
372 | func (s *Server) connectedUsers() []Field { | |
373 | s.mux.Lock() | |
374 | defer s.mux.Unlock() | |
375 | ||
376 | var connectedUsers []Field | |
c7e932c0 | 377 | for _, c := range sortedClients(s.Clients) { |
aebc4d36 | 378 | if !c.Agreed { |
bd1ce113 JH |
379 | continue |
380 | } | |
6988a057 JH |
381 | user := User{ |
382 | ID: *c.ID, | |
383 | Icon: *c.Icon, | |
384 | Flags: *c.Flags, | |
72dd37f1 | 385 | Name: string(c.UserName), |
6988a057 JH |
386 | } |
387 | connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload())) | |
388 | } | |
389 | return connectedUsers | |
390 | } | |
391 | ||
392 | // loadThreadedNews loads the threaded news data from disk | |
393 | func (s *Server) loadThreadedNews(threadedNewsPath string) error { | |
394 | fh, err := os.Open(threadedNewsPath) | |
395 | if err != nil { | |
396 | return err | |
397 | } | |
398 | decoder := yaml.NewDecoder(fh) | |
6988a057 JH |
399 | |
400 | return decoder.Decode(s.ThreadedNews) | |
401 | } | |
402 | ||
403 | // loadAccounts loads account data from disk | |
404 | func (s *Server) loadAccounts(userDir string) error { | |
405 | matches, err := filepath.Glob(path.Join(userDir, "*.yaml")) | |
406 | if err != nil { | |
407 | return err | |
408 | } | |
409 | ||
410 | if len(matches) == 0 { | |
411 | return errors.New("no user accounts found in " + userDir) | |
412 | } | |
413 | ||
414 | for _, file := range matches { | |
d492c46d | 415 | fh, err := FS.Open(file) |
6988a057 JH |
416 | if err != nil { |
417 | return err | |
418 | } | |
419 | ||
420 | account := Account{} | |
421 | decoder := yaml.NewDecoder(fh) | |
6988a057 JH |
422 | if err := decoder.Decode(&account); err != nil { |
423 | return err | |
424 | } | |
425 | ||
426 | s.Accounts[account.Login] = &account | |
427 | } | |
428 | return nil | |
429 | } | |
430 | ||
431 | func (s *Server) loadConfig(path string) error { | |
d492c46d | 432 | fh, err := FS.Open(path) |
6988a057 JH |
433 | if err != nil { |
434 | return err | |
435 | } | |
436 | ||
437 | decoder := yaml.NewDecoder(fh) | |
6988a057 JH |
438 | err = decoder.Decode(s.Config) |
439 | if err != nil { | |
440 | return err | |
441 | } | |
442 | return nil | |
443 | } | |
444 | ||
445 | const ( | |
446 | minTransactionLen = 22 // minimum length of any transaction | |
447 | ) | |
448 | ||
449 | // handleNewConnection takes a new net.Conn and performs the initial login sequence | |
450 | func (s *Server) handleNewConnection(conn net.Conn) error { | |
451 | handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length | |
452 | if _, err := conn.Read(handshakeBuf); err != nil { | |
453 | return err | |
454 | } | |
455 | if err := Handshake(conn, handshakeBuf[:12]); err != nil { | |
456 | return err | |
457 | } | |
458 | ||
459 | buf := make([]byte, 1024) | |
460 | readLen, err := conn.Read(buf) | |
461 | if readLen < minTransactionLen { | |
462 | return err | |
463 | } | |
464 | if err != nil { | |
465 | return err | |
466 | } | |
467 | ||
468 | clientLogin, _, err := ReadTransaction(buf[:readLen]) | |
469 | if err != nil { | |
470 | return err | |
471 | } | |
472 | ||
473 | c := s.NewClientConn(conn) | |
474 | defer c.Disconnect() | |
475 | defer func() { | |
476 | if r := recover(); r != nil { | |
477 | fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) | |
478 | c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) | |
479 | c.Disconnect() | |
480 | } | |
481 | }() | |
482 | ||
483 | encodedLogin := clientLogin.GetField(fieldUserLogin).Data | |
484 | encodedPassword := clientLogin.GetField(fieldUserPassword).Data | |
485 | *c.Version = clientLogin.GetField(fieldVersion).Data | |
486 | ||
487 | var login string | |
488 | for _, char := range encodedLogin { | |
489 | login += string(rune(255 - uint(char))) | |
490 | } | |
491 | if login == "" { | |
492 | login = GuestAccount | |
493 | } | |
494 | ||
495 | // If authentication fails, send error reply and close connection | |
496 | if !c.Authenticate(login, encodedPassword) { | |
72dd37f1 JH |
497 | t := c.NewErrReply(clientLogin, "Incorrect login.") |
498 | b, err := t.MarshalBinary() | |
499 | if err != nil { | |
500 | return err | |
501 | } | |
502 | if _, err := conn.Write(b); err != nil { | |
6988a057 JH |
503 | return err |
504 | } | |
505 | return fmt.Errorf("incorrect login") | |
506 | } | |
507 | ||
6988a057 | 508 | if clientLogin.GetField(fieldUserName).Data != nil { |
72dd37f1 | 509 | c.UserName = clientLogin.GetField(fieldUserName).Data |
6988a057 JH |
510 | } |
511 | ||
512 | if clientLogin.GetField(fieldUserIconID).Data != nil { | |
513 | *c.Icon = clientLogin.GetField(fieldUserIconID).Data | |
514 | } | |
515 | ||
516 | c.Account = c.Server.Accounts[login] | |
517 | ||
518 | if c.Authorize(accessDisconUser) { | |
519 | *c.Flags = []byte{0, 2} | |
520 | } | |
521 | ||
522 | s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String()) | |
523 | ||
524 | s.outbox <- c.NewReply(clientLogin, | |
525 | NewField(fieldVersion, []byte{0x00, 0xbe}), | |
526 | NewField(fieldCommunityBannerID, []byte{0x00, 0x01}), | |
527 | NewField(fieldServerName, []byte(s.Config.Name)), | |
528 | ) | |
529 | ||
530 | // Send user access privs so client UI knows how to behave | |
531 | c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access)) | |
532 | ||
533 | // Show agreement to client | |
534 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement)) | |
535 | ||
bd1ce113 JH |
536 | // assume simplified hotline v1.2.3 login flow that does not require agreement |
537 | if *c.Version == nil { | |
538 | c.Agreed = true | |
003a743e JH |
539 | |
540 | c.notifyOthers( | |
541 | *NewTransaction( | |
542 | tranNotifyChangeUser, nil, | |
543 | NewField(fieldUserName, c.UserName), | |
544 | NewField(fieldUserID, *c.ID), | |
545 | NewField(fieldUserIconID, *c.Icon), | |
546 | NewField(fieldUserFlags, *c.Flags), | |
547 | ), | |
548 | ) | |
6988a057 | 549 | } |
bd1ce113 | 550 | |
6988a057 JH |
551 | c.Server.Stats.LoginCount += 1 |
552 | ||
553 | const readBuffSize = 1024000 // 1KB - TODO: what should this be? | |
6988a057 JH |
554 | tranBuff := make([]byte, 0) |
555 | tReadlen := 0 | |
556 | // Infinite loop where take action on incoming client requests until the connection is closed | |
557 | for { | |
558 | buf = make([]byte, readBuffSize) | |
559 | tranBuff = tranBuff[tReadlen:] | |
560 | ||
561 | readLen, err := c.Connection.Read(buf) | |
562 | if err != nil { | |
563 | return err | |
564 | } | |
565 | tranBuff = append(tranBuff, buf[:readLen]...) | |
566 | ||
567 | // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them | |
568 | // into a slice of transactions | |
569 | var transactions []Transaction | |
570 | if transactions, tReadlen, err = readTransactions(tranBuff); err != nil { | |
571 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
572 | } | |
573 | ||
574 | // iterate over all of the transactions that were parsed from the byte slice and handle them | |
575 | for _, t := range transactions { | |
576 | if err := c.handleTransaction(&t); err != nil { | |
577 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
578 | } | |
579 | } | |
580 | } | |
581 | } | |
582 | ||
6988a057 JH |
583 | // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID |
584 | // in the file transfer request payload, and the file transfer server will use it to map the request | |
585 | // to a transfer | |
586 | func (s *Server) NewTransactionRef() []byte { | |
587 | transactionRef := make([]byte, 4) | |
588 | rand.Read(transactionRef) | |
589 | ||
590 | return transactionRef | |
591 | } | |
592 | ||
593 | func (s *Server) NewPrivateChat(cc *ClientConn) []byte { | |
594 | s.mux.Lock() | |
595 | defer s.mux.Unlock() | |
596 | ||
597 | randID := make([]byte, 4) | |
598 | rand.Read(randID) | |
599 | data := binary.BigEndian.Uint32(randID[:]) | |
600 | ||
601 | s.PrivateChats[data] = &PrivateChat{ | |
602 | Subject: "", | |
603 | ClientConn: make(map[uint16]*ClientConn), | |
604 | } | |
605 | s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc | |
606 | ||
607 | return randID | |
608 | } | |
609 | ||
610 | const dlFldrActionSendFile = 1 | |
611 | const dlFldrActionResumeFile = 2 | |
612 | const dlFldrActionNextFile = 3 | |
613 | ||
85767504 JH |
614 | // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection |
615 | func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error { | |
616 | defer func() { | |
617 | if err := conn.Close(); err != nil { | |
618 | s.Logger.Errorw("error closing connection", "error", err) | |
619 | } | |
620 | }() | |
6988a057 | 621 | |
2e7c03cf JH |
622 | txBuf := make([]byte, 16) |
623 | _, err := conn.Read(txBuf) | |
624 | if err != nil { | |
6988a057 JH |
625 | return err |
626 | } | |
627 | ||
df2735b2 | 628 | var t transfer |
2e7c03cf | 629 | _, err = t.Write(txBuf) |
6988a057 JH |
630 | if err != nil { |
631 | return err | |
632 | } | |
633 | ||
634 | transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:]) | |
635 | fileTransfer := s.FileTransfers[transferRefNum] | |
636 | ||
16a4ad70 JH |
637 | // delete single use transferRefNum |
638 | delete(s.FileTransfers, transferRefNum) | |
639 | ||
6988a057 JH |
640 | switch fileTransfer.Type { |
641 | case FileDownload: | |
92a7e455 JH |
642 | fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
643 | if err != nil { | |
644 | return err | |
645 | } | |
6988a057 | 646 | |
16a4ad70 JH |
647 | var dataOffset int64 |
648 | if fileTransfer.fileResumeData != nil { | |
649 | dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) | |
650 | } | |
651 | ||
652 | ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset) | |
6988a057 JH |
653 | if err != nil { |
654 | return err | |
655 | } | |
656 | ||
85767504 | 657 | s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber) |
6988a057 JH |
658 | |
659 | // Start by sending flat file object to client | |
c5d9af5a | 660 | if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
661 | return err |
662 | } | |
663 | ||
92a7e455 | 664 | file, err := FS.Open(fullFilePath) |
6988a057 JH |
665 | if err != nil { |
666 | return err | |
667 | } | |
668 | ||
669 | sendBuffer := make([]byte, 1048576) | |
16a4ad70 | 670 | var totalSent int64 |
6988a057 JH |
671 | for { |
672 | var bytesRead int | |
16a4ad70 JH |
673 | if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF { |
674 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { | |
675 | return err | |
676 | } | |
6988a057 JH |
677 | break |
678 | } | |
16a4ad70 JH |
679 | if err != nil { |
680 | return err | |
681 | } | |
682 | totalSent += int64(bytesRead) | |
6988a057 JH |
683 | |
684 | fileTransfer.BytesSent += bytesRead | |
685 | ||
6988a057 JH |
686 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { |
687 | return err | |
688 | } | |
689 | } | |
690 | case FileUpload: | |
6988a057 | 691 | destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) |
16a4ad70 JH |
692 | tmpFile := destinationFile + ".incomplete" |
693 | ||
694 | file, err := effectiveFile(destinationFile) | |
695 | if errors.Is(err, fs.ErrNotExist) { | |
696 | file, err = FS.Create(tmpFile) | |
697 | if err != nil { | |
698 | return err | |
699 | } | |
6988a057 | 700 | } |
16a4ad70 JH |
701 | |
702 | defer func() { _ = file.Close() }() | |
6988a057 | 703 | |
85767504 | 704 | s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) |
6988a057 | 705 | |
16a4ad70 JH |
706 | // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data |
707 | if err := receiveFile(conn, file, io.Discard); err != nil { | |
708 | return err | |
709 | } | |
710 | ||
711 | if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil { | |
712 | return err | |
6988a057 | 713 | } |
85767504 JH |
714 | |
715 | s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) | |
6988a057 JH |
716 | case FolderDownload: |
717 | // Folder Download flow: | |
df2735b2 | 718 | // 1. Get filePath from the transfer |
6988a057 JH |
719 | // 2. Iterate over files |
720 | // 3. For each file: | |
721 | // Send file header to client | |
722 | // The client can reply in 3 ways: | |
723 | // | |
724 | // 1. If type is an odd number (unknown type?), or file download for the current file is completed: | |
725 | // client sends []byte{0x00, 0x03} to tell the server to continue to the next file | |
726 | // | |
727 | // 2. If download of a file is to be resumed: | |
728 | // client sends: | |
729 | // []byte{0x00, 0x02} // download folder action | |
730 | // [2]byte // Resume data size | |
731 | // []byte file resume data (see myField_FileResumeData) | |
732 | // | |
16a4ad70 | 733 | // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01} |
6988a057 JH |
734 | // |
735 | // When download is requested (case 2 or 3), server replies with: | |
736 | // [4]byte - file size | |
737 | // []byte - Flattened File Object | |
738 | // | |
739 | // After every file download, client could request next file with: | |
740 | // []byte{0x00, 0x03} | |
741 | // | |
742 | // This notifies the server to send the next item header | |
743 | ||
92a7e455 JH |
744 | fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
745 | if err != nil { | |
746 | return err | |
747 | } | |
6988a057 JH |
748 | |
749 | basePathLen := len(fullFilePath) | |
750 | ||
85767504 | 751 | s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber) |
6988a057 | 752 | |
85767504 JH |
753 | nextAction := make([]byte, 2) |
754 | if _, err := conn.Read(nextAction); err != nil { | |
755 | return err | |
756 | } | |
6988a057 JH |
757 | |
758 | i := 0 | |
85767504 JH |
759 | err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error { |
760 | if err != nil { | |
761 | return err | |
762 | } | |
6988a057 | 763 | i += 1 |
85767504 | 764 | subPath := path[basePathLen+1:] |
6988a057 JH |
765 | s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) |
766 | ||
6988a057 JH |
767 | if i == 1 { |
768 | return nil | |
769 | } | |
770 | ||
85767504 JH |
771 | fileHeader := NewFileHeader(subPath, info.IsDir()) |
772 | ||
6988a057 JH |
773 | // Send the file header to client |
774 | if _, err := conn.Write(fileHeader.Payload()); err != nil { | |
775 | s.Logger.Errorf("error sending file header: %v", err) | |
776 | return err | |
777 | } | |
778 | ||
779 | // Read the client's Next Action request | |
85767504 | 780 | if _, err := conn.Read(nextAction); err != nil { |
6988a057 JH |
781 | return err |
782 | } | |
783 | ||
85767504 | 784 | s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) |
6988a057 | 785 | |
16a4ad70 JH |
786 | var dataOffset int64 |
787 | ||
788 | switch nextAction[1] { | |
789 | case dlFldrActionResumeFile: | |
790 | // client asked to resume this file | |
791 | var frd FileResumeData | |
792 | // get size of resumeData | |
793 | if _, err := conn.Read(nextAction); err != nil { | |
794 | return err | |
795 | } | |
796 | ||
797 | resumeDataLen := binary.BigEndian.Uint16(nextAction) | |
798 | resumeDataBytes := make([]byte, resumeDataLen) | |
799 | if _, err := conn.Read(resumeDataBytes); err != nil { | |
800 | return err | |
801 | } | |
802 | ||
803 | if err := frd.UnmarshalBinary(resumeDataBytes); err != nil { | |
804 | return err | |
805 | } | |
806 | dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:])) | |
807 | case dlFldrActionNextFile: | |
808 | // client asked to skip this file | |
809 | return nil | |
810 | } | |
811 | ||
6988a057 JH |
812 | if info.IsDir() { |
813 | return nil | |
814 | } | |
815 | ||
816 | splitPath := strings.Split(path, "/") | |
6988a057 | 817 | |
16a4ad70 | 818 | ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset) |
6988a057 JH |
819 | if err != nil { |
820 | return err | |
821 | } | |
822 | s.Logger.Infow("File download started", | |
823 | "fileName", info.Name(), | |
824 | "transactionRef", fileTransfer.ReferenceNumber, | |
6988a057 JH |
825 | "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()), |
826 | ) | |
827 | ||
828 | // Send file size to client | |
829 | if _, err := conn.Write(ffo.TransferSize()); err != nil { | |
830 | s.Logger.Error(err) | |
831 | return err | |
832 | } | |
833 | ||
85767504 | 834 | // Send ffo bytes to client |
c5d9af5a | 835 | if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
836 | s.Logger.Error(err) |
837 | return err | |
838 | } | |
839 | ||
d492c46d | 840 | file, err := FS.Open(path) |
6988a057 JH |
841 | if err != nil { |
842 | return err | |
843 | } | |
844 | ||
16a4ad70 JH |
845 | // // Copy N bytes from file to connection |
846 | // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:]))) | |
847 | // if err != nil { | |
848 | // return err | |
849 | // } | |
850 | // file.Close() | |
851 | sendBuffer := make([]byte, 1048576) | |
852 | var totalSent int64 | |
853 | for { | |
854 | var bytesRead int | |
855 | if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF { | |
856 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { | |
857 | return err | |
858 | } | |
859 | break | |
860 | } | |
861 | if err != nil { | |
862 | panic(err) | |
863 | } | |
864 | totalSent += int64(bytesRead) | |
865 | ||
866 | fileTransfer.BytesSent += bytesRead | |
867 | ||
868 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { | |
869 | return err | |
870 | } | |
85767504 | 871 | } |
6988a057 | 872 | |
85767504 | 873 | // TODO: optionally send resource fork header and resource fork data |
6988a057 | 874 | |
16a4ad70 | 875 | // Read the client's Next Action request. This is always 3, I think? |
85767504 JH |
876 | if _, err := conn.Read(nextAction); err != nil { |
877 | return err | |
6988a057 | 878 | } |
85767504 | 879 | |
16a4ad70 | 880 | return nil |
6988a057 JH |
881 | }) |
882 | ||
883 | case FolderUpload: | |
92a7e455 JH |
884 | dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
885 | if err != nil { | |
886 | return err | |
887 | } | |
6988a057 JH |
888 | s.Logger.Infow( |
889 | "Folder upload started", | |
890 | "transactionRef", fileTransfer.ReferenceNumber, | |
6988a057 | 891 | "dstPath", dstPath, |
92a7e455 | 892 | "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize), |
6988a057 JH |
893 | "FolderItemCount", fileTransfer.FolderItemCount, |
894 | ) | |
895 | ||
896 | // Check if the target folder exists. If not, create it. | |
92a7e455 | 897 | if _, err := FS.Stat(dstPath); os.IsNotExist(err) { |
92a7e455 | 898 | if err := FS.Mkdir(dstPath, 0777); err != nil { |
16a4ad70 | 899 | return err |
6988a057 JH |
900 | } |
901 | } | |
902 | ||
6988a057 JH |
903 | // Begin the folder upload flow by sending the "next file action" to client |
904 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
905 | return err | |
906 | } | |
907 | ||
908 | fileSize := make([]byte, 4) | |
85767504 | 909 | readBuffer := make([]byte, 1024) |
16a4ad70 JH |
910 | |
911 | for i := 0; i < fileTransfer.ItemCount(); i++ { | |
912 | ||
85767504 JH |
913 | _, err := conn.Read(readBuffer) |
914 | if err != nil { | |
6988a057 JH |
915 | return err |
916 | } | |
917 | fu := readFolderUpload(readBuffer) | |
918 | ||
919 | s.Logger.Infow( | |
920 | "Folder upload continued", | |
921 | "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), | |
6988a057 JH |
922 | "FormattedPath", fu.FormattedPath(), |
923 | "IsFolder", fmt.Sprintf("%x", fu.IsFolder), | |
c5d9af5a | 924 | "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), |
6988a057 JH |
925 | ) |
926 | ||
c5d9af5a | 927 | if fu.IsFolder == [2]byte{0, 1} { |
6988a057 | 928 | if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) { |
6988a057 | 929 | if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil { |
16a4ad70 | 930 | return err |
6988a057 JH |
931 | } |
932 | } | |
933 | ||
934 | // Tell client to send next file | |
935 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
6988a057 JH |
936 | return err |
937 | } | |
938 | } else { | |
16a4ad70 JH |
939 | nextAction := dlFldrActionSendFile |
940 | ||
941 | // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. | |
942 | _, err := os.Stat(dstPath + "/" + fu.FormattedPath()) | |
943 | if err != nil && !errors.Is(err, fs.ErrNotExist) { | |
6988a057 JH |
944 | return err |
945 | } | |
16a4ad70 JH |
946 | if err == nil { |
947 | nextAction = dlFldrActionNextFile | |
948 | } | |
6988a057 | 949 | |
16a4ad70 JH |
950 | // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. |
951 | inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix) | |
952 | if err != nil && !errors.Is(err, fs.ErrNotExist) { | |
85767504 | 953 | return err |
6988a057 | 954 | } |
16a4ad70 JH |
955 | if err == nil { |
956 | nextAction = dlFldrActionResumeFile | |
957 | } | |
6988a057 | 958 | |
16a4ad70 | 959 | fmt.Printf("Next Action: %v\n", nextAction) |
6988a057 | 960 | |
16a4ad70 | 961 | if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil { |
85767504 JH |
962 | return err |
963 | } | |
964 | ||
16a4ad70 JH |
965 | switch nextAction { |
966 | case dlFldrActionNextFile: | |
967 | continue | |
968 | case dlFldrActionResumeFile: | |
969 | offset := make([]byte, 4) | |
970 | binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size())) | |
971 | ||
972 | file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) | |
973 | if err != nil { | |
974 | return err | |
975 | } | |
976 | ||
977 | fileResumeData := NewFileResumeData([]ForkInfoList{ | |
978 | *NewForkInfoList(offset), | |
979 | }) | |
980 | ||
981 | b, _ := fileResumeData.BinaryMarshal() | |
982 | ||
983 | bs := make([]byte, 2) | |
984 | binary.BigEndian.PutUint16(bs, uint16(len(b))) | |
985 | ||
986 | if _, err := conn.Write(append(bs, b...)); err != nil { | |
987 | return err | |
988 | } | |
989 | ||
990 | if _, err := conn.Read(fileSize); err != nil { | |
991 | return err | |
992 | } | |
993 | ||
994 | if err := receiveFile(conn, file, ioutil.Discard); err != nil { | |
995 | s.Logger.Error(err) | |
996 | } | |
997 | ||
998 | err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath()) | |
999 | if err != nil { | |
1000 | return err | |
1001 | } | |
1002 | ||
1003 | case dlFldrActionSendFile: | |
1004 | if _, err := conn.Read(fileSize); err != nil { | |
1005 | return err | |
1006 | } | |
1007 | ||
1008 | filePath := dstPath + "/" + fu.FormattedPath() | |
1009 | s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize)) | |
1010 | ||
1011 | newFile, err := FS.Create(filePath + ".incomplete") | |
1012 | if err != nil { | |
1013 | return err | |
1014 | } | |
1015 | ||
1016 | if err := receiveFile(conn, newFile, ioutil.Discard); err != nil { | |
1017 | s.Logger.Error(err) | |
1018 | } | |
1019 | _ = newFile.Close() | |
1020 | if err := os.Rename(filePath+".incomplete", filePath); err != nil { | |
1021 | return err | |
1022 | } | |
6988a057 JH |
1023 | } |
1024 | ||
1025 | // Tell client to send next file | |
1026 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
6988a057 JH |
1027 | return err |
1028 | } | |
6988a057 JH |
1029 | } |
1030 | } | |
1031 | s.Logger.Infof("Folder upload complete") | |
1032 | } | |
1033 | ||
1034 | return nil | |
1035 | } | |
1036 | ||
6988a057 JH |
1037 | // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values. |
1038 | // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work. | |
1039 | func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) { | |
1040 | for _, c := range unsortedClients { | |
1041 | clients = append(clients, c) | |
1042 | } | |
1043 | sort.Sort(byClientID(clients)) | |
1044 | return clients | |
1045 | } |