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