middleware.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package http
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime/debug"
  6. "strings"
  7. "time"
  8. "github.com/ethereum/go-ethereum/metrics"
  9. "github.com/ethereum/go-ethereum/swarm/api"
  10. "github.com/ethereum/go-ethereum/swarm/chunk"
  11. "github.com/ethereum/go-ethereum/swarm/log"
  12. "github.com/ethereum/go-ethereum/swarm/sctx"
  13. "github.com/ethereum/go-ethereum/swarm/spancontext"
  14. "github.com/pborman/uuid"
  15. )
  16. // Adapt chains h (main request handler) main handler to adapters (middleware handlers)
  17. // Please note that the order of execution for `adapters` is FIFO (adapters[0] will be executed first)
  18. func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
  19. for i := range adapters {
  20. adapter := adapters[len(adapters)-1-i]
  21. h = adapter(h)
  22. }
  23. return h
  24. }
  25. type Adapter func(http.Handler) http.Handler
  26. func SetRequestID(h http.Handler) http.Handler {
  27. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  28. r = r.WithContext(SetRUID(r.Context(), uuid.New()[:8]))
  29. metrics.GetOrRegisterCounter(fmt.Sprintf("http.request.%s", r.Method), nil).Inc(1)
  30. log.Info("created ruid for request", "ruid", GetRUID(r.Context()), "method", r.Method, "url", r.RequestURI)
  31. h.ServeHTTP(w, r)
  32. })
  33. }
  34. func SetRequestHost(h http.Handler) http.Handler {
  35. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  36. r = r.WithContext(sctx.SetHost(r.Context(), r.Host))
  37. log.Info("setting request host", "ruid", GetRUID(r.Context()), "host", sctx.GetHost(r.Context()))
  38. h.ServeHTTP(w, r)
  39. })
  40. }
  41. func ParseURI(h http.Handler) http.Handler {
  42. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  43. uri, err := api.Parse(strings.TrimLeft(r.URL.Path, "/"))
  44. if err != nil {
  45. w.WriteHeader(http.StatusBadRequest)
  46. respondError(w, r, fmt.Sprintf("invalid URI %q", r.URL.Path), http.StatusBadRequest)
  47. return
  48. }
  49. if uri.Addr != "" && strings.HasPrefix(uri.Addr, "0x") {
  50. uri.Addr = strings.TrimPrefix(uri.Addr, "0x")
  51. msg := fmt.Sprintf(`The requested hash seems to be prefixed with '0x'. You will be redirected to the correct URL within 5 seconds.<br/>
  52. Please click <a href='%[1]s'>here</a> if your browser does not redirect you within 5 seconds.<script>setTimeout("location.href='%[1]s';",5000);</script>`, "/"+uri.String())
  53. w.WriteHeader(http.StatusNotFound)
  54. w.Write([]byte(msg))
  55. return
  56. }
  57. ctx := r.Context()
  58. r = r.WithContext(SetURI(ctx, uri))
  59. log.Debug("parsed request path", "ruid", GetRUID(r.Context()), "method", r.Method, "uri.Addr", uri.Addr, "uri.Path", uri.Path, "uri.Scheme", uri.Scheme)
  60. h.ServeHTTP(w, r)
  61. })
  62. }
  63. func InitLoggingResponseWriter(h http.Handler) http.Handler {
  64. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  65. tn := time.Now()
  66. writer := newLoggingResponseWriter(w)
  67. h.ServeHTTP(writer, r)
  68. ts := time.Since(tn)
  69. log.Info("request served", "ruid", GetRUID(r.Context()), "code", writer.statusCode, "time", ts)
  70. metrics.GetOrRegisterResettingTimer(fmt.Sprintf("http.request.%s.time", r.Method), nil).Update(ts)
  71. metrics.GetOrRegisterResettingTimer(fmt.Sprintf("http.request.%s.%d.time", r.Method, writer.statusCode), nil).Update(ts)
  72. })
  73. }
  74. // InitUploadTag creates a new tag for an upload to the local HTTP proxy
  75. // if a tag is not named using the SwarmTagHeaderName, a fallback name will be used
  76. // when the Content-Length header is set, an ETA on chunking will be available since the
  77. // number of chunks to be split is known in advance (not including enclosing manifest chunks)
  78. // the tag can later be accessed using the appropriate identifier in the request context
  79. func InitUploadTag(h http.Handler, tags *chunk.Tags) http.Handler {
  80. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  81. var (
  82. tagName string
  83. err error
  84. estimatedTotal int64 = 0
  85. contentType = r.Header.Get("Content-Type")
  86. headerTag = r.Header.Get(SwarmTagHeaderName)
  87. )
  88. if headerTag != "" {
  89. tagName = headerTag
  90. log.Trace("got tag name from http header", "tagName", tagName)
  91. } else {
  92. tagName = fmt.Sprintf("unnamed_tag_%d", time.Now().Unix())
  93. }
  94. if !strings.Contains(contentType, "multipart") && r.ContentLength > 0 {
  95. log.Trace("calculating tag size", "contentType", contentType, "contentLength", r.ContentLength)
  96. uri := GetURI(r.Context())
  97. if uri != nil {
  98. log.Debug("got uri from context")
  99. if uri.Addr == "encrypt" {
  100. estimatedTotal = calculateNumberOfChunks(r.ContentLength, true)
  101. } else {
  102. estimatedTotal = calculateNumberOfChunks(r.ContentLength, false)
  103. }
  104. }
  105. }
  106. log.Trace("creating tag", "tagName", tagName, "estimatedTotal", estimatedTotal)
  107. t, err := tags.New(tagName, estimatedTotal)
  108. if err != nil {
  109. log.Error("error creating tag", "err", err, "tagName", tagName)
  110. }
  111. log.Trace("setting tag id to context", "uid", t.Uid)
  112. ctx := sctx.SetTag(r.Context(), t.Uid)
  113. h.ServeHTTP(w, r.WithContext(ctx))
  114. })
  115. }
  116. func InstrumentOpenTracing(h http.Handler) http.Handler {
  117. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  118. uri := GetURI(r.Context())
  119. if uri == nil || r.Method == "" || (uri != nil && uri.Scheme == "") {
  120. h.ServeHTTP(w, r) // soft fail
  121. return
  122. }
  123. spanName := fmt.Sprintf("http.%s.%s", r.Method, uri.Scheme)
  124. ctx, sp := spancontext.StartSpan(r.Context(), spanName)
  125. defer sp.Finish()
  126. h.ServeHTTP(w, r.WithContext(ctx))
  127. })
  128. }
  129. func RecoverPanic(h http.Handler) http.Handler {
  130. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  131. defer func() {
  132. if err := recover(); err != nil {
  133. log.Error("panic recovery!", "stack trace", string(debug.Stack()), "url", r.URL.String(), "headers", r.Header)
  134. }
  135. }()
  136. h.ServeHTTP(w, r)
  137. })
  138. }