server.go 5.7 KB

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