server.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. defer responseBufPool.Put(buf)
  91. gzipData(data, buf)
  92. dataToRespond = buf.Bytes()
  93. }
  94. rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
  95. rw.WriteHeader(200)
  96. rw.Write(dataToRespond)
  97. logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, getTimerSince(ctx), getImageURL(ctx), po))
  98. }
  99. func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
  100. logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
  101. rw.WriteHeader(err.StatusCode)
  102. rw.Write([]byte(err.PublicMessage))
  103. }
  104. func respondWithOptions(reqID string, rw http.ResponseWriter) {
  105. logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
  106. rw.WriteHeader(200)
  107. }
  108. func prepareAuthHeaderMust() []byte {
  109. if len(authHeaderMust) == 0 {
  110. authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  111. }
  112. return authHeaderMust
  113. }
  114. func checkSecret(r *http.Request) bool {
  115. if len(conf.Secret) == 0 {
  116. return true
  117. }
  118. return subtle.ConstantTimeCompare(
  119. []byte(r.Header.Get("Authorization")),
  120. prepareAuthHeaderMust(),
  121. ) == 1
  122. }
  123. func (h *httpHandler) lock() {
  124. h.sem <- struct{}{}
  125. }
  126. func (h *httpHandler) unlock() {
  127. <-h.sem
  128. }
  129. func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  130. reqID, _ := nanoid.Nanoid()
  131. defer func() {
  132. if r := recover(); r != nil {
  133. if err, ok := r.(imgproxyError); ok {
  134. respondWithError(reqID, rw, err)
  135. } else {
  136. respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
  137. }
  138. }
  139. }()
  140. log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
  141. writeCORS(rw)
  142. if r.Method == http.MethodOptions {
  143. respondWithOptions(reqID, rw)
  144. return
  145. }
  146. if r.Method != http.MethodGet {
  147. panic(errInvalidMethod)
  148. }
  149. if !checkSecret(r) {
  150. panic(errInvalidSecret)
  151. }
  152. ctx := context.Background()
  153. if newRelicEnabled {
  154. var newRelicCancel context.CancelFunc
  155. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  156. defer newRelicCancel()
  157. }
  158. h.lock()
  159. defer h.unlock()
  160. if r.URL.RequestURI() == healthPath {
  161. rw.WriteHeader(200)
  162. rw.Write(imgproxyIsRunningMsg)
  163. return
  164. }
  165. ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  166. defer timeoutCancel()
  167. ctx, err := parsePath(ctx, r)
  168. if err != nil {
  169. panic(newError(404, err.Error(), "Invalid image url"))
  170. }
  171. ctx, downloadcancel, err := downloadImage(ctx)
  172. defer downloadcancel()
  173. if err != nil {
  174. if newRelicEnabled {
  175. sendErrorToNewRelic(ctx, err)
  176. }
  177. panic(newError(404, err.Error(), "Image is unreachable"))
  178. }
  179. checkTimeout(ctx)
  180. if conf.ETagEnabled {
  181. eTag := calcETag(ctx)
  182. rw.Header().Set("ETag", eTag)
  183. if eTag == r.Header.Get("If-None-Match") {
  184. panic(errNotModified)
  185. }
  186. }
  187. checkTimeout(ctx)
  188. imageData, err := processImage(ctx)
  189. if err != nil {
  190. if newRelicEnabled {
  191. sendErrorToNewRelic(ctx, err)
  192. }
  193. panic(newError(500, err.Error(), "Error occurred while processing image"))
  194. }
  195. checkTimeout(ctx)
  196. respondWithImage(ctx, reqID, r, rw, imageData)
  197. }