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