server.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package main
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "crypto/subtle"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "image"
  10. "log"
  11. "net/http"
  12. "net/url"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. type httpHandler struct{}
  18. func parsePath(r *http.Request) (string, processingOptions, error) {
  19. var po processingOptions
  20. var err error
  21. path := r.URL.Path
  22. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  23. if len(parts) < 7 {
  24. return "", po, errors.New("Invalid path")
  25. }
  26. token := parts[0]
  27. if err = validatePath(token, strings.TrimPrefix(path, fmt.Sprintf("/%s", token))); err != nil {
  28. return "", po, err
  29. }
  30. po.resize = parts[1]
  31. if po.width, err = strconv.Atoi(parts[2]); err != nil {
  32. return "", po, fmt.Errorf("Invalid width: %s", parts[2])
  33. }
  34. if po.height, err = strconv.Atoi(parts[3]); err != nil {
  35. return "", po, fmt.Errorf("Invalid height: %s", parts[3])
  36. }
  37. if g, ok := gravityTypes[parts[4]]; ok {
  38. po.gravity = g
  39. } else {
  40. return "", po, fmt.Errorf("Invalid gravity: %s", parts[4])
  41. }
  42. po.enlarge = parts[5] != "0"
  43. filenameParts := strings.Split(strings.Join(parts[6:], ""), ".")
  44. if len(filenameParts) < 2 {
  45. po.format = imageTypes["jpg"]
  46. } else if f, ok := imageTypes[filenameParts[1]]; ok {
  47. po.format = f
  48. } else {
  49. return "", po, fmt.Errorf("Invalid image format: %s", filenameParts[1])
  50. }
  51. filename, err := base64.RawURLEncoding.DecodeString(filenameParts[0])
  52. if err != nil {
  53. return "", po, errors.New("Invalid filename encoding")
  54. }
  55. return string(filename), po, nil
  56. }
  57. func imageContentType(b []byte) string {
  58. _, imgtype, _ := image.DecodeConfig(bytes.NewReader(b))
  59. return fmt.Sprintf("image/%s", imgtype)
  60. }
  61. func logResponse(status int, msg string) {
  62. var color int
  63. if status > 500 {
  64. color = 31
  65. } else if status > 400 {
  66. color = 33
  67. } else {
  68. color = 32
  69. }
  70. log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
  71. }
  72. func respondWithImage(r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions, startTime time.Time) {
  73. gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
  74. rw.Header().Set("Content-Type", imageContentType(data))
  75. if gzipped {
  76. rw.Header().Set("Content-Encoding", "gzip")
  77. }
  78. rw.WriteHeader(200)
  79. if gzipped {
  80. gz, _ := gzip.NewWriterLevel(rw, conf.GZipCompression)
  81. gz.Write(data)
  82. gz.Close()
  83. } else {
  84. rw.Write(data)
  85. }
  86. logResponse(200, fmt.Sprintf("Processed in %s: %s; %+v", time.Since(startTime), imgURL, po))
  87. }
  88. func respondWithError(rw http.ResponseWriter, status int, err error, msg string) {
  89. logResponse(status, err.Error())
  90. rw.WriteHeader(status)
  91. rw.Write([]byte(msg))
  92. }
  93. func repondWithForbidden(rw http.ResponseWriter) {
  94. logResponse(403, "Invalid secret")
  95. rw.WriteHeader(403)
  96. rw.Write([]byte("Forbidden"))
  97. }
  98. func checkSecret(s string) bool {
  99. return len(conf.Secret) == 0 || subtle.ConstantTimeCompare([]byte(s), []byte(conf.Secret)) == 1
  100. }
  101. func (h httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  102. log.Printf("GET: %s\n", r.URL.RequestURI())
  103. t := time.Now()
  104. if !checkSecret(r.Header.Get("X-Imgproxy-Secret")) {
  105. repondWithForbidden(rw)
  106. return
  107. }
  108. imgURL, procOpt, err := parsePath(r)
  109. if err != nil {
  110. respondWithError(rw, 404, err, "Invalid image url")
  111. return
  112. }
  113. if _, err = url.ParseRequestURI(imgURL); err != nil {
  114. respondWithError(rw, 404, err, "Invalid image url")
  115. return
  116. }
  117. b, err := downloadImage(imgURL)
  118. if err != nil {
  119. respondWithError(rw, 404, err, "Image is unreacable")
  120. return
  121. }
  122. b, err = processImage(b, procOpt)
  123. if err != nil {
  124. respondWithError(rw, 500, err, "Error occured while processing image")
  125. return
  126. }
  127. respondWithImage(r, rw, b, imgURL, procOpt, t)
  128. }