]>
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" | |
11 | "log" | |
12 | "math/big" | |
13 | "math/rand" | |
14 | "net" | |
15 | "os" | |
16 | "path" | |
17 | "path/filepath" | |
18 | "runtime/debug" | |
19 | "sort" | |
20 | "strings" | |
21 | "sync" | |
22 | "time" | |
23 | ||
24 | "golang.org/x/crypto/bcrypt" | |
25 | "gopkg.in/yaml.v2" | |
26 | ) | |
27 | ||
28 | const ( | |
29 | userIdleSeconds = 300 // time in seconds before an inactive user is marked idle | |
30 | idleCheckInterval = 10 // time in seconds to check for idle users | |
31 | trackerUpdateFrequency = 300 // time in seconds between tracker re-registration | |
32 | ) | |
33 | ||
34 | type Server struct { | |
6988a057 JH |
35 | Port int |
36 | Accounts map[string]*Account | |
37 | Agreement []byte | |
38 | Clients map[uint16]*ClientConn | |
39 | FlatNews []byte | |
40 | ThreadedNews *ThreadedNews | |
41 | FileTransfers map[uint32]*FileTransfer | |
42 | Config *Config | |
43 | ConfigDir string | |
44 | Logger *zap.SugaredLogger | |
45 | PrivateChats map[uint32]*PrivateChat | |
46 | NextGuestID *uint16 | |
47 | TrackerPassID []byte | |
48 | Stats *Stats | |
49 | ||
50 | APIListener net.Listener | |
51 | FileListener net.Listener | |
52 | ||
53 | newsReader io.Reader | |
54 | newsWriter io.WriteCloser | |
55 | ||
56 | outbox chan Transaction | |
57 | ||
58 | mux sync.Mutex | |
59 | flatNewsMux sync.Mutex | |
60 | } | |
61 | ||
62 | type PrivateChat struct { | |
63 | Subject string | |
64 | ClientConn map[uint16]*ClientConn | |
65 | } | |
66 | ||
67 | func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error { | |
68 | s.Logger.Infow("Hotline server started", "version", VERSION) | |
69 | var wg sync.WaitGroup | |
70 | ||
71 | wg.Add(1) | |
72 | go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }() | |
73 | ||
74 | wg.Add(1) | |
75 | go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }() | |
76 | ||
77 | wg.Wait() | |
78 | ||
79 | return nil | |
80 | } | |
81 | ||
82 | func (s *Server) APIPort() int { | |
83 | return s.APIListener.Addr().(*net.TCPAddr).Port | |
84 | } | |
85 | ||
86 | func (s *Server) ServeFileTransfers(ln net.Listener) error { | |
87 | s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1)) | |
88 | ||
89 | for { | |
90 | conn, err := ln.Accept() | |
91 | if err != nil { | |
92 | return err | |
93 | } | |
94 | ||
95 | go func() { | |
96 | if err := s.TransferFile(conn); err != nil { | |
97 | s.Logger.Errorw("file transfer error", "reason", err) | |
98 | } | |
99 | }() | |
100 | } | |
101 | } | |
102 | ||
103 | func (s *Server) sendTransaction(t Transaction) error { | |
104 | requestNum := binary.BigEndian.Uint16(t.Type) | |
105 | clientID, err := byteToInt(*t.clientID) | |
106 | if err != nil { | |
107 | return err | |
108 | } | |
109 | ||
110 | s.mux.Lock() | |
111 | client := s.Clients[uint16(clientID)] | |
112 | s.mux.Unlock() | |
113 | if client == nil { | |
bd1ce113 | 114 | return fmt.Errorf("invalid client id %v", *t.clientID) |
6988a057 | 115 | } |
72dd37f1 | 116 | userName := string(client.UserName) |
6988a057 JH |
117 | login := client.Account.Login |
118 | ||
119 | handler := TransactionHandlers[requestNum] | |
120 | ||
72dd37f1 JH |
121 | b, err := t.MarshalBinary() |
122 | if err != nil { | |
123 | return err | |
124 | } | |
6988a057 | 125 | var n int |
72dd37f1 | 126 | if n, err = client.Connection.Write(b); err != nil { |
6988a057 JH |
127 | return err |
128 | } | |
129 | s.Logger.Debugw("Sent Transaction", | |
130 | "name", userName, | |
131 | "login", login, | |
132 | "IsReply", t.IsReply, | |
133 | "type", handler.Name, | |
134 | "sentBytes", n, | |
135 | "remoteAddr", client.Connection.RemoteAddr(), | |
136 | ) | |
137 | return nil | |
138 | } | |
139 | ||
140 | func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error { | |
141 | s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port)) | |
142 | ||
143 | for { | |
144 | conn, err := ln.Accept() | |
145 | if err != nil { | |
146 | s.Logger.Errorw("error accepting connection", "err", err) | |
147 | } | |
148 | ||
149 | go func() { | |
150 | for { | |
151 | t := <-s.outbox | |
152 | go func() { | |
153 | if err := s.sendTransaction(t); err != nil { | |
154 | s.Logger.Errorw("error sending transaction", "err", err) | |
155 | } | |
156 | }() | |
157 | } | |
158 | }() | |
159 | go func() { | |
160 | if err := s.handleNewConnection(conn); err != nil { | |
161 | if err == io.EOF { | |
162 | s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr()) | |
163 | } else { | |
164 | s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err) | |
165 | } | |
166 | } | |
167 | }() | |
168 | } | |
169 | } | |
170 | ||
171 | const ( | |
c7e932c0 | 172 | agreementFile = "Agreement.txt" |
6988a057 JH |
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), | |
72dd37f1 | 293 | NewField(fieldUserName, c.UserName), |
6988a057 JH |
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}, | |
72dd37f1 | 326 | UserName: []byte{}, |
6988a057 JH |
327 | Connection: conn, |
328 | Server: s, | |
329 | Version: &[]byte{}, | |
330 | IdleTime: new(int), | |
331 | AutoReply: &[]byte{}, | |
332 | Transfers: make(map[int][]*FileTransfer), | |
bd1ce113 | 333 | Agreed: false, |
6988a057 JH |
334 | } |
335 | *s.NextGuestID++ | |
336 | ID := *s.NextGuestID | |
337 | ||
338 | *clientConn.IdleTime = 0 | |
339 | ||
340 | binary.BigEndian.PutUint16(*clientConn.ID, ID) | |
341 | s.Clients[ID] = clientConn | |
342 | ||
343 | return clientConn | |
344 | } | |
345 | ||
346 | // NewUser creates a new user account entry in the server map and config file | |
347 | func (s *Server) NewUser(login, name, password string, access []byte) error { | |
348 | s.mux.Lock() | |
349 | defer s.mux.Unlock() | |
350 | ||
351 | account := Account{ | |
352 | Login: login, | |
353 | Name: name, | |
354 | Password: hashAndSalt([]byte(password)), | |
355 | Access: &access, | |
356 | } | |
357 | out, err := yaml.Marshal(&account) | |
358 | if err != nil { | |
359 | return err | |
360 | } | |
361 | s.Accounts[login] = &account | |
362 | ||
363 | return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666) | |
364 | } | |
365 | ||
366 | // DeleteUser deletes the user account | |
367 | func (s *Server) DeleteUser(login string) error { | |
368 | s.mux.Lock() | |
369 | defer s.mux.Unlock() | |
370 | ||
371 | delete(s.Accounts, login) | |
372 | ||
373 | return os.Remove(s.ConfigDir + "Users/" + login + ".yaml") | |
374 | } | |
375 | ||
376 | func (s *Server) connectedUsers() []Field { | |
377 | s.mux.Lock() | |
378 | defer s.mux.Unlock() | |
379 | ||
380 | var connectedUsers []Field | |
c7e932c0 | 381 | for _, c := range sortedClients(s.Clients) { |
bd1ce113 JH |
382 | if c.Agreed == false { |
383 | continue | |
384 | } | |
6988a057 JH |
385 | user := User{ |
386 | ID: *c.ID, | |
387 | Icon: *c.Icon, | |
388 | Flags: *c.Flags, | |
72dd37f1 | 389 | Name: string(c.UserName), |
6988a057 JH |
390 | } |
391 | connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload())) | |
392 | } | |
393 | return connectedUsers | |
394 | } | |
395 | ||
396 | // loadThreadedNews loads the threaded news data from disk | |
397 | func (s *Server) loadThreadedNews(threadedNewsPath string) error { | |
398 | fh, err := os.Open(threadedNewsPath) | |
399 | if err != nil { | |
400 | return err | |
401 | } | |
402 | decoder := yaml.NewDecoder(fh) | |
403 | decoder.SetStrict(true) | |
404 | ||
405 | return decoder.Decode(s.ThreadedNews) | |
406 | } | |
407 | ||
408 | // loadAccounts loads account data from disk | |
409 | func (s *Server) loadAccounts(userDir string) error { | |
410 | matches, err := filepath.Glob(path.Join(userDir, "*.yaml")) | |
411 | if err != nil { | |
412 | return err | |
413 | } | |
414 | ||
415 | if len(matches) == 0 { | |
416 | return errors.New("no user accounts found in " + userDir) | |
417 | } | |
418 | ||
419 | for _, file := range matches { | |
d492c46d | 420 | fh, err := FS.Open(file) |
6988a057 JH |
421 | if err != nil { |
422 | return err | |
423 | } | |
424 | ||
425 | account := Account{} | |
426 | decoder := yaml.NewDecoder(fh) | |
427 | decoder.SetStrict(true) | |
428 | if err := decoder.Decode(&account); err != nil { | |
429 | return err | |
430 | } | |
431 | ||
432 | s.Accounts[account.Login] = &account | |
433 | } | |
434 | return nil | |
435 | } | |
436 | ||
437 | func (s *Server) loadConfig(path string) error { | |
d492c46d | 438 | fh, err := FS.Open(path) |
6988a057 JH |
439 | if err != nil { |
440 | return err | |
441 | } | |
442 | ||
443 | decoder := yaml.NewDecoder(fh) | |
444 | decoder.SetStrict(true) | |
445 | err = decoder.Decode(s.Config) | |
446 | if err != nil { | |
447 | return err | |
448 | } | |
449 | return nil | |
450 | } | |
451 | ||
452 | const ( | |
453 | minTransactionLen = 22 // minimum length of any transaction | |
454 | ) | |
455 | ||
456 | // handleNewConnection takes a new net.Conn and performs the initial login sequence | |
457 | func (s *Server) handleNewConnection(conn net.Conn) error { | |
458 | handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length | |
459 | if _, err := conn.Read(handshakeBuf); err != nil { | |
460 | return err | |
461 | } | |
462 | if err := Handshake(conn, handshakeBuf[:12]); err != nil { | |
463 | return err | |
464 | } | |
465 | ||
466 | buf := make([]byte, 1024) | |
467 | readLen, err := conn.Read(buf) | |
468 | if readLen < minTransactionLen { | |
469 | return err | |
470 | } | |
471 | if err != nil { | |
472 | return err | |
473 | } | |
474 | ||
475 | clientLogin, _, err := ReadTransaction(buf[:readLen]) | |
476 | if err != nil { | |
477 | return err | |
478 | } | |
479 | ||
480 | c := s.NewClientConn(conn) | |
481 | defer c.Disconnect() | |
482 | defer func() { | |
483 | if r := recover(); r != nil { | |
484 | fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) | |
485 | c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) | |
486 | c.Disconnect() | |
487 | } | |
488 | }() | |
489 | ||
490 | encodedLogin := clientLogin.GetField(fieldUserLogin).Data | |
491 | encodedPassword := clientLogin.GetField(fieldUserPassword).Data | |
492 | *c.Version = clientLogin.GetField(fieldVersion).Data | |
493 | ||
494 | var login string | |
495 | for _, char := range encodedLogin { | |
496 | login += string(rune(255 - uint(char))) | |
497 | } | |
498 | if login == "" { | |
499 | login = GuestAccount | |
500 | } | |
501 | ||
502 | // If authentication fails, send error reply and close connection | |
503 | if !c.Authenticate(login, encodedPassword) { | |
72dd37f1 JH |
504 | t := c.NewErrReply(clientLogin, "Incorrect login.") |
505 | b, err := t.MarshalBinary() | |
506 | if err != nil { | |
507 | return err | |
508 | } | |
509 | if _, err := conn.Write(b); err != nil { | |
6988a057 JH |
510 | return err |
511 | } | |
512 | return fmt.Errorf("incorrect login") | |
513 | } | |
514 | ||
6988a057 | 515 | if clientLogin.GetField(fieldUserName).Data != nil { |
72dd37f1 | 516 | c.UserName = clientLogin.GetField(fieldUserName).Data |
6988a057 JH |
517 | } |
518 | ||
519 | if clientLogin.GetField(fieldUserIconID).Data != nil { | |
520 | *c.Icon = clientLogin.GetField(fieldUserIconID).Data | |
521 | } | |
522 | ||
523 | c.Account = c.Server.Accounts[login] | |
524 | ||
525 | if c.Authorize(accessDisconUser) { | |
526 | *c.Flags = []byte{0, 2} | |
527 | } | |
528 | ||
529 | s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String()) | |
530 | ||
531 | s.outbox <- c.NewReply(clientLogin, | |
532 | NewField(fieldVersion, []byte{0x00, 0xbe}), | |
533 | NewField(fieldCommunityBannerID, []byte{0x00, 0x01}), | |
534 | NewField(fieldServerName, []byte(s.Config.Name)), | |
535 | ) | |
536 | ||
537 | // Send user access privs so client UI knows how to behave | |
538 | c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access)) | |
539 | ||
540 | // Show agreement to client | |
541 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement)) | |
542 | ||
bd1ce113 JH |
543 | // assume simplified hotline v1.2.3 login flow that does not require agreement |
544 | if *c.Version == nil { | |
545 | c.Agreed = true | |
546 | if _, err := c.notifyNewUserHasJoined(); err != nil { | |
547 | return err | |
548 | } | |
6988a057 | 549 | } |
bd1ce113 | 550 | |
6988a057 JH |
551 | c.Server.Stats.LoginCount += 1 |
552 | ||
553 | const readBuffSize = 1024000 // 1KB - TODO: what should this be? | |
6988a057 JH |
554 | tranBuff := make([]byte, 0) |
555 | tReadlen := 0 | |
556 | // Infinite loop where take action on incoming client requests until the connection is closed | |
557 | for { | |
558 | buf = make([]byte, readBuffSize) | |
559 | tranBuff = tranBuff[tReadlen:] | |
560 | ||
561 | readLen, err := c.Connection.Read(buf) | |
562 | if err != nil { | |
563 | return err | |
564 | } | |
565 | tranBuff = append(tranBuff, buf[:readLen]...) | |
566 | ||
567 | // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them | |
568 | // into a slice of transactions | |
569 | var transactions []Transaction | |
570 | if transactions, tReadlen, err = readTransactions(tranBuff); err != nil { | |
571 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
572 | } | |
573 | ||
574 | // iterate over all of the transactions that were parsed from the byte slice and handle them | |
575 | for _, t := range transactions { | |
576 | if err := c.handleTransaction(&t); err != nil { | |
577 | c.Server.Logger.Errorw("Error handling transaction", "err", err) | |
578 | } | |
579 | } | |
580 | } | |
581 | } | |
582 | ||
583 | func hashAndSalt(pwd []byte) string { | |
584 | // Use GenerateFromPassword to hash & salt pwd. | |
585 | // MinCost is just an integer constant provided by the bcrypt | |
586 | // package along with DefaultCost & MaxCost. | |
587 | // The cost can be any value you want provided it isn't lower | |
588 | // than the MinCost (4) | |
589 | hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost) | |
590 | if err != nil { | |
591 | log.Println(err) | |
592 | } | |
593 | // GenerateFromPassword returns a byte slice so we need to | |
594 | // convert the bytes to a string and return it | |
595 | return string(hash) | |
596 | } | |
597 | ||
598 | // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID | |
599 | // in the file transfer request payload, and the file transfer server will use it to map the request | |
600 | // to a transfer | |
601 | func (s *Server) NewTransactionRef() []byte { | |
602 | transactionRef := make([]byte, 4) | |
603 | rand.Read(transactionRef) | |
604 | ||
605 | return transactionRef | |
606 | } | |
607 | ||
608 | func (s *Server) NewPrivateChat(cc *ClientConn) []byte { | |
609 | s.mux.Lock() | |
610 | defer s.mux.Unlock() | |
611 | ||
612 | randID := make([]byte, 4) | |
613 | rand.Read(randID) | |
614 | data := binary.BigEndian.Uint32(randID[:]) | |
615 | ||
616 | s.PrivateChats[data] = &PrivateChat{ | |
617 | Subject: "", | |
618 | ClientConn: make(map[uint16]*ClientConn), | |
619 | } | |
620 | s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc | |
621 | ||
622 | return randID | |
623 | } | |
624 | ||
625 | const dlFldrActionSendFile = 1 | |
626 | const dlFldrActionResumeFile = 2 | |
627 | const dlFldrActionNextFile = 3 | |
628 | ||
629 | func (s *Server) TransferFile(conn net.Conn) error { | |
630 | defer func() { _ = conn.Close() }() | |
631 | ||
632 | buf := make([]byte, 1024) | |
633 | if _, err := conn.Read(buf); err != nil { | |
634 | return err | |
635 | } | |
636 | ||
df2735b2 JH |
637 | var t transfer |
638 | _, err := t.Write(buf[:16]) | |
6988a057 JH |
639 | if err != nil { |
640 | return err | |
641 | } | |
642 | ||
643 | transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:]) | |
644 | fileTransfer := s.FileTransfers[transferRefNum] | |
645 | ||
646 | switch fileTransfer.Type { | |
647 | case FileDownload: | |
92a7e455 JH |
648 | fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
649 | if err != nil { | |
650 | return err | |
651 | } | |
6988a057 JH |
652 | |
653 | ffo, err := NewFlattenedFileObject( | |
92a7e455 JH |
654 | s.Config.FileRoot, |
655 | fileTransfer.FilePath, | |
656 | fileTransfer.FileName, | |
6988a057 JH |
657 | ) |
658 | if err != nil { | |
659 | return err | |
660 | } | |
661 | ||
662 | s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String()) | |
663 | ||
664 | // Start by sending flat file object to client | |
c5d9af5a | 665 | if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
666 | return err |
667 | } | |
668 | ||
92a7e455 | 669 | file, err := FS.Open(fullFilePath) |
6988a057 JH |
670 | if err != nil { |
671 | return err | |
672 | } | |
673 | ||
674 | sendBuffer := make([]byte, 1048576) | |
675 | for { | |
676 | var bytesRead int | |
677 | if bytesRead, err = file.Read(sendBuffer); err == io.EOF { | |
678 | break | |
679 | } | |
680 | ||
681 | fileTransfer.BytesSent += bytesRead | |
682 | ||
683 | delete(s.FileTransfers, transferRefNum) | |
684 | ||
685 | if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { | |
686 | return err | |
687 | } | |
688 | } | |
689 | case FileUpload: | |
690 | if _, err := conn.Read(buf); err != nil { | |
691 | return err | |
692 | } | |
693 | ||
694 | ffo := ReadFlattenedFileObject(buf) | |
c5d9af5a | 695 | payloadLen := len(ffo.BinaryMarshal()) |
6988a057 JH |
696 | fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) |
697 | ||
698 | destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) | |
699 | s.Logger.Infow( | |
700 | "File upload started", | |
701 | "transactionRef", fileTransfer.ReferenceNumber, | |
702 | "RemoteAddr", conn.RemoteAddr().String(), | |
703 | "size", fileSize, | |
704 | "dstFile", destinationFile, | |
705 | ) | |
706 | ||
707 | newFile, err := os.Create(destinationFile) | |
708 | if err != nil { | |
709 | return err | |
710 | } | |
711 | ||
712 | defer func() { _ = newFile.Close() }() | |
713 | ||
714 | const buffSize = 1024 | |
715 | ||
716 | if _, err := newFile.Write(buf[payloadLen:]); err != nil { | |
717 | return err | |
718 | } | |
719 | receivedBytes := buffSize - payloadLen | |
720 | ||
721 | for { | |
722 | if (fileSize - receivedBytes) < buffSize { | |
723 | s.Logger.Infow( | |
724 | "File upload complete", | |
725 | "transactionRef", fileTransfer.ReferenceNumber, | |
726 | "RemoteAddr", conn.RemoteAddr().String(), | |
727 | "size", fileSize, | |
728 | "dstFile", destinationFile, | |
729 | ) | |
730 | ||
731 | if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil { | |
732 | return fmt.Errorf("file transfer failed: %s", err) | |
733 | } | |
734 | return nil | |
735 | } | |
736 | ||
737 | // Copy N bytes from conn to upload file | |
738 | n, err := io.CopyN(newFile, conn, buffSize) | |
739 | if err != nil { | |
740 | return err | |
741 | } | |
742 | receivedBytes += int(n) | |
743 | } | |
744 | case FolderDownload: | |
745 | // Folder Download flow: | |
df2735b2 | 746 | // 1. Get filePath from the transfer |
6988a057 JH |
747 | // 2. Iterate over files |
748 | // 3. For each file: | |
749 | // Send file header to client | |
750 | // The client can reply in 3 ways: | |
751 | // | |
752 | // 1. If type is an odd number (unknown type?), or file download for the current file is completed: | |
753 | // client sends []byte{0x00, 0x03} to tell the server to continue to the next file | |
754 | // | |
755 | // 2. If download of a file is to be resumed: | |
756 | // client sends: | |
757 | // []byte{0x00, 0x02} // download folder action | |
758 | // [2]byte // Resume data size | |
759 | // []byte file resume data (see myField_FileResumeData) | |
760 | // | |
761 | // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01} | |
762 | // | |
763 | // When download is requested (case 2 or 3), server replies with: | |
764 | // [4]byte - file size | |
765 | // []byte - Flattened File Object | |
766 | // | |
767 | // After every file download, client could request next file with: | |
768 | // []byte{0x00, 0x03} | |
769 | // | |
770 | // This notifies the server to send the next item header | |
771 | ||
92a7e455 JH |
772 | fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
773 | if err != nil { | |
774 | return err | |
775 | } | |
6988a057 JH |
776 | |
777 | basePathLen := len(fullFilePath) | |
778 | ||
779 | readBuffer := make([]byte, 1024) | |
780 | ||
781 | s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr()) | |
782 | ||
783 | i := 0 | |
784 | _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error { | |
785 | i += 1 | |
f6d08d0a | 786 | subPath := path[basePathLen:] |
6988a057 JH |
787 | s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) |
788 | ||
789 | fileHeader := NewFileHeader(subPath, info.IsDir()) | |
790 | ||
791 | if i == 1 { | |
792 | return nil | |
793 | } | |
794 | ||
795 | // Send the file header to client | |
796 | if _, err := conn.Write(fileHeader.Payload()); err != nil { | |
797 | s.Logger.Errorf("error sending file header: %v", err) | |
798 | return err | |
799 | } | |
800 | ||
801 | // Read the client's Next Action request | |
802 | //TODO: Remove hardcoded behavior and switch behaviors based on the next action send | |
803 | if _, err := conn.Read(readBuffer); err != nil { | |
6988a057 JH |
804 | return err |
805 | } | |
806 | ||
807 | s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2])) | |
808 | ||
809 | if info.IsDir() { | |
810 | return nil | |
811 | } | |
812 | ||
813 | splitPath := strings.Split(path, "/") | |
6988a057 | 814 | |
92a7e455 JH |
815 | ffo, err := NewFlattenedFileObject( |
816 | strings.Join(splitPath[:len(splitPath)-1], "/"), | |
817 | nil, | |
818 | []byte(info.Name()), | |
819 | ) | |
6988a057 JH |
820 | if err != nil { |
821 | return err | |
822 | } | |
823 | s.Logger.Infow("File download started", | |
824 | "fileName", info.Name(), | |
825 | "transactionRef", fileTransfer.ReferenceNumber, | |
826 | "RemoteAddr", conn.RemoteAddr().String(), | |
827 | "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()), | |
828 | ) | |
829 | ||
830 | // Send file size to client | |
831 | if _, err := conn.Write(ffo.TransferSize()); err != nil { | |
832 | s.Logger.Error(err) | |
833 | return err | |
834 | } | |
835 | ||
836 | // Send file bytes to client | |
c5d9af5a | 837 | if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
838 | s.Logger.Error(err) |
839 | return err | |
840 | } | |
841 | ||
d492c46d | 842 | file, err := FS.Open(path) |
6988a057 JH |
843 | if err != nil { |
844 | return err | |
845 | } | |
846 | ||
847 | sendBuffer := make([]byte, 1048576) | |
c5d9af5a | 848 | totalBytesSent := len(ffo.BinaryMarshal()) |
6988a057 JH |
849 | |
850 | for { | |
851 | bytesRead, err := file.Read(sendBuffer) | |
852 | if err == io.EOF { | |
853 | // Read the client's Next Action request | |
854 | //TODO: Remove hardcoded behavior and switch behaviors based on the next action send | |
855 | if _, err := conn.Read(readBuffer); err != nil { | |
856 | s.Logger.Errorf("error reading next action: %v", err) | |
857 | return err | |
858 | } | |
859 | break | |
860 | } | |
861 | ||
862 | sentBytes, readErr := conn.Write(sendBuffer[:bytesRead]) | |
863 | totalBytesSent += sentBytes | |
864 | if readErr != nil { | |
865 | return err | |
866 | } | |
867 | } | |
868 | return nil | |
869 | }) | |
870 | ||
871 | case FolderUpload: | |
92a7e455 JH |
872 | dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
873 | if err != nil { | |
874 | return err | |
875 | } | |
6988a057 JH |
876 | s.Logger.Infow( |
877 | "Folder upload started", | |
878 | "transactionRef", fileTransfer.ReferenceNumber, | |
879 | "RemoteAddr", conn.RemoteAddr().String(), | |
880 | "dstPath", dstPath, | |
92a7e455 | 881 | "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize), |
6988a057 JH |
882 | "FolderItemCount", fileTransfer.FolderItemCount, |
883 | ) | |
884 | ||
885 | // Check if the target folder exists. If not, create it. | |
92a7e455 JH |
886 | if _, err := FS.Stat(dstPath); os.IsNotExist(err) { |
887 | s.Logger.Infow("Creating target path", "dstPath", dstPath) | |
888 | if err := FS.Mkdir(dstPath, 0777); err != nil { | |
6988a057 JH |
889 | s.Logger.Error(err) |
890 | } | |
891 | } | |
892 | ||
893 | readBuffer := make([]byte, 1024) | |
894 | ||
895 | // Begin the folder upload flow by sending the "next file action" to client | |
896 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
897 | return err | |
898 | } | |
899 | ||
900 | fileSize := make([]byte, 4) | |
901 | itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount) | |
902 | ||
903 | for i := uint16(0); i < itemCount; i++ { | |
904 | if _, err := conn.Read(readBuffer); err != nil { | |
905 | return err | |
906 | } | |
907 | fu := readFolderUpload(readBuffer) | |
908 | ||
909 | s.Logger.Infow( | |
910 | "Folder upload continued", | |
911 | "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), | |
912 | "RemoteAddr", conn.RemoteAddr().String(), | |
913 | "FormattedPath", fu.FormattedPath(), | |
914 | "IsFolder", fmt.Sprintf("%x", fu.IsFolder), | |
c5d9af5a | 915 | "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), |
6988a057 JH |
916 | ) |
917 | ||
c5d9af5a | 918 | if fu.IsFolder == [2]byte{0, 1} { |
6988a057 JH |
919 | if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) { |
920 | s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath) | |
921 | if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil { | |
922 | s.Logger.Error(err) | |
923 | } | |
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 | } else { | |
932 | // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. | |
933 | // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. | |
934 | // Send dlFldrAction_SendFile to client to begin transfer | |
935 | if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil { | |
936 | return err | |
937 | } | |
938 | ||
939 | if _, err := conn.Read(fileSize); err != nil { | |
940 | fmt.Println("Error reading:", err.Error()) // TODO: handle | |
941 | } | |
942 | ||
943 | s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize) | |
944 | ||
945 | if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil { | |
946 | s.Logger.Error(err) | |
947 | } | |
948 | ||
949 | // Tell client to send next file | |
950 | if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
951 | s.Logger.Error(err) | |
952 | return err | |
953 | } | |
954 | ||
955 | // Client sends "MACR" after the file. Read and discard. | |
956 | // TODO: This doesn't seem to be documented. What is this? Maybe resource fork? | |
957 | if _, err := conn.Read(readBuffer); err != nil { | |
958 | return err | |
959 | } | |
960 | } | |
961 | } | |
962 | s.Logger.Infof("Folder upload complete") | |
963 | } | |
964 | ||
965 | return nil | |
966 | } | |
967 | ||
968 | func transferFile(conn net.Conn, dst string) error { | |
969 | const buffSize = 1024 | |
970 | buf := make([]byte, buffSize) | |
971 | ||
972 | // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes | |
973 | if _, err := conn.Read(buf); err != nil { | |
974 | return err | |
975 | } | |
976 | ffo := ReadFlattenedFileObject(buf) | |
c5d9af5a | 977 | payloadLen := len(ffo.BinaryMarshal()) |
6988a057 JH |
978 | fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) |
979 | ||
980 | newFile, err := os.Create(dst) | |
981 | if err != nil { | |
982 | return err | |
983 | } | |
984 | defer func() { _ = newFile.Close() }() | |
985 | if _, err := newFile.Write(buf[payloadLen:]); err != nil { | |
986 | return err | |
987 | } | |
988 | receivedBytes := buffSize - payloadLen | |
989 | ||
990 | for { | |
991 | if (fileSize - receivedBytes) < buffSize { | |
992 | _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)) | |
993 | return err | |
994 | } | |
995 | ||
996 | // Copy N bytes from conn to upload file | |
997 | n, err := io.CopyN(newFile, conn, buffSize) | |
998 | if err != nil { | |
999 | return err | |
1000 | } | |
1001 | receivedBytes += int(n) | |
1002 | } | |
1003 | } | |
1004 | ||
6988a057 JH |
1005 | // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values. |
1006 | // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work. | |
1007 | func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) { | |
1008 | for _, c := range unsortedClients { | |
1009 | clients = append(clients, c) | |
1010 | } | |
1011 | sort.Sort(byClientID(clients)) | |
1012 | return clients | |
1013 | } |