server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package main
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "crypto/subtle"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "time"
  15. nanoid "github.com/matoous/go-nanoid"
  16. )
  17. var mimes = map[imageType]string{
  18. JPEG: "image/jpeg",
  19. PNG: "image/png",
  20. WEBP: "image/webp",
  21. }
  22. type httpHandler struct {
  23. sem chan struct{}
  24. }
  25. func newHTTPHandler() *httpHandler {
  26. return &httpHandler{make(chan struct{}, conf.Concurrency)}
  27. }
  28. func parsePath(r *http.Request) (string, processingOptions, error) {
  29. var po processingOptions
  30. var err error
  31. path := r.URL.Path
  32. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  33. if len(parts) < 7 {
  34. return "", po, errors.New("Invalid path")
  35. }
  36. token := parts[0]
  37. if err = validatePath(token, strings.TrimPrefix(path, fmt.Sprintf("/%s", token))); err != nil {
  38. return "", po, err
  39. }
  40. if r, ok := resizeTypes[parts[1]]; ok {
  41. po.Resize = r
  42. } else {
  43. return "", po, fmt.Errorf("Invalid resize type: %s", parts[1])
  44. }
  45. if po.Width, err = strconv.Atoi(parts[2]); err != nil {
  46. return "", po, fmt.Errorf("Invalid width: %s", parts[2])
  47. }
  48. if po.Height, err = strconv.Atoi(parts[3]); err != nil {
  49. return "", po, fmt.Errorf("Invalid height: %s", parts[3])
  50. }
  51. if g, ok := gravityTypes[parts[4]]; ok {
  52. po.Gravity = g
  53. } else {
  54. return "", po, fmt.Errorf("Invalid gravity: %s", parts[4])
  55. }
  56. po.Enlarge = parts[5] != "0"
  57. filenameParts := strings.Split(strings.Join(parts[6:], ""), ".")
  58. if len(filenameParts) < 2 {
  59. po.Format = imageTypes["jpg"]
  60. } else if f, ok := imageTypes[filenameParts[1]]; ok {
  61. po.Format = f
  62. } else {
  63. return "", po, fmt.Errorf("Invalid image format: %s", filenameParts[1])
  64. }
  65. if !vipsTypeSupportSave[po.Format] {
  66. return "", po, errors.New("Resulting image type not supported")
  67. }
  68. filename, err := base64.RawURLEncoding.DecodeString(filenameParts[0])
  69. if err != nil {
  70. return "", po, errors.New("Invalid filename encoding")
  71. }
  72. return string(filename), po, nil
  73. }
  74. func logResponse(status int, msg string) {
  75. var color int
  76. if status >= 500 {
  77. color = 31
  78. } else if status >= 400 {
  79. color = 33
  80. } else {
  81. color = 32
  82. }
  83. log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
  84. }
  85. func writeCORS(rw http.ResponseWriter) {
  86. if len(conf.AllowOrigin) > 0 {
  87. rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  88. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONs")
  89. }
  90. }
  91. func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions, duration time.Duration) {
  92. gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
  93. rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  94. rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
  95. rw.Header().Set("Content-Type", mimes[po.Format])
  96. dataToRespond := data
  97. if gzipped {
  98. var buf bytes.Buffer
  99. gz, _ := gzip.NewWriterLevel(&buf, conf.GZipCompression)
  100. gz.Write(data)
  101. gz.Close()
  102. dataToRespond = buf.Bytes()
  103. rw.Header().Set("Content-Encoding", "gzip")
  104. }
  105. rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
  106. rw.WriteHeader(200)
  107. rw.Write(dataToRespond)
  108. logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, duration, imgURL, po))
  109. }
  110. func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
  111. logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
  112. rw.WriteHeader(err.StatusCode)
  113. rw.Write([]byte(err.PublicMessage))
  114. }
  115. func respondWithOptions(reqID string, rw http.ResponseWriter) {
  116. logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
  117. rw.WriteHeader(200)
  118. }
  119. func checkSecret(s string) bool {
  120. if len(conf.Secret) == 0 {
  121. return true
  122. }
  123. return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
  124. }
  125. func (h *httpHandler) lock() {
  126. h.sem <- struct{}{}
  127. }
  128. func (h *httpHandler) unlock() {
  129. <-h.sem
  130. }
  131. func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  132. reqID, _ := nanoid.Nanoid()
  133. defer func() {
  134. if r := recover(); r != nil {
  135. if err, ok := r.(imgproxyError); ok {
  136. respondWithError(reqID, rw, err)
  137. } else {
  138. respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
  139. }
  140. }
  141. }()
  142. log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
  143. writeCORS(rw)
  144. if r.Method == http.MethodOptions {
  145. respondWithOptions(reqID, rw)
  146. return
  147. }
  148. if r.Method != http.MethodGet {
  149. panic(invalidMethodErr)
  150. }
  151. if !checkSecret(r.Header.Get("Authorization")) {
  152. panic(invalidSecretErr)
  153. }
  154. h.lock()
  155. defer h.unlock()
  156. if r.URL.Path == "/health" {
  157. rw.WriteHeader(200)
  158. rw.Write([]byte("imgproxy is running"))
  159. return
  160. }
  161. t := startTimer(time.Duration(conf.WriteTimeout)*time.Second, "Processing")
  162. imgURL, procOpt, err := parsePath(r)
  163. if err != nil {
  164. panic(newError(404, err.Error(), "Invalid image url"))
  165. }
  166. if _, err = url.ParseRequestURI(imgURL); err != nil {
  167. panic(newError(404, err.Error(), "Invalid image url"))
  168. }
  169. b, imgtype, err := downloadImage(imgURL)
  170. if err != nil {
  171. panic(newError(404, err.Error(), "Image is unreachable"))
  172. }
  173. t.Check()
  174. if conf.ETagEnabled {
  175. eTag := calcETag(b, &procOpt)
  176. rw.Header().Set("ETag", eTag)
  177. if eTag == r.Header.Get("If-None-Match") {
  178. panic(notModifiedErr)
  179. }
  180. }
  181. t.Check()
  182. b, err = processImage(b, imgtype, procOpt, t)
  183. if err != nil {
  184. panic(newError(500, err.Error(), "Error occurred while processing image"))
  185. }
  186. t.Check()
  187. respondWithImage(reqID, r, rw, b, imgURL, procOpt, t.Since())
  188. }