server.go 4.1 KB

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