-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2808 lines (2449 loc) · 75.3 KB
/
main.go
File metadata and controls
2808 lines (2449 loc) · 75.3 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 (
"archive/zip"
"bufio"
"bytes"
"context"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"html"
"html/template"
"io"
"mime"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
"unicode/utf8"
)
var version = "dev"
// Indirections for testability
var (
exitFunc = os.Exit
listenAndServe = func(srv *http.Server) error { return srv.ListenAndServe() }
pidFile = ""
logFile = ""
logMutex sync.Mutex
)
// ===== ANSI Color Codes =====
const (
// Reset all attributes
colorReset = "\033[0m"
// Text colors
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorYellow = "\033[33m"
colorBlue = "\033[34m"
colorMagenta = "\033[35m"
colorCyan = "\033[36m"
colorWhite = "\033[37m"
// Bright text colors
colorBrightBlack = "\033[90m"
colorBrightGreen = "\033[92m"
colorBrightYellow = "\033[93m"
colorBrightCyan = "\033[96m"
// Text attributes
colorBold = "\033[1m"
)
const helpTpl = `Welcome to <span class="ps1">lsget</span> <span style="color: #666;">v{{.Version}}</span>!
<span style="color: #888;">Type one of the commands below to get started.</span>
<br/>
<span style="color: #aaa;">Available commands:</span>
• <strong>help</strong> - <span style="color: #bbb;">print this message again</span>
• <strong>pwd</strong> - <span style="color: #bbb;">print working directory</span>
• <strong>ls</strong> <span style="color: #888;">[-l] [-h]</span>|<strong>dir</strong> <span style="color: #888;">[-l] [-h]</span> - <span style="color: #bbb;">list files (-h for human readable sizes)</span>
• <strong>cd</strong> <span style="color: #888;">DIR</span> - <span style="color: #bbb;">change directory</span>
• <strong>cat</strong> <span style="color: #888;">FILE</span> - <span style="color: #bbb;">view a text file</span>
• <strong>sum</strong>|<strong>checksum</strong> <span style="color: #888;">FILE</span> - <span style="color: #bbb;">print MD5 and SHA256 checksums</span>
• <strong>get</strong>|<strong>wget</strong>|<strong>download</strong> <span style="color: #888;">FILE</span> - <span style="color: #bbb;">download a file</span>
• <strong>url</strong>|<strong>share</strong> <span style="color: #888;">FILE</span> - <span style="color: #bbb;">get shareable URL (copies to clipboard)</span>
• <strong>tree</strong> <span style="color: #888;">[-L<DEPTH>] [-a]</span> - <span style="color: #bbb;">directory structure</span>
• <strong>find</strong> <span style="color: #888;">[PATH] [-name PATTERN] [-type f|d]</span> - <span style="color: #bbb;">search for files and directories</span>
• <strong>grep</strong> <span style="color: #888;">[-r] [-i] [-n] PATTERN [FILE...]</span> - <span style="color: #bbb;">search for text patterns in files</span>
<br/><br/>
<span style="color: #aaa;">Hint: to autocomplete filenames and dir use</span> <kbd class="ps1">Tab</kbd>
`
func renderHelp() string {
helpMessage := template.Must(template.New("help").Parse(helpTpl))
var b bytes.Buffer
_ = helpMessage.Execute(&b, struct{ Version string }{Version: version})
return b.String()
}
// getFileColor returns the appropriate ANSI color code for a file based on its type and permissions
func getFileColor(info os.FileInfo, name string) string {
mode := info.Mode()
// Directories
if mode.IsDir() {
return colorBlue + colorBold
}
// Executable files
if mode&0o111 != 0 {
return colorGreen
}
// Symbolic links
if mode&os.ModeSymlink != 0 {
return colorCyan
}
// Special files
if mode&os.ModeNamedPipe != 0 {
return colorYellow
}
if mode&os.ModeSocket != 0 {
return colorMagenta
}
if mode&os.ModeDevice != 0 {
return colorYellow + colorBold
}
// Regular files - color by extension
ext := strings.ToLower(filepath.Ext(name))
switch ext {
case ".tar", ".tgz", ".tar.gz", ".tar.bz2", ".tar.xz", ".zip", ".rar", ".7z", ".gz", ".bz2", ".xz":
return colorRed
case ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".ico", ".tiff", ".webp":
return colorMagenta
case ".mp3", ".wav", ".flac", ".aac", ".ogg", ".wma", ".m4a":
return colorGreen
case ".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm", ".m4v":
return colorBrightGreen
case ".pdf", ".doc", ".docx", ".txt", ".md", ".rst", ".tex":
return colorWhite
case ".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".rs", ".cpp", ".c", ".h", ".java", ".kt", ".swift":
return colorYellow
case ".html", ".htm", ".css", ".scss", ".sass", ".xml", ".json", ".yaml", ".yml":
return colorBrightYellow
case ".sh", ".bash", ".zsh", ".fish", ".ps1", ".bat", ".cmd":
return colorGreen
case ".sql", ".db", ".sqlite", ".sqlite3":
return colorBrightCyan
case ".log", ".tmp", ".temp", ".bak", ".backup":
return colorBrightBlack
default:
return colorReset
}
}
// colorizeName wraps a filename with appropriate ANSI color codes
func colorizeName(info os.FileInfo, name string) string {
color := getFileColor(info, name)
// Add trailing / for directories (Unix style)
if info.IsDir() {
return color + name + "/" + colorReset
}
return color + name + colorReset
}
// FileCategory represents supported file types for different commands
type FileCategory int
const (
FileCategoryUnknown FileCategory = iota
FileCategoryText
FileCategoryImage
FileCategoryArchive
FileCategoryVideo
FileCategoryAudio
FileCategoryDocument
)
func (fc FileCategory) String() string {
switch fc {
case FileCategoryText:
return "text"
case FileCategoryImage:
return "image"
case FileCategoryArchive:
return "archive"
case FileCategoryVideo:
return "video"
case FileCategoryAudio:
return "audio"
case FileCategoryDocument:
return "document"
default:
return "unknown"
}
}
// getFileCategory determines the category of a file by extension
func getFileCategory(filename string) FileCategory {
ext := strings.ToLower(filepath.Ext(filename))
switch ext {
// Text files
case ".txt", ".md", ".rst", ".log", ".json", ".xml", ".yaml", ".yml", ".toml", ".ini", ".conf", ".cfg":
return FileCategoryText
case ".html", ".htm", ".css", ".js", ".ts", ".jsx", ".tsx":
return FileCategoryText
case ".c", ".cpp", ".h", ".hpp", ".go", ".rs", ".py", ".rb", ".java", ".php", ".sh", ".bash":
return FileCategoryText
// Images
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".ico":
return FileCategoryImage
// Archives
case ".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".tgz", ".tbz2":
return FileCategoryArchive
// Video
case ".mp4", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".webm", ".m4v":
return FileCategoryVideo
// Audio
case ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".wma":
return FileCategoryAudio
// Documents
case ".pdf", ".doc", ".docx", ".odt", ".xls", ".xlsx", ".ppt", ".pptx":
return FileCategoryDocument
default:
return FileCategoryUnknown
}
}
// readDocFile returns the raw contents of documentation files if present in dir.
// Supports README.md, .txt, .nfo, and .rst files in priority order.
func readDocFile(dir string) (string, string) {
ents, err := os.ReadDir(dir)
if err != nil {
return "", ""
}
// Priority order for documentation files
docFiles := []struct {
pattern string
fileType string
}{
{"README.md", "markdown"},
{"readme.md", "markdown"},
{"README.txt", "text"},
{"readme.txt", "text"},
{"README.rst", "rst"},
{"readme.rst", "rst"},
{"README.nfo", "nfo"},
{"readme.nfo", "nfo"},
}
// First, try exact matches in priority order
for _, docFile := range docFiles {
for _, e := range ents {
if !e.Type().IsRegular() {
continue
}
if strings.EqualFold(e.Name(), docFile.pattern) {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
return string(b), docFile.fileType
}
}
}
// Then try any file with supported extensions
for _, e := range ents {
if !e.Type().IsRegular() {
continue
}
name := strings.ToLower(e.Name())
if strings.HasSuffix(name, ".md") {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
return string(b), "markdown"
} else if strings.HasSuffix(name, ".txt") {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
return string(b), "text"
} else if strings.HasSuffix(name, ".rst") {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
return string(b), "rst"
} else if strings.HasSuffix(name, ".nfo") {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
return string(b), "nfo"
}
}
return "", ""
}
// ===== Embed a fallback index.html (used only if the file isn't on disk) =====
//go:embed index.html
var embeddedIndex []byte
//go:embed assets/js/marked.min.js
var embeddedMarkedJS []byte
//go:embed assets/js/datastar.js
var embeddedDatastarJS []byte
// ===== Server state =====
type session struct {
// virtual cwd like "/sub/dir"
cwd string
}
type server struct {
rootAbs string // absolute filesystem root we expose
catMax int64 // max bytes allowed for `cat`
sessions map[string]*session
mu sync.RWMutex
logfile string // path to log file for statistics
baseURL string // optional: public base URL (e.g., https://files.example.com) - auto-detects from request if empty
}
func newServer(rootAbs string, catMax int64, logfile, baseURL string) *server {
return &server{
rootAbs: rootAbs,
catMax: catMax,
sessions: make(map[string]*session),
logfile: logfile,
baseURL: baseURL,
}
}
// ===== .lsgetignore support =====
// parseIgnoreFile reads and parses a .lsgetignore file, returning a slice of patterns
func parseIgnoreFile(ignoreFilePath string) ([]string, error) {
file, err := os.Open(ignoreFilePath)
if err != nil {
if os.IsNotExist(err) {
return nil, nil // No ignore file is fine
}
return nil, err
}
defer func() { _ = file.Close() }()
var patterns []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
// Skip empty lines and comments
if line == "" || strings.HasPrefix(line, "#") {
continue
}
patterns = append(patterns, line)
}
return patterns, scanner.Err()
}
// shouldIgnore checks if a file/directory should be ignored based on .lsgetignore patterns
// It looks for .lsgetignore files in the current directory and all parent directories up to rootAbs
func (s *server) shouldIgnore(realPath, name string) bool {
// Start from the directory containing the file/directory
currentDir := filepath.Dir(realPath)
// Walk up the directory tree until we reach rootAbs
for {
// Check if we've gone above the root directory
rel, err := filepath.Rel(s.rootAbs, currentDir)
if err != nil || strings.HasPrefix(rel, "..") {
break
}
// Look for .lsgetignore in current directory
ignoreFile := filepath.Join(currentDir, ".lsgetignore")
patterns, err := parseIgnoreFile(ignoreFile)
if err == nil && len(patterns) > 0 {
// Check if the file matches any pattern
for _, pattern := range patterns {
// Support both simple filename matching and path-based matching
matched, err := filepath.Match(pattern, name)
if err == nil && matched {
return true
}
// Also check if the pattern matches the relative path from current directory
relPath, err := filepath.Rel(currentDir, realPath)
if err == nil {
matched, err := filepath.Match(pattern, relPath)
if err == nil && matched {
return true
}
// Also check directory-based patterns
if strings.Contains(relPath, "/") {
matched, err := filepath.Match(pattern, filepath.Base(relPath))
if err == nil && matched {
return true
}
}
}
}
}
// Move up one directory
parentDir := filepath.Dir(currentDir)
if parentDir == currentDir {
break // Reached root
}
currentDir = parentDir
}
return false
}
// ===== Utilities =====
// sitemapEntry represents an entry in the sitemap
type sitemapEntry struct {
loc string
lastmod string
isImage bool
imageURL string
isVideo bool
videoURL string
isDocument bool
isDir bool
fileSize int64
}
// generateSitemap creates a sitemap.xml file in the root directory
func (s *server) generateSitemap() error {
if s.baseURL == "" {
return nil
}
var entries []sitemapEntry
err := filepath.Walk(s.rootAbs, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if s.shouldIgnore(path, filepath.Base(path)) {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
vp, err := s.virtualFromReal(path)
if err != nil {
return nil
}
// Format lastmod in W3C Datetime format (ISO 8601)
lastmod := info.ModTime().Format(time.RFC3339)
entry := sitemapEntry{
loc: s.baseURL + vp,
lastmod: lastmod,
isDir: info.IsDir(),
}
// Check file category for special handling
if !info.IsDir() {
entry.fileSize = info.Size()
category := getFileCategory(filepath.Base(path))
switch category {
case FileCategoryImage:
entry.isImage = true
entry.imageURL = s.baseURL + vp
case FileCategoryVideo:
entry.isVideo = true
entry.videoURL = s.baseURL + vp
case FileCategoryDocument:
entry.isDocument = true
}
}
entries = append(entries, entry)
return nil
})
if err != nil {
return err
}
// Build XML with proper namespaces
var xml strings.Builder
xml.WriteString(`<?xml version="1.0" encoding="UTF-8"?>` + "\n")
xml.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"` + "\n")
xml.WriteString(` xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"` + "\n")
xml.WriteString(` xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"` + "\n")
xml.WriteString(` xmlns:xhtml="http://www.w3.org/1999/xhtml">` + "\n")
for _, entry := range entries {
xml.WriteString(" <url>\n")
xml.WriteString(" <loc>" + template.HTMLEscapeString(entry.loc) + "</loc>\n")
xml.WriteString(" <lastmod>" + entry.lastmod + "</lastmod>\n")
// Add changefreq and priority based on type
if entry.isDir {
xml.WriteString(" <changefreq>daily</changefreq>\n")
xml.WriteString(" <priority>0.8</priority>\n")
} else if entry.isImage {
xml.WriteString(" <changefreq>monthly</changefreq>\n")
xml.WriteString(" <priority>0.6</priority>\n")
// Add image-specific data using Google's image extension
xml.WriteString(" <image:image>\n")
xml.WriteString(" <image:loc>" + template.HTMLEscapeString(entry.imageURL) + "</image:loc>\n")
xml.WriteString(" </image:image>\n")
} else if entry.isVideo {
xml.WriteString(" <changefreq>monthly</changefreq>\n")
xml.WriteString(" <priority>0.7</priority>\n")
// Add video-specific data using Google's video extension
xml.WriteString(" <video:video>\n")
xml.WriteString(" <video:content_loc>" + template.HTMLEscapeString(entry.videoURL) + "</video:content_loc>\n")
// Extract filename without extension for title
videoName := filepath.Base(entry.videoURL)
videoTitle := videoName[:len(videoName)-len(filepath.Ext(videoName))]
xml.WriteString(" <video:title>" + template.HTMLEscapeString(videoTitle) + "</video:title>\n")
xml.WriteString(" <video:description>" + template.HTMLEscapeString("Video file: "+videoName) + "</video:description>\n")
xml.WriteString(" </video:video>\n")
} else if entry.isDocument {
// Documents (PDFs, DOCs, etc.) get higher priority as they're often primary content
xml.WriteString(" <changefreq>monthly</changefreq>\n")
xml.WriteString(" <priority>0.9</priority>\n")
// Add a comment to indicate this is a document (no official schema, but helpful for debugging)
docName := filepath.Base(entry.loc)
xml.WriteString(" <!-- Document: " + template.HTMLEscapeString(docName) + " (" + formatHumanSize(entry.fileSize) + ") -->\n")
} else {
xml.WriteString(" <changefreq>weekly</changefreq>\n")
xml.WriteString(" <priority>0.5</priority>\n")
}
xml.WriteString(" </url>\n")
}
xml.WriteString("</urlset>\n")
sitemapPath := filepath.Join(s.rootAbs, "sitemap.xml")
return os.WriteFile(sitemapPath, []byte(xml.String()), 0644)
}
// startSitemapGenerator starts periodic sitemap regeneration
func (s *server) startSitemapGenerator(intervalMinutes int) {
if intervalMinutes <= 0 || s.baseURL == "" {
return
}
if err := s.generateSitemap(); err != nil {
fmt.Fprintf(os.Stderr, "failed to generate initial sitemap: %v\n", err)
} else {
fmt.Printf("Generated sitemap.xml (%s/sitemap.xml)\n", s.rootAbs)
}
go func() {
ticker := time.NewTicker(time.Duration(intervalMinutes) * time.Minute)
defer ticker.Stop()
for range ticker.C {
if err := s.generateSitemap(); err != nil {
fmt.Fprintf(os.Stderr, "failed to regenerate sitemap: %v\n", err)
}
}
}()
}
// getClientIP extracts the real client IP, checking X-Forwarded-For first
func getClientIP(r *http.Request) string {
// Check X-Forwarded-For header (for reverse proxies)
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
if comma := strings.Index(xff, ","); comma > 0 {
return strings.TrimSpace(xff[:comma])
}
return strings.TrimSpace(xff)
}
// Fallback to RemoteAddr
ip := r.RemoteAddr
if colon := strings.LastIndex(ip, ":"); colon != -1 {
return ip[:colon]
}
return ip
}
// logCommand writes a command execution to the log file
func (s *server) logCommand(cmd, filePath, ip string) {
if s.logfile == "" {
return
}
logMutex.Lock()
defer logMutex.Unlock()
// Ensure log directory exists
logDir := filepath.Dir(s.logfile)
if err := os.MkdirAll(logDir, 0755); err != nil {
return
}
f, err := os.OpenFile(s.logfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return
}
defer func() { _ = f.Close() }()
timestamp := time.Now().Format("[02/Jan/2006:15:04:05 -0700]")
// Format: ip - - timestamp "POST /api/exec?cmd=COMMAND&file=PATH HTTP/1.1" 200 0 "-" "-"
logLine := fmt.Sprintf("%s - - %s \"POST /api/exec?cmd=%s&file=%s HTTP/1.1\" 200 0 \"-\" \"-\"\n",
ip, timestamp, cmd, url.QueryEscape(filePath))
_, _ = f.WriteString(logLine)
}
func newSID() string {
var b [16]byte
_, _ = rand.Read(b[:])
return fmt.Sprintf("%x", b[:])
}
func (s *server) getSession(w http.ResponseWriter, r *http.Request) *session {
ck, err := r.Cookie("sid")
if err == nil {
s.mu.RLock()
if sess, ok := s.sessions[ck.Value]; ok {
s.mu.RUnlock()
return sess
}
s.mu.RUnlock()
}
id := newSID()
sess := &session{cwd: "/"}
s.mu.Lock()
s.sessions[id] = sess
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{
Name: "sid",
Value: id,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
return sess
}
// ensure virtual path always starts with "/" and is cleaned
func cleanVirtual(p string) string {
if p == "" {
return "/"
}
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
return path.Clean(p)
}
// join a virtual base with an argument (which can be absolute or relative),
// then clean and ensure it remains absolute (virtual)
func joinVirtual(base, arg string) string {
if arg == "" {
return cleanVirtual(base)
}
if strings.HasPrefix(arg, "/") {
return cleanVirtual(arg)
}
if base == "" {
base = "/"
}
return cleanVirtual(path.Join(base, arg))
}
// convert a virtual path to a real filesystem path and ensure it is
// rooted inside s.rootAbs
func (s *server) realFromVirtual(v string) (string, error) {
v = cleanVirtual(v)
if v == "/" {
return s.rootAbs, nil
}
rel := strings.TrimPrefix(v, "/")
fsPath := filepath.Join(s.rootAbs, filepath.FromSlash(rel))
abs, err := filepath.Abs(fsPath)
if err != nil {
return "", err
}
// prevent escaping the root via .. or symlinks
// (best-effort: compare cleaned absolute paths)
if abs == s.rootAbs {
return abs, nil
}
rel2, err := filepath.Rel(s.rootAbs, abs)
if err != nil || strings.HasPrefix(rel2, "..") || rel2 == ".." {
return "", errors.New("permission denied")
}
return abs, nil
}
func (s *server) virtualFromReal(realPath string) (string, error) {
rel, err := filepath.Rel(s.rootAbs, realPath)
if err != nil {
return "", err
}
if rel == "." {
return "/", nil
}
return "/" + filepath.ToSlash(rel), nil
}
// simple args parser: supports quotes ("", ”) and backslash escapes inside quotes
func parseArgs(line string) []string {
var args []string
var buf bytes.Buffer
inSingle, inDouble := false, false
flush := func() {
if buf.Len() > 0 || inSingle || inDouble {
args = append(args, buf.String())
buf.Reset()
}
}
for i := 0; i < len(line); i++ {
c := line[i]
if inSingle {
if c == '\'' {
inSingle = false
} else {
buf.WriteByte(c)
}
continue
}
if inDouble {
if c == '"' {
inDouble = false
} else if c == '\\' && i+1 < len(line) {
i++
buf.WriteByte(line[i])
} else {
buf.WriteByte(c)
}
continue
}
switch c {
case ' ', '\t', '\n':
if buf.Len() > 0 {
args = append(args, buf.String())
buf.Reset()
}
case '\'':
inSingle = true
case '"':
inDouble = true
default:
buf.WriteByte(c)
}
}
flush()
return args
}
func formatLong(info os.FileInfo, name string, humanReadable bool) string {
// mode, size, date, name (owner/group omitted for portability)
mode := info.Mode().String()
size := info.Size()
mod := info.ModTime().Format("Jan _2 15:04")
if humanReadable {
sizeStr := formatHumanSize(size)
return fmt.Sprintf("%s %10s %s %s", mode, sizeStr, mod, name)
}
return fmt.Sprintf("%s %10d %s %s", mode, size, mod, name)
}
// formatHumanSize formats byte size in human-readable format
func formatHumanSize(size int64) string {
if size < 1024 {
return fmt.Sprintf("%dB", size)
}
const unit = 1024
if size < unit*unit {
return fmt.Sprintf("%.1fK", float64(size)/unit)
}
if size < unit*unit*unit {
return fmt.Sprintf("%.1fM", float64(size)/(unit*unit))
}
if size < unit*unit*unit*unit {
return fmt.Sprintf("%.1fG", float64(size)/(unit*unit*unit))
}
return fmt.Sprintf("%.1fT", float64(size)/(unit*unit*unit*unit))
}
// text/binary heuristic: reject if contains NUL or too many non-printables;
// accept if UTF-8 valid or printable ratio >= 0.85
func looksText(sample []byte) bool {
if bytes.IndexByte(sample, 0x00) >= 0 {
return false
}
if utf8.Valid(sample) {
return true
}
printable := 0
total := 0
for _, b := range sample {
total++
if b == 9 || b == 10 || b == 13 || (b >= 32 && b <= 126) {
printable++
}
}
if total == 0 {
return true
}
return float64(printable)/float64(total) >= 0.85
}
// ===== HTTP payloads =====
type execReq struct {
Input string `json:"input"`
}
type execResp struct {
Output string `json:"output"`
Download string `json:"download,omitempty"`
CWD string `json:"cwd,omitempty"`
Readme *string `json:"readme,omitempty"`
DocType string `json:"docType,omitempty"`
Clipboard string `json:"clipboard,omitempty"`
HTML string `json:"html,omitempty"`
Redirect string `json:"redirect,omitempty"`
}
type completeReq struct {
Path string `json:"path"`
DirsOnly bool `json:"dirsOnly"`
FilesOnly bool `json:"filesOnly"`
TextOnly bool `json:"textOnly"`
MaxSize int64 `json:"maxSize"`
}
type completeItem struct {
Name string `json:"name"`
Dir bool `json:"dir"`
}
type completeResp struct {
Items []completeItem `json:"items"`
}
type configResp struct {
CatMax int64 `json:"catMax"`
Readme *string `json:"readme,omitempty"`
DocType string `json:"docType,omitempty"`
CWD string `json:"cwd,omitempty"`
}
// ===== Handlers =====
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
// Check for no-JS fallback query parameter
noJS := r.URL.Query().Get("nojs") == "1"
// For root path, check for index.html first
if r.URL.Path == "/" {
indexPath := filepath.Join(s.rootAbs, "index.html")
if indexInfo, err := os.Stat(indexPath); err == nil && !indexInfo.IsDir() {
// Serve index.html instead of lsget interface
s.serveFile(w, r, indexPath, indexInfo)
return
}
// No index.html, serve lsget interface or no-JS fallback
if noJS {
s.serveNoJSDirectory(w, r, "/")
} else {
s.serveMainIndex(w, r, "/")
}
return
}
// For other paths, check if it's a file or directory
requestPath := path.Clean(r.URL.Path)
realPath, err := s.realFromVirtual(requestPath)
if err != nil {
// Path outside root, serve appropriate response
if noJS {
http.NotFound(w, r)
} else {
s.serveMainIndex(w, r, "/")
}
return
}
// Check if path exists
info, err := os.Stat(realPath)
if err != nil {
// Path doesn't exist
if noJS {
http.NotFound(w, r)
} else {
s.serveMainIndex(w, r, "/")
}
return
}
if info.IsDir() {
// Check if directory contains index.html
indexPath := filepath.Join(realPath, "index.html")
if indexInfo, err := os.Stat(indexPath); err == nil && !indexInfo.IsDir() {
// Serve index.html instead of lsget interface
s.serveFile(w, r, indexPath, indexInfo)
return
}
// It's a directory without index.html
if noJS {
s.serveNoJSDirectory(w, r, requestPath)
} else {
s.serveMainIndex(w, r, requestPath)
}
} else {
// It's a file, serve it directly for download
s.serveFile(w, r, realPath, info)
}
}
func (s *server) serveFile(w http.ResponseWriter, r *http.Request, realPath string, info os.FileInfo) {
// Check if file should be ignored based on .lsgetignore patterns
fileName := filepath.Base(realPath)
if s.shouldIgnore(realPath, fileName) {
http.NotFound(w, r)
return
}
// Set appropriate content type based on file extension
contentType := mime.TypeByExtension(filepath.Ext(realPath))
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
// For certain file types, force download with Content-Disposition
ext := strings.ToLower(filepath.Ext(realPath))
switch ext {
case ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".rar", ".7z", ".tar", ".gz":
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
}
// Serve the file
http.ServeFile(w, r, realPath)
}
func (s *server) serveMainIndex(w http.ResponseWriter, r *http.Request, initialPath string) {
var htmlContent []byte
// Serve from disk if available so you can iterate quickly.
if b, err := os.ReadFile("index.html"); err == nil {
htmlContent = b
} else {
// Fallback to embedded.
htmlContent = embeddedIndex
}
// Replace placeholder with actual help message and initial path
processedHTML := s.processHTMLTemplate(htmlContent, initialPath)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(processedHTML)
}
// serveNoJSDirectory serves a plain HTML directory listing for no-JS fallback
func (s *server) serveNoJSDirectory(w http.ResponseWriter, r *http.Request, virtualPath string) {
realPath, err := s.realFromVirtual(virtualPath)
if err != nil {
http.NotFound(w, r)
return
}
entries, err := os.ReadDir(realPath)
if err != nil {
http.Error(w, "Error reading directory", http.StatusInternalServerError)
return
}