]>
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 | ||
6988a057 JH |
23 | "gopkg.in/yaml.v2" |
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() { | |
94 | if err := s.TransferFile(conn); err != nil { | |
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 | ||
368 | return os.Remove(s.ConfigDir + "Users/" + login + ".yaml") | |
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) | |
398 | decoder.SetStrict(true) | |
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) | |
422 | decoder.SetStrict(true) | |
423 | if err := decoder.Decode(&account); err != nil { | |
424 | return err | |
425 | } | |
426 | ||
427 | s.Accounts[account.Login] = &account | |
428 | } | |
429 | return nil | |
430 | } | |
431 | ||
432 | func (s *Server) loadConfig(path string) error { | |
d492c46d | 433 | fh, err := FS.Open(path) |
6988a057 JH |
434 | if err != nil { |
435 | return err | |
436 | } | |
437 | ||
438 | decoder := yaml.NewDecoder(fh) | |
439 | decoder.SetStrict(true) | |
440 | err = decoder.Decode(s.Config) | |
441 | if err != nil { | |
442 | return err | |
443 | } | |
444 | return nil | |
445 | } | |
446 | ||
447 | const ( | |
448 | minTransactionLen = 22 // minimum length of any transaction | |
449 | ) | |
450 | ||
451 | // handleNewConnection takes a new net.Conn and performs the initial login sequence | |
452 | func (s *Server) handleNewConnection(conn net.Conn) error { | |
453 | handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length | |
454 | if _, err := conn.Read(handshakeBuf); err != nil { | |
455 | return err | |
456 | } | |
457 | if err := Handshake(conn, handshakeBuf[:12]); err != nil { | |
458 | return err | |
459 | } | |
460 | ||
461 | buf := make([]byte, 1024) | |
462 | readLen, err := conn.Read(buf) | |
463 | if readLen < minTransactionLen { | |
464 | return err | |
465 | } | |
466 | if err != nil { | |
467 | return err | |
468 | } | |
469 | ||
470 | clientLogin, _, err := ReadTransaction(buf[:readLen]) | |
471 | if err != nil { | |
472 | return err | |
473 | } | |
474 | ||
475 | c := s.NewClientConn(conn) | |
476 | defer c.Disconnect() | |
477 | defer func() { | |
478 | if r := recover(); r != nil { | |
479 | fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) | |
480 | c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) | |
481 | c.Disconnect() | |
482 | } | |
483 | }() | |
484 | ||
485 | encodedLogin := clientLogin.GetField(fieldUserLogin).Data | |
486 | encodedPassword := clientLogin.GetField(fieldUserPassword).Data | |
487 | *c.Version = clientLogin.GetField(fieldVersion).Data | |
488 | ||
489 | var login string | |
490 | for _, char := range encodedLogin { | |
491 | login += string(rune(255 - uint(char))) | |
492 | } | |
493 | if login == "" { | |
494 | login = GuestAccount | |
495 | } | |
496 | ||
497 | // If authentication fails, send error reply and close connection | |
498 | if !c.Authenticate(login, encodedPassword) { | |
72dd37f1 JH |
499 | t := c.NewErrReply(clientLogin, "Incorrect login.") |
500 | b, err := t.MarshalBinary() | |
501 | if err != nil { | |
502 | return err | |
503 | } | |
504 | if _, err := conn.Write(b); err != nil { | |
6988a057 JH |
505 | return err |
506 | } | |
507 | return fmt.Errorf("incorrect login") | |
508 | } | |
509 | ||
6988a057 | 510 | if clientLogin.GetField(fieldUserName).Data != nil { |
72dd37f1 | 511 | c.UserName = clientLogin.GetField(fieldUserName).Data |
6988a057 JH |
512 | } |
513 | ||
514 | if clientLogin.GetField(fieldUserIconID).Data != nil { | |
515 | *c.Icon = clientLogin.GetField(fieldUserIconID).Data | |
516 | } | |
517 | ||
518 | c.Account = c.Server.Accounts[login] | |
519 | ||
520 | if c.Authorize(accessDisconUser) { | |
521 | *c.Flags = []byte{0, 2} | |
522 | } | |
523 | ||
524 | s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String()) | |
525 | ||
526 | s.outbox <- c.NewReply(clientLogin, | |
527 | NewField(fieldVersion, []byte{0x00, 0xbe}), | |
528 | NewField(fieldCommunityBannerID, []byte{0x00, 0x01}), | |
529 | NewField(fieldServerName, []byte(s.Config.Name)), | |
530 | ) | |
531 | ||
532 | // Send user access privs so client UI knows how to behave | |
533 | c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access)) | |
534 | ||
535 | // Show agreement to client | |
536 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement)) | |
537 | ||
bd1ce113 JH |
538 | // assume simplified hotline v1.2.3 login flow that does not require agreement |
539 | if *c.Version == nil { | |
540 | c.Agreed = true | |
541 | if _, err := c.notifyNewUserHasJoined(); err != nil { | |
542 | return err | |
543 | } | |
6988a057 | 544 | } |
bd1ce113 | 545 | |
6988a057 JH |
546 | c.Server.Stats.LoginCount += 1 |
547 | ||
548 | const readBuffSize = 1024000 // 1KB - TODO: what should this be? | |
6988a057 JH |
549 | tranBuff := make([]byte, 0) |
550 | tReadlen := 0 | |
551 | // Infinite loop where take action on incoming client requests until the connection is closed | |
552 | for { | |
553 | buf = make([]byte, readBuffSize) | |
554 | tranBuff = tranBuff[tReadlen:] | |
555 | ||
556 | readLen, err := c.Connection.Read(buf) | |
557 | if err != nil { | |
558 | return err | |
559 | } | |
560 | tranBuff = append(tranBuff, buf[:readLen]...) | |
561 | ||
562 | // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them | |
563 | // into a slice of transactions | |
564 | var transactions []Transaction | |
565 | if transactions, tReadlen, err = readTransactions(tranBuff); err != nil { | |
566 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
567 | } | |
568 | ||
569 | // iterate over all of the transactions that were parsed from the byte slice and handle them | |
570 | for _, t := range transactions { | |
571 | if err := c.handleTransaction(&t); err != nil { | |
572 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
573 | } | |
574 | } | |
575 | } | |
576 | } | |
577 | ||
6988a057 JH |
578 | // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID |
579 | // in the file transfer request payload, and the file transfer server will use it to map the request | |
580 | // to a transfer | |
581 | func (s *Server) NewTransactionRef() []byte { | |
582 | transactionRef := make([]byte, 4) | |
583 | rand.Read(transactionRef) | |
584 | ||
585 | return transactionRef | |
586 | } | |
587 | ||
588 | func (s *Server) NewPrivateChat(cc *ClientConn) []byte { | |
589 | s.mux.Lock() | |
590 | defer s.mux.Unlock() | |
591 | ||
592 | randID := make([]byte, 4) | |
593 | rand.Read(randID) | |
594 | data := binary.BigEndian.Uint32(randID[:]) | |
595 | ||
596 | s.PrivateChats[data] = &PrivateChat{ | |
597 | Subject: "", | |
598 | ClientConn: make(map[uint16]*ClientConn), | |
599 | } | |
600 | s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc | |
601 | ||
602 | return randID | |
603 | } | |
604 | ||
605 | const dlFldrActionSendFile = 1 | |
606 | const dlFldrActionResumeFile = 2 | |
607 | const dlFldrActionNextFile = 3 | |
608 | ||
609 | func (s *Server) TransferFile(conn net.Conn) error { | |
610 | defer func() { _ = conn.Close() }() | |
611 | ||
612 | buf := make([]byte, 1024) | |
613 | if _, err := conn.Read(buf); err != nil { | |
614 | return err | |
615 | } | |
616 | ||
df2735b2 JH |
617 | var t transfer |
618 | _, err := t.Write(buf[:16]) | |
6988a057 JH |
619 | if err != nil { |
620 | return err | |
621 | } | |
622 | ||
623 | transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:]) | |
624 | fileTransfer := s.FileTransfers[transferRefNum] | |
625 | ||
626 | switch fileTransfer.Type { | |
627 | case FileDownload: | |
92a7e455 JH |
628 | fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
629 | if err != nil { | |
630 | return err | |
631 | } | |
6988a057 JH |
632 | |
633 | ffo, err := NewFlattenedFileObject( | |
92a7e455 JH |
634 | s.Config.FileRoot, |
635 | fileTransfer.FilePath, | |
636 | fileTransfer.FileName, | |
6988a057 JH |
637 | ) |
638 | if err != nil { | |
639 | return err | |
640 | } | |
641 | ||
642 | s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String()) | |
643 | ||
644 | // Start by sending flat file object to client | |
c5d9af5a | 645 | if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
646 | return err |
647 | } | |
648 | ||
92a7e455 | 649 | file, err := FS.Open(fullFilePath) |
6988a057 JH |
650 | if err != nil { |
651 | return err | |
652 | } | |
653 | ||
654 | sendBuffer := make([]byte, 1048576) | |
655 | for { | |
656 | var bytesRead int | |
657 | if bytesRead, err = file.Read(sendBuffer); err == io.EOF { | |
658 | break | |
659 | } | |
660 | ||
661 | fileTransfer.BytesSent += bytesRead | |
662 | ||
663 | delete(s.FileTransfers, transferRefNum) | |
664 | ||
665 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { | |
666 | return err | |
667 | } | |
668 | } | |
669 | case FileUpload: | |
670 | if _, err := conn.Read(buf); err != nil { | |
671 | return err | |
672 | } | |
673 | ||
674 | ffo := ReadFlattenedFileObject(buf) | |
c5d9af5a | 675 | payloadLen := len(ffo.BinaryMarshal()) |
6988a057 JH |
676 | fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) |
677 | ||
678 | destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) | |
679 | s.Logger.Infow( | |
680 | "File upload started", | |
681 | "transactionRef", fileTransfer.ReferenceNumber, | |
682 | "RemoteAddr", conn.RemoteAddr().String(), | |
683 | "size", fileSize, | |
684 | "dstFile", destinationFile, | |
685 | ) | |
686 | ||
687 | newFile, err := os.Create(destinationFile) | |
688 | if err != nil { | |
689 | return err | |
690 | } | |
691 | ||
692 | defer func() { _ = newFile.Close() }() | |
693 | ||
694 | const buffSize = 1024 | |
695 | ||
696 | if _, err := newFile.Write(buf[payloadLen:]); err != nil { | |
697 | return err | |
698 | } | |
699 | receivedBytes := buffSize - payloadLen | |
700 | ||
701 | for { | |
702 | if (fileSize - receivedBytes) < buffSize { | |
703 | s.Logger.Infow( | |
704 | "File upload complete", | |
705 | "transactionRef", fileTransfer.ReferenceNumber, | |
706 | "RemoteAddr", conn.RemoteAddr().String(), | |
707 | "size", fileSize, | |
708 | "dstFile", destinationFile, | |
709 | ) | |
710 | ||
711 | if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil { | |
712 | return fmt.Errorf("file transfer failed: %s", err) | |
713 | } | |
714 | return nil | |
715 | } | |
716 | ||
717 | // Copy N bytes from conn to upload file | |
718 | n, err := io.CopyN(newFile, conn, buffSize) | |
719 | if err != nil { | |
720 | return err | |
721 | } | |
722 | receivedBytes += int(n) | |
723 | } | |
724 | case FolderDownload: | |
725 | // Folder Download flow: | |
df2735b2 | 726 | // 1. Get filePath from the transfer |
6988a057 JH |
727 | // 2. Iterate over files |
728 | // 3. For each file: | |
729 | // Send file header to client | |
730 | // The client can reply in 3 ways: | |
731 | // | |
732 | // 1. If type is an odd number (unknown type?), or file download for the current file is completed: | |
733 | // client sends []byte{0x00, 0x03} to tell the server to continue to the next file | |
734 | // | |
735 | // 2. If download of a file is to be resumed: | |
736 | // client sends: | |
737 | // []byte{0x00, 0x02} // download folder action | |
738 | // [2]byte // Resume data size | |
739 | // []byte file resume data (see myField_FileResumeData) | |
740 | // | |
741 | // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01} | |
742 | // | |
743 | // When download is requested (case 2 or 3), server replies with: | |
744 | // [4]byte - file size | |
745 | // []byte - Flattened File Object | |
746 | // | |
747 | // After every file download, client could request next file with: | |
748 | // []byte{0x00, 0x03} | |
749 | // | |
750 | // This notifies the server to send the next item header | |
751 | ||
92a7e455 JH |
752 | fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
753 | if err != nil { | |
754 | return err | |
755 | } | |
6988a057 JH |
756 | |
757 | basePathLen := len(fullFilePath) | |
758 | ||
759 | readBuffer := make([]byte, 1024) | |
760 | ||
761 | s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr()) | |
762 | ||
763 | i := 0 | |
764 | _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error { | |
765 | i += 1 | |
f6d08d0a | 766 | subPath := path[basePathLen:] |
6988a057 JH |
767 | s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) |
768 | ||
769 | fileHeader := NewFileHeader(subPath, info.IsDir()) | |
770 | ||
771 | if i == 1 { | |
772 | return nil | |
773 | } | |
774 | ||
775 | // Send the file header to client | |
776 | if _, err := conn.Write(fileHeader.Payload()); err != nil { | |
777 | s.Logger.Errorf("error sending file header: %v", err) | |
778 | return err | |
779 | } | |
780 | ||
781 | // Read the client's Next Action request | |
aebc4d36 | 782 | // TODO: Remove hardcoded behavior and switch behaviors based on the next action send |
6988a057 | 783 | if _, err := conn.Read(readBuffer); err != nil { |
6988a057 JH |
784 | return err |
785 | } | |
786 | ||
787 | s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2])) | |
788 | ||
789 | if info.IsDir() { | |
790 | return nil | |
791 | } | |
792 | ||
793 | splitPath := strings.Split(path, "/") | |
6988a057 | 794 | |
92a7e455 JH |
795 | ffo, err := NewFlattenedFileObject( |
796 | strings.Join(splitPath[:len(splitPath)-1], "/"), | |
797 | nil, | |
798 | []byte(info.Name()), | |
799 | ) | |
6988a057 JH |
800 | if err != nil { |
801 | return err | |
802 | } | |
803 | s.Logger.Infow("File download started", | |
804 | "fileName", info.Name(), | |
805 | "transactionRef", fileTransfer.ReferenceNumber, | |
806 | "RemoteAddr", conn.RemoteAddr().String(), | |
807 | "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()), | |
808 | ) | |
809 | ||
810 | // Send file size to client | |
811 | if _, err := conn.Write(ffo.TransferSize()); err != nil { | |
812 | s.Logger.Error(err) | |
813 | return err | |
814 | } | |
815 | ||
816 | // Send file bytes to client | |
c5d9af5a | 817 | if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
818 | s.Logger.Error(err) |
819 | return err | |
820 | } | |
821 | ||
d492c46d | 822 | file, err := FS.Open(path) |
6988a057 JH |
823 | if err != nil { |
824 | return err | |
825 | } | |
826 | ||
827 | sendBuffer := make([]byte, 1048576) | |
c5d9af5a | 828 | totalBytesSent := len(ffo.BinaryMarshal()) |
6988a057 JH |
829 | |
830 | for { | |
831 | bytesRead, err := file.Read(sendBuffer) | |
832 | if err == io.EOF { | |
833 | // Read the client's Next Action request | |
aebc4d36 | 834 | // TODO: Remove hardcoded behavior and switch behaviors based on the next action send |
6988a057 JH |
835 | if _, err := conn.Read(readBuffer); err != nil { |
836 | s.Logger.Errorf("error reading next action: %v", err) | |
837 | return err | |
838 | } | |
839 | break | |
840 | } | |
841 | ||
842 | sentBytes, readErr := conn.Write(sendBuffer[:bytesRead]) | |
843 | totalBytesSent += sentBytes | |
844 | if readErr != nil { | |
845 | return err | |
846 | } | |
847 | } | |
848 | return nil | |
849 | }) | |
850 | ||
851 | case FolderUpload: | |
92a7e455 JH |
852 | dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
853 | if err != nil { | |
854 | return err | |
855 | } | |
6988a057 JH |
856 | s.Logger.Infow( |
857 | "Folder upload started", | |
858 | "transactionRef", fileTransfer.ReferenceNumber, | |
859 | "RemoteAddr", conn.RemoteAddr().String(), | |
860 | "dstPath", dstPath, | |
92a7e455 | 861 | "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize), |
6988a057 JH |
862 | "FolderItemCount", fileTransfer.FolderItemCount, |
863 | ) | |
864 | ||
865 | // Check if the target folder exists. If not, create it. | |
92a7e455 JH |
866 | if _, err := FS.Stat(dstPath); os.IsNotExist(err) { |
867 | s.Logger.Infow("Creating target path", "dstPath", dstPath) | |
868 | if err := FS.Mkdir(dstPath, 0777); err != nil { | |
6988a057 JH |
869 | s.Logger.Error(err) |
870 | } | |
871 | } | |
872 | ||
873 | readBuffer := make([]byte, 1024) | |
874 | ||
875 | // Begin the folder upload flow by sending the "next file action" to client | |
876 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
877 | return err | |
878 | } | |
879 | ||
880 | fileSize := make([]byte, 4) | |
881 | itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount) | |
882 | ||
883 | for i := uint16(0); i < itemCount; i++ { | |
884 | if _, err := conn.Read(readBuffer); err != nil { | |
885 | return err | |
886 | } | |
887 | fu := readFolderUpload(readBuffer) | |
888 | ||
889 | s.Logger.Infow( | |
890 | "Folder upload continued", | |
891 | "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), | |
892 | "RemoteAddr", conn.RemoteAddr().String(), | |
893 | "FormattedPath", fu.FormattedPath(), | |
894 | "IsFolder", fmt.Sprintf("%x", fu.IsFolder), | |
c5d9af5a | 895 | "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), |
6988a057 JH |
896 | ) |
897 | ||
c5d9af5a | 898 | if fu.IsFolder == [2]byte{0, 1} { |
6988a057 JH |
899 | if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) { |
900 | s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath) | |
901 | if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil { | |
902 | s.Logger.Error(err) | |
903 | } | |
904 | } | |
905 | ||
906 | // Tell client to send next file | |
907 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
908 | s.Logger.Error(err) | |
909 | return err | |
910 | } | |
911 | } else { | |
912 | // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. | |
913 | // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. | |
914 | // Send dlFldrAction_SendFile to client to begin transfer | |
915 | if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil { | |
916 | return err | |
917 | } | |
918 | ||
919 | if _, err := conn.Read(fileSize); err != nil { | |
920 | fmt.Println("Error reading:", err.Error()) // TODO: handle | |
921 | } | |
922 | ||
923 | s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize) | |
924 | ||
925 | if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil { | |
926 | s.Logger.Error(err) | |
927 | } | |
928 | ||
929 | // Tell client to send next file | |
930 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
931 | s.Logger.Error(err) | |
932 | return err | |
933 | } | |
934 | ||
935 | // Client sends "MACR" after the file. Read and discard. | |
936 | // TODO: This doesn't seem to be documented. What is this? Maybe resource fork? | |
937 | if _, err := conn.Read(readBuffer); err != nil { | |
938 | return err | |
939 | } | |
940 | } | |
941 | } | |
942 | s.Logger.Infof("Folder upload complete") | |
943 | } | |
944 | ||
945 | return nil | |
946 | } | |
947 | ||
948 | func transferFile(conn net.Conn, dst string) error { | |
949 | const buffSize = 1024 | |
950 | buf := make([]byte, buffSize) | |
951 | ||
952 | // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes | |
953 | if _, err := conn.Read(buf); err != nil { | |
954 | return err | |
955 | } | |
956 | ffo := ReadFlattenedFileObject(buf) | |
c5d9af5a | 957 | payloadLen := len(ffo.BinaryMarshal()) |
6988a057 JH |
958 | fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) |
959 | ||
960 | newFile, err := os.Create(dst) | |
961 | if err != nil { | |
962 | return err | |
963 | } | |
964 | defer func() { _ = newFile.Close() }() | |
965 | if _, err := newFile.Write(buf[payloadLen:]); err != nil { | |
966 | return err | |
967 | } | |
968 | receivedBytes := buffSize - payloadLen | |
969 | ||
970 | for { | |
971 | if (fileSize - receivedBytes) < buffSize { | |
972 | _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)) | |
973 | return err | |
974 | } | |
975 | ||
976 | // Copy N bytes from conn to upload file | |
977 | n, err := io.CopyN(newFile, conn, buffSize) | |
978 | if err != nil { | |
979 | return err | |
980 | } | |
981 | receivedBytes += int(n) | |
982 | } | |
983 | } | |
984 | ||
6988a057 JH |
985 | // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values. |
986 | // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work. | |
987 | func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) { | |
988 | for _, c := range unsortedClients { | |
989 | clients = append(clients, c) | |
990 | } | |
991 | sort.Sort(byClientID(clients)) | |
992 | return clients | |
993 | } |