server.go 4.3 KB

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