server.go 5.9 KB

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