]>
Commit | Line | Data |
---|---|---|
6988a057 JH |
1 | package hotline |
2 | ||
3 | import ( | |
4 | "bytes" | |
5 | "context" | |
6 | "encoding/binary" | |
7 | "errors" | |
8 | "fmt" | |
9 | "go.uber.org/zap" | |
10 | "io" | |
11 | "io/ioutil" | |
12 | "log" | |
13 | "math/big" | |
14 | "math/rand" | |
15 | "net" | |
16 | "os" | |
17 | "path" | |
18 | "path/filepath" | |
19 | "runtime/debug" | |
20 | "sort" | |
21 | "strings" | |
22 | "sync" | |
23 | "time" | |
24 | ||
25 | "golang.org/x/crypto/bcrypt" | |
26 | "gopkg.in/yaml.v2" | |
27 | ) | |
28 | ||
29 | const ( | |
30 | userIdleSeconds = 300 // time in seconds before an inactive user is marked idle | |
31 | idleCheckInterval = 10 // time in seconds to check for idle users | |
32 | trackerUpdateFrequency = 300 // time in seconds between tracker re-registration | |
33 | ) | |
34 | ||
35 | type Server struct { | |
36 | Interface string | |
37 | Port int | |
38 | Accounts map[string]*Account | |
39 | Agreement []byte | |
40 | Clients map[uint16]*ClientConn | |
41 | FlatNews []byte | |
42 | ThreadedNews *ThreadedNews | |
43 | FileTransfers map[uint32]*FileTransfer | |
44 | Config *Config | |
45 | ConfigDir string | |
46 | Logger *zap.SugaredLogger | |
47 | PrivateChats map[uint32]*PrivateChat | |
48 | NextGuestID *uint16 | |
49 | TrackerPassID []byte | |
50 | Stats *Stats | |
51 | ||
52 | APIListener net.Listener | |
53 | FileListener net.Listener | |
54 | ||
55 | newsReader io.Reader | |
56 | newsWriter io.WriteCloser | |
57 | ||
58 | outbox chan Transaction | |
59 | ||
60 | mux sync.Mutex | |
61 | flatNewsMux sync.Mutex | |
62 | } | |
63 | ||
64 | type PrivateChat struct { | |
65 | Subject string | |
66 | ClientConn map[uint16]*ClientConn | |
67 | } | |
68 | ||
69 | func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error { | |
70 | s.Logger.Infow("Hotline server started", "version", VERSION) | |
71 | var wg sync.WaitGroup | |
72 | ||
73 | wg.Add(1) | |
74 | go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }() | |
75 | ||
76 | wg.Add(1) | |
77 | go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }() | |
78 | ||
79 | wg.Wait() | |
80 | ||
81 | return nil | |
82 | } | |
83 | ||
84 | func (s *Server) APIPort() int { | |
85 | return s.APIListener.Addr().(*net.TCPAddr).Port | |
86 | } | |
87 | ||
88 | func (s *Server) ServeFileTransfers(ln net.Listener) error { | |
89 | s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1)) | |
90 | ||
91 | for { | |
92 | conn, err := ln.Accept() | |
93 | if err != nil { | |
94 | return err | |
95 | } | |
96 | ||
97 | go func() { | |
98 | if err := s.TransferFile(conn); err != nil { | |
99 | s.Logger.Errorw("file transfer error", "reason", err) | |
100 | } | |
101 | }() | |
102 | } | |
103 | } | |
104 | ||
105 | func (s *Server) sendTransaction(t Transaction) error { | |
106 | requestNum := binary.BigEndian.Uint16(t.Type) | |
107 | clientID, err := byteToInt(*t.clientID) | |
108 | if err != nil { | |
109 | return err | |
110 | } | |
111 | ||
112 | s.mux.Lock() | |
113 | client := s.Clients[uint16(clientID)] | |
114 | s.mux.Unlock() | |
115 | if client == nil { | |
116 | return errors.New("invalid client") | |
117 | } | |
118 | userName := string(*client.UserName) | |
119 | login := client.Account.Login | |
120 | ||
121 | handler := TransactionHandlers[requestNum] | |
122 | ||
123 | var n int | |
124 | if n, err = client.Connection.Write(t.Payload()); err != nil { | |
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 ( | |
170 | agreementFile = "Agreement.txt" | |
171 | messageBoardFile = "MessageBoard.txt" | |
172 | threadedNewsFile = "ThreadedNews.yaml" | |
173 | ) | |
174 | ||
175 | // NewServer constructs a new Server from a config dir | |
176 | func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) { | |
177 | server := Server{ | |
178 | Port: netPort, | |
179 | Accounts: make(map[string]*Account), | |
180 | Config: new(Config), | |
181 | Clients: make(map[uint16]*ClientConn), | |
182 | FileTransfers: make(map[uint32]*FileTransfer), | |
183 | PrivateChats: make(map[uint32]*PrivateChat), | |
184 | ConfigDir: configDir, | |
185 | Logger: logger, | |
186 | NextGuestID: new(uint16), | |
187 | outbox: make(chan Transaction), | |
188 | Stats: &Stats{StartTime: time.Now()}, | |
189 | ThreadedNews: &ThreadedNews{}, | |
190 | TrackerPassID: make([]byte, 4), | |
191 | } | |
192 | ||
193 | ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort)) | |
194 | if err != nil { | |
195 | return nil, err | |
196 | } | |
197 | server.APIListener = ln | |
198 | ||
199 | if netPort != 0 { | |
200 | netPort += 1 | |
201 | } | |
202 | ||
203 | ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort)) | |
204 | server.FileListener = ln2 | |
205 | if err != nil { | |
206 | return nil, err | |
207 | } | |
208 | ||
209 | // generate a new random passID for tracker registration | |
210 | if _, err := rand.Read(server.TrackerPassID); err != nil { | |
211 | return nil, err | |
212 | } | |
213 | ||
214 | server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile) | |
215 | if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil { | |
216 | return nil, err | |
217 | } | |
218 | ||
219 | if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil { | |
220 | return nil, err | |
221 | } | |
222 | ||
223 | if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil { | |
224 | return nil, err | |
225 | } | |
226 | ||
227 | if err := server.loadConfig(configDir + "config.yaml"); err != nil { | |
228 | return nil, err | |
229 | } | |
230 | ||
231 | if err := server.loadAccounts(configDir + "Users/"); err != nil { | |
232 | return nil, err | |
233 | } | |
234 | ||
235 | server.Config.FileRoot = configDir + "Files/" | |
236 | ||
237 | *server.NextGuestID = 1 | |
238 | ||
239 | if server.Config.EnableTrackerRegistration { | |
240 | go func() { | |
241 | for { | |
242 | tr := TrackerRegistration{ | |
243 | Port: []byte{0x15, 0x7c}, | |
244 | UserCount: server.userCount(), | |
245 | PassID: server.TrackerPassID, | |
246 | Name: server.Config.Name, | |
247 | Description: server.Config.Description, | |
248 | } | |
249 | for _, t := range server.Config.Trackers { | |
250 | server.Logger.Infof("Registering with tracker %v", t) | |
251 | ||
252 | if err := register(t, tr); err != nil { | |
253 | server.Logger.Errorw("unable to register with tracker %v", "error", err) | |
254 | } | |
255 | } | |
256 | ||
257 | time.Sleep(trackerUpdateFrequency * time.Second) | |
258 | } | |
259 | }() | |
260 | } | |
261 | ||
262 | // Start Client Keepalive go routine | |
263 | go server.keepaliveHandler() | |
264 | ||
265 | return &server, nil | |
266 | } | |
267 | ||
268 | func (s *Server) userCount() int { | |
269 | s.mux.Lock() | |
270 | defer s.mux.Unlock() | |
271 | ||
272 | return len(s.Clients) | |
273 | } | |
274 | ||
275 | func (s *Server) keepaliveHandler() { | |
276 | for { | |
277 | time.Sleep(idleCheckInterval * time.Second) | |
278 | s.mux.Lock() | |
279 | ||
280 | for _, c := range s.Clients { | |
281 | *c.IdleTime += idleCheckInterval | |
282 | if *c.IdleTime > userIdleSeconds && !c.Idle { | |
283 | c.Idle = true | |
284 | ||
285 | flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags))) | |
286 | flagBitmap.SetBit(flagBitmap, userFlagAway, 1) | |
287 | binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64())) | |
288 | ||
289 | c.sendAll( | |
290 | tranNotifyChangeUser, | |
291 | NewField(fieldUserID, *c.ID), | |
292 | NewField(fieldUserFlags, *c.Flags), | |
293 | NewField(fieldUserName, *c.UserName), | |
294 | NewField(fieldUserIconID, *c.Icon), | |
295 | ) | |
296 | } | |
297 | } | |
298 | s.mux.Unlock() | |
299 | } | |
300 | } | |
301 | ||
302 | func (s *Server) writeThreadedNews() error { | |
303 | s.mux.Lock() | |
304 | defer s.mux.Unlock() | |
305 | ||
306 | out, err := yaml.Marshal(s.ThreadedNews) | |
307 | if err != nil { | |
308 | return err | |
309 | } | |
310 | err = ioutil.WriteFile( | |
311 | s.ConfigDir+"ThreadedNews.yaml", | |
312 | out, | |
313 | 0666, | |
314 | ) | |
315 | return err | |
316 | } | |
317 | ||
318 | func (s *Server) NewClientConn(conn net.Conn) *ClientConn { | |
319 | s.mux.Lock() | |
320 | defer s.mux.Unlock() | |
321 | ||
322 | clientConn := &ClientConn{ | |
323 | ID: &[]byte{0, 0}, | |
324 | Icon: &[]byte{0, 0}, | |
325 | Flags: &[]byte{0, 0}, | |
326 | UserName: &[]byte{}, | |
327 | Connection: conn, | |
328 | Server: s, | |
329 | Version: &[]byte{}, | |
330 | IdleTime: new(int), | |
331 | AutoReply: &[]byte{}, | |
332 | Transfers: make(map[int][]*FileTransfer), | |
333 | } | |
334 | *s.NextGuestID++ | |
335 | ID := *s.NextGuestID | |
336 | ||
337 | *clientConn.IdleTime = 0 | |
338 | ||
339 | binary.BigEndian.PutUint16(*clientConn.ID, ID) | |
340 | s.Clients[ID] = clientConn | |
341 | ||
342 | return clientConn | |
343 | } | |
344 | ||
345 | // NewUser creates a new user account entry in the server map and config file | |
346 | func (s *Server) NewUser(login, name, password string, access []byte) error { | |
347 | s.mux.Lock() | |
348 | defer s.mux.Unlock() | |
349 | ||
350 | account := Account{ | |
351 | Login: login, | |
352 | Name: name, | |
353 | Password: hashAndSalt([]byte(password)), | |
354 | Access: &access, | |
355 | } | |
356 | out, err := yaml.Marshal(&account) | |
357 | if err != nil { | |
358 | return err | |
359 | } | |
360 | s.Accounts[login] = &account | |
361 | ||
362 | return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666) | |
363 | } | |
364 | ||
365 | // DeleteUser deletes the user account | |
366 | func (s *Server) DeleteUser(login string) error { | |
367 | s.mux.Lock() | |
368 | defer s.mux.Unlock() | |
369 | ||
370 | delete(s.Accounts, login) | |
371 | ||
372 | return os.Remove(s.ConfigDir + "Users/" + login + ".yaml") | |
373 | } | |
374 | ||
375 | func (s *Server) connectedUsers() []Field { | |
376 | s.mux.Lock() | |
377 | defer s.mux.Unlock() | |
378 | ||
379 | var connectedUsers []Field | |
380 | for _, c := range s.Clients { | |
381 | user := User{ | |
382 | ID: *c.ID, | |
383 | Icon: *c.Icon, | |
384 | Flags: *c.Flags, | |
385 | Name: string(*c.UserName), | |
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) | |
399 | decoder.SetStrict(true) | |
400 | ||
401 | return decoder.Decode(s.ThreadedNews) | |
402 | } | |
403 | ||
404 | // loadAccounts loads account data from disk | |
405 | func (s *Server) loadAccounts(userDir string) error { | |
406 | matches, err := filepath.Glob(path.Join(userDir, "*.yaml")) | |
407 | if err != nil { | |
408 | return err | |
409 | } | |
410 | ||
411 | if len(matches) == 0 { | |
412 | return errors.New("no user accounts found in " + userDir) | |
413 | } | |
414 | ||
415 | for _, file := range matches { | |
416 | fh, err := os.Open(file) | |
417 | if err != nil { | |
418 | return err | |
419 | } | |
420 | ||
421 | account := Account{} | |
422 | decoder := yaml.NewDecoder(fh) | |
423 | decoder.SetStrict(true) | |
424 | if err := decoder.Decode(&account); err != nil { | |
425 | return err | |
426 | } | |
427 | ||
428 | s.Accounts[account.Login] = &account | |
429 | } | |
430 | return nil | |
431 | } | |
432 | ||
433 | func (s *Server) loadConfig(path string) error { | |
434 | fh, err := os.Open(path) | |
435 | if err != nil { | |
436 | return err | |
437 | } | |
438 | ||
439 | decoder := yaml.NewDecoder(fh) | |
440 | decoder.SetStrict(true) | |
441 | err = decoder.Decode(s.Config) | |
442 | if err != nil { | |
443 | return err | |
444 | } | |
445 | return nil | |
446 | } | |
447 | ||
448 | const ( | |
449 | minTransactionLen = 22 // minimum length of any transaction | |
450 | ) | |
451 | ||
452 | // handleNewConnection takes a new net.Conn and performs the initial login sequence | |
453 | func (s *Server) handleNewConnection(conn net.Conn) error { | |
454 | handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length | |
455 | if _, err := conn.Read(handshakeBuf); err != nil { | |
456 | return err | |
457 | } | |
458 | if err := Handshake(conn, handshakeBuf[:12]); err != nil { | |
459 | return err | |
460 | } | |
461 | ||
462 | buf := make([]byte, 1024) | |
463 | readLen, err := conn.Read(buf) | |
464 | if readLen < minTransactionLen { | |
465 | return err | |
466 | } | |
467 | if err != nil { | |
468 | return err | |
469 | } | |
470 | ||
471 | clientLogin, _, err := ReadTransaction(buf[:readLen]) | |
472 | if err != nil { | |
473 | return err | |
474 | } | |
475 | ||
476 | c := s.NewClientConn(conn) | |
477 | defer c.Disconnect() | |
478 | defer func() { | |
479 | if r := recover(); r != nil { | |
480 | fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) | |
481 | c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) | |
482 | c.Disconnect() | |
483 | } | |
484 | }() | |
485 | ||
486 | encodedLogin := clientLogin.GetField(fieldUserLogin).Data | |
487 | encodedPassword := clientLogin.GetField(fieldUserPassword).Data | |
488 | *c.Version = clientLogin.GetField(fieldVersion).Data | |
489 | ||
490 | var login string | |
491 | for _, char := range encodedLogin { | |
492 | login += string(rune(255 - uint(char))) | |
493 | } | |
494 | if login == "" { | |
495 | login = GuestAccount | |
496 | } | |
497 | ||
498 | // If authentication fails, send error reply and close connection | |
499 | if !c.Authenticate(login, encodedPassword) { | |
500 | rep := c.NewErrReply(clientLogin, "Incorrect login.") | |
501 | if _, err := conn.Write(rep.Payload()); err != nil { | |
502 | return err | |
503 | } | |
504 | return fmt.Errorf("incorrect login") | |
505 | } | |
506 | ||
6988a057 JH |
507 | if clientLogin.GetField(fieldUserName).Data != nil { |
508 | *c.UserName = clientLogin.GetField(fieldUserName).Data | |
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 | ||
6988a057 JH |
535 | if _, err := c.notifyNewUserHasJoined(); err != nil { |
536 | return err | |
537 | } | |
538 | c.Server.Stats.LoginCount += 1 | |
539 | ||
540 | const readBuffSize = 1024000 // 1KB - TODO: what should this be? | |
541 | const maxTranSize = 1024000 | |
542 | tranBuff := make([]byte, 0) | |
543 | tReadlen := 0 | |
544 | // Infinite loop where take action on incoming client requests until the connection is closed | |
545 | for { | |
546 | buf = make([]byte, readBuffSize) | |
547 | tranBuff = tranBuff[tReadlen:] | |
548 | ||
549 | readLen, err := c.Connection.Read(buf) | |
550 | if err != nil { | |
551 | return err | |
552 | } | |
553 | tranBuff = append(tranBuff, buf[:readLen]...) | |
554 | ||
555 | // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them | |
556 | // into a slice of transactions | |
557 | var transactions []Transaction | |
558 | if transactions, tReadlen, err = readTransactions(tranBuff); err != nil { | |
559 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
560 | } | |
561 | ||
562 | // iterate over all of the transactions that were parsed from the byte slice and handle them | |
563 | for _, t := range transactions { | |
564 | if err := c.handleTransaction(&t); err != nil { | |
565 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
566 | } | |
567 | } | |
568 | } | |
569 | } | |
570 | ||
571 | func hashAndSalt(pwd []byte) string { | |
572 | // Use GenerateFromPassword to hash & salt pwd. | |
573 | // MinCost is just an integer constant provided by the bcrypt | |
574 | // package along with DefaultCost & MaxCost. | |
575 | // The cost can be any value you want provided it isn't lower | |
576 | // than the MinCost (4) | |
577 | hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost) | |
578 | if err != nil { | |
579 | log.Println(err) | |
580 | } | |
581 | // GenerateFromPassword returns a byte slice so we need to | |
582 | // convert the bytes to a string and return it | |
583 | return string(hash) | |
584 | } | |
585 | ||
586 | // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID | |
587 | // in the file transfer request payload, and the file transfer server will use it to map the request | |
588 | // to a transfer | |
589 | func (s *Server) NewTransactionRef() []byte { | |
590 | transactionRef := make([]byte, 4) | |
591 | rand.Read(transactionRef) | |
592 | ||
593 | return transactionRef | |
594 | } | |
595 | ||
596 | func (s *Server) NewPrivateChat(cc *ClientConn) []byte { | |
597 | s.mux.Lock() | |
598 | defer s.mux.Unlock() | |
599 | ||
600 | randID := make([]byte, 4) | |
601 | rand.Read(randID) | |
602 | data := binary.BigEndian.Uint32(randID[:]) | |
603 | ||
604 | s.PrivateChats[data] = &PrivateChat{ | |
605 | Subject: "", | |
606 | ClientConn: make(map[uint16]*ClientConn), | |
607 | } | |
608 | s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc | |
609 | ||
610 | return randID | |
611 | } | |
612 | ||
613 | const dlFldrActionSendFile = 1 | |
614 | const dlFldrActionResumeFile = 2 | |
615 | const dlFldrActionNextFile = 3 | |
616 | ||
617 | func (s *Server) TransferFile(conn net.Conn) error { | |
618 | defer func() { _ = conn.Close() }() | |
619 | ||
620 | buf := make([]byte, 1024) | |
621 | if _, err := conn.Read(buf); err != nil { | |
622 | return err | |
623 | } | |
624 | ||
df2735b2 JH |
625 | var t transfer |
626 | _, err := t.Write(buf[:16]) | |
6988a057 JH |
627 | if err != nil { |
628 | return err | |
629 | } | |
630 | ||
631 | transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:]) | |
632 | fileTransfer := s.FileTransfers[transferRefNum] | |
633 | ||
634 | switch fileTransfer.Type { | |
635 | case FileDownload: | |
636 | fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName)) | |
637 | ||
638 | ffo, err := NewFlattenedFileObject( | |
639 | s.Config.FileRoot+string(fileTransfer.FilePath), | |
640 | string(fileTransfer.FileName), | |
641 | ) | |
642 | if err != nil { | |
643 | return err | |
644 | } | |
645 | ||
646 | s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String()) | |
647 | ||
648 | // Start by sending flat file object to client | |
649 | if _, err := conn.Write(ffo.Payload()); err != nil { | |
650 | return err | |
651 | } | |
652 | ||
653 | file, err := os.Open(fullFilePath) | |
654 | if err != nil { | |
655 | return err | |
656 | } | |
657 | ||
658 | sendBuffer := make([]byte, 1048576) | |
659 | for { | |
660 | var bytesRead int | |
661 | if bytesRead, err = file.Read(sendBuffer); err == io.EOF { | |
662 | break | |
663 | } | |
664 | ||
665 | fileTransfer.BytesSent += bytesRead | |
666 | ||
667 | delete(s.FileTransfers, transferRefNum) | |
668 | ||
669 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { | |
670 | return err | |
671 | } | |
672 | } | |
673 | case FileUpload: | |
674 | if _, err := conn.Read(buf); err != nil { | |
675 | return err | |
676 | } | |
677 | ||
678 | ffo := ReadFlattenedFileObject(buf) | |
679 | payloadLen := len(ffo.Payload()) | |
680 | fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) | |
681 | ||
682 | destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) | |
683 | s.Logger.Infow( | |
684 | "File upload started", | |
685 | "transactionRef", fileTransfer.ReferenceNumber, | |
686 | "RemoteAddr", conn.RemoteAddr().String(), | |
687 | "size", fileSize, | |
688 | "dstFile", destinationFile, | |
689 | ) | |
690 | ||
691 | newFile, err := os.Create(destinationFile) | |
692 | if err != nil { | |
693 | return err | |
694 | } | |
695 | ||
696 | defer func() { _ = newFile.Close() }() | |
697 | ||
698 | const buffSize = 1024 | |
699 | ||
700 | if _, err := newFile.Write(buf[payloadLen:]); err != nil { | |
701 | return err | |
702 | } | |
703 | receivedBytes := buffSize - payloadLen | |
704 | ||
705 | for { | |
706 | if (fileSize - receivedBytes) < buffSize { | |
707 | s.Logger.Infow( | |
708 | "File upload complete", | |
709 | "transactionRef", fileTransfer.ReferenceNumber, | |
710 | "RemoteAddr", conn.RemoteAddr().String(), | |
711 | "size", fileSize, | |
712 | "dstFile", destinationFile, | |
713 | ) | |
714 | ||
715 | if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil { | |
716 | return fmt.Errorf("file transfer failed: %s", err) | |
717 | } | |
718 | return nil | |
719 | } | |
720 | ||
721 | // Copy N bytes from conn to upload file | |
722 | n, err := io.CopyN(newFile, conn, buffSize) | |
723 | if err != nil { | |
724 | return err | |
725 | } | |
726 | receivedBytes += int(n) | |
727 | } | |
728 | case FolderDownload: | |
729 | // Folder Download flow: | |
df2735b2 | 730 | // 1. Get filePath from the transfer |
6988a057 JH |
731 | // 2. Iterate over files |
732 | // 3. For each file: | |
733 | // Send file header to client | |
734 | // The client can reply in 3 ways: | |
735 | // | |
736 | // 1. If type is an odd number (unknown type?), or file download for the current file is completed: | |
737 | // client sends []byte{0x00, 0x03} to tell the server to continue to the next file | |
738 | // | |
739 | // 2. If download of a file is to be resumed: | |
740 | // client sends: | |
741 | // []byte{0x00, 0x02} // download folder action | |
742 | // [2]byte // Resume data size | |
743 | // []byte file resume data (see myField_FileResumeData) | |
744 | // | |
745 | // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01} | |
746 | // | |
747 | // When download is requested (case 2 or 3), server replies with: | |
748 | // [4]byte - file size | |
749 | // []byte - Flattened File Object | |
750 | // | |
751 | // After every file download, client could request next file with: | |
752 | // []byte{0x00, 0x03} | |
753 | // | |
754 | // This notifies the server to send the next item header | |
755 | ||
756 | fh := NewFilePath(fileTransfer.FilePath) | |
757 | fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+fh.String(), string(fileTransfer.FileName)) | |
758 | ||
759 | basePathLen := len(fullFilePath) | |
760 | ||
761 | readBuffer := make([]byte, 1024) | |
762 | ||
763 | s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr()) | |
764 | ||
765 | i := 0 | |
766 | _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error { | |
767 | i += 1 | |
f6d08d0a | 768 | subPath := path[basePathLen:] |
6988a057 JH |
769 | s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) |
770 | ||
771 | fileHeader := NewFileHeader(subPath, info.IsDir()) | |
772 | ||
773 | if i == 1 { | |
774 | return nil | |
775 | } | |
776 | ||
777 | // Send the file header to client | |
778 | if _, err := conn.Write(fileHeader.Payload()); err != nil { | |
779 | s.Logger.Errorf("error sending file header: %v", err) | |
780 | return err | |
781 | } | |
782 | ||
783 | // Read the client's Next Action request | |
784 | //TODO: Remove hardcoded behavior and switch behaviors based on the next action send | |
785 | if _, err := conn.Read(readBuffer); err != nil { | |
786 | s.Logger.Errorf("error reading next action: %v", err) | |
787 | return err | |
788 | } | |
789 | ||
790 | s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2])) | |
791 | ||
792 | if info.IsDir() { | |
793 | return nil | |
794 | } | |
795 | ||
796 | splitPath := strings.Split(path, "/") | |
797 | //strings.Join(splitPath[:len(splitPath)-1], "/") | |
798 | ||
799 | ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), info.Name()) | |
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 | |
817 | if _, err := conn.Write(ffo.Payload()); err != nil { | |
818 | s.Logger.Error(err) | |
819 | return err | |
820 | } | |
821 | ||
822 | file, err := os.Open(path) | |
823 | if err != nil { | |
824 | return err | |
825 | } | |
826 | ||
827 | sendBuffer := make([]byte, 1048576) | |
828 | totalBytesSent := len(ffo.Payload()) | |
829 | ||
830 | for { | |
831 | bytesRead, err := file.Read(sendBuffer) | |
832 | if err == io.EOF { | |
833 | // Read the client's Next Action request | |
834 | //TODO: Remove hardcoded behavior and switch behaviors based on the next action send | |
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: | |
852 | dstPath := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) | |
853 | s.Logger.Infow( | |
854 | "Folder upload started", | |
855 | "transactionRef", fileTransfer.ReferenceNumber, | |
856 | "RemoteAddr", conn.RemoteAddr().String(), | |
857 | "dstPath", dstPath, | |
858 | "TransferSize", fileTransfer.TransferSize, | |
859 | "FolderItemCount", fileTransfer.FolderItemCount, | |
860 | ) | |
861 | ||
862 | // Check if the target folder exists. If not, create it. | |
863 | if _, err := os.Stat(dstPath); os.IsNotExist(err) { | |
864 | s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath) | |
865 | if err := os.Mkdir(dstPath, 0777); err != nil { | |
866 | s.Logger.Error(err) | |
867 | } | |
868 | } | |
869 | ||
870 | readBuffer := make([]byte, 1024) | |
871 | ||
872 | // Begin the folder upload flow by sending the "next file action" to client | |
873 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
874 | return err | |
875 | } | |
876 | ||
877 | fileSize := make([]byte, 4) | |
878 | itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount) | |
879 | ||
880 | for i := uint16(0); i < itemCount; i++ { | |
881 | if _, err := conn.Read(readBuffer); err != nil { | |
882 | return err | |
883 | } | |
884 | fu := readFolderUpload(readBuffer) | |
885 | ||
886 | s.Logger.Infow( | |
887 | "Folder upload continued", | |
888 | "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), | |
889 | "RemoteAddr", conn.RemoteAddr().String(), | |
890 | "FormattedPath", fu.FormattedPath(), | |
891 | "IsFolder", fmt.Sprintf("%x", fu.IsFolder), | |
892 | "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount), | |
893 | ) | |
894 | ||
895 | if bytes.Equal(fu.IsFolder, []byte{0, 1}) { | |
896 | if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) { | |
897 | s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath) | |
898 | if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil { | |
899 | s.Logger.Error(err) | |
900 | } | |
901 | } | |
902 | ||
903 | // Tell client to send next file | |
904 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
905 | s.Logger.Error(err) | |
906 | return err | |
907 | } | |
908 | } else { | |
909 | // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. | |
910 | // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. | |
911 | // Send dlFldrAction_SendFile to client to begin transfer | |
912 | if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil { | |
913 | return err | |
914 | } | |
915 | ||
916 | if _, err := conn.Read(fileSize); err != nil { | |
917 | fmt.Println("Error reading:", err.Error()) // TODO: handle | |
918 | } | |
919 | ||
920 | s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize) | |
921 | ||
922 | if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil { | |
923 | s.Logger.Error(err) | |
924 | } | |
925 | ||
926 | // Tell client to send next file | |
927 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
928 | s.Logger.Error(err) | |
929 | return err | |
930 | } | |
931 | ||
932 | // Client sends "MACR" after the file. Read and discard. | |
933 | // TODO: This doesn't seem to be documented. What is this? Maybe resource fork? | |
934 | if _, err := conn.Read(readBuffer); err != nil { | |
935 | return err | |
936 | } | |
937 | } | |
938 | } | |
939 | s.Logger.Infof("Folder upload complete") | |
940 | } | |
941 | ||
942 | return nil | |
943 | } | |
944 | ||
945 | func transferFile(conn net.Conn, dst string) error { | |
946 | const buffSize = 1024 | |
947 | buf := make([]byte, buffSize) | |
948 | ||
949 | // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes | |
950 | if _, err := conn.Read(buf); err != nil { | |
951 | return err | |
952 | } | |
953 | ffo := ReadFlattenedFileObject(buf) | |
954 | payloadLen := len(ffo.Payload()) | |
955 | fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) | |
956 | ||
957 | newFile, err := os.Create(dst) | |
958 | if err != nil { | |
959 | return err | |
960 | } | |
961 | defer func() { _ = newFile.Close() }() | |
962 | if _, err := newFile.Write(buf[payloadLen:]); err != nil { | |
963 | return err | |
964 | } | |
965 | receivedBytes := buffSize - payloadLen | |
966 | ||
967 | for { | |
968 | if (fileSize - receivedBytes) < buffSize { | |
969 | _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)) | |
970 | return err | |
971 | } | |
972 | ||
973 | // Copy N bytes from conn to upload file | |
974 | n, err := io.CopyN(newFile, conn, buffSize) | |
975 | if err != nil { | |
976 | return err | |
977 | } | |
978 | receivedBytes += int(n) | |
979 | } | |
980 | } | |
981 | ||
982 | // 00 28 // DataSize | |
983 | // 00 00 // IsFolder | |
984 | // 00 02 // PathItemCount | |
985 | // | |
986 | // 00 00 | |
987 | // 09 | |
988 | // 73 75 62 66 6f 6c 64 65 72 // "subfolder" | |
989 | // | |
990 | // 00 00 | |
991 | // 15 | |
992 | // 73 75 62 66 6f 6c 64 65 72 2d 74 65 73 74 66 69 6c 65 2d 35 6b // "subfolder-testfile-5k" | |
993 | func readFolderUpload(buf []byte) folderUpload { | |
994 | dataLen := binary.BigEndian.Uint16(buf[0:2]) | |
995 | ||
996 | fu := folderUpload{ | |
997 | DataSize: buf[0:2], // Size of this structure (not including data size element itself) | |
998 | IsFolder: buf[2:4], | |
999 | PathItemCount: buf[4:6], | |
1000 | FileNamePath: buf[6 : dataLen+2], | |
1001 | } | |
1002 | ||
1003 | return fu | |
1004 | } | |
1005 | ||
1006 | type folderUpload struct { | |
1007 | DataSize []byte | |
1008 | IsFolder []byte | |
1009 | PathItemCount []byte | |
1010 | FileNamePath []byte | |
1011 | } | |
1012 | ||
1013 | func (fu *folderUpload) FormattedPath() string { | |
1014 | pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount) | |
1015 | ||
1016 | var pathSegments []string | |
1017 | pathData := fu.FileNamePath | |
1018 | ||
1019 | for i := uint16(0); i < pathItemLen; i++ { | |
1020 | segLen := pathData[2] | |
1021 | pathSegments = append(pathSegments, string(pathData[3:3+segLen])) | |
1022 | pathData = pathData[3+segLen:] | |
1023 | } | |
1024 | ||
1025 | return strings.Join(pathSegments, pathSeparator) | |
1026 | } | |
1027 | ||
1028 | // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values. | |
1029 | // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work. | |
1030 | func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) { | |
1031 | for _, c := range unsortedClients { | |
1032 | clients = append(clients, c) | |
1033 | } | |
1034 | sort.Sort(byClientID(clients)) | |
1035 | return clients | |
1036 | } |