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