forked from nielsAD/autoindex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
190 lines (160 loc) · 4.72 KB
/
main.go
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
// Author: Niels A.D.
// Project: autoindex (https://github.com/nielsAD/autoindex)
// License: Mozilla Public License, v2.0
package main
import (
"context"
"flag"
"log"
"net"
"net/http"
"os"
"os/signal"
"path"
"strings"
"syscall"
"time"
_ "github.com/mattn/go-sqlite3"
"github.com/ulule/limiter/v3"
"github.com/ulule/limiter/v3/drivers/middleware/stdlib"
"github.com/ulule/limiter/v3/drivers/store/memory"
)
var (
addr = flag.String("a", ":80", "TCP network address to listen for connections")
db = flag.String("d", "file::memory:?cache=shared", "Database location")
dir = flag.String("r", ".", "Root directory to serve")
dirhide = flag.String("dirhide", "", "Directories to hide in listing, separated with spaces")
refresh = flag.String("i", "1h", "Refresh interval")
ratelimit = flag.Int64("l", 5, "Request rate limit (req/sec per IP)")
timeout = flag.Duration("t", time.Second, "Request timeout")
forwarded = flag.Bool("forwarded", false, "Trust X-Real-IP and X-Forwarded-For headers")
cached = flag.Bool("cached", false, "Serve everything from cache (rather than search/recursive queries only)")
)
var logOut = log.New(os.Stdout, "", 0)
var logErr = log.New(os.Stderr, "", 0)
func main() {
flag.Parse()
var interval time.Duration
if *refresh != "" {
i, err := time.ParseDuration(*refresh)
if err != nil {
logErr.Fatal(err)
}
interval = i
}
fs, err := New(*db, *dir)
if err != nil {
logErr.Fatal(err)
}
fs.Timeout = *timeout
fs.Cached = *cached
var tempDirHide = *dirhide
fs.dirHide = strings.Split(tempDirHide, " ")
defer fs.Close()
go func() {
last := 0
for {
n, err := fs.Fill()
if err != nil {
logErr.Printf("Fill: %s\n", err.Error())
}
if n != last {
logErr.Printf("%d records in database after update (%+d)\n", n, n-last)
last = n
}
if interval == 0 {
break
}
time.Sleep(interval)
}
}()
pub := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := path.Join("./public/", r.URL.Path)
if s, err := os.Stat(p); err == nil && !s.IsDir() {
http.ServeFile(w, r, p)
} else {
http.ServeFile(w, r, "./public/index.html")
}
})
limit := stdlib.NewMiddleware(limiter.New(memory.NewStore(), limiter.Rate{Period: time.Second, Limit: *ratelimit}))
srv := &http.Server{Addr: *addr}
handleDefault := func(p string, h http.Handler) { http.Handle(p, realIP(*forwarded, checkMethod(h))) }
handleLimited := func(p string, h http.Handler) { handleDefault(p, limit.Handler(logRequest(http.StripPrefix(p, h)))) }
handleLimited("/idx/", fs)
handleLimited("/dl/", nodir(http.FileServer(http.Dir(fs.Root))))
handleLimited("/urllist.txt", http.HandlerFunc(fs.Sitemap))
handleDefault("/", pub)
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(ctx)
}()
logErr.Printf("Serving files in '%s' on %s\n", *dir, *addr)
logErr.Println(srv.ListenAndServe())
fs.Close()
}
func orHyphen(s string) string {
if s != "" {
return s
}
return "-"
}
func checkMethod(han http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "HEAD" && r.Method != "GET" {
http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed)
return
}
han.ServeHTTP(w, r)
})
}
func realIP(trustForward bool, han http.Handler) http.Handler {
if !trustForward {
return han
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if realHost := r.Header.Get("X-Forwarded-Host"); realHost != "" {
r.Host = realHost
}
if realIP := r.Header.Get("X-Real-IP"); realIP != "" {
r.RemoteAddr = realIP + ":0"
}
han.ServeHTTP(w, r)
})
}
func nodir(han http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "" || strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
han.ServeHTTP(w, r)
})
}
func logRequest(han http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, _, _ := r.BasicAuth()
h, _, _ := net.SplitHostPort(r.RemoteAddr)
logOut.Printf("%.128s - %.256s [%s] %.2048q 0 0 %.2048q %.1024q\n",
h,
orHyphen(u),
time.Now().Format("02/Jan/2006:15:04:05 -0700"),
r.Method+" "+r.URL.String()+" "+r.Proto,
orHyphen(r.Referer()),
orHyphen(r.UserAgent()),
)
han.ServeHTTP(w, r)
})
}
func logError(code int, err error, w http.ResponseWriter, r *http.Request) {
h, _, _ := net.SplitHostPort(r.RemoteAddr)
logErr.Printf("%.128s %.2048q %q\n",
h,
r.Method+" "+r.URL.String()+" "+r.Proto,
err.Error(),
)
http.Error(w, err.Error(), code)
}