]>
Commit | Line | Data |
---|---|---|
1 | package hotline | |
2 | ||
3 | import ( | |
4 | "bufio" | |
5 | "bytes" | |
6 | "context" | |
7 | "encoding/binary" | |
8 | "errors" | |
9 | "fmt" | |
10 | "github.com/go-playground/validator/v10" | |
11 | "go.uber.org/zap" | |
12 | "gopkg.in/yaml.v3" | |
13 | "io" | |
14 | "io/fs" | |
15 | "io/ioutil" | |
16 | "math/big" | |
17 | "math/rand" | |
18 | "net" | |
19 | "os" | |
20 | "path/filepath" | |
21 | "strings" | |
22 | "sync" | |
23 | "time" | |
24 | ) | |
25 | ||
26 | type contextKey string | |
27 | ||
28 | var contextKeyReq = contextKey("req") | |
29 | ||
30 | type requestCtx struct { | |
31 | remoteAddr string | |
32 | login string | |
33 | name string | |
34 | } | |
35 | ||
36 | var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client | |
37 | var frogblastVersion = []byte{0, 0, 0, 0xb9} // version ID used by the Frogblast 1.2.4 client | |
38 | ||
39 | type Server struct { | |
40 | Port int | |
41 | Accounts map[string]*Account | |
42 | Agreement []byte | |
43 | Clients map[uint16]*ClientConn | |
44 | fileTransfers map[[4]byte]*FileTransfer | |
45 | ||
46 | Config *Config | |
47 | ConfigDir string | |
48 | Logger *zap.SugaredLogger | |
49 | ||
50 | PrivateChatsMu sync.Mutex | |
51 | PrivateChats map[uint32]*PrivateChat | |
52 | ||
53 | NextGuestID *uint16 | |
54 | TrackerPassID [4]byte | |
55 | ||
56 | StatsMu sync.Mutex | |
57 | Stats *Stats | |
58 | ||
59 | FS FileStore // Storage backend to use for File storage | |
60 | ||
61 | outbox chan Transaction | |
62 | mux sync.Mutex | |
63 | ||
64 | threadedNewsMux sync.Mutex | |
65 | ThreadedNews *ThreadedNews | |
66 | ||
67 | flatNewsMux sync.Mutex | |
68 | FlatNews []byte | |
69 | ||
70 | banListMU sync.Mutex | |
71 | banList map[string]*time.Time | |
72 | } | |
73 | ||
74 | func (s *Server) CurrentStats() Stats { | |
75 | s.StatsMu.Lock() | |
76 | defer s.StatsMu.Unlock() | |
77 | ||
78 | stats := s.Stats | |
79 | stats.CurrentlyConnected = len(s.Clients) | |
80 | ||
81 | return *stats | |
82 | } | |
83 | ||
84 | type PrivateChat struct { | |
85 | Subject string | |
86 | ClientConn map[uint16]*ClientConn | |
87 | } | |
88 | ||
89 | func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error { | |
90 | s.Logger.Infow("Hotline server started", | |
91 | "version", VERSION, | |
92 | "API port", fmt.Sprintf(":%v", s.Port), | |
93 | "Transfer port", fmt.Sprintf(":%v", s.Port+1), | |
94 | ) | |
95 | ||
96 | var wg sync.WaitGroup | |
97 | ||
98 | wg.Add(1) | |
99 | go func() { | |
100 | ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port)) | |
101 | if err != nil { | |
102 | s.Logger.Fatal(err) | |
103 | } | |
104 | ||
105 | s.Logger.Fatal(s.Serve(ctx, ln)) | |
106 | }() | |
107 | ||
108 | wg.Add(1) | |
109 | go func() { | |
110 | ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1)) | |
111 | if err != nil { | |
112 | s.Logger.Fatal(err) | |
113 | ||
114 | } | |
115 | ||
116 | s.Logger.Fatal(s.ServeFileTransfers(ctx, ln)) | |
117 | }() | |
118 | ||
119 | wg.Wait() | |
120 | ||
121 | return nil | |
122 | } | |
123 | ||
124 | func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error { | |
125 | for { | |
126 | conn, err := ln.Accept() | |
127 | if err != nil { | |
128 | return err | |
129 | } | |
130 | ||
131 | go func() { | |
132 | defer func() { _ = conn.Close() }() | |
133 | ||
134 | err = s.handleFileTransfer( | |
135 | context.WithValue(ctx, contextKeyReq, requestCtx{ | |
136 | remoteAddr: conn.RemoteAddr().String(), | |
137 | }), | |
138 | conn, | |
139 | ) | |
140 | ||
141 | if err != nil { | |
142 | s.Logger.Errorw("file transfer error", "reason", err) | |
143 | } | |
144 | }() | |
145 | } | |
146 | } | |
147 | ||
148 | func (s *Server) sendTransaction(t Transaction) error { | |
149 | clientID, err := byteToInt(*t.clientID) | |
150 | if err != nil { | |
151 | return err | |
152 | } | |
153 | ||
154 | s.mux.Lock() | |
155 | client := s.Clients[uint16(clientID)] | |
156 | if client == nil { | |
157 | return fmt.Errorf("invalid client id %v", *t.clientID) | |
158 | } | |
159 | ||
160 | s.mux.Unlock() | |
161 | ||
162 | b, err := t.MarshalBinary() | |
163 | if err != nil { | |
164 | return err | |
165 | } | |
166 | ||
167 | if _, err := client.Connection.Write(b); err != nil { | |
168 | return err | |
169 | } | |
170 | ||
171 | return nil | |
172 | } | |
173 | ||
174 | func (s *Server) processOutbox() { | |
175 | for { | |
176 | t := <-s.outbox | |
177 | go func() { | |
178 | if err := s.sendTransaction(t); err != nil { | |
179 | s.Logger.Errorw("error sending transaction", "err", err) | |
180 | } | |
181 | }() | |
182 | } | |
183 | } | |
184 | ||
185 | func (s *Server) Serve(ctx context.Context, ln net.Listener) error { | |
186 | go s.processOutbox() | |
187 | ||
188 | for { | |
189 | conn, err := ln.Accept() | |
190 | if err != nil { | |
191 | s.Logger.Errorw("error accepting connection", "err", err) | |
192 | } | |
193 | connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{ | |
194 | remoteAddr: conn.RemoteAddr().String(), | |
195 | }) | |
196 | ||
197 | go func() { | |
198 | s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr()) | |
199 | ||
200 | defer conn.Close() | |
201 | if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil { | |
202 | if err == io.EOF { | |
203 | s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr()) | |
204 | } else { | |
205 | s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err) | |
206 | } | |
207 | } | |
208 | }() | |
209 | } | |
210 | } | |
211 | ||
212 | const ( | |
213 | agreementFile = "Agreement.txt" | |
214 | ) | |
215 | ||
216 | // NewServer constructs a new Server from a config dir | |
217 | func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) { | |
218 | server := Server{ | |
219 | Port: netPort, | |
220 | Accounts: make(map[string]*Account), | |
221 | Config: new(Config), | |
222 | Clients: make(map[uint16]*ClientConn), | |
223 | fileTransfers: make(map[[4]byte]*FileTransfer), | |
224 | PrivateChats: make(map[uint32]*PrivateChat), | |
225 | ConfigDir: configDir, | |
226 | Logger: logger, | |
227 | NextGuestID: new(uint16), | |
228 | outbox: make(chan Transaction), | |
229 | Stats: &Stats{Since: time.Now()}, | |
230 | ThreadedNews: &ThreadedNews{}, | |
231 | FS: FS, | |
232 | banList: make(map[string]*time.Time), | |
233 | } | |
234 | ||
235 | var err error | |
236 | ||
237 | // generate a new random passID for tracker registration | |
238 | if _, err := rand.Read(server.TrackerPassID[:]); err != nil { | |
239 | return nil, err | |
240 | } | |
241 | ||
242 | server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile)) | |
243 | if err != nil { | |
244 | return nil, err | |
245 | } | |
246 | ||
247 | if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil { | |
248 | return nil, err | |
249 | } | |
250 | ||
251 | // try to load the ban list, but ignore errors as this file may not be present or may be empty | |
252 | _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml")) | |
253 | ||
254 | if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil { | |
255 | return nil, err | |
256 | } | |
257 | ||
258 | if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil { | |
259 | return nil, err | |
260 | } | |
261 | ||
262 | if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil { | |
263 | return nil, err | |
264 | } | |
265 | ||
266 | server.Config.FileRoot = filepath.Join(configDir, "Files") | |
267 | ||
268 | *server.NextGuestID = 1 | |
269 | ||
270 | if server.Config.EnableTrackerRegistration { | |
271 | server.Logger.Infow( | |
272 | "Tracker registration enabled", | |
273 | "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency), | |
274 | "trackers", server.Config.Trackers, | |
275 | ) | |
276 | ||
277 | go func() { | |
278 | for { | |
279 | tr := &TrackerRegistration{ | |
280 | UserCount: server.userCount(), | |
281 | PassID: server.TrackerPassID[:], | |
282 | Name: server.Config.Name, | |
283 | Description: server.Config.Description, | |
284 | } | |
285 | binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port)) | |
286 | for _, t := range server.Config.Trackers { | |
287 | if err := register(t, tr); err != nil { | |
288 | server.Logger.Errorw("unable to register with tracker %v", "error", err) | |
289 | } | |
290 | server.Logger.Debugw("Sent Tracker registration", "addr", t) | |
291 | } | |
292 | ||
293 | time.Sleep(trackerUpdateFrequency * time.Second) | |
294 | } | |
295 | }() | |
296 | } | |
297 | ||
298 | // Start Client Keepalive go routine | |
299 | go server.keepaliveHandler() | |
300 | ||
301 | return &server, nil | |
302 | } | |
303 | ||
304 | func (s *Server) userCount() int { | |
305 | s.mux.Lock() | |
306 | defer s.mux.Unlock() | |
307 | ||
308 | return len(s.Clients) | |
309 | } | |
310 | ||
311 | func (s *Server) keepaliveHandler() { | |
312 | for { | |
313 | time.Sleep(idleCheckInterval * time.Second) | |
314 | s.mux.Lock() | |
315 | ||
316 | for _, c := range s.Clients { | |
317 | c.IdleTime += idleCheckInterval | |
318 | if c.IdleTime > userIdleSeconds && !c.Idle { | |
319 | c.Idle = true | |
320 | ||
321 | flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags))) | |
322 | flagBitmap.SetBit(flagBitmap, userFlagAway, 1) | |
323 | binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64())) | |
324 | ||
325 | c.sendAll( | |
326 | tranNotifyChangeUser, | |
327 | NewField(fieldUserID, *c.ID), | |
328 | NewField(fieldUserFlags, c.Flags), | |
329 | NewField(fieldUserName, c.UserName), | |
330 | NewField(fieldUserIconID, c.Icon), | |
331 | ) | |
332 | } | |
333 | } | |
334 | s.mux.Unlock() | |
335 | } | |
336 | } | |
337 | ||
338 | func (s *Server) writeBanList() error { | |
339 | s.banListMU.Lock() | |
340 | defer s.banListMU.Unlock() | |
341 | ||
342 | out, err := yaml.Marshal(s.banList) | |
343 | if err != nil { | |
344 | return err | |
345 | } | |
346 | err = ioutil.WriteFile( | |
347 | filepath.Join(s.ConfigDir, "Banlist.yaml"), | |
348 | out, | |
349 | 0666, | |
350 | ) | |
351 | return err | |
352 | } | |
353 | ||
354 | func (s *Server) writeThreadedNews() error { | |
355 | s.threadedNewsMux.Lock() | |
356 | defer s.threadedNewsMux.Unlock() | |
357 | ||
358 | out, err := yaml.Marshal(s.ThreadedNews) | |
359 | if err != nil { | |
360 | return err | |
361 | } | |
362 | err = s.FS.WriteFile( | |
363 | filepath.Join(s.ConfigDir, "ThreadedNews.yaml"), | |
364 | out, | |
365 | 0666, | |
366 | ) | |
367 | return err | |
368 | } | |
369 | ||
370 | func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn { | |
371 | s.mux.Lock() | |
372 | defer s.mux.Unlock() | |
373 | ||
374 | clientConn := &ClientConn{ | |
375 | ID: &[]byte{0, 0}, | |
376 | Icon: []byte{0, 0}, | |
377 | Flags: []byte{0, 0}, | |
378 | UserName: []byte{}, | |
379 | Connection: conn, | |
380 | Server: s, | |
381 | Version: []byte{}, | |
382 | AutoReply: []byte{}, | |
383 | transfers: map[int]map[[4]byte]*FileTransfer{}, | |
384 | Agreed: false, | |
385 | RemoteAddr: remoteAddr, | |
386 | } | |
387 | clientConn.transfers = map[int]map[[4]byte]*FileTransfer{ | |
388 | FileDownload: {}, | |
389 | FileUpload: {}, | |
390 | FolderDownload: {}, | |
391 | FolderUpload: {}, | |
392 | bannerDownload: {}, | |
393 | } | |
394 | ||
395 | *s.NextGuestID++ | |
396 | ID := *s.NextGuestID | |
397 | ||
398 | binary.BigEndian.PutUint16(*clientConn.ID, ID) | |
399 | s.Clients[ID] = clientConn | |
400 | ||
401 | return clientConn | |
402 | } | |
403 | ||
404 | // NewUser creates a new user account entry in the server map and config file | |
405 | func (s *Server) NewUser(login, name, password string, access accessBitmap) error { | |
406 | s.mux.Lock() | |
407 | defer s.mux.Unlock() | |
408 | ||
409 | account := Account{ | |
410 | Login: login, | |
411 | Name: name, | |
412 | Password: hashAndSalt([]byte(password)), | |
413 | Access: access, | |
414 | } | |
415 | out, err := yaml.Marshal(&account) | |
416 | if err != nil { | |
417 | return err | |
418 | } | |
419 | s.Accounts[login] = &account | |
420 | ||
421 | return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666) | |
422 | } | |
423 | ||
424 | func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error { | |
425 | s.mux.Lock() | |
426 | defer s.mux.Unlock() | |
427 | ||
428 | // update renames the user login | |
429 | if login != newLogin { | |
430 | err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml")) | |
431 | if err != nil { | |
432 | return err | |
433 | } | |
434 | s.Accounts[newLogin] = s.Accounts[login] | |
435 | delete(s.Accounts, login) | |
436 | } | |
437 | ||
438 | account := s.Accounts[newLogin] | |
439 | account.Access = access | |
440 | account.Name = name | |
441 | account.Password = password | |
442 | ||
443 | out, err := yaml.Marshal(&account) | |
444 | if err != nil { | |
445 | return err | |
446 | } | |
447 | ||
448 | if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil { | |
449 | return err | |
450 | } | |
451 | ||
452 | return nil | |
453 | } | |
454 | ||
455 | // DeleteUser deletes the user account | |
456 | func (s *Server) DeleteUser(login string) error { | |
457 | s.mux.Lock() | |
458 | defer s.mux.Unlock() | |
459 | ||
460 | delete(s.Accounts, login) | |
461 | ||
462 | return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml")) | |
463 | } | |
464 | ||
465 | func (s *Server) connectedUsers() []Field { | |
466 | s.mux.Lock() | |
467 | defer s.mux.Unlock() | |
468 | ||
469 | var connectedUsers []Field | |
470 | for _, c := range sortedClients(s.Clients) { | |
471 | if !c.Agreed { | |
472 | continue | |
473 | } | |
474 | user := User{ | |
475 | ID: *c.ID, | |
476 | Icon: c.Icon, | |
477 | Flags: c.Flags, | |
478 | Name: string(c.UserName), | |
479 | } | |
480 | connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload())) | |
481 | } | |
482 | return connectedUsers | |
483 | } | |
484 | ||
485 | func (s *Server) loadBanList(path string) error { | |
486 | fh, err := os.Open(path) | |
487 | if err != nil { | |
488 | return err | |
489 | } | |
490 | decoder := yaml.NewDecoder(fh) | |
491 | ||
492 | return decoder.Decode(s.banList) | |
493 | } | |
494 | ||
495 | // loadThreadedNews loads the threaded news data from disk | |
496 | func (s *Server) loadThreadedNews(threadedNewsPath string) error { | |
497 | fh, err := os.Open(threadedNewsPath) | |
498 | if err != nil { | |
499 | return err | |
500 | } | |
501 | decoder := yaml.NewDecoder(fh) | |
502 | ||
503 | return decoder.Decode(s.ThreadedNews) | |
504 | } | |
505 | ||
506 | // loadAccounts loads account data from disk | |
507 | func (s *Server) loadAccounts(userDir string) error { | |
508 | matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml")) | |
509 | if err != nil { | |
510 | return err | |
511 | } | |
512 | ||
513 | if len(matches) == 0 { | |
514 | return errors.New("no user accounts found in " + userDir) | |
515 | } | |
516 | ||
517 | for _, file := range matches { | |
518 | fh, err := s.FS.Open(file) | |
519 | if err != nil { | |
520 | return err | |
521 | } | |
522 | ||
523 | account := Account{} | |
524 | decoder := yaml.NewDecoder(fh) | |
525 | if err := decoder.Decode(&account); err != nil { | |
526 | return err | |
527 | } | |
528 | ||
529 | s.Accounts[account.Login] = &account | |
530 | } | |
531 | return nil | |
532 | } | |
533 | ||
534 | func (s *Server) loadConfig(path string) error { | |
535 | fh, err := s.FS.Open(path) | |
536 | if err != nil { | |
537 | return err | |
538 | } | |
539 | ||
540 | decoder := yaml.NewDecoder(fh) | |
541 | err = decoder.Decode(s.Config) | |
542 | if err != nil { | |
543 | return err | |
544 | } | |
545 | ||
546 | validate := validator.New() | |
547 | err = validate.Struct(s.Config) | |
548 | if err != nil { | |
549 | return err | |
550 | } | |
551 | return nil | |
552 | } | |
553 | ||
554 | // handleNewConnection takes a new net.Conn and performs the initial login sequence | |
555 | func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error { | |
556 | defer dontPanic(s.Logger) | |
557 | ||
558 | if err := Handshake(rwc); err != nil { | |
559 | return err | |
560 | } | |
561 | ||
562 | // Create a new scanner for parsing incoming bytes into transaction tokens | |
563 | scanner := bufio.NewScanner(rwc) | |
564 | scanner.Split(transactionScanner) | |
565 | ||
566 | scanner.Scan() | |
567 | ||
568 | // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the | |
569 | // scanner re-uses the buffer for subsequent scans. | |
570 | buf := make([]byte, len(scanner.Bytes())) | |
571 | copy(buf, scanner.Bytes()) | |
572 | ||
573 | var clientLogin Transaction | |
574 | if _, err := clientLogin.Write(buf); err != nil { | |
575 | return err | |
576 | } | |
577 | ||
578 | c := s.NewClientConn(rwc, remoteAddr) | |
579 | ||
580 | // check if remoteAddr is present in the ban list | |
581 | if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok { | |
582 | // permaban | |
583 | if banUntil == nil { | |
584 | s.outbox <- *NewTransaction( | |
585 | tranServerMsg, | |
586 | c.ID, | |
587 | NewField(fieldData, []byte("You are permanently banned on this server")), | |
588 | NewField(fieldChatOptions, []byte{0, 0}), | |
589 | ) | |
590 | time.Sleep(1 * time.Second) | |
591 | return nil | |
592 | } else if time.Now().Before(*banUntil) { | |
593 | s.outbox <- *NewTransaction( | |
594 | tranServerMsg, | |
595 | c.ID, | |
596 | NewField(fieldData, []byte("You are temporarily banned on this server")), | |
597 | NewField(fieldChatOptions, []byte{0, 0}), | |
598 | ) | |
599 | time.Sleep(1 * time.Second) | |
600 | return nil | |
601 | } | |
602 | ||
603 | } | |
604 | defer c.Disconnect() | |
605 | ||
606 | encodedLogin := clientLogin.GetField(fieldUserLogin).Data | |
607 | encodedPassword := clientLogin.GetField(fieldUserPassword).Data | |
608 | c.Version = clientLogin.GetField(fieldVersion).Data | |
609 | ||
610 | var login string | |
611 | for _, char := range encodedLogin { | |
612 | login += string(rune(255 - uint(char))) | |
613 | } | |
614 | if login == "" { | |
615 | login = GuestAccount | |
616 | } | |
617 | ||
618 | c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login) | |
619 | ||
620 | // If authentication fails, send error reply and close connection | |
621 | if !c.Authenticate(login, encodedPassword) { | |
622 | t := c.NewErrReply(&clientLogin, "Incorrect login.") | |
623 | b, err := t.MarshalBinary() | |
624 | if err != nil { | |
625 | return err | |
626 | } | |
627 | if _, err := rwc.Write(b); err != nil { | |
628 | return err | |
629 | } | |
630 | ||
631 | c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version)) | |
632 | ||
633 | return nil | |
634 | } | |
635 | ||
636 | if clientLogin.GetField(fieldUserIconID).Data != nil { | |
637 | c.Icon = clientLogin.GetField(fieldUserIconID).Data | |
638 | } | |
639 | ||
640 | c.Account = c.Server.Accounts[login] | |
641 | ||
642 | if clientLogin.GetField(fieldUserName).Data != nil { | |
643 | if c.Authorize(accessAnyName) { | |
644 | c.UserName = clientLogin.GetField(fieldUserName).Data | |
645 | } else { | |
646 | c.UserName = []byte(c.Account.Name) | |
647 | } | |
648 | } | |
649 | ||
650 | if c.Authorize(accessDisconUser) { | |
651 | c.Flags = []byte{0, 2} | |
652 | } | |
653 | ||
654 | s.outbox <- c.NewReply(&clientLogin, | |
655 | NewField(fieldVersion, []byte{0x00, 0xbe}), | |
656 | NewField(fieldCommunityBannerID, []byte{0, 0}), | |
657 | NewField(fieldServerName, []byte(s.Config.Name)), | |
658 | ) | |
659 | ||
660 | // Send user access privs so client UI knows how to behave | |
661 | c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:])) | |
662 | ||
663 | // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between | |
664 | // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send | |
665 | // tranShowAgreement but with the NoServerAgreement field set to 1. | |
666 | if c.Authorize(accessNoAgreement) { | |
667 | // If client version is nil, then the client uses the 1.2.3 login behavior | |
668 | if c.Version != nil { | |
669 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1})) | |
670 | } | |
671 | } else { | |
672 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement)) | |
673 | } | |
674 | ||
675 | // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed | |
676 | if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) { | |
677 | c.Agreed = true | |
678 | c.logger = c.logger.With("name", string(c.UserName)) | |
679 | c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }())) | |
680 | ||
681 | for _, t := range c.notifyOthers( | |
682 | *NewTransaction( | |
683 | tranNotifyChangeUser, nil, | |
684 | NewField(fieldUserName, c.UserName), | |
685 | NewField(fieldUserID, *c.ID), | |
686 | NewField(fieldUserIconID, c.Icon), | |
687 | NewField(fieldUserFlags, c.Flags), | |
688 | ), | |
689 | ) { | |
690 | c.Server.outbox <- t | |
691 | } | |
692 | } | |
693 | ||
694 | c.Server.Stats.ConnectionCounter += 1 | |
695 | if len(s.Clients) > c.Server.Stats.ConnectionPeak { | |
696 | c.Server.Stats.ConnectionPeak = len(s.Clients) | |
697 | } | |
698 | ||
699 | // Scan for new transactions and handle them as they come in. | |
700 | for scanner.Scan() { | |
701 | // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the | |
702 | // scanner re-uses the buffer for subsequent scans. | |
703 | buf := make([]byte, len(scanner.Bytes())) | |
704 | copy(buf, scanner.Bytes()) | |
705 | ||
706 | var t Transaction | |
707 | if _, err := t.Write(buf); err != nil { | |
708 | return err | |
709 | } | |
710 | ||
711 | if err := c.handleTransaction(t); err != nil { | |
712 | c.logger.Errorw("Error handling transaction", "err", err) | |
713 | } | |
714 | } | |
715 | return nil | |
716 | } | |
717 | ||
718 | func (s *Server) NewPrivateChat(cc *ClientConn) []byte { | |
719 | s.PrivateChatsMu.Lock() | |
720 | defer s.PrivateChatsMu.Unlock() | |
721 | ||
722 | randID := make([]byte, 4) | |
723 | rand.Read(randID) | |
724 | data := binary.BigEndian.Uint32(randID[:]) | |
725 | ||
726 | s.PrivateChats[data] = &PrivateChat{ | |
727 | ClientConn: make(map[uint16]*ClientConn), | |
728 | } | |
729 | s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc | |
730 | ||
731 | return randID | |
732 | } | |
733 | ||
734 | const dlFldrActionSendFile = 1 | |
735 | const dlFldrActionResumeFile = 2 | |
736 | const dlFldrActionNextFile = 3 | |
737 | ||
738 | // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection | |
739 | func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error { | |
740 | defer dontPanic(s.Logger) | |
741 | ||
742 | txBuf := make([]byte, 16) | |
743 | if _, err := io.ReadFull(rwc, txBuf); err != nil { | |
744 | return err | |
745 | } | |
746 | ||
747 | var t transfer | |
748 | if _, err := t.Write(txBuf); err != nil { | |
749 | return err | |
750 | } | |
751 | ||
752 | defer func() { | |
753 | s.mux.Lock() | |
754 | delete(s.fileTransfers, t.ReferenceNumber) | |
755 | s.mux.Unlock() | |
756 | ||
757 | // Wait a few seconds before closing the connection: this is a workaround for problems | |
758 | // observed with Windows clients where the client must initiate close of the TCP connection before | |
759 | // the server does. This is gross and seems unnecessary. TODO: Revisit? | |
760 | time.Sleep(3 * time.Second) | |
761 | }() | |
762 | ||
763 | s.mux.Lock() | |
764 | fileTransfer, ok := s.fileTransfers[t.ReferenceNumber] | |
765 | s.mux.Unlock() | |
766 | if !ok { | |
767 | return errors.New("invalid transaction ID") | |
768 | } | |
769 | ||
770 | defer func() { | |
771 | fileTransfer.ClientConn.transfersMU.Lock() | |
772 | delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber) | |
773 | fileTransfer.ClientConn.transfersMU.Unlock() | |
774 | }() | |
775 | ||
776 | rLogger := s.Logger.With( | |
777 | "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr, | |
778 | "login", fileTransfer.ClientConn.Account.Login, | |
779 | "name", string(fileTransfer.ClientConn.UserName), | |
780 | ) | |
781 | ||
782 | fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) | |
783 | if err != nil { | |
784 | return err | |
785 | } | |
786 | ||
787 | switch fileTransfer.Type { | |
788 | case bannerDownload: | |
789 | if err := s.bannerDownload(rwc); err != nil { | |
790 | return err | |
791 | } | |
792 | case FileDownload: | |
793 | s.Stats.DownloadCounter += 1 | |
794 | s.Stats.DownloadsInProgress += 1 | |
795 | defer func() { | |
796 | s.Stats.DownloadsInProgress -= 1 | |
797 | }() | |
798 | ||
799 | var dataOffset int64 | |
800 | if fileTransfer.fileResumeData != nil { | |
801 | dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) | |
802 | } | |
803 | ||
804 | fw, err := newFileWrapper(s.FS, fullPath, 0) | |
805 | if err != nil { | |
806 | return err | |
807 | } | |
808 | ||
809 | rLogger.Infow("File download started", "filePath", fullPath) | |
810 | ||
811 | // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client | |
812 | if fileTransfer.options == nil { | |
813 | // Start by sending flat file object to client | |
814 | if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil { | |
815 | return err | |
816 | } | |
817 | } | |
818 | ||
819 | file, err := fw.dataForkReader() | |
820 | if err != nil { | |
821 | return err | |
822 | } | |
823 | ||
824 | br := bufio.NewReader(file) | |
825 | if _, err := br.Discard(int(dataOffset)); err != nil { | |
826 | return err | |
827 | } | |
828 | ||
829 | if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil { | |
830 | return err | |
831 | } | |
832 | ||
833 | // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data | |
834 | if fileTransfer.fileResumeData == nil { | |
835 | err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader()) | |
836 | if err != nil { | |
837 | return err | |
838 | } | |
839 | } | |
840 | ||
841 | rFile, err := fw.rsrcForkFile() | |
842 | if err != nil { | |
843 | return nil | |
844 | } | |
845 | ||
846 | if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { | |
847 | return err | |
848 | } | |
849 | ||
850 | case FileUpload: | |
851 | s.Stats.UploadCounter += 1 | |
852 | s.Stats.UploadsInProgress += 1 | |
853 | defer func() { s.Stats.UploadsInProgress -= 1 }() | |
854 | ||
855 | var file *os.File | |
856 | ||
857 | // A file upload has three possible cases: | |
858 | // 1) Upload a new file | |
859 | // 2) Resume a partially transferred file | |
860 | // 3) Replace a fully uploaded file | |
861 | // We have to infer which case applies by inspecting what is already on the filesystem | |
862 | ||
863 | // 1) Check for existing file: | |
864 | _, err = os.Stat(fullPath) | |
865 | if err == nil { | |
866 | return errors.New("existing file found at " + fullPath) | |
867 | } | |
868 | if errors.Is(err, fs.ErrNotExist) { | |
869 | // If not found, open or create a new .incomplete file | |
870 | file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) | |
871 | if err != nil { | |
872 | return err | |
873 | } | |
874 | } | |
875 | ||
876 | f, err := newFileWrapper(s.FS, fullPath, 0) | |
877 | if err != nil { | |
878 | return err | |
879 | } | |
880 | ||
881 | rLogger.Infow("File upload started", "dstFile", fullPath) | |
882 | ||
883 | rForkWriter := io.Discard | |
884 | iForkWriter := io.Discard | |
885 | if s.Config.PreserveResourceForks { | |
886 | rForkWriter, err = f.rsrcForkWriter() | |
887 | if err != nil { | |
888 | return err | |
889 | } | |
890 | ||
891 | iForkWriter, err = f.infoForkWriter() | |
892 | if err != nil { | |
893 | return err | |
894 | } | |
895 | } | |
896 | ||
897 | if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { | |
898 | s.Logger.Error(err) | |
899 | } | |
900 | ||
901 | if err := file.Close(); err != nil { | |
902 | return err | |
903 | } | |
904 | ||
905 | if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil { | |
906 | return err | |
907 | } | |
908 | ||
909 | rLogger.Infow("File upload complete", "dstFile", fullPath) | |
910 | ||
911 | case FolderDownload: | |
912 | s.Stats.DownloadCounter += 1 | |
913 | s.Stats.DownloadsInProgress += 1 | |
914 | defer func() { s.Stats.DownloadsInProgress -= 1 }() | |
915 | ||
916 | // Folder Download flow: | |
917 | // 1. Get filePath from the transfer | |
918 | // 2. Iterate over files | |
919 | // 3. For each fileWrapper: | |
920 | // Send fileWrapper header to client | |
921 | // The client can reply in 3 ways: | |
922 | // | |
923 | // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed: | |
924 | // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper | |
925 | // | |
926 | // 2. If download of a fileWrapper is to be resumed: | |
927 | // client sends: | |
928 | // []byte{0x00, 0x02} // download folder action | |
929 | // [2]byte // Resume data size | |
930 | // []byte fileWrapper resume data (see myField_FileResumeData) | |
931 | // | |
932 | // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01} | |
933 | // | |
934 | // When download is requested (case 2 or 3), server replies with: | |
935 | // [4]byte - fileWrapper size | |
936 | // []byte - Flattened File Object | |
937 | // | |
938 | // After every fileWrapper download, client could request next fileWrapper with: | |
939 | // []byte{0x00, 0x03} | |
940 | // | |
941 | // This notifies the server to send the next item header | |
942 | ||
943 | basePathLen := len(fullPath) | |
944 | ||
945 | rLogger.Infow("Start folder download", "path", fullPath) | |
946 | ||
947 | nextAction := make([]byte, 2) | |
948 | if _, err := io.ReadFull(rwc, nextAction); err != nil { | |
949 | return err | |
950 | } | |
951 | ||
952 | i := 0 | |
953 | err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error { | |
954 | s.Stats.DownloadCounter += 1 | |
955 | i += 1 | |
956 | ||
957 | if err != nil { | |
958 | return err | |
959 | } | |
960 | ||
961 | // skip dot files | |
962 | if strings.HasPrefix(info.Name(), ".") { | |
963 | return nil | |
964 | } | |
965 | ||
966 | hlFile, err := newFileWrapper(s.FS, path, 0) | |
967 | if err != nil { | |
968 | return err | |
969 | } | |
970 | ||
971 | subPath := path[basePathLen+1:] | |
972 | rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir()) | |
973 | ||
974 | if i == 1 { | |
975 | return nil | |
976 | } | |
977 | ||
978 | fileHeader := NewFileHeader(subPath, info.IsDir()) | |
979 | ||
980 | // Send the fileWrapper header to client | |
981 | if _, err := rwc.Write(fileHeader.Payload()); err != nil { | |
982 | s.Logger.Errorf("error sending file header: %v", err) | |
983 | return err | |
984 | } | |
985 | ||
986 | // Read the client's Next Action request | |
987 | if _, err := io.ReadFull(rwc, nextAction); err != nil { | |
988 | return err | |
989 | } | |
990 | ||
991 | rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) | |
992 | ||
993 | var dataOffset int64 | |
994 | ||
995 | switch nextAction[1] { | |
996 | case dlFldrActionResumeFile: | |
997 | // get size of resumeData | |
998 | resumeDataByteLen := make([]byte, 2) | |
999 | if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil { | |
1000 | return err | |
1001 | } | |
1002 | ||
1003 | resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen) | |
1004 | resumeDataBytes := make([]byte, resumeDataLen) | |
1005 | if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil { | |
1006 | return err | |
1007 | } | |
1008 | ||
1009 | var frd FileResumeData | |
1010 | if err := frd.UnmarshalBinary(resumeDataBytes); err != nil { | |
1011 | return err | |
1012 | } | |
1013 | dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:])) | |
1014 | case dlFldrActionNextFile: | |
1015 | // client asked to skip this file | |
1016 | return nil | |
1017 | } | |
1018 | ||
1019 | if info.IsDir() { | |
1020 | return nil | |
1021 | } | |
1022 | ||
1023 | rLogger.Infow("File download started", | |
1024 | "fileName", info.Name(), | |
1025 | "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)), | |
1026 | ) | |
1027 | ||
1028 | // Send file size to client | |
1029 | if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil { | |
1030 | s.Logger.Error(err) | |
1031 | return err | |
1032 | } | |
1033 | ||
1034 | // Send ffo bytes to client | |
1035 | if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil { | |
1036 | s.Logger.Error(err) | |
1037 | return err | |
1038 | } | |
1039 | ||
1040 | file, err := s.FS.Open(path) | |
1041 | if err != nil { | |
1042 | return err | |
1043 | } | |
1044 | ||
1045 | // wr := bufio.NewWriterSize(rwc, 1460) | |
1046 | if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil { | |
1047 | return err | |
1048 | } | |
1049 | ||
1050 | if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 { | |
1051 | err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader()) | |
1052 | if err != nil { | |
1053 | return err | |
1054 | } | |
1055 | ||
1056 | rFile, err := hlFile.rsrcForkFile() | |
1057 | if err != nil { | |
1058 | return err | |
1059 | } | |
1060 | ||
1061 | if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { | |
1062 | return err | |
1063 | } | |
1064 | } | |
1065 | ||
1066 | // Read the client's Next Action request. This is always 3, I think? | |
1067 | if _, err := io.ReadFull(rwc, nextAction); err != nil { | |
1068 | return err | |
1069 | } | |
1070 | ||
1071 | return nil | |
1072 | }) | |
1073 | ||
1074 | if err != nil { | |
1075 | return err | |
1076 | } | |
1077 | ||
1078 | case FolderUpload: | |
1079 | s.Stats.UploadCounter += 1 | |
1080 | s.Stats.UploadsInProgress += 1 | |
1081 | defer func() { s.Stats.UploadsInProgress -= 1 }() | |
1082 | rLogger.Infow( | |
1083 | "Folder upload started", | |
1084 | "dstPath", fullPath, | |
1085 | "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize), | |
1086 | "FolderItemCount", fileTransfer.FolderItemCount, | |
1087 | ) | |
1088 | ||
1089 | // Check if the target folder exists. If not, create it. | |
1090 | if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) { | |
1091 | if err := s.FS.Mkdir(fullPath, 0777); err != nil { | |
1092 | return err | |
1093 | } | |
1094 | } | |
1095 | ||
1096 | // Begin the folder upload flow by sending the "next file action" to client | |
1097 | if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
1098 | return err | |
1099 | } | |
1100 | ||
1101 | fileSize := make([]byte, 4) | |
1102 | ||
1103 | for i := 0; i < fileTransfer.ItemCount(); i++ { | |
1104 | s.Stats.UploadCounter += 1 | |
1105 | ||
1106 | var fu folderUpload | |
1107 | if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil { | |
1108 | return err | |
1109 | } | |
1110 | if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil { | |
1111 | return err | |
1112 | } | |
1113 | if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil { | |
1114 | return err | |
1115 | } | |
1116 | ||
1117 | fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes | |
1118 | ||
1119 | if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil { | |
1120 | return err | |
1121 | } | |
1122 | ||
1123 | rLogger.Infow( | |
1124 | "Folder upload continued", | |
1125 | "FormattedPath", fu.FormattedPath(), | |
1126 | "IsFolder", fmt.Sprintf("%x", fu.IsFolder), | |
1127 | "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), | |
1128 | ) | |
1129 | ||
1130 | if fu.IsFolder == [2]byte{0, 1} { | |
1131 | if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) { | |
1132 | if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil { | |
1133 | return err | |
1134 | } | |
1135 | } | |
1136 | ||
1137 | // Tell client to send next file | |
1138 | if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
1139 | return err | |
1140 | } | |
1141 | } else { | |
1142 | nextAction := dlFldrActionSendFile | |
1143 | ||
1144 | // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. | |
1145 | _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath())) | |
1146 | if err != nil && !errors.Is(err, fs.ErrNotExist) { | |
1147 | return err | |
1148 | } | |
1149 | if err == nil { | |
1150 | nextAction = dlFldrActionNextFile | |
1151 | } | |
1152 | ||
1153 | // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. | |
1154 | incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix)) | |
1155 | if err != nil && !errors.Is(err, fs.ErrNotExist) { | |
1156 | return err | |
1157 | } | |
1158 | if err == nil { | |
1159 | nextAction = dlFldrActionResumeFile | |
1160 | } | |
1161 | ||
1162 | if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil { | |
1163 | return err | |
1164 | } | |
1165 | ||
1166 | switch nextAction { | |
1167 | case dlFldrActionNextFile: | |
1168 | continue | |
1169 | case dlFldrActionResumeFile: | |
1170 | offset := make([]byte, 4) | |
1171 | binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size())) | |
1172 | ||
1173 | file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) | |
1174 | if err != nil { | |
1175 | return err | |
1176 | } | |
1177 | ||
1178 | fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)}) | |
1179 | ||
1180 | b, _ := fileResumeData.BinaryMarshal() | |
1181 | ||
1182 | bs := make([]byte, 2) | |
1183 | binary.BigEndian.PutUint16(bs, uint16(len(b))) | |
1184 | ||
1185 | if _, err := rwc.Write(append(bs, b...)); err != nil { | |
1186 | return err | |
1187 | } | |
1188 | ||
1189 | if _, err := io.ReadFull(rwc, fileSize); err != nil { | |
1190 | return err | |
1191 | } | |
1192 | ||
1193 | if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil { | |
1194 | s.Logger.Error(err) | |
1195 | } | |
1196 | ||
1197 | err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath()) | |
1198 | if err != nil { | |
1199 | return err | |
1200 | } | |
1201 | ||
1202 | case dlFldrActionSendFile: | |
1203 | if _, err := io.ReadFull(rwc, fileSize); err != nil { | |
1204 | return err | |
1205 | } | |
1206 | ||
1207 | filePath := filepath.Join(fullPath, fu.FormattedPath()) | |
1208 | ||
1209 | hlFile, err := newFileWrapper(s.FS, filePath, 0) | |
1210 | if err != nil { | |
1211 | return err | |
1212 | } | |
1213 | ||
1214 | rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize)) | |
1215 | ||
1216 | incWriter, err := hlFile.incFileWriter() | |
1217 | if err != nil { | |
1218 | return err | |
1219 | } | |
1220 | ||
1221 | rForkWriter := io.Discard | |
1222 | iForkWriter := io.Discard | |
1223 | if s.Config.PreserveResourceForks { | |
1224 | iForkWriter, err = hlFile.infoForkWriter() | |
1225 | if err != nil { | |
1226 | return err | |
1227 | } | |
1228 | ||
1229 | rForkWriter, err = hlFile.rsrcForkWriter() | |
1230 | if err != nil { | |
1231 | return err | |
1232 | } | |
1233 | } | |
1234 | if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { | |
1235 | return err | |
1236 | } | |
1237 | ||
1238 | if err := os.Rename(filePath+".incomplete", filePath); err != nil { | |
1239 | return err | |
1240 | } | |
1241 | } | |
1242 | ||
1243 | // Tell client to send next fileWrapper | |
1244 | if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
1245 | return err | |
1246 | } | |
1247 | } | |
1248 | } | |
1249 | rLogger.Infof("Folder upload complete") | |
1250 | } | |
1251 | ||
1252 | return nil | |
1253 | } |