package webread import ( "compress/gzip" "context" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/hex" "errors" "fmt" "io" "net" "net/http" "net/netip" "os" "strconv" "strings" "syscall" "time" "amadan.net/oficina/equipo/internal/attach" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/websource" ) // deps are what tests replace: the resolver, the dial (nil is the checked // production dialer), the trusted roots (nil is the system's) and the // bounds. type deps struct { lookup func(context.Context, string) ([]netip.Addr, error) dial func(context.Context, string, string) (net.Conn, error) roots *x509.CertPool connect, firstByte, request, overall time.Duration maxBytes int64 } func defaults() deps { return deps{ lookup: func(ctx context.Context, host string) ([]netip.Addr, error) { return net.DefaultResolver.LookupNetIP(ctx, "ip", host) }, connect: ConnectTimeout, firstByte: FirstByteTimeout, request: RequestTimeout, overall: OverallTimeout, maxBytes: MaxBytes, } } // refusal is a reason code as an error, so a dial's Control hook can // carry it out through net.OpError. type refusal string func (r refusal) Error() string { return "webread: " + string(r) } // refusalOf is err's reason code, "" when err is not a refusal. func refusalOf(err error) string { var r refusal if errors.As(err, &r) { return string(r) } return "" } // Fetch runs the fetch phase for plan and writes its bundle into dir, an // existing empty directory. Each source's outcome is in the manifest's // log; an error means no bundle (a refused plan, or the directory). func Fetch(ctx context.Context, plan Plan, dir string) (Manifest, error) { return fetch(ctx, plan, dir, defaults()) } type fetcher struct { d deps inventory []netip.Prefix refused map[string]bool requests int used int64 text int64 images int64 out *bundleWriter log []Entry seen map[string]bool err error // known4 and known6: the inventory holds a public prefix of that // family, so the site's egress in it is known. known4, known6 bool } func newFetcher(p Plan, d deps) *fetcher { f := &fetcher{d: d, refused: map[string]bool{}, seen: map[string]bool{}} for _, pr := range p.Inventory { // An IPv4-mapped prefix covers the IPv4 addresses it maps. if pr.Addr().Is4In6() && pr.Bits() >= 96 { pr = netip.PrefixFrom(pr.Addr().Unmap(), pr.Bits()-96) } f.inventory = append(f.inventory, pr) if websource.PublicAddress(pr.Addr()) { f.known4 = f.known4 || pr.Addr().Is4() f.known6 = f.known6 || pr.Addr().Is6() } } for _, h := range []string{p.Instance, p.Forge} { if h != "" { f.refused[h] = true } } return f } type job struct { id, origin, parent string url websource.URL raw string refused error } func fetch(ctx context.Context, p Plan, dir string, d deps) (Manifest, error) { if err := p.Validate(); err != nil { return Manifest{}, err } if err := emptyDir(dir); err != nil { return Manifest{}, err } f := newFetcher(p, d) f.out = &bundleWriter{dir: dir} var spent Spent if p.Spent != nil { spent = *p.Spent } // Earlier passes' requests, bytes and time count here too. f.requests, f.used = spent.Requests, spent.Bytes start := time.Now() ctx, cancel := context.WithTimeout(ctx, d.overall-time.Duration(spent.Millis)*time.Millisecond) defer cancel() var expanded []job for _, s := range p.Sources { f.seen[s.URL.String()] = true } for _, s := range p.Sources { pg, final := f.one(ctx, job{id: s.ID, origin: s.Origin, url: s.URL}) if pg == nil { continue } n := 0 for _, c := range expansions(*pg, final) { if c.err == nil { if f.seen[c.url.String()] { continue } f.seen[c.url.String()] = true } n++ expanded = append(expanded, job{id: fmt.Sprintf("%s.%d", s.ID, n), origin: OriginExpanded, parent: s.ID, url: c.url, raw: c.raw, refused: c.err}) } } for _, j := range expanded { f.one(ctx, j) } if f.err != nil { return Manifest{}, f.err } if len(f.log) > MaxLogEntries { return Manifest{}, fmt.Errorf("webread: %d log entries", len(f.log)) } return f.out.finish(f.log, Spent{Requests: f.requests, Bytes: f.used, Millis: spent.Millis + time.Since(start).Milliseconds()}) } // one fetches one source and logs it. It returns the page to expand when // the source was approved (not expanded) and turned out to be HTML. func (f *fetcher) one(ctx context.Context, j job) (*page, websource.URL) { start := time.Now() e := Entry{Source: j.id, Origin: j.origin, Parent: j.parent, URL: j.url.String()} defer func() { e.Millis = time.Since(start).Milliseconds() f.log = append(f.log, e) }() if f.err != nil { e.Reason = ReasonRequest return nil, websource.URL{} } if j.refused != nil { e.URL = clipRaw(j.raw) e.Reason = websource.Reason(j.refused) return nil, websource.URL{} } resp, cancel, final, reason := f.get(ctx, j.url, &e) if reason != "" { e.Reason = reason return nil, websource.URL{} } defer cancel() defer resp.Body.Close() body, reason := f.read(resp, &e) if reason != "" { e.Reason = reason return nil, websource.URL{} } sum := sha256.Sum256(body) e.SHA256 = hex.EncodeToString(sum[:]) kind, typ := sniff(body, resp.Header.Get("Content-Type")) e.Type = typ switch kind { case KindImage: out, w, h, reason := normaliseImage(typ, body) if reason == "" && f.images+int64(len(out)) > MaxImageTotal { reason = ReasonBudget } if reason != "" { e.Reason = reason return nil, websource.URL{} } file, err := f.out.addImage(j.id, out, w, h) if err != nil { f.err, e.Reason = err, ReasonRequest return nil, websource.URL{} } f.images += file.Size e.File = file.Name return nil, websource.URL{} case KindText: content := string(body) var pg *page if typ == "text/html" { p := extractHTML(body, final) content, pg = pageText(p), &p } room := min(int64(MaxPageText), MaxTotalText-f.text) if room <= 0 { e.Reason = ReasonTextBudget return nil, websource.URL{} } file, err := f.out.add(j.id, KindText, typ, []byte(clip(content, int(room)))) if err != nil { f.err, e.Reason = err, ReasonRequest return nil, websource.URL{} } f.text += file.Size e.File = file.Name if pg != nil && j.origin != OriginExpanded { return pg, final } return nil, websource.URL{} } e.Reason = ReasonType return nil, websource.URL{} } func isRedirect(code int) bool { switch code { case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: return true } return false } // get requests u, following at most MaxRedirects redirects, each a fresh // request to a target checked as if approved. The caller closes the body // and calls cancel, which ends the final request's deadline. func (f *fetcher) get(ctx context.Context, u websource.URL, e *Entry) (*http.Response, context.CancelFunc, websource.URL, string) { for hop := 0; ; hop++ { e.Hops = append(e.Hops, Hop{URL: u.String()}) h := &e.Hops[len(e.Hops)-1] if ctx.Err() != nil { return nil, nil, u, ReasonTimeout } if f.refused[u.Host] { return nil, nil, u, ReasonHostRefused } // Reserve before the request: it counts whether it succeeds or not. if f.requests >= MaxRequests || f.used >= f.d.maxBytes { return nil, nil, u, ReasonBudget } f.requests++ rctx, cancel := context.WithTimeout(ctx, f.d.request) resp, addr, reason := f.roundTrip(rctx, u) if addr.IsValid() { h.Address, e.Address = addr.String(), addr.String() } if reason != "" { cancel() return nil, nil, u, reason } h.Status, e.Status = resp.StatusCode, resp.StatusCode if !isRedirect(resp.StatusCode) { if resp.StatusCode != http.StatusOK { resp.Body.Close() cancel() return nil, nil, u, ReasonStatus } return resp, cancel, u, "" } location := resp.Header.Get("Location") resp.Body.Close() cancel() if hop == MaxRedirects { return nil, nil, u, ReasonRedirects } if location == "" { return nil, nil, u, ReasonBadRedirect } next, err := websource.Resolve(u, location) if err != nil { e.Hops = append(e.Hops, Hop{URL: clipRaw(location)}) return nil, nil, u, websource.Reason(err) } if u.Scheme == "https" && next.Scheme != "https" { e.Hops = append(e.Hops, Hop{URL: next.String()}) return nil, nil, u, ReasonDowngrade } u = next } } // check is the address rule for every connection: public, in a family // whose egress the inventory knows, and not the site's own. func (f *fetcher) check(a netip.Addr) string { a = a.Unmap() if !egress.PublicAddress(a) { return ReasonNotPublic } if a.Is4() && !f.known4 || a.Is6() && !f.known6 { return ReasonFamilyUnknown } for _, p := range f.inventory { if p.Contains(a) { return ReasonInventory } } return "" } // control runs on the socket before connect: the address actually dialled // must pass the same rule as the lookup's answer, on the scheme's port. func (f *fetcher) control(_, address string, _ syscall.RawConn) error { ap, err := netip.ParseAddrPort(address) if err != nil { return refusal(ReasonNotPublic) } if r := f.check(ap.Addr()); r != "" { return refusal(r) } if p := ap.Port(); p != 443 && p != 80 { return refusal("port_refused") } return nil } func (f *fetcher) dialer() *net.Dialer { return &net.Dialer{Timeout: f.d.connect, KeepAlive: -1, Control: f.control} } // roundTrip makes one request to u on one new connection: one lookup, // the whole answer checked, the first address dialled as a literal. func (f *fetcher) roundTrip(ctx context.Context, u websource.URL) (*http.Response, netip.Addr, string) { var connected netip.Addr var refused string want := net.JoinHostPort(u.Host, strconv.Itoa(u.Port)) connect := func(ctx context.Context, network, addr string) (net.Conn, error) { if addr != want || network != "tcp" { refused = ReasonHostRefused return nil, refusal(refused) } cctx, cancel := context.WithTimeout(ctx, f.d.connect) defer cancel() answer, err := f.d.lookup(cctx, u.Host) if err != nil || len(answer) == 0 { refused = ReasonLookup if isTimeout(err) { refused = ReasonTimeout } return nil, refusal(refused) } for _, a := range answer { if r := f.check(a); r != "" { refused = r return nil, refusal(r) } } a := answer[0].Unmap() dial := f.d.dial if dial == nil { dial = f.dialer().DialContext } conn, err := dial(cctx, "tcp", netip.AddrPortFrom(a, uint16(u.Port)).String()) if err != nil { refused = refusalOf(err) if refused == "" { refused = ReasonConnect if isTimeout(err) { refused = ReasonTimeout } } return nil, err } connected = a if u.Scheme != "https" { return conn, nil } tc := tls.Client(conn, &tls.Config{ServerName: u.Host, RootCAs: f.d.roots, MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}}) if err = tc.HandshakeContext(cctx); err != nil { conn.Close() refused = "tls_failed" if isTimeout(err) { refused = ReasonTimeout } return nil, err } return tc, nil } tr := &http.Transport{ Proxy: nil, DialContext: connect, DialTLSContext: connect, DisableKeepAlives: true, DisableCompression: true, MaxResponseHeaderBytes: MaxHeaderBytes, ResponseHeaderTimeout: f.d.firstByte, TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, } defer tr.CloseIdleConnections() req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return nil, connected, websource.Reason(err) } req.Header = http.Header{"User-Agent": {UserAgent}, "Accept": {accept}, "Accept-Encoding": {"gzip"}} resp, err := tr.RoundTrip(req) if err != nil { switch { case refused != "": return nil, connected, refused case strings.Contains(err.Error(), "headers exceeded"): return nil, connected, ReasonTooLarge case isTimeout(err) || ctx.Err() != nil: return nil, connected, ReasonTimeout } return nil, connected, ReasonRequest } return resp, connected, "" } func isTimeout(err error) bool { if err == nil { return false } var ne net.Error return errors.Is(err, context.DeadlineExceeded) || errors.Is(err, os.ErrDeadlineExceeded) || (errors.As(err, &ne) && ne.Timeout()) || strings.Contains(err.Error(), "timeout awaiting response headers") } type countReader struct { r io.Reader n int64 } func (c *countReader) Read(p []byte) (int, error) { n, err := c.r.Read(p) c.n += int64(n) return n, err } // read takes the body, decompressing gzip itself. Content-Length is // checked before any byte is read; then the first bytes say whether this // is an image (8 MB cap) or anything else (2 MB), and bytes are counted // against that cap and the byte budget as they arrive. Bytes read are // charged to the budget whatever happens next. func (f *fetcher) read(resp *http.Response, e *Entry) ([]byte, string) { remaining := f.d.maxBytes - f.used if resp.ContentLength > MaxImageBytes { return nil, ReasonTooLarge } if resp.ContentLength > remaining { return nil, ReasonBudget } wireBound := min(int64(MaxImageBytes), remaining) wire := &countReader{r: io.LimitReader(resp.Body, wireBound+1)} var body []byte defer func() { f.used += max(wire.n, int64(len(body))) }() var r io.Reader = wire switch strings.ToLower(strings.TrimSpace(resp.Header.Get("Content-Encoding"))) { case "", "identity": case "gzip", "x-gzip": zr, err := gzip.NewReader(wire) if err != nil { if isTimeout(err) { return nil, ReasonTimeout } return nil, ReasonEncoding } defer zr.Close() r = zr default: return nil, ReasonEncoding } head := make([]byte, 512) n, err := io.ReadFull(r, head) body = head[:n] if err == io.EOF || err == io.ErrUnexpectedEOF { err = nil } else if err == nil { limit := int64(MaxTextBytes) switch attach.Sniff(body) { case attach.PNG, attach.JPEG, attach.GIF: limit = MaxImageBytes } bound := min(limit, remaining) var rest []byte rest, err = io.ReadAll(io.LimitReader(r, bound+1-int64(n))) body = append(body, rest...) if int64(len(body)) > bound || wire.n > wireBound { e.Bytes = int64(len(body)) if bound < limit { return nil, ReasonBudget } return nil, ReasonTooLarge } } e.Bytes = int64(len(body)) if wire.n > wireBound { return nil, ReasonBudget } if err != nil { if isTimeout(err) { return nil, ReasonTimeout } return nil, ReasonRequest } return body, "" } // clipRaw makes a URL a page or a server wrote safe to log: valid UTF-8, // at most websource.MaxURL bytes. func clipRaw(s string) string { return clip(strings.ToValidUTF8(s, "?"), websource.MaxURL) } // pageText is what the bundle keeps of an HTML page. func pageText(p page) string { var b strings.Builder if p.title != "" { b.WriteString("Title: " + p.title + "\n") } for _, m := range p.metas { b.WriteString(m.name + ": " + m.content + "\n") } if p.text != "" { b.WriteString("\n" + p.text + "\n") } var links []string for _, r := range p.refs { if r.err != nil { continue } line := kindName[r.kind] + " " + r.url.String() if r.logo { line += " (logo)" } links = append(links, line) } if len(links) > 0 { b.WriteString("\nLinks:\n" + strings.Join(links, "\n") + "\n") } if p.styles != "" { b.WriteString("\nStyles:\n" + p.styles + "\n") } return b.String() }