server.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/subtle"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "time"
  10. nanoid "github.com/matoous/go-nanoid"
  11. "github.com/valyala/fasthttp"
  12. )
  13. var (
  14. mimes = map[imageType]string{
  15. imageTypeJPEG: "image/jpeg",
  16. imageTypePNG: "image/png",
  17. imageTypeWEBP: "image/webp",
  18. }
  19. authHeaderMust []byte
  20. healthPath = []byte("/health")
  21. serverMutex mutex
  22. errInvalidMethod = newError(422, "Invalid request method", "Method doesn't allowed")
  23. errInvalidSecret = newError(403, "Invalid secret", "Forbidden")
  24. )
  25. func startServer() *fasthttp.Server {
  26. serverMutex = newMutex(conf.Concurrency)
  27. s := &fasthttp.Server{
  28. Name: "imgproxy",
  29. Handler: serveHTTP,
  30. Concurrency: conf.MaxClients,
  31. ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
  32. }
  33. go func() {
  34. log.Printf("Starting server at %s\n", conf.Bind)
  35. if err := s.ListenAndServe(conf.Bind); err != nil {
  36. log.Fatalln(err)
  37. }
  38. }()
  39. return s
  40. }
  41. func shutdownServer(s *fasthttp.Server) {
  42. log.Println("Shutting down the server...")
  43. s.Shutdown()
  44. }
  45. func logResponse(status int, msg string) {
  46. var color int
  47. if status >= 500 {
  48. color = 31
  49. } else if status >= 400 {
  50. color = 33
  51. } else {
  52. color = 32
  53. }
  54. log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
  55. }
  56. func writeCORS(rctx *fasthttp.RequestCtx) {
  57. if len(conf.AllowOrigin) > 0 {
  58. rctx.Request.Header.Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  59. rctx.Request.Header.Set("Access-Control-Allow-Methods", "GET, OPTIONs")
  60. }
  61. }
  62. func respondWithImage(ctx context.Context, reqID string, rctx *fasthttp.RequestCtx, data []byte) {
  63. rctx.SetStatusCode(200)
  64. po := getProcessingOptions(ctx)
  65. rctx.SetContentType(mimes[po.Format])
  66. rctx.Response.Header.Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
  67. rctx.Response.Header.Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  68. if conf.GZipCompression > 0 && rctx.Request.Header.HasAcceptEncodingBytes([]byte("gzip")) {
  69. rctx.Response.Header.Set("Content-Encoding", "gzip")
  70. gzipData(data, rctx)
  71. } else {
  72. rctx.SetBody(data)
  73. }
  74. logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, getTimerSince(ctx), getImageURL(ctx), po))
  75. }
  76. func respondWithError(reqID string, rctx *fasthttp.RequestCtx, err imgproxyError) {
  77. logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
  78. rctx.SetStatusCode(err.StatusCode)
  79. rctx.SetBodyString(err.PublicMessage)
  80. }
  81. func respondWithOptions(reqID string, rctx *fasthttp.RequestCtx) {
  82. logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
  83. rctx.SetStatusCode(200)
  84. }
  85. func prepareAuthHeaderMust() []byte {
  86. if len(authHeaderMust) == 0 {
  87. authHeaderMust = []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  88. }
  89. return authHeaderMust
  90. }
  91. func checkSecret(rctx *fasthttp.RequestCtx) bool {
  92. if len(conf.Secret) == 0 {
  93. return true
  94. }
  95. return subtle.ConstantTimeCompare(
  96. rctx.Request.Header.Peek("Authorization"),
  97. prepareAuthHeaderMust(),
  98. ) == 1
  99. }
  100. func serveHTTP(rctx *fasthttp.RequestCtx) {
  101. reqID, _ := nanoid.Nanoid()
  102. defer func() {
  103. if r := recover(); r != nil {
  104. if err, ok := r.(imgproxyError); ok {
  105. respondWithError(reqID, rctx, err)
  106. } else {
  107. respondWithError(reqID, rctx, newUnexpectedError(r.(error), 4))
  108. }
  109. }
  110. }()
  111. log.Printf("[%s] %s: %s\n", reqID, rctx.Method(), rctx.Path())
  112. writeCORS(rctx)
  113. if rctx.Request.Header.IsOptions() {
  114. respondWithOptions(reqID, rctx)
  115. return
  116. }
  117. if !rctx.IsGet() {
  118. panic(errInvalidMethod)
  119. }
  120. if !checkSecret(rctx) {
  121. panic(errInvalidSecret)
  122. }
  123. serverMutex.Lock()
  124. defer serverMutex.Unock()
  125. if bytes.Equal(rctx.Path(), healthPath) {
  126. rctx.SetStatusCode(200)
  127. rctx.SetBodyString("imgproxy is running")
  128. return
  129. }
  130. ctx, timeoutCancel := startTimer(time.Duration(conf.WriteTimeout) * time.Second)
  131. defer timeoutCancel()
  132. ctx, err := parsePath(ctx, rctx)
  133. if err != nil {
  134. panic(newError(404, err.Error(), "Invalid image url"))
  135. }
  136. ctx, downloadcancel, err := downloadImage(ctx)
  137. defer downloadcancel()
  138. if err != nil {
  139. panic(newError(404, err.Error(), "Image is unreachable"))
  140. }
  141. checkTimeout(ctx)
  142. if conf.ETagEnabled {
  143. eTag := calcETag(ctx)
  144. rctx.Response.Header.SetBytesV("ETag", eTag)
  145. if bytes.Equal(eTag, rctx.Request.Header.Peek("If-None-Match")) {
  146. panic(errNotModified)
  147. }
  148. }
  149. checkTimeout(ctx)
  150. imageData, err := processImage(ctx)
  151. if err != nil {
  152. panic(newError(500, err.Error(), "Error occurred while processing image"))
  153. }
  154. checkTimeout(ctx)
  155. respondWithImage(ctx, reqID, rctx, imageData)
  156. }