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