-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiles.go
More file actions
2427 lines (2223 loc) · 87.2 KB
/
files.go
File metadata and controls
2427 lines (2223 loc) · 87.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/sha1"
"crypto/tls"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
proxyproto "github.com/pires/go-proxyproto"
"golang.org/x/net/webdav"
)
// serverPublicBaseURL is set from --url (no trailing slash). Empty means use the HTTP request host for generated links.
var serverPublicBaseURL string
// serverNamePrefix and serverNameSuffix are set from --prefix / --suffix (display labels only; URLs still use displayName).
var serverNamePrefix, serverNameSuffix string
// getRealIP extracts the real client IP from the request, handling proxy headers
// Checks headers in order: X-Forwarded-For, X-Real-IP, X-Forwarded, CF-Connecting-IP
// Falls back to RemoteAddr if no proxy headers are present
func getRealIP(r *http.Request) string {
// Check X-Forwarded-For header (most common, can contain multiple IPs)
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
// X-Forwarded-For can contain multiple IPs: "client, proxy1, proxy2"
// The first one is the original client IP
ips := strings.Split(xff, ",")
if len(ips) > 0 {
ip := strings.TrimSpace(ips[0])
if ip != "" {
return ip
}
}
}
// Check X-Real-IP header (common in nginx and other proxies)
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return strings.TrimSpace(xri)
}
// Check X-Forwarded header
if xf := r.Header.Get("X-Forwarded"); xf != "" {
// X-Forwarded format: "for=192.0.2.60;proto=http;by=203.0.113.43"
parts := strings.Split(xf, ";")
for _, part := range parts {
if strings.HasPrefix(part, "for=") {
ip := strings.TrimPrefix(part, "for=")
ip = strings.TrimSpace(ip)
// Remove port if present (for=192.0.2.60:12345)
if idx := strings.LastIndex(ip, ":"); idx > 0 {
ip = ip[:idx]
}
if ip != "" {
return ip
}
}
}
}
// Check CF-Connecting-IP (Cloudflare)
if cfip := r.Header.Get("CF-Connecting-IP"); cfip != "" {
return strings.TrimSpace(cfip)
}
// Fall back to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
// If SplitHostPort fails, RemoteAddr might not have a port
return r.RemoteAddr
}
return ip
}
// copyClientsSnapshot returns a sorted copy of per-client full/partial stats (for JSON APIs).
func copyClientsSnapshot() []apiDownloadClient {
perClientMu.Lock()
defer perClientMu.Unlock()
ips := make([]string, 0, len(perClientFileStats))
for ip := range perClientFileStats {
ips = append(ips, ip)
}
sort.Strings(ips)
clients := make([]apiDownloadClient, 0, len(ips))
for _, ip := range ips {
m := perClientFileStats[ip]
paths := make([]string, 0, len(m))
for p := range m {
paths = append(paths, p)
}
sort.Strings(paths)
files := make([]apiDownloadFile, 0, len(paths))
for _, p := range paths {
st := m[p]
files = append(files, apiDownloadFile{Path: p, Full: st.Full, Partial: st.Partial})
}
clients = append(clients, apiDownloadClient{IP: ip, Files: files})
}
return clients
}
func buildAPIStatusResponse() apiStatusResponse {
statsMutex.Lock()
paths := make([]string, 0, len(downloadStats))
for p := range downloadStats {
paths = append(paths, p)
}
sort.Strings(paths)
files := make([]apiStatusFile, 0, len(paths))
var totalDL int64
for _, p := range paths {
s := downloadStats[p]
totalDL += s.Bytes
files = append(files, apiStatusFile{Path: p, Count: s.Count, Bytes: s.Bytes})
}
listing := totalBytesSentForListings
statsMutex.Unlock()
return apiStatusResponse{
Version: getAppVersion(),
TotalDownloadBytes: totalDL,
TotalListingBytes: listing,
Files: files,
Clients: copyClientsSnapshot(),
Activity: copyActivitySnapshot(),
Events: copyServerEventsSnapshot(),
}
}
// logFileTransferStart prints when the server is about to send a file body (GET), so operators see activity before a long transfer finishes.
func logFileTransferStart(clientIP, relPath, mode string, isRange bool, fileSize int64) {
m := mode
if m == "" {
m = "download"
}
rng := "range_request=false"
if isRange {
rng = "range_request=true"
}
outPrintf("[download-start] client_ip=%s path=%s mode=%s %s size=%d\n", clientIP, relPath, m, rng, fileSize)
}
func serveFile(w http.ResponseWriter, r *http.Request, bandwidthLimit int64, validatedPath string, mode string) {
clientIP := getRealIP(r)
isHEAD := r.Method == "HEAD"
if t := r.URL.Query().Get("token"); t != "" {
if !tryConsumeOneTimeToken(t) {
http.Error(w, "Invalid or expired one-time token", http.StatusForbidden)
return
}
}
// Default behavior is download unless explicitly overridden.
switch mode {
case "", "download":
filename := filepath.Base(validatedPath)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
case "play":
// Let browser play/render inline based on content type.
case "preview":
// Inline in browser (images, PDF, text, etc.); no attachment header.
case "stream":
// Serve an M3U playlist pointing to the inline-play URL so external
// players (VLC/mpv/etc.) can open the stream reliably across browsers.
var streamURL string
if serverPublicBaseURL != "" {
streamURL = serverPublicBaseURL + r.URL.Path + "?mode=play"
} else {
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
streamURL = fmt.Sprintf("%s://%s%s?mode=play", scheme, r.Host, r.URL.Path)
}
filename := filepath.Base(validatedPath)
w.Header().Set("Content-Type", "audio/x-mpegurl; charset=utf-8")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename+".m3u"))
if isHEAD {
w.WriteHeader(http.StatusOK)
return
}
relM3U := normalizeStatsPath(getRelativePath(validatedPath, allowedPaths))
outPrintf("[download-start] client_ip=%s path=%s mode=stream kind=m3u_playlist\n", clientIP, relM3U)
_, _ = fmt.Fprintf(w, "#EXTM3U\n#EXTINF:-1,%s\n%s\n", filename, streamURL)
return
default:
// Unknown mode falls back to safe default (download).
filename := filepath.Base(validatedPath)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
}
// Apply bandwidth limiting if specified (not needed for HEAD requests)
finalWriter := http.ResponseWriter(w)
if bandwidthLimit > 0 && !isHEAD {
finalWriter = &rateLimitedWriter{
ResponseWriter: w,
bytesPerSecond: bandwidthLimit,
lastWrite: time.Now(),
}
}
// Determine the file size
fileInfo, err := os.Stat(validatedPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
fileSize := fileInfo.Size()
relKey := normalizeStatsPath(getRelativePath(validatedPath, allowedPaths))
if !isHEAD {
if bytesLimitExceeded() {
http.Error(w, "Byte limit for this share has been reached", http.StatusServiceUnavailable)
return
}
if serverCfg.MaxDownloadPerFile > 0 {
statsMutex.Lock()
n := downloadStats[relKey].Count
statsMutex.Unlock()
if n >= serverCfg.MaxDownloadPerFile {
http.Error(w, "Max download count reached for this file", http.StatusForbidden)
return
}
}
}
// Password-protected zstd download (--encrypt): only for attachment-style download, not play/preview/stream
if serverCfg.EncryptPassword != "" && (mode == "" || mode == "download") {
relPath := getRelativePath(validatedPath, allowedPaths)
fw := http.ResponseWriter(w)
if bandwidthLimit > 0 && !isHEAD {
fw = &rateLimitedWriter{
ResponseWriter: w,
bytesPerSecond: bandwidthLimit,
lastWrite: time.Now(),
}
}
if isHEAD {
if err := serveEncryptedZstd(fw, r, validatedPath, serverCfg.EncryptPassword); err != nil {
return
}
return
}
cw := &countingWriter{
ResponseWriter: fw,
path: relPath,
clientIP: clientIP,
isRangeRequest: false,
fileSize: 0,
startedAt: time.Now(),
}
logFileTransferStart(clientIP, relPath, mode, false, fileSize)
if err := serveEncryptedZstd(cw, r, validatedPath, serverCfg.EncryptPassword); err != nil {
return
}
cw.finish()
return
}
// Check if this is a Range request (for resuming downloads or partial fetches)
isRangeRequest := r.Header.Get("Range") != ""
// Only wrap with countingWriter if not HEAD (HEAD requests don't send body, so no need to count)
var cw *countingWriter
if !isHEAD {
// Use relative path for logging to avoid leaking full paths
relPath := getRelativePath(validatedPath, allowedPaths)
cw = &countingWriter{
ResponseWriter: finalWriter,
path: relPath,
clientIP: clientIP,
isRangeRequest: isRangeRequest,
fileSize: fileSize,
startedAt: time.Now(),
}
finalWriter = cw
logFileTransferStart(clientIP, relPath, mode, isRangeRequest, fileSize)
}
// http.ServeFile automatically handles HTTP Range requests (206 Partial Content)
// and HEAD requests (returns headers only, no body)
// This enables resuming downloads, partial file fetches, and probing files without downloading
// Use validatedPath to ensure we only serve allowed files
http.ServeFile(finalWriter, r, validatedPath)
// Only track stats and check completion for non-HEAD requests
if !isHEAD && cw != nil {
cw.finish()
// Check if the download was complete (only warn for non-Range requests)
// Range requests intentionally send fewer bytes, so don't warn for those
if !isRangeRequest && cw.bytesWritten < fileSize {
relPath := getRelativePath(validatedPath, allowedPaths)
outPrintf("Warning: File %s was not fully downloaded. Sent %d bytes out of %d total bytes.\n", relPath, cw.bytesWritten, fileSize)
}
}
}
// updateLastActivity updates the last activity timestamp (thread-safe)
func updateLastActivity() {
lastActivityMu.Lock()
lastActivity = time.Now()
lastActivityMu.Unlock()
}
// effectiveListRoots includes --upload dir in listings when it is not already shared.
func effectiveListRoots(filePaths []string) []string {
out := append([]string{}, filePaths...)
if serverCfg.UploadDir == "" {
return out
}
u := filepath.Clean(serverCfg.UploadDir)
for _, p := range out {
ap, err := filepath.Abs(p)
if err != nil {
continue
}
if filepath.Clean(ap) == u {
return out
}
}
return append(out, serverCfg.UploadDir)
}
// serveFiles sets up the HTTP server and handlers.
func serveFiles(filePaths []string, ip string, port string, showHidden bool, hash bool, maxHashSize int64, bandwidthLimit int64, colorScheme *colorScheme, enableReload bool, idleTimeout time.Duration, publicBaseURL string, namePrefix string, nameSuffix string, frpProxy bool) {
serverPublicBaseURL = publicBaseURL
serverNamePrefix = namePrefix
serverNameSuffix = nameSuffix
// Initialize allowed paths for security validation
if err := initAllowedPaths(filePaths); err != nil {
outPrintf("Error initializing allowed paths: %v\n", err)
os.Exit(1)
}
if serverCfg.UploadDir != "" {
if err := registerUploadDir(serverCfg.UploadDir); err != nil {
outPrintf("Error: upload directory: %v\n", err)
os.Exit(1)
}
outPrintf("Upload target: %s (POST /api/upload)\n", serverCfg.UploadDir)
}
listRoots := effectiveListRoots(filePaths)
// Set up idle timeout tracking
if idleTimeout > 0 {
// Initialize last activity to now
updateLastActivity()
// Start idle timeout checker
go func() {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for range ticker.C {
lastActivityMu.RLock()
last := lastActivity
lastActivityMu.RUnlock()
if time.Since(last) >= idleTimeout {
outPrintf("\n[Idle Timeout] No activity for %v, shutting down server...\n", idleTimeout)
// Cleanup rate limiter
rateLimiterMutex.Lock()
if globalRateLimiter != nil {
globalRateLimiter.stop()
}
rateLimiterMutex.Unlock()
// Cleanup file watcher
fileWatcherMutex.Lock()
if globalFileWatcher != nil {
globalFileWatcher.stop()
}
fileWatcherMutex.Unlock()
// Shutdown HTTP server gracefully
httpServerMu.RLock()
server := httpServer
httpServerMu.RUnlock()
if server != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := server.Shutdown(ctx); err != nil {
outPrintf("[Idle Timeout] Error shutting down server: %v\n", err)
}
cancel()
}
printStats()
os.Exit(0)
}
}
}()
outPrintf("[Idle Timeout] Server will shut down after %v of inactivity\n", idleTimeout)
}
// API endpoint for JSON data
http.HandleFunc("/api/events", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
handleEventsJSON(w, r)
}))
http.HandleFunc("/events", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
handleEventsSSE(w, r)
}))
http.HandleFunc("/manifest.json", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
handleManifestJSON(w, r, listRoots, showHidden, hash, maxHashSize)
}))
if serverCfg.UploadDir != "" {
http.HandleFunc("/api/upload", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
handleUpload(w, r)
ip := getRealIP(r)
recordActivity(ip, "upload", "POST /api/upload")
}))
}
http.HandleFunc("/api/one-time-token", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet && r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
tok := issueOneTimeToken()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(map[string]string{"token": tok})
}))
if serverCfg.EnableStatsPage {
http.HandleFunc("/stats", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(buildAPIStatusResponse())
}))
}
if serverCfg.EnableSingleStream {
http.HandleFunc("/archive", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
handleArchive(w, r)
}))
}
http.HandleFunc("/api/files", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get path parameter (optional, defaults to root)
requestedPath := strings.TrimSpace(r.URL.Query().Get("path"))
if requestedPath != "" {
if decoded, err := url.PathUnescape(requestedPath); err == nil {
requestedPath = decoded
}
before := strings.Trim(requestedPath, "/")
requestedPath = normalizeURLPath(requestedPath)
if requestedPath == "" && before != "" {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
}
var filesInfo []FileInfo
var err error
displayBasePath := ""
useDisplayBasePath := false
if requestedPath == "" {
// Root path - list all shared files/directories
filesInfo, err = listFiles(listRoots, showHidden, hash, maxHashSize)
} else {
// Validate path
validatedPath, allowed := isPathAllowed(requestedPath)
if !allowed {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
var fileInfo os.FileInfo
fileInfo, err = os.Stat(validatedPath)
if err != nil {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
if fileInfo.IsDir() {
filesInfo, err = listFilesInDir(validatedPath, showHidden, hash, maxHashSize)
displayBasePath = validatedPath
useDisplayBasePath = true
} else {
// Single file
filesInfo = []FileInfo{{
Name: validatedPath,
DisplayName: getRelativePath(validatedPath, allowedPaths),
Size: fileInfo.Size(),
ModTime: fileInfo.ModTime(),
IsDir: false,
}}
err = nil
}
}
if err != nil {
http.Error(w, "Failed to list files", http.StatusInternalServerError)
return
}
// Convert to display names and calculate totals
displayFiles := make([]FileInfo, len(filesInfo))
var totalSize int64
var fileCount int
for i, f := range filesInfo {
displayFiles[i] = f
if displayFiles[i].DisplayName == "" {
if useDisplayBasePath {
relPath, relErr := filepath.Rel(displayBasePath, f.Name)
if relErr == nil && !strings.HasPrefix(relPath, "..") {
// Use slash separators in URLs regardless of host OS.
displayFiles[i].DisplayName = filepath.ToSlash(relPath)
} else {
displayFiles[i].DisplayName = getRelativePath(f.Name, allowedPaths)
}
} else {
displayFiles[i].DisplayName = getRelativePath(f.Name, allowedPaths)
}
}
// Check if it's a directory
fileInfo, err := os.Stat(f.Name)
if err == nil {
displayFiles[i].IsDir = fileInfo.IsDir()
if !fileInfo.IsDir() {
totalSize += f.Size
fileCount++
}
}
}
for i := range displayFiles {
decorateFileDisplay(&displayFiles[i])
if !displayFiles[i].IsDir {
displayFiles[i].DownloadCount = lookupDownloadCount(displayFiles[i].DisplayName)
}
}
// Return JSON response
w.Header().Set("Content-Type", "application/json")
response := apiResponse{
Files: displayFiles,
TotalSize: totalSize,
FileCount: fileCount,
ShowHash: hash,
}
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
ip := getRealIP(r)
listDetail := "path=(root)"
if requestedPath != "" {
listDetail = "path=" + filepath.ToSlash(requestedPath)
}
recordActivity(ip, "list", listDetail)
}))
// API endpoint for searching files/directories by name
http.HandleFunc("/api/search", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
query := strings.TrimSpace(r.URL.Query().Get("q"))
requestedPath := strings.TrimSpace(r.URL.Query().Get("path"))
if requestedPath != "" {
if decoded, err := url.PathUnescape(requestedPath); err == nil {
requestedPath = decoded
}
before := strings.Trim(requestedPath, "/")
requestedPath = normalizeURLPath(requestedPath)
if requestedPath == "" && before != "" {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
}
if query == "" {
http.Error(w, "Missing search query", http.StatusBadRequest)
return
}
// Determine search base paths.
searchBases := make([]string, 0)
useRelativeToBase := false
if requestedPath == "" {
searchBases = append(searchBases, allowedPaths...)
} else {
validatedPath, allowed := isPathAllowed(requestedPath)
if !allowed {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
info, err := os.Stat(validatedPath)
if err != nil {
http.Error(w, "Path not found", http.StatusNotFound)
return
}
if info.IsDir() {
searchBases = append(searchBases, validatedPath)
useRelativeToBase = true
} else {
// If searching from a file path, search in its parent directory.
searchBases = append(searchBases, filepath.Dir(validatedPath))
useRelativeToBase = true
}
}
filesInfo, err := searchFiles(searchBases, query, showHidden, hash, maxHashSize, useRelativeToBase)
if err != nil {
http.Error(w, "Failed to search files", http.StatusInternalServerError)
return
}
var totalSize int64
var fileCount int
for _, f := range filesInfo {
if !f.IsDir {
totalSize += f.Size
fileCount++
}
}
for i := range filesInfo {
decorateFileDisplay(&filesInfo[i])
if !filesInfo[i].IsDir {
filesInfo[i].DownloadCount = lookupDownloadCount(filesInfo[i].DisplayName)
}
}
w.Header().Set("Content-Type", "application/json")
response := apiResponse{
Files: filesInfo,
TotalSize: totalSize,
FileCount: fileCount,
ShowHash: hash,
}
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
searchDetail := fmt.Sprintf("q=%q", query)
if requestedPath != "" {
searchDetail += fmt.Sprintf(" scope=%q", filepath.ToSlash(requestedPath))
}
recordActivity(getRealIP(r), "search", searchDetail)
}))
// GET /api/downloads — per-client IP: which files were fetched in full vs partial (Range/incomplete)
http.HandleFunc("/api/downloads", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
clients := copyClientsSnapshot()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(apiDownloadsResponse{Clients: clients})
}))
// GET /api/status — aggregate download and listing stats (for scripts and shareplane status)
http.HandleFunc("/api/status", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(buildAPIStatusResponse())
}))
// GET /verify?file=relative/path — returns JSON with SHA1 for a single shared file
http.HandleFunc("/verify", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
q := strings.TrimSpace(r.URL.Query().Get("file"))
if q == "" {
q = strings.TrimSpace(r.URL.Query().Get("path"))
}
if q == "" {
http.Error(w, "Missing file or path query parameter", http.StatusBadRequest)
return
}
if decoded, err := url.PathUnescape(q); err == nil {
q = decoded
}
before := strings.Trim(q, "/")
q = normalizeURLPath(q)
if q == "" && before != "" {
http.Error(w, "File not found", http.StatusNotFound)
return
}
validatedPath, allowed := isPathAllowed(q)
if !allowed {
http.Error(w, "File not found", http.StatusNotFound)
return
}
info, err := os.Stat(validatedPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
if info.IsDir() {
http.Error(w, "Path is a directory, not a file", http.StatusBadRequest)
return
}
hash, err := calculateSHA1(validatedPath)
if err != nil {
http.Error(w, "Failed to read file", http.StatusInternalServerError)
return
}
rel := getRelativePath(validatedPath, allowedPaths)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(struct {
SHA1 string `json:"sha1"`
Path string `json:"path"`
}{SHA1: hash, Path: rel})
}))
http.HandleFunc("/", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
if r.URL.Path != "/" {
// Strip the leading slash and validate path
requestedPath := r.URL.Path[1:]
decodedPath, err := url.PathUnescape(requestedPath)
if err == nil {
requestedPath = decodedPath
}
beforeNorm := strings.Trim(requestedPath, "/")
requestedPath = normalizeURLPath(requestedPath)
if requestedPath == "" && beforeNorm != "" {
http.Error(w, "File not found", http.StatusNotFound)
return
}
// SECURITY: Validate that the requested path is within allowed directories
validatedPath, allowed := isPathAllowed(requestedPath)
if !allowed {
http.Error(w, "File not found", http.StatusNotFound)
return
}
fileInfo, err := os.Stat(validatedPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
if fileInfo.IsDir() {
// Handle HEAD requests for directories
if r.Method == "HEAD" {
// Return headers only for HEAD requests on directories
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
return
}
// It's a directory - serve the client-side HTML app with path parameter
if r.Method == http.MethodGet {
recordActivity(getRealIP(r), "browse", "path=/"+filepath.ToSlash(requestedPath))
}
renderClientApp(w, hash, colorScheme, getAppVersion(), serverCfg.EnableQR, serverCfg.EnableSingleStream, serverCfg.UploadDir != "")
return
}
// It's a file, serve it normally (validatedPath is already validated)
mode := r.URL.Query().Get("mode")
serveFile(w, r, bandwidthLimit, validatedPath, mode)
return
}
// Root path - serve the client-side HTML app
// Handle HEAD requests for root
if r.Method == "HEAD" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
return
}
// Serve the client-side HTML that will fetch from /api/files
if r.Method == http.MethodGet {
recordActivity(getRealIP(r), "browse", "path=/")
}
renderClientApp(w, hash, colorScheme, getAppVersion(), serverCfg.EnableQR, serverCfg.EnableSingleStream, serverCfg.UploadDir != "")
}))
// Start file watcher if reload is enabled
if enableReload {
fileWatcherMutex.Lock()
watcher, err := newFileWatcher(listRoots, showHidden)
if err != nil {
outPrintf("Warning: Failed to initialize file watcher: %v\n", err)
outPrintln("Auto-reload will not be available.")
} else {
globalFileWatcher = watcher
globalFileWatcher.start()
outPrintln("Auto-reload enabled: monitoring files for changes in real-time...")
}
fileWatcherMutex.Unlock()
}
listenAddress := fmt.Sprintf("%s:%s", ip, port)
tlsCfg, err := tlsConfigForServer()
if err != nil {
outPrintf("TLS: %v\n", err)
os.Exit(1)
}
scheme := "http"
if tlsCfg != nil {
scheme = "https"
}
// If listening on 0.0.0.0, show all available IP addresses
if ip == "0.0.0.0" {
outPrintf("Serving on %s://%s\n", scheme, listenAddress)
outPrintln("Available on:")
interfaces, err := net.Interfaces()
if err == nil {
for _, iface := range interfaces {
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
outPrintf(" %s://%s:%s\n", scheme, ipNet.IP.String(), port)
}
}
}
}
}
// Also show localhost
outPrintf(" %s://127.0.0.1:%s\n", scheme, port)
outPrintf(" %s://localhost:%s\n", scheme, port)
} else {
outPrintf("Serving on %s://%s\n", scheme, listenAddress)
}
if tlsCfg != nil {
if serverCfg.TLSCertFile != "" {
outPrintf("TLS: using certificate file %s and key %s\n", serverCfg.TLSCertFile, serverCfg.TLSKeyFile)
} else {
outPrintln("Using ephemeral TLS certificate (self-signed, not saved). Expect browser warnings.")
}
} else if frpProxy {
outPrintln("Note: --frp only applies when TLS is enabled (--https or --cert and --key).")
}
// Create HTTP server for graceful shutdown support
server := &http.Server{
Addr: listenAddress,
Handler: nil,
}
// Store server reference for idle timeout shutdown
httpServerMu.Lock()
httpServer = server
httpServerMu.Unlock()
if serverCfg.EnableWebDAV {
rootDav := allowedPaths[0]
if len(allowedPaths) > 1 {
outPrintln("Note: --webdav exports only the first shared path as WebDAV root.")
}
wdh := &webdav.Handler{
FileSystem: webdav.Dir(rootDav),
LockSystem: webdav.NewMemLS(),
}
http.Handle("/webdav/", wrapHandler(func(w http.ResponseWriter, r *http.Request) {
updateLastActivity()
http.StripPrefix("/webdav", wdh).ServeHTTP(w, r)
}))
outPrintf("WebDAV enabled at /webdav/ (root: %s)\n", rootDav)
}
if !serverCfg.TTLDeadline.IsZero() {
d := time.Until(serverCfg.TTLDeadline)
if d > 0 {
outPrintf("Share TTL: server stops after %v (at %s UTC)\n", d, serverCfg.TTLDeadline.UTC().Format(time.RFC3339))
go func() {
time.Sleep(d)
outPrintln("Share TTL expired; shutting down...")
httpServerMu.RLock()
srv := httpServer
httpServerMu.RUnlock()
if srv != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_ = srv.Shutdown(ctx)
cancel()
}
printStats()
os.Exit(0)
}()
}
}
// Plain HTTP: always accept optional HAProxy PROXY v1/v2 before HTTP.
// HTTPS: wrap with PROXY listener only when --frp (upstream sends PROXY before TLS).
baseListener, err := net.Listen("tcp", listenAddress)
if err != nil {
log.Fatal(err)
}
proxyLn := &proxyproto.Listener{
Listener: baseListener,
ReadHeaderTimeout: 5 * time.Second,
}
var outer net.Listener
if tlsCfg != nil {
if frpProxy {
outer = tls.NewListener(proxyLn, tlsCfg)
outPrintln("TLS (--frp): PROXY protocol v1/v2, when sent by the upstream, is handled before the TLS handshake.")
} else {
outer = tls.NewListener(baseListener, tlsCfg)
}
} else {
outer = proxyLn
}
if serverCfg.EnableTUI {
go func() {
if err := server.Serve(outer); err != nil && err != http.ErrServerClosed {
outPrintf("HTTP server: %v\n", err)
}
}()
runTUIBlocking(port)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_ = server.Shutdown(ctx)
cancel()
printStats()
os.Exit(0)
return
}
if err := server.Serve(outer); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}
// isHidden checks if a file or directory name starts with a dot (hidden file).
func isHidden(name string) bool {
base := filepath.Base(name)
return len(base) > 0 && base[0] == '.'
}
// calculateSHA1 calculates the SHA1 hash of a file.
func calculateSHA1(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer func() {
_ = file.Close()
}()
hash := sha1.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil