1
0

server.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  100. buf := responseGzipBufPool.get()
  101. defer responseGzipBufPool.put(buf)
  102. gz := responseGzipPool.get(buf)
  103. defer responseGzipPool.put(gz)
  104. gz.Write(data)
  105. gz.Close()
  106. rw.Header().Set("Content-Encoding", "gzip")
  107. rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
  108. rw.WriteHeader(200)
  109. buf.WriteTo(rw)
  110. } else {
  111. rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
  112. rw.WriteHeader(200)
  113. rw.Write(data)
  114. }
  115. logResponse(reqID, 200, fmt.Sprintf("Processed in %s: %s; %+v", getTimerSince(ctx), getImageURL(ctx), po))
  116. }
  117. func respondWithError(reqID string, rw http.ResponseWriter, err *imgproxyError) {
  118. logResponse(reqID, err.StatusCode, err.Message)
  119. rw.WriteHeader(err.StatusCode)
  120. rw.Write([]byte(err.PublicMessage))
  121. }
  122. func respondWithOptions(reqID string, rw http.ResponseWriter) {
  123. logResponse(reqID, 200, "Respond with options")
  124. rw.WriteHeader(200)
  125. }
  126. func respondWithNotModified(reqID string, rw http.ResponseWriter) {
  127. logResponse(reqID, 200, "Not modified")
  128. rw.WriteHeader(304)
  129. }
  130. func prepareAuthHeaderMust() []byte {
  131. if len(authHeaderMust) == 0 {
  132. authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  133. }
  134. return authHeaderMust
  135. }
  136. func checkSecret(r *http.Request) bool {
  137. if len(conf.Secret) == 0 {
  138. return true
  139. }
  140. return subtle.ConstantTimeCompare(
  141. []byte(r.Header.Get("Authorization")),
  142. prepareAuthHeaderMust(),
  143. ) == 1
  144. }
  145. func (h *httpHandler) lock() {
  146. h.sem <- struct{}{}
  147. }
  148. func (h *httpHandler) unlock() {
  149. <-h.sem
  150. }
  151. func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  152. reqID, _ := nanoid.Nanoid()
  153. defer func() {
  154. if rerr := recover(); rerr != nil {
  155. if err, ok := rerr.(error); ok {
  156. reportError(err, r)
  157. if ierr, ok := err.(*imgproxyError); ok {
  158. respondWithError(reqID, rw, ierr)
  159. } else {
  160. respondWithError(reqID, rw, newUnexpectedError(err, 4))
  161. }
  162. } else {
  163. panic(rerr)
  164. }
  165. }
  166. }()
  167. logRequest(reqID, r)
  168. writeCORS(rw)
  169. if r.Method == http.MethodOptions {
  170. respondWithOptions(reqID, rw)
  171. return
  172. }
  173. if r.Method != http.MethodGet {
  174. panic(errInvalidMethod)
  175. }
  176. if !checkSecret(r) {
  177. panic(errInvalidSecret)
  178. }
  179. if r.URL.RequestURI() == healthPath {
  180. rw.WriteHeader(200)
  181. rw.Write(imgproxyIsRunningMsg)
  182. return
  183. }
  184. ctx := context.Background()
  185. if newRelicEnabled {
  186. var newRelicCancel context.CancelFunc
  187. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  188. defer newRelicCancel()
  189. }
  190. if prometheusEnabled {
  191. prometheusRequestsTotal.Inc()
  192. defer startPrometheusDuration(prometheusRequestDuration)()
  193. }
  194. h.lock()
  195. defer h.unlock()
  196. ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  197. defer timeoutCancel()
  198. ctx, err := parsePath(ctx, r)
  199. if err != nil {
  200. panic(err)
  201. }
  202. ctx, downloadcancel, err := downloadImage(ctx)
  203. defer downloadcancel()
  204. if err != nil {
  205. if newRelicEnabled {
  206. sendErrorToNewRelic(ctx, err)
  207. }
  208. if prometheusEnabled {
  209. incrementPrometheusErrorsTotal("download")
  210. }
  211. panic(err)
  212. }
  213. checkTimeout(ctx)
  214. if conf.ETagEnabled {
  215. eTag := calcETag(ctx)
  216. rw.Header().Set("ETag", eTag)
  217. if eTag == r.Header.Get("If-None-Match") {
  218. respondWithNotModified(reqID, rw)
  219. return
  220. }
  221. }
  222. checkTimeout(ctx)
  223. imageData, processcancel, err := processImage(ctx)
  224. defer processcancel()
  225. if err != nil {
  226. if newRelicEnabled {
  227. sendErrorToNewRelic(ctx, err)
  228. }
  229. if prometheusEnabled {
  230. incrementPrometheusErrorsTotal("processing")
  231. }
  232. panic(err)
  233. }
  234. checkTimeout(ctx)
  235. respondWithImage(ctx, reqID, r, rw, imageData)
  236. }