-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
418 lines (371 loc) · 10.4 KB
/
server.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
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
// Copyright 2020, 2023, 2024 Juca Crispim <[email protected]>
// This file is part of tupi.
// tupi is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// tupi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with tupi. If not, see <http://www.gnu.org/licenses/>.
package tupi
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
)
const UPLOAD_CONTENT_TYPE = "multipart/form-data"
const indexFile = "index.html"
var config Config
var certsCache map[string]tls.Certificate = make(map[string]tls.Certificate, 0)
type TupiServer struct {
Conf Config
// We have one server for each port we listen
Servers []*http.Server
}
func (s *TupiServer) LoadPlugins() {
for domain, conf := range s.Conf.Domains {
if conf.AuthPlugin != "" {
err := LoadAuthPlugin(conf.AuthPlugin, domain, &conf.AuthPluginConf)
if err != nil {
Errorf("Error loading auth plugin %s", err.Error())
}
}
if conf.ServePlugin != "" {
err := LoadServePlugin(conf.ServePlugin, domain, &conf.ServePluginConf)
if err != nil {
Errorf("Error loading serve plugin %s", err.Error())
}
}
}
}
func (s *TupiServer) Run() {
startServer := getStartServerFn()
use_ssl := s.Conf.HasSSL()
if len(s.Servers) == 1 {
startServer(s.Servers[0], use_ssl)
} else {
server := s.Servers[0]
for _, serv := range s.Servers[1:] {
go startServer(serv, false)
}
startServer(server, use_ssl)
}
}
type statusedResponseWriter struct {
http.ResponseWriter
status int
}
func (w *statusedResponseWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
type requestError struct {
StatusCode int
Err error
}
// SetupServer creates a new instance of the tupi
// http server. You can start it using “TupiServer.Run“
func SetupServer(conf Config) TupiServer {
// read this for new implementation
// https://github.com/golang/go/issues/35626
setConfig(conf)
loglevel := conf.Domains["default"].LogLevel
SetLogLevelStr(loglevel)
handler := logRequest(http.HandlerFunc(route))
s := TupiServer{
Conf: conf,
}
servers := make([]*http.Server, 0)
host := conf.Domains["default"].Host
timeout := conf.Domains["default"].Timeout
port := conf.Domains["default"].Port
redir := conf.Domains["default"].redirToHttps
altPort := conf.Domains["default"].AlternativePort
addr := fmt.Sprintf(
"%s:%s",
host,
strconv.FormatInt(int64(port), 10))
server := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: time.Duration(timeout) * time.Second,
WriteTimeout: time.Duration(timeout) * time.Second,
}
servers = append(servers, server)
if altPort > 0 {
var altHandler http.Handler
if redir {
altHandler = logRequest(http.HandlerFunc(redir2https))
} else {
altHandler = logRequest(http.HandlerFunc(route))
}
addr := fmt.Sprintf(
"%s:%s",
host,
strconv.FormatInt(int64(altPort), 10))
server := &http.Server{
Addr: addr,
Handler: altHandler,
ReadTimeout: time.Duration(timeout) * time.Second,
WriteTimeout: time.Duration(timeout) * time.Second,
}
servers = append(servers, server)
}
s.Servers = servers
s.LoadPlugins()
return s
}
// Call the default tupi actions or a pluging based
// in the domain config
func route(w http.ResponseWriter, req *http.Request) {
c := getConfigForRequest(req)
if shouldAuthenticate(req, c) {
ok, status := authenticate(req, c)
if !ok {
if c.AuthPlugin == "" {
w.Header().Set("WWW-Authenticate", "Basic realm=xZsd234-1M82sa")
}
http.Error(w, "Bad auth", status)
return
}
}
if c.ServePlugin == "" {
serveDefaultTupi(w, req, c)
return
}
wr := w.(*statusedResponseWriter)
servePlugin(wr.ResponseWriter, req, c)
}
func redir2https(w http.ResponseWriter, req *http.Request) {
loc := strings.Replace(req.URL.String(), "http", "https", 1)
conf := getConfigForRequest(req)
httpPort := fmt.Sprintf(":%d", conf.AlternativePort)
if strings.Index(loc, httpPort) >= 1 {
httpsPort := fmt.Sprintf(":%d", conf.Port)
loc = strings.Replace(loc, httpPort, httpsPort, 1)
}
w.WriteHeader(http.StatusMovedPermanently)
w.Header().Add("Location", loc)
}
// Does the default tupi actions, serve and receive files.
func serveDefaultTupi(w http.ResponseWriter, req *http.Request, c *DomainConfig) {
if req.URL.Path == c.UploadPath {
recieveFile(w, req, c)
} else if req.URL.Path == c.ExtractPath {
recieveAndExtract(w, req, c)
} else {
showFile(w, req, c)
}
}
func servePlugin(w http.ResponseWriter, req *http.Request, c *DomainConfig) {
fn, err := GetServePlugin(c.ServePlugin)
if err != nil {
// notest
http.Error(w, err.Error(), http.StatusInternalServerError)
}
fn(w, req, &c.ServePluginConf)
}
func recieveFile(w http.ResponseWriter, req *http.Request, c *DomainConfig) {
reader, err := checkUploadRequest(w, req, c)
if err != nil {
e, _ := err.(*requestError)
http.Error(w, string(err.Error()), e.StatusCode)
return
}
fname, err := writeFile(c.RootDir, reader, false, c.PreventOverwrite)
if err != nil && err != io.EOF {
if isBadRequest(err) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// notest
Errorf("%s\n", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte(fname + "\n"))
}
func recieveAndExtract(w http.ResponseWriter, req *http.Request, c *DomainConfig) {
reader, err := checkUploadRequest(w, req, c)
if err != nil {
e, _ := err.(*requestError)
http.Error(w, string(err.Error()), e.StatusCode)
return
}
f, err := getFileFromRequest(reader)
if err != nil {
// notest
Errorf("%s\n", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
freader := bytes.NewBuffer(f.content)
files, err := extractFiles(freader, c.RootDir, c.PreventOverwrite)
if err != nil {
// notest
Errorf("%s\n", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
for _, f := range files {
w.Write([]byte(f + "\n"))
}
}
func showFile(w http.ResponseWriter, req *http.Request, c *DomainConfig) {
if req.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if containsDotDot(req.URL.Path) {
http.Error(w, "invalid URL path", http.StatusBadRequest)
return
}
fpath := req.URL.Path
if strings.HasSuffix(fpath, "/") && c.DefaultToIndex {
fpath += indexFile
}
path := c.RootDir + fpath
dir, file := filepath.Split(path)
serveFile(w, req, http.Dir(dir), file)
}
// Returns a certificate based on the host config.
func getCertificate(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
domain := info.ServerName
if cert, exists := certsCache[domain]; exists {
return &cert, nil
}
conf, exists := config.Domains[domain]
if !exists {
conf = config.Domains["default"]
}
AcquireLock(domain)
defer ReleaseLock(domain)
// check if the cert was created while waiting for the lock
if cert, exists := certsCache[domain]; exists {
// notest
return &cert, nil
}
cert, err := tls.LoadX509KeyPair(conf.CertFilePath, conf.KeyFilePath)
certsCache[domain] = cert
return &cert, err
}
func setConfig(conf Config) {
config = conf
}
func getDomainForRequest(req *http.Request) string {
domain := strings.Split(req.Host, ":")[0]
domain = strings.ToLower(domain)
return domain
}
func getConfigForRequest(req *http.Request) *DomainConfig {
domain := getDomainForRequest(req)
if conf, exists := config.Domains[domain]; exists {
return &conf
}
default_confg := config.Domains["default"]
return &default_confg
}
func (r *requestError) Error() string {
return fmt.Sprintf("%s", r.Err)
}
func shouldAuthenticate(req *http.Request, c *DomainConfig) bool {
for _, meth := range c.AuthMethods {
if strings.ToUpper(meth) == strings.ToUpper(req.Method) {
return true
}
}
return false
}
func checkUploadRequest(
w http.ResponseWriter, req *http.Request,
c *DomainConfig) (*multipart.Reader, error) {
err := &requestError{}
if req.Method != "POST" {
err.StatusCode = http.StatusMethodNotAllowed
err.Err = errors.New("Method not allowed")
return nil, err
}
ctype := req.Header.Get("Content-Type")
if !strings.HasPrefix(ctype, UPLOAD_CONTENT_TYPE) {
msg := "Bad request. Use Content-Type: " + UPLOAD_CONTENT_TYPE
err.StatusCode = http.StatusBadRequest
err.Err = errors.New(msg)
return nil, err
}
req.Body = http.MaxBytesReader(w, req.Body, c.MaxUploadSize)
reader, mperr := req.MultipartReader()
if mperr != nil {
// notest
err.StatusCode = http.StatusBadRequest
err.Err = errors.New("Bad request")
return nil, err
}
return reader, nil
}
func logRequest(h http.Handler) http.Handler {
handler := func(w http.ResponseWriter, req *http.Request) {
sw := &statusedResponseWriter{w, http.StatusOK}
h.ServeHTTP(sw, req)
remote := getIp(req)
path := req.URL.Path
method := req.Method
ua := req.Header.Get("User-Agent")
Infof("%s %s %s %d %s\n", remote, method, path, sw.status, ua)
}
return http.HandlerFunc(handler)
}
func getIp(req *http.Request) string {
ip := req.Header.Get("X-Real-Ip")
if ip == "" {
ip = req.Header.Get("X-Forwarded-For")
}
if ip == "" {
ip = req.RemoteAddr
}
return ip
}
func isBadRequest(err error) bool {
msg := err.Error()
return msg == INVALID_PREFIX_MSG || strings.Contains(msg, "already exists")
}
// for tests
type startServerFn func(server *http.Server, use_ssl bool)
var startServerTestFn startServerFn = nil
func getStartServerFn() startServerFn {
// notest
if startServerTestFn != nil {
return startServerTestFn
}
startServer := func(server *http.Server, use_ssl bool) {
if use_ssl {
if server.TLSConfig == nil {
server.TLSConfig = &tls.Config{}
}
tls_conf := server.TLSConfig
tls_conf.GetCertificate = getCertificate
err := server.ListenAndServeTLS("", "")
if err != nil {
panic(err.Error())
}
} else {
err := server.ListenAndServe()
if err != nil {
panic(err.Error())
}
}
}
return startServer
}