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