-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_http_web_index.go
299 lines (267 loc) · 7.36 KB
/
handler_http_web_index.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
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
package main
import (
"bytes"
_ "embed"
"fmt"
"io"
"io/fs"
"mime"
"net/http"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"text/template"
"github.com/mileusna/useragent"
"github.com/phuslu/log"
)
type HTTPWebIndexHandler struct {
Location string
Root string
Headers string
Body string
File string
Functions template.FuncMap
headers *template.Template
body *template.Template
}
func (h *HTTPWebIndexHandler) Load() (err error) {
if h.Body == "" && h.Root != "" {
h.Body = autoindexTemplate
}
h.headers, err = template.New(h.Headers).Funcs(h.Functions).Parse(h.Headers)
if err != nil {
return
}
h.body, err = template.New(h.Body).Funcs(h.Functions).Parse(h.Body)
if err != nil {
return
}
return
}
func (h *HTTPWebIndexHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ri := req.Context().Value(RequestInfoContextKey).(*RequestInfo)
log.Debug().Context(ri.LogContext).Interface("headers", req.Header).Msg("web index request")
if h.Root == "" && h.Headers == "" && h.Body == "" && h.File == "" {
http.NotFound(rw, req)
return
}
if h.Root == "" {
h.addHeaders(rw, req, ri)
if s := mime.TypeByExtension(filepath.Ext(req.URL.Path)); s != "" {
rw.Header().Set("content-type", s)
}
tmpl := h.body
var fi fs.FileInfo
if h.File != "" {
file, err := os.Open(h.File)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
fi, err = file.Stat()
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if !slices.Contains([]string{".tpl", ".html", ".pac"}, filepath.Ext(h.File)) {
io.Copy(rw, file)
return
}
data, err := io.ReadAll(file)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
tmpl, err = template.New(h.File).Funcs(h.Functions).Parse(string(data))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
}
tmpl.Execute(rw, struct {
Request *http.Request
UserAgent *useragent.UserAgent
ServerAddr string
FileInfo fs.FileInfo
}{req, &ri.UserAgent, ri.ServerAddr, fi})
return
}
fullname := filepath.Join(h.Root, strings.TrimPrefix(req.URL.Path, h.Location))
fi, err := os.Stat(fullname)
if err != nil {
http.NotFound(rw, req)
return
}
if fi.IsDir() {
// .htpasswd
htfile := filepath.Join(fullname, ".htpasswd")
if err = HtpasswdVerify(htfile, req); err != nil && !os.IsNotExist(err) {
rw.Header().Set("www-authenticate", `Basic realm="Authentication Required"`)
http.Error(rw, "401 unauthorised: "+err.Error(), http.StatusUnauthorized)
return
}
// index.html
index := filepath.Join(fullname, "index.html")
if fi2, err := os.Stat(index); err == nil && !fi2.IsDir() {
fullname = index
fi = fi2
}
}
if !fi.IsDir() {
file, err := os.Open(fullname)
if err != nil {
http.Error(rw, "500 internal server error", http.StatusInternalServerError)
return
}
defer file.Close()
h.addHeaders(rw, req, ri)
if s := mime.TypeByExtension(filepath.Ext(fullname)); s != "" {
rw.Header().Set("content-type", s)
} else {
rw.Header().Set("content-type", "application/octet-stream")
}
rw.Header().Set("accept-ranges", "bytes")
if s := req.Header.Get("range"); s == "" {
rw.Header().Set("content-length", strconv.FormatInt(fi.Size(), 10))
rw.WriteHeader(http.StatusOK)
n, err := io.CopyBuffer(rw, file, make([]byte, 1<<20))
log.Info().Context(ri.LogContext).Err(err).Int("http_status", http.StatusOK).Int64("http_content_length", n).Msg("web_root request")
} else {
if !strings.HasPrefix(s, "bytes=") {
http.Error(rw, "400 bad request", http.StatusBadRequest)
return
}
parts := strings.SplitN(s[6:], "-", 2)
if len(parts) != 2 {
http.Error(rw, "400 bad request", http.StatusBadRequest)
return
}
// calc ranges
var filesize = fi.Size()
var ranges [2]int64
switch {
case parts[0] == "":
ranges[0] = 0
case parts[1] == "":
ranges[0], _ = strconv.ParseInt(parts[0], 10, 64)
if filesize == 0 {
ranges[1] = 0
} else {
ranges[1] = filesize - 1
}
default:
for i, part := range parts {
ranges[i], err = strconv.ParseInt(part, 10, 64)
if err != nil {
http.Error(rw, "400 bad request", http.StatusBadRequest)
return
}
}
}
// content-length
length := ranges[1] - ranges[0] + 1
switch {
case length < 0:
http.Error(rw, "400 bad request", http.StatusBadRequest)
return
case length == 0:
rw.WriteHeader(http.StatusNoContent)
return
}
// limit reader
if ranges[0] > 0 {
file.Seek(ranges[0], 0)
}
var fr io.Reader = file
if ranges[1] < filesize-1 {
fr = io.LimitReader(file, length)
}
// send data
rw.Header().Set("content-range", fmt.Sprintf("bytes %d-%d/%d", ranges[0], ranges[1], filesize))
rw.Header().Set("content-length", strconv.FormatInt(length, 10))
rw.WriteHeader(http.StatusPartialContent)
n, err := io.CopyBuffer(rw, fr, make([]byte, 1<<20))
log.Info().Context(ri.LogContext).Err(err).Int("http_status", http.StatusOK).Int64("http_content_length", n).Msg("web_root request")
}
return
}
entries, err := os.ReadDir(fullname)
if err != nil {
http.Error(rw, "500 internal server error", http.StatusInternalServerError)
return
}
infos := make([]fs.FileInfo, 0, len(entries))
for i := range []int{0, 1} {
for _, entry := range entries {
switch {
case entry.Name()[0] == '.':
continue
case i == 0 && !entry.IsDir():
continue
case i == 1 && entry.IsDir():
continue
}
info, _ := entry.Info()
infos = append(infos, info)
}
}
var b bytes.Buffer
err = h.body.Execute(&b, struct {
WebRoot string
Request *http.Request
UserAgent *useragent.UserAgent
ServerAddr string
FileInfos []fs.FileInfo
}{h.Root, req, &ri.UserAgent, ri.ServerAddr, infos})
if err != nil {
http.Error(rw, "500 internal server error", http.StatusInternalServerError)
return
}
h.addHeaders(rw, req, ri)
rw.Header().Set("content-type", "text/html;charset=utf-8")
rw.Write(b.Bytes())
}
func (h *HTTPWebIndexHandler) addHeaders(rw http.ResponseWriter, req *http.Request, ri *RequestInfo) {
var sb strings.Builder
h.headers.Execute(&sb, struct {
WebRoot string
Request *http.Request
UserAgent *useragent.UserAgent
ServerAddr string
FileInfos []fs.FileInfo
}{h.Root, req, &ri.UserAgent, ri.ServerAddr, nil})
var statusCode int
for _, line := range strings.Split(sb.String(), "\n") {
parts := strings.SplitN(line, ":", 2)
if len(parts) != 2 {
continue
}
key, value := parts[0], strings.TrimSpace(parts[1])
if key == "status" {
statusCode, _ = strconv.Atoi(value)
} else {
rw.Header().Add(key, value)
}
}
if statusCode != 0 {
rw.WriteHeader(statusCode)
}
}
const autoindexTemplate = `
<html>
<head><title>Index of {{.Request.URL.Path}}</title></head>
<body>
<h1>Index of {{.Request.URL.Path}}</h1><hr><pre><a href="../">../</a>
{{range .FileInfos -}}
{{if .IsDir -}}
<a href="{{.Name}}/">{{.Name}}/</a> {{.ModTime.Format "02-Jan-2006 15:04"}} -
{{else -}}
<a href="{{.Name}}">{{.Name}}</a> {{.ModTime.Format "02-Jan-2006 15:04"}} {{.Size}}
{{end -}}
{{end}}</pre><hr></body>
</html>
{{ readfile "autoindex.html" }}
`