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