Hard-coded 60s URL and 10s host floors with jitter and per-host backoff, shared between dibs processes through a locked state file. The scheduler shuffles due URLs each round and runs one worker per host; 'dibs --headless' watches and logs JSON.
141 lines
4.3 KiB
Go
141 lines
4.3 KiB
Go
// Package fetch downloads product pages with a browser-like TLS and HTTP/2
|
|
// fingerprint and tells real pages apart from bot checks.
|
|
package fetch
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
stdhttp "net/http"
|
|
"net/url"
|
|
"time"
|
|
|
|
http "github.com/bogdanfinn/fhttp"
|
|
tlsclient "github.com/bogdanfinn/tls-client"
|
|
|
|
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
|
)
|
|
|
|
const (
|
|
DefaultTimeout = 30 * time.Second
|
|
DefaultMaxBody = 16 << 20
|
|
)
|
|
|
|
// ErrBodyTooLarge is returned when a response exceeds Options.MaxBody.
|
|
var ErrBodyTooLarge = errors.New("response body too large")
|
|
|
|
// Limiter decides when a page may be fetched. Every request waits for it.
|
|
type Limiter interface {
|
|
WaitCheck(ctx context.Context, url string) error
|
|
}
|
|
|
|
type Options struct {
|
|
// Limiter defaults to a new in-memory ratelimit.Limiter, so requests are
|
|
// never unlimited.
|
|
Limiter Limiter
|
|
// Browser defaults to DefaultBrowser().
|
|
Browser *Browser
|
|
// Jar defaults to a new, empty jar.
|
|
Jar *Jar
|
|
// Timeout covers a request and its redirects. It defaults to
|
|
// DefaultTimeout.
|
|
Timeout time.Duration
|
|
// MaxBody limits the body after decompression. It defaults to
|
|
// DefaultMaxBody.
|
|
MaxBody int64
|
|
}
|
|
|
|
// Client fetches pages. It is safe for concurrent use.
|
|
type Client struct {
|
|
http tlsclient.HttpClient
|
|
limiter Limiter
|
|
browser Browser
|
|
jar *Jar
|
|
maxBody int64
|
|
}
|
|
|
|
type Response struct {
|
|
URL string // as requested
|
|
FinalURL string // after redirects
|
|
Status int
|
|
Header stdhttp.Header
|
|
Body []byte
|
|
Verdict Verdict
|
|
// Challenge names the bot check found, such as "cloudflare", when
|
|
// Verdict is Challenge.
|
|
Challenge string
|
|
Elapsed time.Duration
|
|
}
|
|
|
|
func New(opts Options) (*Client, error) {
|
|
browser := DefaultBrowser()
|
|
if opts.Browser != nil { browser = *opts.Browser }
|
|
if opts.Limiter == nil { opts.Limiter = ratelimit.New(nil) }
|
|
if opts.Jar == nil { opts.Jar = NewJar() }
|
|
if opts.Timeout == 0 { opts.Timeout = DefaultTimeout }
|
|
if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody }
|
|
|
|
hc, err := tlsclient.NewHttpClient(nil,
|
|
tlsclient.WithClientProfile(browser.Profile),
|
|
tlsclient.WithRandomTLSExtensionOrder(),
|
|
tlsclient.WithCookieJar(opts.Jar),
|
|
tlsclient.WithTimeoutMilliseconds(int(opts.Timeout/time.Millisecond)),
|
|
)
|
|
if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) }
|
|
|
|
return &Client{http: hc, limiter: opts.Limiter, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil
|
|
}
|
|
|
|
func (c *Client) Jar() *Jar { return c.jar }
|
|
|
|
// Get fetches rawURL the way Chrome opens a bookmark, once the limiter allows
|
|
// a check of it. A response with a bad status is not an error; its Verdict
|
|
// says what it is.
|
|
func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) {
|
|
u, err := url.Parse(rawURL)
|
|
if err != nil { return nil, err }
|
|
if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) }
|
|
|
|
if err := c.limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err }
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
|
if err != nil { return nil, err }
|
|
req.Header = c.browser.navigationHeaders(u)
|
|
|
|
start := time.Now()
|
|
resp, err := c.http.Do(req)
|
|
if err != nil { return nil, err }
|
|
|
|
// fhttp's decompressing readers close the raw body with them.
|
|
body := resp.Body
|
|
if !resp.Uncompressed && resp.Header.Get("Content-Encoding") != "" { body = http.DecompressBody(resp) }
|
|
defer func() { _ = body.Close() }()
|
|
|
|
data, err := io.ReadAll(io.LimitReader(body, c.maxBody+1))
|
|
if err != nil { return nil, fmt.Errorf("reading body: %w", err) }
|
|
if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) }
|
|
|
|
r := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data)
|
|
r.Elapsed = time.Since(start)
|
|
|
|
return r, nil
|
|
}
|
|
|
|
// NewResponse builds and classifies a Response for a page obtained another
|
|
// way, such as a saved fixture or the browser fallback.
|
|
func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response {
|
|
if header == nil { header = stdhttp.Header{} }
|
|
|
|
r := &Response{
|
|
URL: rawURL,
|
|
FinalURL: finalURL,
|
|
Status: status,
|
|
Header: header,
|
|
Body: body,
|
|
}
|
|
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
|
|
|
|
return r
|
|
}
|