server.go 6.8 KB

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