diff --git a/fetch/clients.go b/fetch/clients.go index 89448b6..9135619 100644 --- a/fetch/clients.go +++ b/fetch/clients.go @@ -90,7 +90,7 @@ type reply struct { // the public-only dialer (and through it any proxy UseProxy set) and the // redirect rules, never uses HTTP/3 (QUIC would bypass the dialer), and keeps // no cookies between fetches. -func chromeGet(ctx context.Context, rawURL string, timeout time.Duration) (reply, error) { +func chromeGet(ctx context.Context, rawURL string, timeout time.Duration, files bool) (reply, error) { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() opts := []tlsclient.HttpClientOption{ @@ -123,17 +123,19 @@ func chromeGet(ctx context.Context, rawURL string, timeout time.Duration) (reply } defer func() { _ = resp.Body.Close() }() ct := resp.Header.Get("Content-Type") - body, err := readBody(resp.Body, ct) + body, err := readBody(resp.Body, ct, files) return reply{resp.StatusCode, body, ct, resp.Header.Get("Cf-Mitigated"), resp.Request.URL.String()}, err } // readBody reads a response body: a page up to MaxBytes, cut there; a // response that may be a PDF or office file, by its type or its first -// bytes, up to MaxDocBytes, as a cut file cannot be read at all. -func readBody(r io.Reader, contentType string) ([]byte, error) { +// bytes, or with files any file that is not text, up to MaxDocBytes, as a +// cut file cannot be read at all. +func readBody(r io.Reader, contentType string, files bool) ([]byte, error) { body, err := io.ReadAll(io.LimitReader(r, MaxBytes)) mt, _, _ := mime.ParseMediaType(contentType) - if err != nil || len(body) < MaxBytes || !isDocType(mt) && !mayBeDocument(body) { + whole := isDocType(mt) || mayBeDocument(body) || files && NotText(contentType, body) != "" + if err != nil || len(body) < MaxBytes || !whole { return body, err } rest, err := io.ReadAll(io.LimitReader(r, MaxDocBytes+1-MaxBytes)) @@ -151,7 +153,7 @@ var plainClient = &http.Client{ }, } -func plainGet(ctx context.Context, rawURL, userAgent string, timeout time.Duration) (reply, error) { +func plainGet(ctx context.Context, rawURL, userAgent string, timeout time.Duration, files bool) (reply, error) { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, http.NoBody) @@ -165,7 +167,7 @@ func plainGet(ctx context.Context, rawURL, userAgent string, timeout time.Durati } defer func() { _ = resp.Body.Close() }() ct := resp.Header.Get("Content-Type") - body, err := readBody(resp.Body, ct) + body, err := readBody(resp.Body, ct, files) return reply{resp.StatusCode, body, ct, resp.Header.Get("Cf-Mitigated"), resp.Request.URL.String()}, err } diff --git a/fetch/document_test.go b/fetch/document_test.go index 7dd9118..0f1261b 100644 --- a/fetch/document_test.go +++ b/fetch/document_test.go @@ -4,6 +4,7 @@ import ( "archive/zip" "bytes" "compress/zlib" + "context" "errors" "fmt" "strings" @@ -243,20 +244,74 @@ func TestGetReadsADocument(t *testing.T) { func TestReadBody(t *testing.T) { big := strings.Repeat("x", MaxBytes+10) - if b, err := readBody(strings.NewReader(big), "text/html"); err != nil || len(b) != MaxBytes { + if b, err := readBody(strings.NewReader(big), "text/html", false); err != nil || len(b) != MaxBytes { t.Errorf("a page is cut at MaxBytes: %d, %v", len(b), err) } - if b, err := readBody(strings.NewReader(big), "application/pdf"); err != nil || len(b) != len(big) { + if b, err := readBody(strings.NewReader(big), "application/pdf", false); err != nil || len(b) != len(big) { t.Errorf("a document may pass MaxBytes: %d, %v", len(b), err) } - if _, err := readBody(strings.NewReader(strings.Repeat("x", MaxDocBytes+1)), "application/octet-stream"); err == nil { + if _, err := readBody(strings.NewReader(strings.Repeat("x", MaxDocBytes+1)), "application/octet-stream", false); err == nil { t.Error("a document over MaxDocBytes must fail") } - if b, err := readBody(strings.NewReader("%PDF-"+big), "application/force-download"); err != nil || len(b) != len(big)+5 { + if b, err := readBody(strings.NewReader("%PDF-"+big), "application/force-download", false); err != nil || len(b) != len(big)+5 { t.Errorf("a PDF under another type may pass MaxBytes: %d, %v", len(b), err) } } +func TestReadBodyRawFiles(t *testing.T) { + big := "\x89PNG\r\n\x1a\n" + strings.Repeat("\xff", MaxBytes) + if b, err := readBody(strings.NewReader(big), "image/png", true); err != nil || len(b) != len(big) { + t.Errorf("a file may pass MaxBytes: %d, %v", len(b), err) + } + if b, err := readBody(strings.NewReader(big), "", true); err != nil || len(b) != len(big) { + t.Errorf("an untyped file is found by its bytes: %d, %v", len(b), err) + } + if b, err := readBody(strings.NewReader(big), "image/png", false); err != nil || len(b) != MaxBytes { + t.Errorf("without raw files a file is cut at MaxBytes: %d, %v", len(b), err) + } + if b, err := readBody(strings.NewReader(strings.Repeat("x", MaxBytes+10)), "text/html", true); err != nil || len(b) != MaxBytes { + t.Errorf("a page is still cut at MaxBytes: %d, %v", len(b), err) + } + if _, err := readBody(strings.NewReader(strings.Repeat("\xff", MaxDocBytes+1)), "image/png", true); err == nil || !strings.Contains(err.Error(), "larger than") { + t.Errorf("a file over MaxDocBytes must fail: %v", err) + } +} + +func TestGetRawFiles(t *testing.T) { + const img, doc = "https://example.com/frame.png", "https://example.com/report.pdf" + png := "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\xe9\xff\x80" + pages := map[string]page{ + img: {status: 200, body: png, ct: "image/png"}, + doc: {status: 200, body: string(makePDF("BT /F1 12 Tf 72 720 Td (Quarterly report) Tj ET")), ct: "application/pdf"}, + } + var attempts []Attempt + f := &Fetcher{RawFiles: true, chrome: fake(pages, nil), Record: func(a Attempt) { attempts = append(attempts, a) }} + p, err := f.Get(t.Context(), img) + if err != nil || !bytes.Equal(p.Body, []byte(png)) || p.ContentType != "image/png" || p.URL != img { + t.Errorf("raw file: %v, %q %q %q", err, p.Body, p.ContentType, p.URL) + } + if len(attempts) != 1 || attempts[0].Outcome != OutcomeOK || attempts[0].Bytes != len(png) { + t.Errorf("one ok attempt expected: %+v", attempts) + } + if p, err := f.Get(t.Context(), doc); err != nil || string(p.Body) != "Quarterly report" || p.ContentType != TypeMarkdown { + t.Errorf("a document is still Markdown: %v, %q %q", err, p.Body, p.ContentType) + } + pages[img] = page{status: 200, body: png, ct: "application/octet-stream"} + if p, err := f.Get(t.Context(), img); err != nil || p.ContentType != "application/octet-stream" { + t.Errorf("the server's type is kept: %v, %q", err, p.ContentType) + } + f.chrome = func(context.Context, string) (reply, error) { + return reply{status: 200, body: []byte(png), url: img}, nil + } + if p, err := f.Get(t.Context(), img); err != nil || p.ContentType != "image/png" { + t.Errorf("an untyped file is typed by its bytes: %v, %q", err, p.ContentType) + } + f.RawFiles = false + if _, err := f.Get(t.Context(), img); !errors.Is(err, ErrNotText) { + t.Errorf("without raw files: %v", err) + } +} + func TestDocumentTextStaysMarkdown(t *testing.T) { const md = " roadmap\n\n- ship in May" if got := Markdown([]byte(md), TypeMarkdown, nil); got != md { diff --git a/fetch/fetch.go b/fetch/fetch.go index 5ae3653..3e3e5fe 100644 --- a/fetch/fetch.go +++ b/fetch/fetch.go @@ -5,6 +5,7 @@ package fetch import ( + "cmp" "context" "errors" "fmt" @@ -84,6 +85,7 @@ type Fetcher struct { UserAgent string // the plain client's User-Agent; DefaultUserAgent when empty RobotsAgent string // the robots.txt agent name; DefaultRobotsAgent when empty Timeout time.Duration // per client; DefaultTimeout when zero + RawFiles bool // return a file that is neither text nor a document, such as an image, as its bytes, up to MaxDocBytes, instead of ErrNotText Record func(Attempt) // called after every attempt, if set plain, chrome getter // tests replace them @@ -145,6 +147,7 @@ func (f *Fetcher) try(ctx context.Context, p *Page, client, rawURL string) error start := time.Now() r, err := get(ctx, rawURL) status, body, ct := r.status, r.body, r.contentType + raw := false a := Attempt{URL: rawURL, Client: client, Status: status, Bytes: len(body), Duration: time.Since(start), Outcome: OutcomeOK} switch { case err != nil: @@ -165,6 +168,9 @@ func (f *Fetcher) try(ctx context.Context, p *Page, client, rawURL string) error case NotText(ct, body) != "": md, ok, derr := Document(ctx, body) switch { + case !ok && f.RawFiles: + raw = true + ct = cmp.Or(ct, NotText(ct, body)) case !ok: a.Outcome = OutcomeError err = fmt.Errorf("%w (%s)", ErrNotText, NotText(ct, body)) @@ -183,10 +189,13 @@ func (f *Fetcher) try(ctx context.Context, p *Page, client, rawURL string) error } f.record(p, &a) p.ErrorBody = nil - if err == nil { + switch { + case err == nil && raw: + p.Body, p.ContentType, p.URL = body, ct, r.url + case err == nil: p.Body, p.ContentType = toUTF8(body, ct) p.URL = r.url - } else if status >= http.StatusBadRequest { + case status >= http.StatusBadRequest: p.ErrorBody = body } if a.Outcome == OutcomeNeedsJS { @@ -202,14 +211,14 @@ func (f *Fetcher) getter(client string) getter { return f.chrome } return func(ctx context.Context, u string) (reply, error) { - return chromeGet(ctx, u, f.timeout()) + return chromeGet(ctx, u, f.timeout(), f.RawFiles) } } if f.plain != nil { return f.plain } return func(ctx context.Context, u string) (reply, error) { - return plainGet(ctx, u, f.userAgent(), f.timeout()) + return plainGet(ctx, u, f.userAgent(), f.timeout(), f.RawFiles) } } diff --git a/fetch/fetch_test.go b/fetch/fetch_test.go index 81866a6..79244c3 100644 --- a/fetch/fetch_test.go +++ b/fetch/fetch_test.go @@ -183,10 +183,10 @@ func TestBothClientsRefuseNonPublicAddresses(t *testing.T) { t.Cleanup(tls.Close) gets := map[string]getter{ "plain": func(ctx context.Context, u string) (reply, error) { - return plainGet(ctx, u, DefaultUserAgent, 5*time.Second) + return plainGet(ctx, u, DefaultUserAgent, 5*time.Second, false) }, "chrome": func(ctx context.Context, u string) (reply, error) { - return chromeGet(ctx, u, 5*time.Second) + return chromeGet(ctx, u, 5*time.Second, false) }, } for name, get := range gets { diff --git a/fetch/proxy_test.go b/fetch/proxy_test.go index bf38541..94ed0bd 100644 --- a/fetch/proxy_test.go +++ b/fetch/proxy_test.go @@ -73,10 +73,10 @@ func TestProxyTunnelsBothClients(t *testing.T) { cp := withProxy(t, url.UserPassword("agent", "s3cret")) for name, get := range map[string]func() (reply, error){ "plain": func() (reply, error) { - return plainGet(t.Context(), "http://refetch-test.invalid/page", "refetch-test", 5*time.Second) + return plainGet(t.Context(), "http://refetch-test.invalid/page", "refetch-test", 5*time.Second, false) }, "chrome_like": func() (reply, error) { - return chromeGet(t.Context(), "http://refetch-test.invalid/page", 5*time.Second) + return chromeGet(t.Context(), "http://refetch-test.invalid/page", 5*time.Second, false) }, } { r, err := get()