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