Skip to content

Commit

Permalink
BackingImage does not download URL correctly in some situation
Browse files Browse the repository at this point in the history
Remove the `Referer` header that is automatically added by the http client. Without this header it is possible to download files that are redirected several times. This mimics the behaviour of `curl` and `wget` which do not submit the `referer` header by default.

Signed-off-by: Volker Theile <[email protected]>
  • Loading branch information
votdev committed Feb 12, 2024
1 parent b3275a8 commit d888aa9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
25 changes: 23 additions & 2 deletions pkg/sync/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"os"
"strconv"
"strings"
"time"

"github.com/pkg/errors"
Expand Down Expand Up @@ -39,7 +40,7 @@ func (h *HTTPHandler) GetSizeFromURL(url string) (size int64, err error) {
return 0, err
}

client := http.Client{}
client := NewDownloadHttpClient()
resp, err := client.Do(rr)
if err != nil {
return 0, err
Expand Down Expand Up @@ -72,7 +73,7 @@ func (h *HTTPHandler) DownloadFromURL(ctx context.Context, url, filePath string,
return 0, err
}

client := http.Client{}
client := NewDownloadHttpClient()
resp, err := client.Do(rr)
if err != nil {
return 0, err
Expand Down Expand Up @@ -176,6 +177,26 @@ func IdleTimeoutCopy(ctx context.Context, cancel context.CancelFunc, src io.Read
return copied, err
}

func removeReferer(req *http.Request) {
for k, _ := range req.Header {
if strings.ToLower(k) == "referer" {
delete(req.Header, k)
}
}
}

func NewDownloadHttpClient() http.Client {
return http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// Remove the "Referer" header to enable downloads via multiple
// redirects. This is the same behaviour of curl or wget in the
// default configuration.
removeReferer(req)
return nil
},
}
}

const (
MockFileSize = 4096
)
Expand Down
20 changes: 20 additions & 0 deletions pkg/sync/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package sync

import (
. "gopkg.in/check.v1"
"net/http"
)

type TestSuite struct{}

var _ = Suite(&TestSuite{})

func (s *TestSuite) TestRemoveReferer(c *C) {
req, err := http.NewRequest("HEAD", "https://foo.bar", nil)
c.Assert(err, IsNil)
req.Header.Set("Referer", "https://foo.bar")
req.Header.Set("Foo", "foo")
removeReferer(req)
c.Assert(req.Referer(), Equals, "")
c.Assert(req.Header, HasLen, 1)
}

0 comments on commit d888aa9

Please sign in to comment.