server.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/subtle"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "time"
  13. nanoid "github.com/matoous/go-nanoid"
  14. "github.com/valyala/fasthttp"
  15. )
  16. const (
  17. contextDispositionFilenameFallback = "image"
  18. xRequestIDHeader = "X-Request-ID"
  19. )
  20. var (
  21. mimes = map[imageType]string{
  22. imageTypeJPEG: "image/jpeg",
  23. imageTypePNG: "image/png",
  24. imageTypeWEBP: "image/webp",
  25. imageTypeGIF: "image/gif",
  26. imageTypeICO: "image/x-icon",
  27. }
  28. contentDispositionsFmt = map[imageType]string{
  29. imageTypeJPEG: "inline; filename=\"%s.jpg\"",
  30. imageTypePNG: "inline; filename=\"%s.png\"",
  31. imageTypeWEBP: "inline; filename=\"%s.webp\"",
  32. imageTypeGIF: "inline; filename=\"%s.gif\"",
  33. imageTypeICO: "inline; filename=\"%s.ico\"",
  34. }
  35. authHeaderMust []byte
  36. healthPath = []byte("/health")
  37. imgproxyIsRunningMsg = []byte("imgproxy is running")
  38. errInvalidMethod = newError(422, "Invalid request method", "Method doesn't allowed")
  39. errInvalidSecret = newError(403, "Invalid secret", "Forbidden")
  40. responseGzipPool *gzipPool
  41. requestIDRe = regexp.MustCompile(`^[A-Za-z0-9_\-]+$`)
  42. )
  43. type httpHandler struct {
  44. sem chan struct{}
  45. }
  46. func newHTTPHandler() *httpHandler {
  47. return &httpHandler{make(chan struct{}, conf.Concurrency)}
  48. }
  49. func startServer() *fasthttp.Server {
  50. handler := newHTTPHandler()
  51. server := &fasthttp.Server{
  52. Name: "imgproxy",
  53. Handler: handler.ServeHTTP,
  54. Concurrency: conf.MaxClients,
  55. ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
  56. }
  57. if conf.GZipCompression > 0 {
  58. responseGzipPool = newGzipPool(conf.Concurrency)
  59. }
  60. if conf.ETagEnabled {
  61. eTagCalcPool = newEtagPool(conf.Concurrency)
  62. }
  63. go func() {
  64. logNotice("Starting server at %s", conf.Bind)
  65. if err := server.ListenAndServe(conf.Bind); err != nil {
  66. logFatal(err.Error())
  67. }
  68. }()
  69. return server
  70. }
  71. func shutdownServer(s *fasthttp.Server) {
  72. logNotice("Shutting down the server...")
  73. s.Shutdown()
  74. }
  75. func writeCORS(rctx *fasthttp.RequestCtx) {
  76. if len(conf.AllowOrigin) > 0 {
  77. rctx.Response.Header.Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  78. rctx.Response.Header.Set("Access-Control-Allow-Methods", "GET, OPTIONs")
  79. }
  80. }
  81. func contentDisposition(imageURL string, imgtype imageType) string {
  82. url, err := url.Parse(imageURL)
  83. if err != nil {
  84. return fmt.Sprintf(contentDispositionsFmt[imgtype], contextDispositionFilenameFallback)
  85. }
  86. _, filename := filepath.Split(url.Path)
  87. if len(filename) == 0 {
  88. return fmt.Sprintf(contentDispositionsFmt[imgtype], contextDispositionFilenameFallback)
  89. }
  90. return fmt.Sprintf(contentDispositionsFmt[imgtype], strings.TrimSuffix(filename, filepath.Ext(filename)))
  91. }
  92. func respondWithImage(ctx context.Context, reqID string, rctx *fasthttp.RequestCtx, data []byte) {
  93. po := getProcessingOptions(ctx)
  94. rctx.SetStatusCode(200)
  95. rctx.Response.Header.Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  96. rctx.Response.Header.Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
  97. rctx.Response.Header.Set("Content-Type", mimes[po.Format])
  98. rctx.Response.Header.Set("Content-Disposition", contentDisposition(getImageURL(ctx), po.Format))
  99. addVaryHeader(rctx)
  100. if conf.GZipCompression > 0 && rctx.Request.Header.HasAcceptEncoding("gzip") {
  101. gz := responseGzipPool.Get(rctx)
  102. defer responseGzipPool.Put(gz)
  103. gz.Write(data)
  104. gz.Close()
  105. rctx.Response.Header.Set("Content-Encoding", "gzip")
  106. } else {
  107. rctx.SetBody(data)
  108. }
  109. logResponse(reqID, 200, fmt.Sprintf("Processed in %s: %s; %+v", getTimerSince(ctx), getImageURL(ctx), po))
  110. }
  111. func addVaryHeader(rctx *fasthttp.RequestCtx) {
  112. vary := make([]string, 0, 5)
  113. if conf.EnableWebpDetection || conf.EnforceWebp {
  114. vary = append(vary, "Accept")
  115. }
  116. if conf.GZipCompression > 0 {
  117. vary = append(vary, "Accept-Encoding")
  118. }
  119. if conf.EnableClientHints {
  120. vary = append(vary, "DPR", "Viewport-Width", "Width")
  121. }
  122. if len(vary) > 0 {
  123. rctx.Response.Header.Set("Vary", strings.Join(vary, ", "))
  124. }
  125. }
  126. func respondWithError(reqID string, rctx *fasthttp.RequestCtx, err *imgproxyError) {
  127. logResponse(reqID, err.StatusCode, err.Message)
  128. rctx.SetStatusCode(err.StatusCode)
  129. rctx.SetBodyString(err.PublicMessage)
  130. }
  131. func respondWithOptions(reqID string, rctx *fasthttp.RequestCtx) {
  132. logResponse(reqID, 200, "Respond with options")
  133. rctx.SetStatusCode(200)
  134. }
  135. func respondWithNotModified(reqID string, rctx *fasthttp.RequestCtx) {
  136. logResponse(reqID, 304, "Not modified")
  137. rctx.SetStatusCode(304)
  138. }
  139. func generateRequestID(rctx *fasthttp.RequestCtx) (reqID string) {
  140. reqIDb := rctx.Request.Header.Peek(xRequestIDHeader)
  141. if len(reqIDb) > 0 && requestIDRe.Match(reqIDb) {
  142. reqID = string(reqIDb)
  143. } else {
  144. reqID, _ = nanoid.Nanoid()
  145. }
  146. rctx.Response.Header.Set(xRequestIDHeader, reqID)
  147. return
  148. }
  149. func prepareAuthHeaderMust() []byte {
  150. if len(authHeaderMust) == 0 {
  151. authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  152. }
  153. return authHeaderMust
  154. }
  155. func checkSecret(rctx *fasthttp.RequestCtx) bool {
  156. if len(conf.Secret) == 0 {
  157. return true
  158. }
  159. return subtle.ConstantTimeCompare(
  160. rctx.Request.Header.Peek("Authorization"),
  161. prepareAuthHeaderMust(),
  162. ) == 1
  163. }
  164. func requestCtxToRequest(rctx *fasthttp.RequestCtx) *http.Request {
  165. if r, ok := rctx.UserValue("httpRequest").(*http.Request); ok {
  166. return r
  167. }
  168. reqURL, _ := url.Parse(rctx.Request.URI().String())
  169. r := &http.Request{
  170. Method: http.MethodGet, // Only GET is supported
  171. URL: reqURL,
  172. Proto: "HTTP/1.0",
  173. ProtoMajor: 1,
  174. ProtoMinor: 0,
  175. Header: make(http.Header),
  176. Body: http.NoBody,
  177. Host: reqURL.Host,
  178. RequestURI: reqURL.RequestURI(),
  179. RemoteAddr: rctx.RemoteAddr().String(),
  180. }
  181. rctx.Request.Header.VisitAll(func(key, value []byte) {
  182. r.Header.Add(string(key), string(value))
  183. })
  184. rctx.SetUserValue("httpRequest", r)
  185. return r
  186. }
  187. func (h *httpHandler) lock() {
  188. h.sem <- struct{}{}
  189. }
  190. func (h *httpHandler) unlock() {
  191. <-h.sem
  192. }
  193. func (h *httpHandler) ServeHTTP(rctx *fasthttp.RequestCtx) {
  194. reqID := generateRequestID(rctx)
  195. defer func() {
  196. if rerr := recover(); rerr != nil {
  197. if err, ok := rerr.(error); ok {
  198. reportError(err, requestCtxToRequest(rctx))
  199. if ierr, ok := err.(*imgproxyError); ok {
  200. respondWithError(reqID, rctx, ierr)
  201. } else {
  202. respondWithError(reqID, rctx, newUnexpectedError(err, 4))
  203. }
  204. } else {
  205. panic(rerr)
  206. }
  207. }
  208. }()
  209. logRequest(reqID, rctx)
  210. writeCORS(rctx)
  211. if rctx.Request.Header.IsOptions() {
  212. respondWithOptions(reqID, rctx)
  213. return
  214. }
  215. if !rctx.Request.Header.IsGet() {
  216. panic(errInvalidMethod)
  217. }
  218. if bytes.Equal(rctx.RequestURI(), healthPath) {
  219. rctx.SetStatusCode(200)
  220. rctx.SetBody(imgproxyIsRunningMsg)
  221. return
  222. }
  223. if !checkSecret(rctx) {
  224. panic(errInvalidSecret)
  225. }
  226. ctx := context.Background()
  227. if newRelicEnabled {
  228. var newRelicCancel context.CancelFunc
  229. ctx, newRelicCancel = startNewRelicTransaction(ctx, requestCtxToRequest(rctx))
  230. defer newRelicCancel()
  231. }
  232. if prometheusEnabled {
  233. prometheusRequestsTotal.Inc()
  234. defer startPrometheusDuration(prometheusRequestDuration)()
  235. }
  236. h.lock()
  237. defer h.unlock()
  238. ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  239. defer timeoutCancel()
  240. ctx, err := parsePath(ctx, rctx)
  241. if err != nil {
  242. panic(err)
  243. }
  244. ctx, downloadcancel, err := downloadImage(ctx)
  245. defer downloadcancel()
  246. if err != nil {
  247. if newRelicEnabled {
  248. sendErrorToNewRelic(ctx, err)
  249. }
  250. if prometheusEnabled {
  251. incrementPrometheusErrorsTotal("download")
  252. }
  253. panic(err)
  254. }
  255. checkTimeout(ctx)
  256. if conf.ETagEnabled {
  257. eTag, etagcancel := calcETag(ctx)
  258. defer etagcancel()
  259. rctx.Response.Header.SetBytesV("ETag", eTag)
  260. if bytes.Equal(eTag, rctx.Request.Header.Peek("If-None-Match")) {
  261. respondWithNotModified(reqID, rctx)
  262. return
  263. }
  264. }
  265. checkTimeout(ctx)
  266. imageData, processcancel, err := processImage(ctx)
  267. defer processcancel()
  268. if err != nil {
  269. if newRelicEnabled {
  270. sendErrorToNewRelic(ctx, err)
  271. }
  272. if prometheusEnabled {
  273. incrementPrometheusErrorsTotal("processing")
  274. }
  275. panic(err)
  276. }
  277. checkTimeout(ctx)
  278. respondWithImage(ctx, reqID, rctx, imageData)
  279. }