server.go 6.1 KB

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