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