server.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package main
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. nanoid "github.com/matoous/go-nanoid"
  14. "golang.org/x/net/netutil"
  15. )
  16. const (
  17. healthPath = "/health"
  18. contextDispositionFilenameFallback = "image"
  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. imgproxyIsRunningMsg = []byte("imgproxy is running")
  37. errInvalidMethod = newError(422, "Invalid request method", "Method doesn't allowed")
  38. errInvalidSecret = newError(403, "Invalid secret", "Forbidden")
  39. responseGzipBufPool *bufPool
  40. responseGzipPool *gzipPool
  41. )
  42. type httpHandler struct {
  43. sem chan struct{}
  44. }
  45. func newHTTPHandler() *httpHandler {
  46. return &httpHandler{make(chan struct{}, conf.Concurrency)}
  47. }
  48. func startServer() *http.Server {
  49. l, err := net.Listen("tcp", conf.Bind)
  50. if err != nil {
  51. logFatal(err.Error())
  52. }
  53. s := &http.Server{
  54. Handler: newHTTPHandler(),
  55. ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
  56. MaxHeaderBytes: 1 << 20,
  57. }
  58. if conf.GZipCompression > 0 {
  59. responseGzipBufPool = newBufPool(conf.Concurrency, conf.GZipBufferSize)
  60. responseGzipPool = newGzipPool(conf.Concurrency)
  61. }
  62. go func() {
  63. logNotice("Starting server at %s", conf.Bind)
  64. if err := s.Serve(netutil.LimitListener(l, conf.MaxClients)); err != nil && err != http.ErrServerClosed {
  65. logFatal(err.Error())
  66. }
  67. }()
  68. return s
  69. }
  70. func shutdownServer(s *http.Server) {
  71. logNotice("Shutting down the server...")
  72. ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
  73. defer close()
  74. s.Shutdown(ctx)
  75. }
  76. func writeCORS(rw http.ResponseWriter) {
  77. if len(conf.AllowOrigin) > 0 {
  78. rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  79. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONs")
  80. }
  81. }
  82. func contentDisposition(imageURL string, imgtype imageType) string {
  83. url, err := url.Parse(imageURL)
  84. if err != nil {
  85. return fmt.Sprintf(contentDispositionsFmt[imgtype], contextDispositionFilenameFallback)
  86. }
  87. _, filename := filepath.Split(url.Path)
  88. if len(filename) == 0 {
  89. return fmt.Sprintf(contentDispositionsFmt[imgtype], contextDispositionFilenameFallback)
  90. }
  91. return fmt.Sprintf(contentDispositionsFmt[imgtype], strings.TrimSuffix(filename, filepath.Ext(filename)))
  92. }
  93. func respondWithImage(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter, data []byte) {
  94. po := getProcessingOptions(ctx)
  95. rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  96. rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
  97. rw.Header().Set("Content-Type", mimes[po.Format])
  98. rw.Header().Set("Content-Disposition", contentDisposition(getImageURL(ctx), po.Format))
  99. addVaryHeader(rw)
  100. if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  101. buf := responseGzipBufPool.get()
  102. defer responseGzipBufPool.put(buf)
  103. gz := responseGzipPool.get(buf)
  104. defer responseGzipPool.put(gz)
  105. gz.Write(data)
  106. gz.Close()
  107. rw.Header().Set("Content-Encoding", "gzip")
  108. rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
  109. rw.WriteHeader(200)
  110. buf.WriteTo(rw)
  111. } else {
  112. rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
  113. rw.WriteHeader(200)
  114. rw.Write(data)
  115. }
  116. logResponse(reqID, 200, fmt.Sprintf("Processed in %s: %s; %+v", getTimerSince(ctx), getImageURL(ctx), po))
  117. }
  118. func addVaryHeader(rw http.ResponseWriter) {
  119. vary := make([]string, 0)
  120. if conf.EnableWebpDetection || conf.EnforceWebp {
  121. vary = append(vary, "Accept")
  122. }
  123. if conf.GZipCompression > 0 {
  124. vary = append(vary, "Accept-Encoding")
  125. }
  126. if conf.EnableClientHints {
  127. vary = append(vary, "DPR", "Viewport-Width", "Width")
  128. }
  129. if len(vary) > 0 {
  130. rw.Header().Set("Vary", strings.Join(vary, ", "))
  131. }
  132. }
  133. func respondWithError(reqID string, rw http.ResponseWriter, err *imgproxyError) {
  134. logResponse(reqID, err.StatusCode, err.Message)
  135. rw.WriteHeader(err.StatusCode)
  136. rw.Write([]byte(err.PublicMessage))
  137. }
  138. func respondWithOptions(reqID string, rw http.ResponseWriter) {
  139. logResponse(reqID, 200, "Respond with options")
  140. rw.WriteHeader(200)
  141. }
  142. func respondWithNotModified(reqID string, rw http.ResponseWriter) {
  143. logResponse(reqID, 200, "Not modified")
  144. rw.WriteHeader(304)
  145. }
  146. func prepareAuthHeaderMust() []byte {
  147. if len(authHeaderMust) == 0 {
  148. authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  149. }
  150. return authHeaderMust
  151. }
  152. func checkSecret(r *http.Request) bool {
  153. if len(conf.Secret) == 0 {
  154. return true
  155. }
  156. return subtle.ConstantTimeCompare(
  157. []byte(r.Header.Get("Authorization")),
  158. prepareAuthHeaderMust(),
  159. ) == 1
  160. }
  161. func (h *httpHandler) lock() {
  162. h.sem <- struct{}{}
  163. }
  164. func (h *httpHandler) unlock() {
  165. <-h.sem
  166. }
  167. func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  168. reqID, _ := nanoid.Nanoid()
  169. defer func() {
  170. if rerr := recover(); rerr != nil {
  171. if err, ok := rerr.(error); ok {
  172. reportError(err, r)
  173. if ierr, ok := err.(*imgproxyError); ok {
  174. respondWithError(reqID, rw, ierr)
  175. } else {
  176. respondWithError(reqID, rw, newUnexpectedError(err, 4))
  177. }
  178. } else {
  179. panic(rerr)
  180. }
  181. }
  182. }()
  183. logRequest(reqID, r)
  184. writeCORS(rw)
  185. if r.Method == http.MethodOptions {
  186. respondWithOptions(reqID, rw)
  187. return
  188. }
  189. if r.Method != http.MethodGet {
  190. panic(errInvalidMethod)
  191. }
  192. if r.URL.RequestURI() == healthPath {
  193. rw.WriteHeader(200)
  194. rw.Write(imgproxyIsRunningMsg)
  195. return
  196. }
  197. if !checkSecret(r) {
  198. panic(errInvalidSecret)
  199. }
  200. ctx := context.Background()
  201. if newRelicEnabled {
  202. var newRelicCancel context.CancelFunc
  203. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  204. defer newRelicCancel()
  205. }
  206. if prometheusEnabled {
  207. prometheusRequestsTotal.Inc()
  208. defer startPrometheusDuration(prometheusRequestDuration)()
  209. }
  210. h.lock()
  211. defer h.unlock()
  212. ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  213. defer timeoutCancel()
  214. ctx, err := parsePath(ctx, r)
  215. if err != nil {
  216. panic(err)
  217. }
  218. ctx, downloadcancel, err := downloadImage(ctx)
  219. defer downloadcancel()
  220. if err != nil {
  221. if newRelicEnabled {
  222. sendErrorToNewRelic(ctx, err)
  223. }
  224. if prometheusEnabled {
  225. incrementPrometheusErrorsTotal("download")
  226. }
  227. panic(err)
  228. }
  229. checkTimeout(ctx)
  230. if conf.ETagEnabled {
  231. eTag := calcETag(ctx)
  232. rw.Header().Set("ETag", eTag)
  233. if eTag == r.Header.Get("If-None-Match") {
  234. respondWithNotModified(reqID, rw)
  235. return
  236. }
  237. }
  238. checkTimeout(ctx)
  239. imageData, processcancel, err := processImage(ctx)
  240. defer processcancel()
  241. if err != nil {
  242. if newRelicEnabled {
  243. sendErrorToNewRelic(ctx, err)
  244. }
  245. if prometheusEnabled {
  246. incrementPrometheusErrorsTotal("processing")
  247. }
  248. panic(err)
  249. }
  250. checkTimeout(ctx)
  251. respondWithImage(ctx, reqID, r, rw, imageData)
  252. }