server.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package main
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "crypto/subtle"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "time"
  15. nanoid "github.com/matoous/go-nanoid"
  16. "golang.org/x/net/netutil"
  17. )
  18. var mimes = map[imageType]string{
  19. imageTypeJPEG: "image/jpeg",
  20. imageTypePNG: "image/png",
  21. imageTypeWEBP: "image/webp",
  22. }
  23. type httpHandler struct {
  24. sem chan struct{}
  25. }
  26. func newHTTPHandler() *httpHandler {
  27. return &httpHandler{make(chan struct{}, conf.Concurrency)}
  28. }
  29. func startServer() *http.Server {
  30. l, err := net.Listen("tcp", conf.Bind)
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. s := &http.Server{
  35. Handler: newHTTPHandler(),
  36. ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
  37. MaxHeaderBytes: 1 << 20,
  38. }
  39. go func() {
  40. log.Printf("Starting server at %s\n", conf.Bind)
  41. log.Fatal(s.Serve(netutil.LimitListener(l, conf.MaxClients)))
  42. }()
  43. return s
  44. }
  45. func shutdownServer(s *http.Server) {
  46. log.Println("Shutting down the server...")
  47. ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
  48. defer close()
  49. s.Shutdown(ctx)
  50. }
  51. func logResponse(status int, msg string) {
  52. var color int
  53. if status >= 500 {
  54. color = 31
  55. } else if status >= 400 {
  56. color = 33
  57. } else {
  58. color = 32
  59. }
  60. log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
  61. }
  62. func writeCORS(rw http.ResponseWriter) {
  63. if len(conf.AllowOrigin) > 0 {
  64. rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  65. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONs")
  66. }
  67. }
  68. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions, duration time.Duration) {
  69. gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
  70. rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  71. rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
  72. rw.Header().Set("Content-Type", mimes[po.Format])
  73. dataToRespond := data
  74. if gzipped {
  75. var buf bytes.Buffer
  76. gz, _ := gzip.NewWriterLevel(&buf, conf.GZipCompression)
  77. gz.Write(data)
  78. gz.Close()
  79. dataToRespond = buf.Bytes()
  80. rw.Header().Set("Content-Encoding", "gzip")
  81. }
  82. rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
  83. rw.WriteHeader(200)
  84. rw.Write(dataToRespond)
  85. logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, duration, imgURL, po))
  86. }
  87. func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
  88. logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
  89. rw.WriteHeader(err.StatusCode)
  90. rw.Write([]byte(err.PublicMessage))
  91. }
  92. func respondWithOptions(reqID string, rw http.ResponseWriter) {
  93. logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
  94. rw.WriteHeader(200)
  95. }
  96. func checkSecret(s string) bool {
  97. if len(conf.Secret) == 0 {
  98. return true
  99. }
  100. return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
  101. }
  102. func (h *httpHandler) lock() {
  103. h.sem <- struct{}{}
  104. }
  105. func (h *httpHandler) unlock() {
  106. <-h.sem
  107. }
  108. func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  109. reqID, _ := nanoid.Nanoid()
  110. defer func() {
  111. if r := recover(); r != nil {
  112. if err, ok := r.(imgproxyError); ok {
  113. respondWithError(reqID, rw, err)
  114. } else {
  115. respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
  116. }
  117. }
  118. }()
  119. log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
  120. writeCORS(rw)
  121. if r.Method == http.MethodOptions {
  122. respondWithOptions(reqID, rw)
  123. return
  124. }
  125. if r.Method != http.MethodGet {
  126. panic(invalidMethodErr)
  127. }
  128. if !checkSecret(r.Header.Get("Authorization")) {
  129. panic(invalidSecretErr)
  130. }
  131. h.lock()
  132. defer h.unlock()
  133. if r.URL.Path == "/health" {
  134. rw.WriteHeader(200)
  135. rw.Write([]byte("imgproxy is running"))
  136. return
  137. }
  138. t := startTimer(time.Duration(conf.WriteTimeout)*time.Second, "Processing")
  139. imgURL, procOpt, err := parsePath(r)
  140. if err != nil {
  141. panic(newError(404, err.Error(), "Invalid image url"))
  142. }
  143. if _, err = url.ParseRequestURI(imgURL); err != nil {
  144. panic(newError(404, err.Error(), "Invalid image url"))
  145. }
  146. b, imgtype, err := downloadImage(imgURL)
  147. if err != nil {
  148. panic(newError(404, err.Error(), "Image is unreachable"))
  149. }
  150. t.Check()
  151. if conf.ETagEnabled {
  152. eTag := calcETag(b, &procOpt)
  153. rw.Header().Set("ETag", eTag)
  154. if eTag == r.Header.Get("If-None-Match") {
  155. panic(notModifiedErr)
  156. }
  157. }
  158. t.Check()
  159. b, err = processImage(b, imgtype, procOpt, t)
  160. if err != nil {
  161. panic(newError(500, err.Error(), "Error occurred while processing image"))
  162. }
  163. t.Check()
  164. respondWithImage(reqID, r, rw, b, imgURL, procOpt, t.Since())
  165. }