]>
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 | |
f4cdaddc JH |
568 | // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the |
569 | // scanner re-uses the buffer for subsequent scans. | |
570 | buf := make([]byte, len(scanner.Bytes())) | |
571 | copy(buf, scanner.Bytes()) | |
572 | ||
854a92fc | 573 | var clientLogin Transaction |
f4cdaddc | 574 | if _, err := clientLogin.Write(buf); err != nil { |
854a92fc | 575 | return err |
6988a057 JH |
576 | } |
577 | ||
3178ae58 | 578 | c := s.NewClientConn(rwc, remoteAddr) |
46862572 JH |
579 | |
580 | // check if remoteAddr is present in the ban list | |
581 | if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok { | |
582 | // permaban | |
583 | if banUntil == nil { | |
584 | s.outbox <- *NewTransaction( | |
585 | tranServerMsg, | |
586 | c.ID, | |
587 | NewField(fieldData, []byte("You are permanently banned on this server")), | |
588 | NewField(fieldChatOptions, []byte{0, 0}), | |
589 | ) | |
590 | time.Sleep(1 * time.Second) | |
591 | return nil | |
592 | } else if time.Now().Before(*banUntil) { | |
593 | s.outbox <- *NewTransaction( | |
594 | tranServerMsg, | |
595 | c.ID, | |
596 | NewField(fieldData, []byte("You are temporarily banned on this server")), | |
597 | NewField(fieldChatOptions, []byte{0, 0}), | |
598 | ) | |
599 | time.Sleep(1 * time.Second) | |
600 | return nil | |
601 | } | |
602 | ||
603 | } | |
6988a057 | 604 | defer c.Disconnect() |
6988a057 JH |
605 | |
606 | encodedLogin := clientLogin.GetField(fieldUserLogin).Data | |
607 | encodedPassword := clientLogin.GetField(fieldUserPassword).Data | |
a7216f67 | 608 | c.Version = clientLogin.GetField(fieldVersion).Data |
6988a057 JH |
609 | |
610 | var login string | |
611 | for _, char := range encodedLogin { | |
612 | login += string(rune(255 - uint(char))) | |
613 | } | |
614 | if login == "" { | |
615 | login = GuestAccount | |
616 | } | |
617 | ||
0da28a1f JH |
618 | c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login) |
619 | ||
6988a057 JH |
620 | // If authentication fails, send error reply and close connection |
621 | if !c.Authenticate(login, encodedPassword) { | |
854a92fc | 622 | t := c.NewErrReply(&clientLogin, "Incorrect login.") |
72dd37f1 JH |
623 | b, err := t.MarshalBinary() |
624 | if err != nil { | |
625 | return err | |
626 | } | |
3178ae58 | 627 | if _, err := rwc.Write(b); err != nil { |
6988a057 JH |
628 | return err |
629 | } | |
0da28a1f | 630 | |
a7216f67 | 631 | c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version)) |
0da28a1f JH |
632 | |
633 | return nil | |
6988a057 JH |
634 | } |
635 | ||
59097464 | 636 | if clientLogin.GetField(fieldUserIconID).Data != nil { |
a7216f67 | 637 | c.Icon = clientLogin.GetField(fieldUserIconID).Data |
59097464 JH |
638 | } |
639 | ||
640 | c.Account = c.Server.Accounts[login] | |
641 | ||
6988a057 | 642 | if clientLogin.GetField(fieldUserName).Data != nil { |
ea5d8c51 JH |
643 | if c.Authorize(accessAnyName) { |
644 | c.UserName = clientLogin.GetField(fieldUserName).Data | |
645 | } else { | |
646 | c.UserName = []byte(c.Account.Name) | |
647 | } | |
6988a057 JH |
648 | } |
649 | ||
6988a057 | 650 | if c.Authorize(accessDisconUser) { |
a7216f67 | 651 | c.Flags = []byte{0, 2} |
6988a057 JH |
652 | } |
653 | ||
854a92fc | 654 | s.outbox <- c.NewReply(&clientLogin, |
6988a057 | 655 | NewField(fieldVersion, []byte{0x00, 0xbe}), |
9067f234 | 656 | NewField(fieldCommunityBannerID, []byte{0, 0}), |
6988a057 JH |
657 | NewField(fieldServerName, []byte(s.Config.Name)), |
658 | ) | |
659 | ||
660 | // Send user access privs so client UI knows how to behave | |
187d6dc5 | 661 | c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:])) |
6988a057 | 662 | |
a322be02 JH |
663 | // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between |
664 | // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send | |
665 | // tranShowAgreement but with the NoServerAgreement field set to 1. | |
688c86d2 | 666 | if c.Authorize(accessNoAgreement) { |
a322be02 JH |
667 | // If client version is nil, then the client uses the 1.2.3 login behavior |
668 | if c.Version != nil { | |
669 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1})) | |
670 | } | |
688c86d2 JH |
671 | } else { |
672 | c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement)) | |
673 | } | |
6988a057 | 674 | |
a82b93cf | 675 | // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed |
361928c9 | 676 | if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) { |
bd1ce113 | 677 | c.Agreed = true |
67db911d | 678 | c.logger = c.logger.With("name", string(c.UserName)) |
0db54aa7 | 679 | c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }())) |
67db911d | 680 | |
21581958 | 681 | for _, t := range c.notifyOthers( |
003a743e JH |
682 | *NewTransaction( |
683 | tranNotifyChangeUser, nil, | |
684 | NewField(fieldUserName, c.UserName), | |
685 | NewField(fieldUserID, *c.ID), | |
a7216f67 JH |
686 | NewField(fieldUserIconID, c.Icon), |
687 | NewField(fieldUserFlags, c.Flags), | |
003a743e | 688 | ), |
21581958 JH |
689 | ) { |
690 | c.Server.outbox <- t | |
691 | } | |
6988a057 | 692 | } |
bd1ce113 | 693 | |
00913df3 JH |
694 | c.Server.Stats.ConnectionCounter += 1 |
695 | if len(s.Clients) > c.Server.Stats.ConnectionPeak { | |
696 | c.Server.Stats.ConnectionPeak = len(s.Clients) | |
697 | } | |
6988a057 | 698 | |
3178ae58 JH |
699 | // Scan for new transactions and handle them as they come in. |
700 | for scanner.Scan() { | |
701 | // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the | |
702 | // scanner re-uses the buffer for subsequent scans. | |
703 | buf := make([]byte, len(scanner.Bytes())) | |
704 | copy(buf, scanner.Bytes()) | |
6988a057 | 705 | |
854a92fc JH |
706 | var t Transaction |
707 | if _, err := t.Write(buf); err != nil { | |
708 | return err | |
6988a057 | 709 | } |
854a92fc JH |
710 | |
711 | if err := c.handleTransaction(t); err != nil { | |
0fcfa5d5 | 712 | c.logger.Errorw("Error handling transaction", "err", err) |
6988a057 | 713 | } |
6988a057 | 714 | } |
3178ae58 | 715 | return nil |
6988a057 JH |
716 | } |
717 | ||
6988a057 | 718 | func (s *Server) NewPrivateChat(cc *ClientConn) []byte { |
c1c44744 JH |
719 | s.PrivateChatsMu.Lock() |
720 | defer s.PrivateChatsMu.Unlock() | |
6988a057 JH |
721 | |
722 | randID := make([]byte, 4) | |
723 | rand.Read(randID) | |
724 | data := binary.BigEndian.Uint32(randID[:]) | |
725 | ||
726 | s.PrivateChats[data] = &PrivateChat{ | |
6988a057 JH |
727 | ClientConn: make(map[uint16]*ClientConn), |
728 | } | |
729 | s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc | |
730 | ||
731 | return randID | |
732 | } | |
733 | ||
734 | const dlFldrActionSendFile = 1 | |
735 | const dlFldrActionResumeFile = 2 | |
736 | const dlFldrActionNextFile = 3 | |
737 | ||
85767504 | 738 | // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection |
7cd900d6 | 739 | func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error { |
37a954c8 | 740 | defer dontPanic(s.Logger) |
0a92e50b | 741 | |
2e7c03cf | 742 | txBuf := make([]byte, 16) |
7cd900d6 | 743 | if _, err := io.ReadFull(rwc, txBuf); err != nil { |
6988a057 JH |
744 | return err |
745 | } | |
746 | ||
df2735b2 | 747 | var t transfer |
0a92e50b | 748 | if _, err := t.Write(txBuf); err != nil { |
6988a057 JH |
749 | return err |
750 | } | |
751 | ||
0a92e50b JH |
752 | defer func() { |
753 | s.mux.Lock() | |
df1ade54 | 754 | delete(s.fileTransfers, t.ReferenceNumber) |
0a92e50b | 755 | s.mux.Unlock() |
df1ade54 | 756 | |
94742e2f JH |
757 | // Wait a few seconds before closing the connection: this is a workaround for problems |
758 | // observed with Windows clients where the client must initiate close of the TCP connection before | |
759 | // the server does. This is gross and seems unnecessary. TODO: Revisit? | |
760 | time.Sleep(3 * time.Second) | |
0a92e50b | 761 | }() |
6988a057 | 762 | |
0a92e50b | 763 | s.mux.Lock() |
df1ade54 | 764 | fileTransfer, ok := s.fileTransfers[t.ReferenceNumber] |
0a92e50b JH |
765 | s.mux.Unlock() |
766 | if !ok { | |
767 | return errors.New("invalid transaction ID") | |
768 | } | |
16a4ad70 | 769 | |
df1ade54 JH |
770 | defer func() { |
771 | fileTransfer.ClientConn.transfersMU.Lock() | |
772 | delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber) | |
773 | fileTransfer.ClientConn.transfersMU.Unlock() | |
774 | }() | |
775 | ||
7cd900d6 JH |
776 | rLogger := s.Logger.With( |
777 | "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr, | |
df1ade54 JH |
778 | "login", fileTransfer.ClientConn.Account.Login, |
779 | "name", string(fileTransfer.ClientConn.UserName), | |
7cd900d6 JH |
780 | ) |
781 | ||
df1ade54 JH |
782 | fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) |
783 | if err != nil { | |
784 | return err | |
785 | } | |
786 | ||
6988a057 | 787 | switch fileTransfer.Type { |
9067f234 JH |
788 | case bannerDownload: |
789 | if err := s.bannerDownload(rwc); err != nil { | |
790 | return err | |
791 | } | |
6988a057 | 792 | case FileDownload: |
23411fc2 | 793 | s.Stats.DownloadCounter += 1 |
00913df3 | 794 | s.Stats.DownloadsInProgress += 1 |
94742e2f JH |
795 | defer func() { |
796 | s.Stats.DownloadsInProgress -= 1 | |
797 | }() | |
23411fc2 | 798 | |
16a4ad70 JH |
799 | var dataOffset int64 |
800 | if fileTransfer.fileResumeData != nil { | |
801 | dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) | |
802 | } | |
803 | ||
df1ade54 | 804 | fw, err := newFileWrapper(s.FS, fullPath, 0) |
6988a057 JH |
805 | if err != nil { |
806 | return err | |
807 | } | |
808 | ||
df1ade54 | 809 | rLogger.Infow("File download started", "filePath", fullPath) |
7cd900d6 JH |
810 | |
811 | // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client | |
d1cd6664 JH |
812 | if fileTransfer.options == nil { |
813 | // Start by sending flat file object to client | |
df1ade54 | 814 | if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil { |
d1cd6664 JH |
815 | return err |
816 | } | |
6988a057 JH |
817 | } |
818 | ||
7cd900d6 | 819 | file, err := fw.dataForkReader() |
6988a057 JH |
820 | if err != nil { |
821 | return err | |
822 | } | |
823 | ||
df1ade54 JH |
824 | br := bufio.NewReader(file) |
825 | if _, err := br.Discard(int(dataOffset)); err != nil { | |
7cd900d6 JH |
826 | return err |
827 | } | |
828 | ||
df1ade54 | 829 | if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil { |
7cd900d6 JH |
830 | return err |
831 | } | |
832 | ||
df1ade54 | 833 | // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data |
7cd900d6 | 834 | if fileTransfer.fileResumeData == nil { |
df1ade54 | 835 | err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader()) |
16a4ad70 JH |
836 | if err != nil { |
837 | return err | |
838 | } | |
6988a057 | 839 | } |
7cd900d6 JH |
840 | |
841 | rFile, err := fw.rsrcForkFile() | |
842 | if err != nil { | |
843 | return nil | |
844 | } | |
845 | ||
df1ade54 | 846 | if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { |
7cd900d6 JH |
847 | return err |
848 | } | |
849 | ||
6988a057 | 850 | case FileUpload: |
23411fc2 | 851 | s.Stats.UploadCounter += 1 |
00913df3 JH |
852 | s.Stats.UploadsInProgress += 1 |
853 | defer func() { s.Stats.UploadsInProgress -= 1 }() | |
23411fc2 | 854 | |
5c14e4c9 JH |
855 | var file *os.File |
856 | ||
857 | // A file upload has three possible cases: | |
858 | // 1) Upload a new file | |
859 | // 2) Resume a partially transferred file | |
860 | // 3) Replace a fully uploaded file | |
7cd900d6 | 861 | // We have to infer which case applies by inspecting what is already on the filesystem |
5c14e4c9 JH |
862 | |
863 | // 1) Check for existing file: | |
df1ade54 | 864 | _, err = os.Stat(fullPath) |
5c14e4c9 | 865 | if err == nil { |
df1ade54 | 866 | return errors.New("existing file found at " + fullPath) |
5c14e4c9 | 867 | } |
16a4ad70 | 868 | if errors.Is(err, fs.ErrNotExist) { |
7cd900d6 | 869 | // If not found, open or create a new .incomplete file |
df1ade54 | 870 | file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) |
16a4ad70 JH |
871 | if err != nil { |
872 | return err | |
873 | } | |
6988a057 | 874 | } |
16a4ad70 | 875 | |
df1ade54 | 876 | f, err := newFileWrapper(s.FS, fullPath, 0) |
7cd900d6 JH |
877 | if err != nil { |
878 | return err | |
879 | } | |
880 | ||
df1ade54 | 881 | rLogger.Infow("File upload started", "dstFile", fullPath) |
6988a057 | 882 | |
7cd900d6 JH |
883 | rForkWriter := io.Discard |
884 | iForkWriter := io.Discard | |
885 | if s.Config.PreserveResourceForks { | |
886 | rForkWriter, err = f.rsrcForkWriter() | |
887 | if err != nil { | |
888 | return err | |
889 | } | |
890 | ||
891 | iForkWriter, err = f.infoForkWriter() | |
892 | if err != nil { | |
893 | return err | |
894 | } | |
895 | } | |
896 | ||
df1ade54 JH |
897 | if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { |
898 | s.Logger.Error(err) | |
16a4ad70 JH |
899 | } |
900 | ||
e00ff8fe JH |
901 | if err := file.Close(); err != nil { |
902 | return err | |
903 | } | |
67db911d | 904 | |
df1ade54 | 905 | if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil { |
16a4ad70 | 906 | return err |
6988a057 | 907 | } |
85767504 | 908 | |
df1ade54 | 909 | rLogger.Infow("File upload complete", "dstFile", fullPath) |
00913df3 | 910 | |
6988a057 | 911 | case FolderDownload: |
00913df3 JH |
912 | s.Stats.DownloadCounter += 1 |
913 | s.Stats.DownloadsInProgress += 1 | |
914 | defer func() { s.Stats.DownloadsInProgress -= 1 }() | |
915 | ||
6988a057 | 916 | // Folder Download flow: |
df2735b2 | 917 | // 1. Get filePath from the transfer |
6988a057 | 918 | // 2. Iterate over files |
7cd900d6 JH |
919 | // 3. For each fileWrapper: |
920 | // Send fileWrapper header to client | |
6988a057 JH |
921 | // The client can reply in 3 ways: |
922 | // | |
7cd900d6 JH |
923 | // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed: |
924 | // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper | |
6988a057 | 925 | // |
7cd900d6 | 926 | // 2. If download of a fileWrapper is to be resumed: |
6988a057 JH |
927 | // client sends: |
928 | // []byte{0x00, 0x02} // download folder action | |
929 | // [2]byte // Resume data size | |
7cd900d6 | 930 | // []byte fileWrapper resume data (see myField_FileResumeData) |
6988a057 | 931 | // |
7cd900d6 | 932 | // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01} |
6988a057 JH |
933 | // |
934 | // When download is requested (case 2 or 3), server replies with: | |
7cd900d6 | 935 | // [4]byte - fileWrapper size |
6988a057 JH |
936 | // []byte - Flattened File Object |
937 | // | |
7cd900d6 | 938 | // After every fileWrapper download, client could request next fileWrapper with: |
6988a057 JH |
939 | // []byte{0x00, 0x03} |
940 | // | |
941 | // This notifies the server to send the next item header | |
942 | ||
df1ade54 | 943 | basePathLen := len(fullPath) |
6988a057 | 944 | |
df1ade54 | 945 | rLogger.Infow("Start folder download", "path", fullPath) |
6988a057 | 946 | |
85767504 | 947 | nextAction := make([]byte, 2) |
7cd900d6 | 948 | if _, err := io.ReadFull(rwc, nextAction); err != nil { |
85767504 JH |
949 | return err |
950 | } | |
6988a057 JH |
951 | |
952 | i := 0 | |
df1ade54 | 953 | err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error { |
23411fc2 | 954 | s.Stats.DownloadCounter += 1 |
7cd900d6 | 955 | i += 1 |
23411fc2 | 956 | |
85767504 JH |
957 | if err != nil { |
958 | return err | |
959 | } | |
7cd900d6 JH |
960 | |
961 | // skip dot files | |
962 | if strings.HasPrefix(info.Name(), ".") { | |
963 | return nil | |
964 | } | |
965 | ||
966 | hlFile, err := newFileWrapper(s.FS, path, 0) | |
967 | if err != nil { | |
968 | return err | |
969 | } | |
970 | ||
85767504 | 971 | subPath := path[basePathLen+1:] |
df1ade54 | 972 | rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir()) |
6988a057 | 973 | |
6988a057 JH |
974 | if i == 1 { |
975 | return nil | |
976 | } | |
977 | ||
85767504 JH |
978 | fileHeader := NewFileHeader(subPath, info.IsDir()) |
979 | ||
7cd900d6 JH |
980 | // Send the fileWrapper header to client |
981 | if _, err := rwc.Write(fileHeader.Payload()); err != nil { | |
6988a057 JH |
982 | s.Logger.Errorf("error sending file header: %v", err) |
983 | return err | |
984 | } | |
985 | ||
986 | // Read the client's Next Action request | |
7cd900d6 | 987 | if _, err := io.ReadFull(rwc, nextAction); err != nil { |
6988a057 JH |
988 | return err |
989 | } | |
990 | ||
df1ade54 | 991 | rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) |
6988a057 | 992 | |
16a4ad70 JH |
993 | var dataOffset int64 |
994 | ||
995 | switch nextAction[1] { | |
996 | case dlFldrActionResumeFile: | |
16a4ad70 | 997 | // get size of resumeData |
7cd900d6 JH |
998 | resumeDataByteLen := make([]byte, 2) |
999 | if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil { | |
16a4ad70 JH |
1000 | return err |
1001 | } | |
1002 | ||
7cd900d6 | 1003 | resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen) |
16a4ad70 | 1004 | resumeDataBytes := make([]byte, resumeDataLen) |
7cd900d6 | 1005 | if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil { |
16a4ad70 JH |
1006 | return err |
1007 | } | |
1008 | ||
7cd900d6 | 1009 | var frd FileResumeData |
16a4ad70 JH |
1010 | if err := frd.UnmarshalBinary(resumeDataBytes); err != nil { |
1011 | return err | |
1012 | } | |
1013 | dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:])) | |
1014 | case dlFldrActionNextFile: | |
1015 | // client asked to skip this file | |
1016 | return nil | |
1017 | } | |
1018 | ||
6988a057 JH |
1019 | if info.IsDir() { |
1020 | return nil | |
1021 | } | |
1022 | ||
df1ade54 | 1023 | rLogger.Infow("File download started", |
6988a057 | 1024 | "fileName", info.Name(), |
7cd900d6 | 1025 | "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)), |
6988a057 JH |
1026 | ) |
1027 | ||
1028 | // Send file size to client | |
7cd900d6 | 1029 | if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil { |
6988a057 JH |
1030 | s.Logger.Error(err) |
1031 | return err | |
1032 | } | |
1033 | ||
85767504 | 1034 | // Send ffo bytes to client |
7cd900d6 | 1035 | if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil { |
6988a057 JH |
1036 | s.Logger.Error(err) |
1037 | return err | |
1038 | } | |
1039 | ||
b196a50a | 1040 | file, err := s.FS.Open(path) |
6988a057 JH |
1041 | if err != nil { |
1042 | return err | |
1043 | } | |
1044 | ||
7cd900d6 | 1045 | // wr := bufio.NewWriterSize(rwc, 1460) |
df1ade54 | 1046 | if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil { |
7cd900d6 JH |
1047 | return err |
1048 | } | |
1049 | ||
1050 | if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 { | |
1051 | err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader()) | |
16a4ad70 | 1052 | if err != nil { |
7cd900d6 | 1053 | return err |
16a4ad70 | 1054 | } |
16a4ad70 | 1055 | |
7cd900d6 JH |
1056 | rFile, err := hlFile.rsrcForkFile() |
1057 | if err != nil { | |
1058 | return err | |
1059 | } | |
16a4ad70 | 1060 | |
df1ade54 | 1061 | if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { |
16a4ad70 JH |
1062 | return err |
1063 | } | |
85767504 | 1064 | } |
6988a057 | 1065 | |
16a4ad70 | 1066 | // Read the client's Next Action request. This is always 3, I think? |
7cd900d6 | 1067 | if _, err := io.ReadFull(rwc, nextAction); err != nil { |
85767504 | 1068 | return err |
6988a057 | 1069 | } |
85767504 | 1070 | |
16a4ad70 | 1071 | return nil |
6988a057 JH |
1072 | }) |
1073 | ||
67db911d JH |
1074 | if err != nil { |
1075 | return err | |
1076 | } | |
1077 | ||
6988a057 | 1078 | case FolderUpload: |
00913df3 JH |
1079 | s.Stats.UploadCounter += 1 |
1080 | s.Stats.UploadsInProgress += 1 | |
1081 | defer func() { s.Stats.UploadsInProgress -= 1 }() | |
df1ade54 | 1082 | rLogger.Infow( |
6988a057 | 1083 | "Folder upload started", |
df1ade54 JH |
1084 | "dstPath", fullPath, |
1085 | "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize), | |
6988a057 JH |
1086 | "FolderItemCount", fileTransfer.FolderItemCount, |
1087 | ) | |
1088 | ||
1089 | // Check if the target folder exists. If not, create it. | |
df1ade54 JH |
1090 | if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) { |
1091 | if err := s.FS.Mkdir(fullPath, 0777); err != nil { | |
16a4ad70 | 1092 | return err |
6988a057 JH |
1093 | } |
1094 | } | |
1095 | ||
6988a057 | 1096 | // Begin the folder upload flow by sending the "next file action" to client |
7cd900d6 | 1097 | if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { |
6988a057 JH |
1098 | return err |
1099 | } | |
1100 | ||
1101 | fileSize := make([]byte, 4) | |
16a4ad70 JH |
1102 | |
1103 | for i := 0; i < fileTransfer.ItemCount(); i++ { | |
ba29c43b JH |
1104 | s.Stats.UploadCounter += 1 |
1105 | ||
1106 | var fu folderUpload | |
7cd900d6 | 1107 | if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil { |
ba29c43b JH |
1108 | return err |
1109 | } | |
7cd900d6 | 1110 | if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil { |
ba29c43b JH |
1111 | return err |
1112 | } | |
7cd900d6 | 1113 | if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil { |
ba29c43b JH |
1114 | return err |
1115 | } | |
ba29c43b | 1116 | |
7cd900d6 JH |
1117 | fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes |
1118 | ||
1119 | if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil { | |
6988a057 JH |
1120 | return err |
1121 | } | |
6988a057 | 1122 | |
df1ade54 | 1123 | rLogger.Infow( |
6988a057 | 1124 | "Folder upload continued", |
6988a057 JH |
1125 | "FormattedPath", fu.FormattedPath(), |
1126 | "IsFolder", fmt.Sprintf("%x", fu.IsFolder), | |
c5d9af5a | 1127 | "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), |
6988a057 JH |
1128 | ) |
1129 | ||
c5d9af5a | 1130 | if fu.IsFolder == [2]byte{0, 1} { |
df1ade54 JH |
1131 | if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) { |
1132 | if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil { | |
16a4ad70 | 1133 | return err |
6988a057 JH |
1134 | } |
1135 | } | |
1136 | ||
1137 | // Tell client to send next file | |
7cd900d6 | 1138 | if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { |
6988a057 JH |
1139 | return err |
1140 | } | |
1141 | } else { | |
16a4ad70 JH |
1142 | nextAction := dlFldrActionSendFile |
1143 | ||
1144 | // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. | |
df1ade54 | 1145 | _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath())) |
16a4ad70 | 1146 | if err != nil && !errors.Is(err, fs.ErrNotExist) { |
6988a057 JH |
1147 | return err |
1148 | } | |
16a4ad70 JH |
1149 | if err == nil { |
1150 | nextAction = dlFldrActionNextFile | |
1151 | } | |
6988a057 | 1152 | |
16a4ad70 | 1153 | // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. |
df1ade54 | 1154 | incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix)) |
16a4ad70 | 1155 | if err != nil && !errors.Is(err, fs.ErrNotExist) { |
85767504 | 1156 | return err |
6988a057 | 1157 | } |
16a4ad70 JH |
1158 | if err == nil { |
1159 | nextAction = dlFldrActionResumeFile | |
1160 | } | |
6988a057 | 1161 | |
7cd900d6 | 1162 | if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil { |
85767504 JH |
1163 | return err |
1164 | } | |
1165 | ||
16a4ad70 JH |
1166 | switch nextAction { |
1167 | case dlFldrActionNextFile: | |
1168 | continue | |
1169 | case dlFldrActionResumeFile: | |
1170 | offset := make([]byte, 4) | |
7cd900d6 | 1171 | binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size())) |
16a4ad70 | 1172 | |
df1ade54 | 1173 | file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) |
16a4ad70 JH |
1174 | if err != nil { |
1175 | return err | |
1176 | } | |
1177 | ||
7cd900d6 | 1178 | fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)}) |
16a4ad70 JH |
1179 | |
1180 | b, _ := fileResumeData.BinaryMarshal() | |
1181 | ||
1182 | bs := make([]byte, 2) | |
1183 | binary.BigEndian.PutUint16(bs, uint16(len(b))) | |
1184 | ||
7cd900d6 | 1185 | if _, err := rwc.Write(append(bs, b...)); err != nil { |
16a4ad70 JH |
1186 | return err |
1187 | } | |
1188 | ||
7cd900d6 | 1189 | if _, err := io.ReadFull(rwc, fileSize); err != nil { |
16a4ad70 JH |
1190 | return err |
1191 | } | |
1192 | ||
df1ade54 | 1193 | if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil { |
16a4ad70 JH |
1194 | s.Logger.Error(err) |
1195 | } | |
1196 | ||
df1ade54 | 1197 | err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath()) |
16a4ad70 JH |
1198 | if err != nil { |
1199 | return err | |
1200 | } | |
1201 | ||
1202 | case dlFldrActionSendFile: | |
7cd900d6 | 1203 | if _, err := io.ReadFull(rwc, fileSize); err != nil { |
16a4ad70 JH |
1204 | return err |
1205 | } | |
1206 | ||
df1ade54 | 1207 | filePath := filepath.Join(fullPath, fu.FormattedPath()) |
16a4ad70 | 1208 | |
7cd900d6 | 1209 | hlFile, err := newFileWrapper(s.FS, filePath, 0) |
16a4ad70 JH |
1210 | if err != nil { |
1211 | return err | |
1212 | } | |
1213 | ||
df1ade54 | 1214 | rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize)) |
7cd900d6 JH |
1215 | |
1216 | incWriter, err := hlFile.incFileWriter() | |
1217 | if err != nil { | |
1218 | return err | |
1219 | } | |
1220 | ||
1221 | rForkWriter := io.Discard | |
1222 | iForkWriter := io.Discard | |
1223 | if s.Config.PreserveResourceForks { | |
1224 | iForkWriter, err = hlFile.infoForkWriter() | |
1225 | if err != nil { | |
1226 | return err | |
1227 | } | |
1228 | ||
1229 | rForkWriter, err = hlFile.rsrcForkWriter() | |
1230 | if err != nil { | |
1231 | return err | |
1232 | } | |
16a4ad70 | 1233 | } |
df1ade54 | 1234 | if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { |
7cd900d6 JH |
1235 | return err |
1236 | } | |
df1ade54 | 1237 | |
16a4ad70 JH |
1238 | if err := os.Rename(filePath+".incomplete", filePath); err != nil { |
1239 | return err | |
1240 | } | |
6988a057 JH |
1241 | } |
1242 | ||
7cd900d6 JH |
1243 | // Tell client to send next fileWrapper |
1244 | if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { | |
6988a057 JH |
1245 | return err |
1246 | } | |
6988a057 JH |
1247 | } |
1248 | } | |
df1ade54 | 1249 | rLogger.Infof("Folder upload complete") |
6988a057 JH |
1250 | } |
1251 | ||
1252 | return nil | |
1253 | } |