server.go 4.6 KB

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