server.go 6.5 KB

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