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