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