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