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