server.go 7.6 KB

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