handler.go 5.2 KB

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