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