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