server.go 3.5 KB

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