server.go 6.2 KB

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