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