server.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  75. rw.Header().Set("Cache-Control", fmt.Sprintf("Cache-Control: max-age=%d", conf.TTL))
  76. rw.Header().Set("Content-Type", imageContentType(data))
  77. if gzipped {
  78. rw.Header().Set("Content-Encoding", "gzip")
  79. }
  80. rw.WriteHeader(200)
  81. if gzipped {
  82. gz, _ := gzip.NewWriterLevel(rw, conf.GZipCompression)
  83. gz.Write(data)
  84. gz.Close()
  85. } else {
  86. rw.Write(data)
  87. }
  88. logResponse(200, fmt.Sprintf("Processed in %s: %s; %+v", time.Since(startTime), imgURL, po))
  89. }
  90. func respondWithError(rw http.ResponseWriter, status int, err error, msg string) {
  91. logResponse(status, err.Error())
  92. rw.WriteHeader(status)
  93. rw.Write([]byte(msg))
  94. }
  95. func repondWithForbidden(rw http.ResponseWriter) {
  96. logResponse(403, "Invalid secret")
  97. rw.WriteHeader(403)
  98. rw.Write([]byte("Forbidden"))
  99. }
  100. func checkSecret(s string) bool {
  101. if len(conf.Secret) == 0 {
  102. return true
  103. }
  104. return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
  105. }
  106. func (h httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  107. log.Printf("GET: %s\n", r.URL.RequestURI())
  108. t := time.Now()
  109. if !checkSecret(r.Header.Get("Authorization")) {
  110. repondWithForbidden(rw)
  111. return
  112. }
  113. imgURL, procOpt, err := parsePath(r)
  114. if err != nil {
  115. respondWithError(rw, 404, err, "Invalid image url")
  116. return
  117. }
  118. if _, err = url.ParseRequestURI(imgURL); err != nil {
  119. respondWithError(rw, 404, err, "Invalid image url")
  120. return
  121. }
  122. b, err := downloadImage(imgURL)
  123. if err != nil {
  124. respondWithError(rw, 404, err, "Image is unreacable")
  125. return
  126. }
  127. b, err = processImage(b, procOpt)
  128. if err != nil {
  129. respondWithError(rw, 500, err, "Error occured while processing image")
  130. return
  131. }
  132. respondWithImage(r, rw, b, imgURL, procOpt, t)
  133. }