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