1
0

server.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. sem chan struct{}
  19. }
  20. func newHttpHandler() httpHandler {
  21. return httpHandler{make(chan struct{}, conf.Concurrency)}
  22. }
  23. func parsePath(r *http.Request) (string, processingOptions, error) {
  24. var po processingOptions
  25. var err error
  26. path := r.URL.Path
  27. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  28. if len(parts) < 7 {
  29. return "", po, errors.New("Invalid path")
  30. }
  31. token := parts[0]
  32. if err = validatePath(token, strings.TrimPrefix(path, fmt.Sprintf("/%s", token))); err != nil {
  33. return "", po, err
  34. }
  35. po.resize = parts[1]
  36. if po.width, err = strconv.Atoi(parts[2]); err != nil {
  37. return "", po, fmt.Errorf("Invalid width: %s", parts[2])
  38. }
  39. if po.height, err = strconv.Atoi(parts[3]); err != nil {
  40. return "", po, fmt.Errorf("Invalid height: %s", parts[3])
  41. }
  42. if g, ok := gravityTypes[parts[4]]; ok {
  43. po.gravity = g
  44. } else {
  45. return "", po, fmt.Errorf("Invalid gravity: %s", parts[4])
  46. }
  47. po.enlarge = parts[5] != "0"
  48. filenameParts := strings.Split(strings.Join(parts[6:], ""), ".")
  49. if len(filenameParts) < 2 {
  50. po.format = imageTypes["jpg"]
  51. } else if f, ok := imageTypes[filenameParts[1]]; ok {
  52. po.format = f
  53. } else {
  54. return "", po, fmt.Errorf("Invalid image format: %s", filenameParts[1])
  55. }
  56. filename, err := base64.RawURLEncoding.DecodeString(filenameParts[0])
  57. if err != nil {
  58. return "", po, errors.New("Invalid filename encoding")
  59. }
  60. return string(filename), po, nil
  61. }
  62. func imageContentType(b []byte) string {
  63. _, imgtype, _ := image.DecodeConfig(bytes.NewReader(b))
  64. return fmt.Sprintf("image/%s", imgtype)
  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", imageContentType(data))
  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 occured while processing image")
  143. return
  144. }
  145. respondWithImage(r, rw, b, imgURL, procOpt, t)
  146. }