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