server.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 prepareAuthHeaderMust() []byte {
  118. if len(authHeaderMust) == 0 {
  119. authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  120. }
  121. return authHeaderMust
  122. }
  123. func checkSecret(r *http.Request) bool {
  124. if len(conf.Secret) == 0 {
  125. return true
  126. }
  127. return subtle.ConstantTimeCompare(
  128. []byte(r.Header.Get("Authorization")),
  129. prepareAuthHeaderMust(),
  130. ) == 1
  131. }
  132. func (h *httpHandler) lock() {
  133. h.sem <- struct{}{}
  134. }
  135. func (h *httpHandler) unlock() {
  136. <-h.sem
  137. }
  138. func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  139. reqID, _ := nanoid.Nanoid()
  140. defer func() {
  141. if rerr := recover(); rerr != nil {
  142. if err, ok := rerr.(error); ok {
  143. if err != errNotModified {
  144. reportError(err, r)
  145. }
  146. if ierr, ok := err.(imgproxyError); ok {
  147. respondWithError(reqID, rw, ierr)
  148. } else {
  149. respondWithError(reqID, rw, newUnexpectedError(err, 4))
  150. }
  151. } else {
  152. panic(rerr)
  153. }
  154. }
  155. }()
  156. log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
  157. writeCORS(rw)
  158. if r.Method == http.MethodOptions {
  159. respondWithOptions(reqID, rw)
  160. return
  161. }
  162. if r.Method != http.MethodGet {
  163. panic(errInvalidMethod)
  164. }
  165. if !checkSecret(r) {
  166. panic(errInvalidSecret)
  167. }
  168. ctx := context.Background()
  169. if newRelicEnabled {
  170. var newRelicCancel context.CancelFunc
  171. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  172. defer newRelicCancel()
  173. }
  174. if prometheusEnabled {
  175. prometheusRequestsTotal.Inc()
  176. defer startPrometheusDuration(prometheusRequestDuration)()
  177. }
  178. h.lock()
  179. defer h.unlock()
  180. if r.URL.RequestURI() == healthPath {
  181. rw.WriteHeader(200)
  182. rw.Write(imgproxyIsRunningMsg)
  183. return
  184. }
  185. ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  186. defer timeoutCancel()
  187. ctx, err := parsePath(ctx, r)
  188. if err != nil {
  189. panic(newError(404, err.Error(), "Invalid image url"))
  190. }
  191. ctx, downloadcancel, err := downloadImage(ctx)
  192. defer downloadcancel()
  193. if err != nil {
  194. if newRelicEnabled {
  195. sendErrorToNewRelic(ctx, err)
  196. }
  197. if prometheusEnabled {
  198. incrementPrometheusErrorsTotal("download")
  199. }
  200. panic(newError(404, err.Error(), "Image is unreachable"))
  201. }
  202. checkTimeout(ctx)
  203. if conf.ETagEnabled {
  204. eTag := calcETag(ctx)
  205. rw.Header().Set("ETag", eTag)
  206. if eTag == r.Header.Get("If-None-Match") {
  207. panic(errNotModified)
  208. }
  209. }
  210. checkTimeout(ctx)
  211. imageData, err := processImage(ctx)
  212. if err != nil {
  213. if newRelicEnabled {
  214. sendErrorToNewRelic(ctx, err)
  215. }
  216. if prometheusEnabled {
  217. incrementPrometheusErrorsTotal("processing")
  218. }
  219. panic(newError(500, err.Error(), "Error occurred while processing image"))
  220. }
  221. checkTimeout(ctx)
  222. respondWithImage(ctx, reqID, r, rw, imageData)
  223. }