-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserve.go
369 lines (306 loc) · 7.99 KB
/
serve.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
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
package server
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
)
type xFile struct {
size int
offset int
b *bytes.Buffer
c chan struct{}
}
func (route *Route) Error(statusCode int, message string, a ...any) {
route.W.WriteHeader(statusCode)
route.errMessage = message
if message == "" {
route.errMessage = "Error"
}
route.logErrMessage = route.errMessage
if len(a) > 0 {
var v []string
for _, el := range a {
v = append(v, fmt.Sprint(el))
}
route.logErrMessage = strings.Join(v, " ")
}
}
func (route *Route) ServeRootedFile(path string) {
route.ServeFile(route.Website.Dir + path)
}
func (route *Route) ServeFile(path string) {
if !isAbs(path) {
if route.Website.Dir != "" {
path = route.Website.Dir + "/" + path
} else {
path = route.Srv.ServerPath + "/" + path
}
}
if strings.HasPrefix(path, "~") {
home, err := os.UserHomeDir()
if err == nil {
path = strings.Replace(path, "~", home, 1)
}
}
if strings.Contains(path, "..") {
route.Error(http.StatusBadRequest, "Bad request URL", "URL contains ..")
return
}
for _, hidden := range route.Website.HiddenFolders {
if strings.HasPrefix(route.RequestURI, hidden) {
route.Error(http.StatusNotFound, "Not found", "Not serving potential file inside hidden directory", hidden)
return
}
}
fileInfo, err := os.Stat(path)
if err == nil {
if fileInfo.IsDir() {
route.Error(http.StatusNotFound, "Not found", "Cannot serve directory", path)
return
}
http.ServeFile(route.W, route.R, path)
return
}
fileInfo, err = os.Stat(path + ".html")
if err != nil {
route.Error(http.StatusNotFound, "Not found")
return
}
f, err := os.Open(path + ".html")
if err != nil {
route.Error(http.StatusInternalServerError, "Error retreiving page", fmt.Sprintf("Error opening file %s: %v", path + ".html", err))
return
}
defer f.Close()
http.ServeContent(route.W, route.R, fileInfo.Name(), fileInfo.ModTime(), f)
}
func (route *Route) ServeCustomFileWithTime(name string, data []byte, t time.Time) {
http.ServeContent(route.W, route.R, "", t, bytes.NewReader(data))
}
func (route *Route) ServeCustomFile(name string, data []byte) {
http.ServeContent(route.W, route.R, "", time.Now(), bytes.NewReader(data))
}
func (route *Route) ServeData(data []byte) {
route.W.Write(data)
}
func (route *Route) ServeText(text string) {
route.ServeData([]byte(text))
}
func (route *Route) StaticServe(serveHTML bool) {
if route.Method != "GET" && route.Method != "HEAD" {
route.Error(http.StatusMethodNotAllowed, "Method not allowed")
return
}
if route.RequestURI == "/" {
route.ServeFile(route.Website.Dir + "/index.html")
return
}
if strings.HasSuffix(route.RequestURI, ".html") && !serveHTML {
route.Error(http.StatusNotFound, "Not Found")
return
}
if strings.Count(route.RequestURI, "/") == 1 {
route.ServeFile(route.Website.Dir + route.RequestURI)
return
}
for _, s := range route.Website.AllFolders {
if strings.HasPrefix(route.RequestURI, s) {
if strings.HasSuffix(route.RequestURI, ".css") && route.Website.EnableCSSX {
route.serveCSSX()
return
}
route.ServeFile(route.Website.Dir + route.RequestURI)
return
}
}
route.Error(http.StatusNotFound, "Not Found")
}
func (route *Route) serveCSSX() {
info, err := os.Stat(route.Website.Dir + route.RequestURI + "x")
if err != nil {
route.Error(http.StatusNotFound, "Not Found")
return
}
cssx, err := os.Open(route.Website.Dir + route.RequestURI + "x")
if err != nil {
route.Error(http.StatusInternalServerError, "Internal server error", fmt.Sprintf("Error opening file %s: %v", route.Website.Dir + route.RequestURI + "x", err))
return
}
defer cssx.Close()
basePathSplit := strings.Split(route.Website.Dir + route.RequestURI, "/")
var basePath string
for _, s := range basePathSplit[:len(basePathSplit)-1] {
basePath += s + "/"
}
var size int
modTime := info.ModTime()
fileNames := make([]string, 0)
sc := bufio.NewScanner(cssx)
for sc.Scan() {
info, err = os.Stat(basePath + sc.Text())
if err != nil {
continue
}
if info.ModTime().After(modTime) {
modTime = info.ModTime()
}
size += int(info.Size()) + 2
fileNames = append(fileNames, basePath + sc.Text())
}
css := newXFile(size)
go func() {
for _, s := range fileNames {
data, err := os.ReadFile(s)
if err != nil {
continue
}
css.Write(data)
css.Write([]byte("\n\n"))
}
}()
http.ServeContent(route.W, route.R, basePathSplit[len(basePathSplit)-1], modTime, css)
}
func (route *Route) SetCookie(name string, value interface{}, maxAge int) error {
encValue, err := route.Srv.secureCookie.Encode(name, value)
if err != nil {
return err
}
http.SetCookie(route.W, &http.Cookie{
Name: GenerateHashString([]byte(name)),
Value: encValue,
Domain: route.DomainName,
MaxAge: maxAge,
Secure: route.Secure,
HttpOnly: route.Secure,
})
return nil
}
func (route *Route) DeleteCookie(name string) {
http.SetCookie(route.W, &http.Cookie{
Name: GenerateHashString([]byte(name)),
Value: "",
Domain: route.DomainName,
MaxAge: -1,
Secure: route.Secure,
HttpOnly: route.Secure,
})
}
func (route *Route) DecodeCookie(name string, value interface{}) (bool, error) {
if cookie, err := route.R.Cookie(GenerateHashString([]byte(name))); err == nil {
return true, route.Srv.secureCookie.Decode(name, cookie.Value, value)
}
return false, nil
}
func (route *Route) SetCookiePerm(name string, value interface{}, maxAge int) error {
encValue, err := route.Srv.secureCookiePerm.Encode(name, value)
if err != nil {
return err
}
http.SetCookie(route.W, &http.Cookie{
Name: GenerateHashString([]byte(name)),
Value: encValue,
Domain: route.DomainName,
MaxAge: maxAge,
Secure: route.Secure,
HttpOnly: route.Secure,
})
return nil
}
func (route *Route) DecodeCookiePerm(name string, value interface{}) (bool, error) {
if cookie, err := route.R.Cookie(GenerateHashString([]byte(name))); err == nil {
return true, route.Srv.secureCookiePerm.Decode(name, cookie.Value, value)
}
return false, nil
}
func (route *Route) ReverseProxy(URL string) error {
urlParsed, err := url.Parse(URL)
if err != nil {
return err
}
proxyServer := httputil.NewSingleHostReverseProxy(urlParsed)
noLogFile, _ := os.Open(os.DevNull)
proxyServer.ErrorLog = log.New(noLogFile, "", 0)
proxyServer.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
route.Error(http.StatusBadGateway, "Bad gateway", err.Error())
}
proxyServer.ServeHTTP(route.W, route.R)
return nil
}
func newXFile(len int) *xFile {
return &xFile {
size: len,
b: &bytes.Buffer{},
c: make(chan struct{}, 10),
}
}
func (x *xFile) Write(p []byte) {
x.b.Write(p)
x.c <- struct{}{}
}
func (x *xFile) Read(p []byte) (n int, err error) {
switch {
case len(p) == 0:
return 0, nil
case x.offset >= x.size:
return 0, io.EOF
case x.b.Len() == x.size || len(p) <= x.b.Len() - x.offset:
data := x.b.Bytes()
var i int
for i = 0; i < len(p) && i < x.b.Len() - x.offset; i++ {
p[i] = data[x.offset+i]
}
x.offset += i
return i, nil
default:
for {
<- x.c
if len(p) <= x.b.Len() - x.offset {
return x.Read(p)
}
}
}
}
func (x *xFile) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
if offset < 0 {
return 0, fmt.Errorf("seek out of bound")
}
x.offset = int(offset)
return offset, nil
case io.SeekCurrent:
if x.offset + int(offset) < 0 {
return 0, fmt.Errorf("seek out of bound")
}
x.offset += int(offset)
return offset, nil
case io.SeekEnd:
if (x.size -1 ) + int(offset) < 0 {
return 0, fmt.Errorf("seek out of bound")
}
x.offset = (x.size - 1) + int(offset)
return int64(x.offset), nil
default:
return 0, fmt.Errorf("invalid operation")
}
}
func ReadJSON[T any](route *Route) (value T, err error) {
var data []byte
data, err = io.ReadAll(route.R.Body)
if err != nil {
return value, err
}
if err = json.Unmarshal(data, &value); err != nil {
return value, err
}
return value, nil
}