server.go 7.7 KB

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