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