Debian Codegraph @

http/http.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package http
5
6 import (
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "html/template"
13 "math/rand"
14 "net"
15 "net/http"
16 "os"
17 "path/filepath"
18 "sort"
19 "strconv"
20 "strings"
21 "sync"
22 "time"
23
24 systemd "github.com/coreos/go-systemd/daemon"
25 . "github.com/etix/mirrorbits/config"
26 "github.com/etix/mirrorbits/core"
27 "github.com/etix/mirrorbits/database"
28 "github.com/etix/mirrorbits/filesystem"
29 "github.com/etix/mirrorbits/logs"
30 "github.com/etix/mirrorbits/mirrors"
31 "github.com/etix/mirrorbits/network"
32 "github.com/etix/mirrorbits/utils"
33 "github.com/gomodule/redigo/redis"
34 "github.com/op/go-logging"
35 "gopkg.in/tylerb/graceful.v1"
36 )
37
38 var (
39 log = logging.MustGetLogger("main")
40 )
41
42 // HTTP represents an instance of the HTTP webserver
43 type HTTP struct {
44 geoip *network.GeoIP
45 redis *database.Redis
46 templates Templates
47 Listener *net.Listener
48 server *graceful.Server
49 serverStopChan <-chan struct{}
50 stats *Stats
51 cache *mirrors.Cache
52 engine mirrorSelection
53 Restarting bool
54 stopped bool
55 stoppedMutex sync.Mutex
56 }
57
58 // Templates is a struct embedding instances of the precompiled templates
59 type Templates struct {
60 *sync.RWMutex
61
62 mirrorlist *template.Template
63 mirrorstats *template.Template
64 }
65
66 // HTTPServer is the constructor of the HTTP server
67 func HTTPServer(redis *database.Redis, cache *mirrors.Cache) *HTTP {
68 h := new(HTTP)
69 h.redis = redis
70 h.geoip = network.NewGeoIP()
71 h.templates.RWMutex = new(sync.RWMutex)
72 h.templates.mirrorlist = template.Must(h.LoadTemplates("mirrorlist"))
73 h.templates.mirrorstats = template.Must(h.LoadTemplates("mirrorstats"))
74 h.cache = cache
75 h.stats = NewStats(redis)
76 h.engine = DefaultEngine{}
77 http.Handle("/", NewGzipHandler(h.requestDispatcher))
78
79 // Load the GeoIP databases
80 if err := h.geoip.LoadGeoIP(); err != nil {
81 var gerr network.GeoIPError
82 if errors.As(err, &gerr) {
83 for _, e := range gerr.Errors {
84 log.Critical(e.Error())
85 }
86 if gerr.IsFatal() {
87 if len(GetConfig().Fallbacks) == 0 {
88 log.Fatal("Can't load the GeoIP databases, please set a valid path in the mirrorbits configuration")
89 } else {
90 log.Critical("Can't load the GeoIP databases, all requests will be served by the fallback mirrors")
91 }
92 } else {
93 log.Critical("One or more GeoIP database could not be loaded, service will run in degraded mode")
94 }
95 }
96 }
97
98 // Initialize the random number generator
99 rand.Seed(time.Now().UnixNano())
100 return h
101 }
102
103 // SetListener can be used to set a different listener that should be used by the
104 // HTTP server. This is primarily used during seamless binary upgrade.
105 func (h *HTTP) SetListener(l net.Listener) {
106 h.Listener = &l
107 }
108
109 // Stop gracefully stops the HTTP server with a timeout to let
110 // the remaining connections finish
111 func (h *HTTP) Stop(timeout time.Duration) {
112 /* Close the server and process remaining connections */
113 h.stoppedMutex.Lock()
114 defer h.stoppedMutex.Unlock()
115 if h.stopped {
116 return
117 }
118 h.stopped = true
119 h.server.Stop(timeout)
120 }
121
122 // Terminate terminates the current HTTP server gracefully
123 func (h *HTTP) Terminate() {
124 /* Wait for the server to stop */
125 select {
126 case <-h.serverStopChan:
127 }
128 /* Commit the latest recorded stats to the database */
129 h.stats.Terminate()
130 }
131
132 // StopChan returns a channel that notifies when the server is stopped
133 func (h *HTTP) StopChan() <-chan struct{} {
134 return h.serverStopChan
135 }
136
137 // Reload the configuration
138 func (h *HTTP) Reload() {
139 // Reload the GeoIP database
140 h.geoip.LoadGeoIP()
141
142 // Reload the templates
143 h.templates.Lock()
144 if t, err := h.LoadTemplates("mirrorlist"); err == nil {
145 h.templates.mirrorlist = t
146 } else {
147 log.Errorf("could not reload templates 'mirrorlist': %s", err.Error())
148 }
149 if t, err := h.LoadTemplates("mirrorstats"); err == nil {
150 h.templates.mirrorstats = t
151 } else {
152 log.Errorf("could not reload templates 'mirrorstats': %s", err.Error())
153 }
154 h.templates.Unlock()
155 }
156
157 // RunServer is the main function used to start the HTTP server
158 func (h *HTTP) RunServer() (err error) {
159 // If listener isn't nil that means that we're running a seamless
160 // binary upgrade and we have recovered an already running listener
161 if h.Listener == nil {
162 proto := "tcp"
163 address := GetConfig().ListenAddress
164 if strings.HasPrefix(address, "unix:") {
165 proto = "unix"
166 address = strings.TrimPrefix(address, "unix:")
167 }
168 listener, err := net.Listen(proto, address)
169 if err != nil {
170 log.Fatal("Listen: ", err)
171 }
172 h.SetListener(listener)
173 }
174
175 h.server = &graceful.Server{
176 // http
177 Server: &http.Server{
178 Handler: nil,
179 ReadTimeout: 10 * time.Second,
180 WriteTimeout: 10 * time.Second,
181 MaxHeaderBytes: 1 << 20,
182 },
183
184 // graceful
185 Timeout: 10 * time.Second,
186 NoSignalHandling: true,
187 }
188 h.serverStopChan = h.server.StopChan()
189
190 log.Infof("Service listening on %s", GetConfig().ListenAddress)
191
192 // Since main blocks here until completion, tell systemd we're ready.
193 // This is a no-op if NOTIFY_SOCKET isn't set.
194 if os.Getenv("NOTIFY_SOCKET") != "" {
195 log.Debug("Notifying systemd of readiness")
196 systemd.SdNotify(false, systemd.SdNotifyReady)
197 }
198
199 /* Serve until we receive a SIGTERM */
200 return h.server.Serve(*h.Listener)
201 }
202
203 func (h *HTTP) requestDispatcher(w http.ResponseWriter, r *http.Request) {
204 h.templates.RLock()
205 ctx := NewContext(w, r, h.templates)
206 h.templates.RUnlock()
207
208 w.Header().Set("Server", "Mirrorbits/"+core.VERSION)
209
210 switch ctx.Type() {
211 case MIRRORLIST:
212 fallthrough
213 case STANDARD:
214 h.mirrorHandler(w, r, ctx)
215 case MIRRORSTATS:
216 h.mirrorStatsHandler(w, r, ctx)
217 case FILESTATS:
218 h.fileStatsHandler(w, r, ctx)
219 case CHECKSUM:
220 h.checksumHandler(w, r, ctx)
221 }
222 }
223
224 func (h *HTTP) mirrorHandler(w http.ResponseWriter, r *http.Request, ctx *Context) {
225 //XXX it would be safer to recover in case of panic
226
227 // Sanitize path
228 urlPath, err := filesystem.EvaluateFilePath(GetConfig().Repository, r.URL.Path)
229 if err != nil {
230 if err == filesystem.ErrOutsideRepo {
231 http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
232 return
233 }
234 http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
235 return
236 }
237
238 // Get details about the requested file. Errors are not fatal, and
239 // expected when the database is not ready: fallbacks will handle it.
240 fileInfo, err := h.cache.GetFileInfo(urlPath)
241 if err != nil {
242 //log.Debugf("Error while fetching Fileinfo: %s", err.Error())
243 }
244
245 if checkIfModifiedSince(r, fileInfo.ModTime) == condFalse {
246 setLastModified(w, fileInfo.ModTime)
247 writeNotModified(w)
248 return
249 }
250
251 remoteIP := network.ExtractRemoteIP(r.Header.Get("X-Forwarded-For"))
252 if len(remoteIP) == 0 {
253 remoteIP = network.RemoteIPFromAddr(r.RemoteAddr)
254 }
255
256 if ctx.IsMirrorlist() {
257 fromip := ctx.QueryParam("fromip")
258 if net.ParseIP(fromip) != nil {
259 remoteIP = fromip
260 }
261 }
262
263 clientInfo := h.geoip.GetRecord(remoteIP) //TODO return a pointer?
264
265 mlist, excluded, err := h.engine.Selection(ctx, h.cache, &fileInfo, clientInfo)
266
267 /* Handle errors */
268 fallback := false
269 var netErr net.Error
270 if errors.As(err, &netErr) || len(mlist) == 0 {
271 /* Handle fallbacks */
272 fallbacks := GetConfig().Fallbacks
273 if len(fallbacks) > 0 {
274 fallback = true
275 for i, f := range fallbacks {
276 // Set the absolute URL
277 var absURL string
278 if utils.HasAnyPrefix(f.URL, "http://", "https://") {
279 absURL = f.URL
280 } else if ctx.SecureOption() == WITHOUTTLS {
281 absURL = "http://" + f.URL
282 } else {
283 absURL = "https://" + f.URL
284 }
285
286 // Create a mirror object and add it to the result
287 mlist = append(mlist, mirrors.Mirror{
288 ID: i * -1,
289 Name: fmt.Sprintf("fallback%d", i),
290 HttpURL: f.URL,
291 CountryCodes: strings.ToUpper(f.CountryCode),
292 CountryFields: []string{strings.ToUpper(f.CountryCode)},
293 ContinentCode: strings.ToUpper(f.ContinentCode),
294 AbsoluteURL: absURL})
295 }
296 sort.Sort(mirrors.ByRank{Mirrors: mlist, ClientInfo: clientInfo})
297 } else {
298 // No fallback in stock, there's nothing else we can do
299 http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
300 return
301 }
302 } else if err != nil {
303 http.Error(w, err.Error(), http.StatusInternalServerError)
304 return
305 }
306
307 results := &mirrors.Results{
308 FileInfo: fileInfo,
309 MirrorList: mlist,
310 ExcludedList: excluded,
311 ClientInfo: clientInfo,
312 IP: remoteIP,
313 Fallback: fallback,
314 LocalJSPath: GetConfig().LocalJSPath,
315 }
316
317 var resultRenderer resultsRenderer
318
319 if ctx.IsMirrorlist() {
320 resultRenderer = &MirrorListRenderer{}
321 } else {
322 switch GetConfig().OutputMode {
323 case "json":
324 resultRenderer = &JSONRenderer{}
325 case "redirect":
326 resultRenderer = &RedirectRenderer{}
327 case "auto":
328 accept := r.Header.Get("Accept")
329 if strings.Index(accept, "application/json") >= 0 {
330 resultRenderer = &JSONRenderer{}
331 } else {
332 resultRenderer = &RedirectRenderer{}
333 }
334 default:
335 http.Error(w, "No page renderer", http.StatusInternalServerError)
336 return
337 }
338 }
339
340 w.Header().Set("Cache-Control", "private, no-cache")
341
342 status, err := resultRenderer.Write(ctx, results)
343 if err != nil {
344 http.Error(w, err.Error(), status)
345 }
346
347 if !ctx.IsMirrorlist() {
348 logs.LogDownload(resultRenderer.Type(), r.Method, status, results, err)
349 if len(mlist) > 0 && r.Method == "GET" && resultRenderer.Type() == "REDIRECT" {
350 timeout := GetConfig().SameDownloadInterval
351 if r.Header.Get("Range") == "" || timeout == 0 {
352 h.stats.CountDownload(mlist[0], fileInfo)
353 } else {
354 downloaderID := remoteIP+"/"+r.Header.Get("User-Agent")
355 hash := sha256.New()
356 hash.Write([]byte(downloaderID))
357 chk := hex.EncodeToString(hash.Sum(nil))
358
359 rconn := h.redis.Get()
360 defer rconn.Close()
361
362 tempKey := "DOWNLOADED_"+chk+"_"+urlPath
363
364 prev := ""
365 if h.redis.IsAtLeastVersion("6.2.0") {
366 // Get and set the key in one command.
367 prev, _ = redis.String(rconn.Do("SET", tempKey, 1, "GET", "EX", timeout))
368 } else {
369 prev, _ = redis.String(rconn.Do("GET", tempKey))
370 }
371 if prev == "" {
372 // Only count partial requests as a new download if
373 // we haven't had any recently from the same client
374 // (i.e. same (IP, user-agent) hash). This prevents
375 // from counting multiple times a single client
376 // downloading a single file in pieces, such as
377 // torrent clients when files are used as web seeds.
378 h.stats.CountDownload(mlist[0], fileInfo)
379 }
380
381 if ! h.redis.IsAtLeastVersion("6.2.0") {
382 // Set the key anyway to reset the timer.
383 rconn.Send("SET", tempKey, 1, "EX", timeout)
384 }
385 }
386 }
387 }
388
389 return
390 }
391
392 // LoadTemplates pre-loads templates from the configured template directory
393 func (h *HTTP) LoadTemplates(name string) (t *template.Template, err error) {
394 t = template.New("t")
395 t.Funcs(template.FuncMap{
396 "add": utils.Add,
397 "sizeof": utils.ReadableSize,
398 "version": utils.Version,
399 "hostname": utils.Hostname,
400 "concaturl": utils.ConcatURL,
401 "dateutc": utils.FormattedDateUTC,
402 "iszero": utils.IsZero,
403 })
404 t, err = t.ParseFiles(
405 filepath.Clean(GetConfig().Templates+"/base.html"),
406 filepath.Clean(fmt.Sprintf("%s/%s.html", GetConfig().Templates, name)))
407 if err != nil {
408 var e *os.PathError
409 if errors.As(err, &e) {
410 log.Fatalf(fmt.Sprintf("Cannot load template %s: %s", e.Path, e.Err.Error()))
411 } else {
412 log.Fatal(err.Error())
413 }
414 }
415 return t, err
416 }
417
418 // StatsFileNow is the structure containing the latest stats of a file
419 type StatsFileNow struct {
420 Today int64
421 Month int64
422 Year int64
423 Total int64
424 }
425
426 // StatsFilePeriod is the structure containing the stats for the given period
427 type StatsFilePeriod struct {
428 Period string
429 Downloads int64
430 }
431
432 // See stats.go header for the storage structure
433 func (h *HTTP) fileStatsHandler(w http.ResponseWriter, r *http.Request, ctx *Context) {
434 var output []byte
435
436 rconn := h.redis.Get()
437 defer rconn.Close()
438
439 req := strings.SplitN(ctx.QueryParam("stats"), "-", 3)
440
441 // Sanity check
442 for _, e := range req {
443 if e == "" {
444 continue
445 }
446 if _, err := strconv.ParseInt(e, 10, 0); err != nil {
447 http.Error(w, "Invalid period", http.StatusBadRequest)
448 return
449 }
450 }
451
452 if len(req) == 0 || req[0] == "" {
453 fkey := fmt.Sprintf("STATS_FILE_%s", time.Now().Format("2006_01_02"))
454
455 rconn.Send("MULTI")
456
457 for i := 0; i < 4; i++ {
458 rconn.Send("HGET", fkey, r.URL.Path)
459 fkey = fkey[:strings.LastIndex(fkey, "_")]
460 }
461
462 res, err := redis.Values(rconn.Do("EXEC"))
463
464 if err != nil && err != redis.ErrNil {
465 http.Error(w, err.Error(), http.StatusInternalServerError)
466 return
467 }
468
469 s := &StatsFileNow{}
470 s.Today, _ = redis.Int64(res[0], err)
471 s.Month, _ = redis.Int64(res[1], err)
472 s.Year, _ = redis.Int64(res[2], err)
473 s.Total, _ = redis.Int64(res[3], err)
474
475 output, err = json.MarshalIndent(s, "", " ")
476 } else {
477 // Generate the redis key
478 dkey := "STATS_FILE_"
479 for _, e := range req {
480 dkey += fmt.Sprintf("%s_", e)
481 }
482 dkey = dkey[:len(dkey)-1]
483
484 v, err := redis.Int64(rconn.Do("HGET", dkey, r.URL.Path))
485 if err != nil && err != redis.ErrNil {
486 http.Error(w, err.Error(), http.StatusInternalServerError)
487 return
488 }
489 s := &StatsFilePeriod{Period: ctx.QueryParam("stats"), Downloads: v}
490
491 output, err = json.MarshalIndent(s, "", " ")
492 }
493
494 w.Write(output)
495 }
496
497 func (h *HTTP) checksumHandler(w http.ResponseWriter, r *http.Request, ctx *Context) {
498
499 // Sanitize path
500 urlPath, err := filesystem.EvaluateFilePath(GetConfig().Repository, r.URL.Path)
501 if err != nil {
502 if err == filesystem.ErrOutsideRepo {
503 http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
504 return
505 }
506 http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
507 return
508 }
509
510 // Get details about the requested file
511 fileInfo, err := h.cache.GetFileInfo(urlPath)
512 if err != nil {
513 log.Errorf("Error while fetching Fileinfo: %s", err.Error())
514 http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
515 return
516 }
517
518 var hash string
519
520 if ctx.paramBool("md5") {
521 hash = fileInfo.Md5
522 } else if ctx.paramBool("sha1") {
523 hash = fileInfo.Sha1
524 } else if ctx.paramBool("sha256") {
525 hash = fileInfo.Sha256
526 }
527
528 if len(hash) == 0 {
529 http.Error(w, "Hash type not supported", http.StatusNotFound)
530 return
531 }
532
533 w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
534 w.Write([]byte(fmt.Sprintf("%s %s", hash, filepath.Base(fileInfo.Path))))
535
536 return
537 }
538
539 // MirrorStats contains the stats of a given mirror
540 type MirrorStats struct {
541 ID int
542 Name string
543 Downloads int64
544 Bytes int64
545 PercentD float32
546 PercentB float32
547 SyncOffset SyncOffset
548 TZOffset time.Duration
549 }
550
551 // SyncOffset contains the time offset between the mirror and the local repository
552 type SyncOffset struct {
553 Valid bool
554 Value int // in hours
555 HumanReadable string
556 }
557
558 // MirrorStatsPage contains the values needed to generate the mirrorstats page
559 type MirrorStatsPage struct {
560 List []MirrorStats
561 MirrorList []mirrors.Mirror
562 LocalJSPath string
563 HasTZAdjustement bool
564 }
565
566 // byDownloadNumbers is a sorting function
567 type byDownloadNumbers struct {
568 mirrorStatsSlice
569 }
570
571 func (b byDownloadNumbers) Less(i, j int) bool {
572 if b.mirrorStatsSlice[i].Downloads > b.mirrorStatsSlice[j].Downloads {
573 return true
574 }
575 return false
576 }
577
578 // mirrorStatsSlice is a slice of MirrorStats
579 type mirrorStatsSlice []MirrorStats
580
581 func (s mirrorStatsSlice) Len() int { return len(s) }
582 func (s mirrorStatsSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
583
584 func (h *HTTP) mirrorStatsHandler(w http.ResponseWriter, r *http.Request, ctx *Context) {
585
586 rconn := h.redis.Get()
587 defer rconn.Close()
588
589 // Get all mirrors ID
590 mirrorsMap, err := h.redis.GetListOfMirrors()
591 if err != nil {
592 http.Error(w, "Cannot fetch the list of mirrors", http.StatusInternalServerError)
593 return
594 }
595
596 var mirrorsIDs []int
597 for id := range mirrorsMap {
598 // We need a common order to iterate the
599 // results from Redis.
600 mirrorsIDs = append(mirrorsIDs, id)
601 }
602
603 rconn.Send("MULTI")
604
605 // Get all mirrors stats
606 for _, id := range mirrorsIDs {
607 today := time.Now().UTC().Format("2006_01_02")
608 rconn.Send("HGET", "STATS_MIRROR_"+today, id)
609 rconn.Send("HGET", "STATS_MIRROR_BYTES_"+today, id)
610 }
611
612 stats, err := redis.Values(rconn.Do("EXEC"))
613 if err != nil {
614 http.Error(w, "Cannot fetch stats", http.StatusInternalServerError)
615 return
616 }
617
618 var hasTZAdjustement bool
619 var maxdownloads int64
620 var maxbytes int64
621 var results []MirrorStats
622 var index int64
623 mlist := make([]mirrors.Mirror, 0, len(mirrorsIDs))
624 for _, id := range mirrorsIDs {
625 mirror, err := h.cache.GetMirror(id)
626 if err != nil {
627 continue
628 }
629 mlist = append(mlist, mirror)
630
631 var downloads int64
632 if v, _ := redis.String(stats[index], nil); v != "" {
633 downloads, _ = strconv.ParseInt(v, 10, 64)
634 }
635 var bytes int64
636 if v, _ := redis.String(stats[index+1], nil); v != "" {
637 bytes, _ = strconv.ParseInt(v, 10, 64)
638 }
639
640 if downloads > maxdownloads {
641 maxdownloads = downloads
642 }
643 if bytes > maxbytes {
644 maxbytes = bytes
645 }
646
647 var lastModTime time.Time
648
649 if !mirror.LastModTime.IsZero() {
650 lastModTime = mirror.LastModTime.Time
651 }
652
653 elapsed := time.Since(lastModTime)
654
655 tzoffset, _ := time.ParseDuration(fmt.Sprintf("%dms", mirror.TZOffset))
656 if tzoffset != 0 {
657 hasTZAdjustement = true
658 }
659
660 s := MirrorStats{
661 ID: id,
662 Name: mirror.Name,
663 Downloads: downloads,
664 Bytes: bytes,
665 SyncOffset: SyncOffset{
666 Valid: !lastModTime.IsZero(),
667 Value: int(elapsed.Hours()),
668 HumanReadable: utils.FuzzyTimeStr(elapsed),
669 },
670 TZOffset: tzoffset,
671 }
672 results = append(results, s)
673 index += 2
674 }
675
676 sort.Sort(byDownloadNumbers{results})
677
678 for i := 0; i < len(results); i++ {
679 results[i].PercentD = float32(results[i].Downloads) * 100 / float32(maxdownloads)
680 results[i].PercentB = float32(results[i].Bytes) * 100 / float32(maxbytes)
681 }
682
683 w.Header().Set("Content-Type", "text/html; charset=utf-8")
684 err = ctx.Templates().mirrorstats.ExecuteTemplate(w, "base", MirrorStatsPage{results, mlist, GetConfig().LocalJSPath, hasTZAdjustement})
685 if err != nil {
686 log.Errorf("HTTP error: %s", err.Error())
687 http.Error(w, err.Error(), http.StatusInternalServerError)
688 return
689 }
690 }