server.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 !vipsTypeSupportedSave(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, startTime time.Time) {
  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("Cache-Control: max-age=%d", 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", time.Since(startTime), imgURL, po))
  100. }
  101. func respondWithError(rw http.ResponseWriter, status int, err error, msg string) {
  102. logResponse(status, err.Error())
  103. rw.WriteHeader(status)
  104. rw.Write([]byte(msg))
  105. }
  106. func repondWithForbidden(rw http.ResponseWriter) {
  107. logResponse(403, "Invalid secret")
  108. rw.WriteHeader(403)
  109. rw.Write([]byte("Forbidden"))
  110. }
  111. func checkSecret(s string) bool {
  112. if len(conf.Secret) == 0 {
  113. return true
  114. }
  115. return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
  116. }
  117. func (h *httpHandler) lock() {
  118. h.sem <- struct{}{}
  119. }
  120. func (h *httpHandler) unlock() {
  121. defer func() { <-h.sem }()
  122. }
  123. func (h httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  124. log.Printf("GET: %s\n", r.URL.RequestURI())
  125. h.lock()
  126. defer h.unlock()
  127. t := time.Now()
  128. if !checkSecret(r.Header.Get("Authorization")) {
  129. repondWithForbidden(rw)
  130. return
  131. }
  132. imgURL, procOpt, err := parsePath(r)
  133. if err != nil {
  134. respondWithError(rw, 404, err, "Invalid image url")
  135. return
  136. }
  137. if _, err = url.ParseRequestURI(imgURL); err != nil {
  138. respondWithError(rw, 404, err, "Invalid image url")
  139. return
  140. }
  141. b, imgtype, err := downloadImage(imgURL)
  142. if err != nil {
  143. respondWithError(rw, 404, err, "Image is unreachable")
  144. return
  145. }
  146. b, err = processImage(b, imgtype, procOpt)
  147. if err != nil {
  148. respondWithError(rw, 500, err, "Error occurred while processing image")
  149. return
  150. }
  151. respondWithImage(r, rw, b, imgURL, procOpt, t)
  152. }