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