handler.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package stream
  2. import (
  3. "context"
  4. "io"
  5. "net/http"
  6. "sync"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/imgproxy/imgproxy/v3/cookies"
  9. "github.com/imgproxy/imgproxy/v3/fetcher"
  10. "github.com/imgproxy/imgproxy/v3/httpheaders"
  11. "github.com/imgproxy/imgproxy/v3/ierrors"
  12. "github.com/imgproxy/imgproxy/v3/monitoring"
  13. "github.com/imgproxy/imgproxy/v3/monitoring/stats"
  14. "github.com/imgproxy/imgproxy/v3/options"
  15. "github.com/imgproxy/imgproxy/v3/server"
  16. )
  17. const (
  18. streamBufferSize = 4096 // Size of the buffer used for streaming
  19. categoryStreaming = "streaming" // Streaming error category
  20. )
  21. var (
  22. // streamBufPool is a sync.Pool for reusing byte slices used for streaming
  23. streamBufPool = sync.Pool{
  24. New: func() any {
  25. buf := make([]byte, streamBufferSize)
  26. return &buf
  27. },
  28. }
  29. )
  30. // Handler handles image passthrough requests, allowing images to be streamed directly
  31. type Handler struct {
  32. config *Config // Configuration for the streamer
  33. fetcher *fetcher.Fetcher // Fetcher instance to handle image fetching
  34. }
  35. // request holds the parameters and state for a single streaming request
  36. type request struct {
  37. handler *Handler
  38. imageRequest *http.Request
  39. imageURL string
  40. reqID string
  41. po *options.ProcessingOptions
  42. rw server.ResponseWriter
  43. }
  44. // New creates new handler object
  45. func New(config *Config, fetcher *fetcher.Fetcher) (*Handler, error) {
  46. if err := config.Validate(); err != nil {
  47. return nil, err
  48. }
  49. return &Handler{
  50. fetcher: fetcher,
  51. config: config,
  52. }, nil
  53. }
  54. // Stream handles the image passthrough request, streaming the image directly to the response writer
  55. func (s *Handler) Execute(
  56. ctx context.Context,
  57. userRequest *http.Request,
  58. imageURL string,
  59. reqID string,
  60. po *options.ProcessingOptions,
  61. rw server.ResponseWriter,
  62. ) error {
  63. stream := &request{
  64. handler: s,
  65. imageRequest: userRequest,
  66. imageURL: imageURL,
  67. reqID: reqID,
  68. po: po,
  69. rw: rw,
  70. }
  71. return stream.execute(ctx)
  72. }
  73. // execute handles the actual streaming logic
  74. func (s *request) execute(ctx context.Context) error {
  75. stats.IncImagesInProgress()
  76. defer stats.DecImagesInProgress()
  77. defer monitoring.StartStreamingSegment(ctx)()
  78. // Passthrough request headers from the original request
  79. requestHeaders := s.getImageRequestHeaders()
  80. cookieJar, err := s.getCookieJar()
  81. if err != nil {
  82. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  83. }
  84. // Build the request to fetch the image
  85. r, err := s.handler.fetcher.BuildRequest(ctx, s.imageURL, requestHeaders, cookieJar)
  86. if r != nil {
  87. defer r.Cancel()
  88. }
  89. if err != nil {
  90. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  91. }
  92. // Send the request to fetch the image
  93. res, err := r.Send()
  94. if res != nil {
  95. defer res.Body.Close()
  96. }
  97. if err != nil {
  98. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  99. }
  100. // Output streaming response headers
  101. s.rw.SetOriginHeaders(res.Header)
  102. s.rw.Passthrough(s.handler.config.PassthroughResponseHeaders...) // NOTE: priority? This is lowest as it was
  103. s.rw.SetContentLength(int(res.ContentLength))
  104. s.rw.SetCanonical(s.imageURL)
  105. s.rw.SetExpires(s.po.Expires)
  106. // Set the Content-Disposition header
  107. s.setContentDisposition(r.URL().Path, res)
  108. // Copy the status code from the original response
  109. s.rw.WriteHeader(res.StatusCode)
  110. // Write the actual data
  111. s.streamData(res)
  112. return nil
  113. }
  114. // getCookieJar returns non-empty cookie jar if cookie passthrough is enabled
  115. func (s *request) getCookieJar() (http.CookieJar, error) {
  116. if !s.handler.config.CookiePassthrough {
  117. return nil, nil
  118. }
  119. return cookies.JarFromRequest(s.imageRequest)
  120. }
  121. // getImageRequestHeaders returns a new http.Header containing only
  122. // the headers that should be passed through from the user request
  123. func (s *request) getImageRequestHeaders() http.Header {
  124. h := make(http.Header)
  125. httpheaders.CopyFromRequest(s.imageRequest, h, s.handler.config.PassthroughRequestHeaders)
  126. return h
  127. }
  128. // setContentDisposition writes the headers to the response writer
  129. func (s *request) setContentDisposition(imagePath string, serverResponse *http.Response) {
  130. // Try to set correct Content-Disposition file name and extension
  131. if serverResponse.StatusCode < 200 || serverResponse.StatusCode >= 300 {
  132. return
  133. }
  134. ct := serverResponse.Header.Get(httpheaders.ContentType)
  135. s.rw.SetContentDisposition(
  136. imagePath,
  137. s.po.Filename,
  138. "",
  139. ct,
  140. s.po.ReturnAttachment,
  141. )
  142. }
  143. // streamData copies the image data from the response body to the response writer
  144. func (s *request) streamData(res *http.Response) {
  145. buf := streamBufPool.Get().(*[]byte)
  146. defer streamBufPool.Put(buf)
  147. _, copyerr := io.CopyBuffer(s.rw, res.Body, *buf)
  148. server.LogResponse(
  149. s.reqID, s.imageRequest, res.StatusCode, nil,
  150. log.Fields{
  151. "image_url": s.imageURL,
  152. "processing_options": s.po,
  153. },
  154. )
  155. // We've got to skip logging here
  156. if copyerr != nil {
  157. panic(http.ErrAbortHandler)
  158. }
  159. }