oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package webread
2
3import (
4 "compress/gzip"
5 "context"
6 "crypto/sha256"
7 "crypto/tls"
8 "crypto/x509"
9 "encoding/hex"
10 "errors"
11 "fmt"
12 "io"
13 "net"
14 "net/http"
15 "net/netip"
16 "os"
17 "strconv"
18 "strings"
19 "syscall"
20 "time"
21
22 "amadan.net/oficina/equipo/internal/attach"
23 "amadan.net/oficina/equipo/internal/runner/egress"
24 "amadan.net/oficina/equipo/internal/websource"
25)
26
27// deps are what tests replace: the resolver, the dial (nil is the checked
28// production dialer), the trusted roots (nil is the system's) and the
29// bounds.
30type deps struct {
31 lookup func(context.Context, string) ([]netip.Addr, error)
32 dial func(context.Context, string, string) (net.Conn, error)
33 roots *x509.CertPool
34 connect, firstByte, request, overall time.Duration
35 maxBytes int64
36}
37
38func defaults() deps {
39 return deps{
40 lookup: func(ctx context.Context, host string) ([]netip.Addr, error) {
41 return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
42 },
43 connect: ConnectTimeout, firstByte: FirstByteTimeout, request: RequestTimeout, overall: OverallTimeout,
44 maxBytes: MaxBytes,
45 }
46}
47
48// refusal is a reason code as an error, so a dial's Control hook can
49// carry it out through net.OpError.
50type refusal string
51
52func (r refusal) Error() string { return "webread: " + string(r) }
53
54// refusalOf is err's reason code, "" when err is not a refusal.
55func refusalOf(err error) string {
56 var r refusal
57 if errors.As(err, &r) {
58 return string(r)
59 }
60 return ""
61}
62
63// Fetch runs the fetch phase for plan and writes its bundle into dir, an
64// existing empty directory. Each source's outcome is in the manifest's
65// log; an error means no bundle (a refused plan, or the directory).
66func Fetch(ctx context.Context, plan Plan, dir string) (Manifest, error) {
67 return fetch(ctx, plan, dir, defaults())
68}
69
70type fetcher struct {
71 d deps
72 inventory []netip.Prefix
73 refused map[string]bool
74 requests int
75 used int64
76 text int64
77 images int64
78 out *bundleWriter
79 log []Entry
80 seen map[string]bool
81 err error
82
83 // known4 and known6: the inventory holds a public prefix of that
84 // family, so the site's egress in it is known.
85 known4, known6 bool
86}
87
88func newFetcher(p Plan, d deps) *fetcher {
89 f := &fetcher{d: d, refused: map[string]bool{}, seen: map[string]bool{}}
90 for _, pr := range p.Inventory {
91 // An IPv4-mapped prefix covers the IPv4 addresses it maps.
92 if pr.Addr().Is4In6() && pr.Bits() >= 96 {
93 pr = netip.PrefixFrom(pr.Addr().Unmap(), pr.Bits()-96)
94 }
95 f.inventory = append(f.inventory, pr)
96 if websource.PublicAddress(pr.Addr()) {
97 f.known4 = f.known4 || pr.Addr().Is4()
98 f.known6 = f.known6 || pr.Addr().Is6()
99 }
100 }
101 for _, h := range []string{p.Instance, p.Forge} {
102 if h != "" {
103 f.refused[h] = true
104 }
105 }
106 return f
107}
108
109type job struct {
110 id, origin, parent string
111 url websource.URL
112 raw string
113 refused error
114}
115
116func fetch(ctx context.Context, p Plan, dir string, d deps) (Manifest, error) {
117 if err := p.Validate(); err != nil {
118 return Manifest{}, err
119 }
120 if err := emptyDir(dir); err != nil {
121 return Manifest{}, err
122 }
123 f := newFetcher(p, d)
124 f.out = &bundleWriter{dir: dir}
125 var spent Spent
126 if p.Spent != nil {
127 spent = *p.Spent
128 }
129 // Earlier passes' requests, bytes and time count here too.
130 f.requests, f.used = spent.Requests, spent.Bytes
131 start := time.Now()
132 ctx, cancel := context.WithTimeout(ctx, d.overall-time.Duration(spent.Millis)*time.Millisecond)
133 defer cancel()
134 var expanded []job
135 for _, s := range p.Sources {
136 f.seen[s.URL.String()] = true
137 }
138 for _, s := range p.Sources {
139 pg, final := f.one(ctx, job{id: s.ID, origin: s.Origin, url: s.URL})
140 if pg == nil {
141 continue
142 }
143 n := 0
144 for _, c := range expansions(*pg, final) {
145 if c.err == nil {
146 if f.seen[c.url.String()] {
147 continue
148 }
149 f.seen[c.url.String()] = true
150 }
151 n++
152 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})
153 }
154 }
155 for _, j := range expanded {
156 f.one(ctx, j)
157 }
158 if f.err != nil {
159 return Manifest{}, f.err
160 }
161 if len(f.log) > MaxLogEntries {
162 return Manifest{}, fmt.Errorf("webread: %d log entries", len(f.log))
163 }
164 return f.out.finish(f.log, Spent{Requests: f.requests, Bytes: f.used, Millis: spent.Millis + time.Since(start).Milliseconds()})
165}
166
167// one fetches one source and logs it. It returns the page to expand when
168// the source was approved (not expanded) and turned out to be HTML.
169func (f *fetcher) one(ctx context.Context, j job) (*page, websource.URL) {
170 start := time.Now()
171 e := Entry{Source: j.id, Origin: j.origin, Parent: j.parent, URL: j.url.String()}
172 defer func() {
173 e.Millis = time.Since(start).Milliseconds()
174 f.log = append(f.log, e)
175 }()
176 if f.err != nil {
177 e.Reason = ReasonRequest
178 return nil, websource.URL{}
179 }
180 if j.refused != nil {
181 e.URL = clipRaw(j.raw)
182 e.Reason = websource.Reason(j.refused)
183 return nil, websource.URL{}
184 }
185 resp, cancel, final, reason := f.get(ctx, j.url, &e)
186 if reason != "" {
187 e.Reason = reason
188 return nil, websource.URL{}
189 }
190 defer cancel()
191 defer resp.Body.Close()
192 body, reason := f.read(resp, &e)
193 if reason != "" {
194 e.Reason = reason
195 return nil, websource.URL{}
196 }
197 sum := sha256.Sum256(body)
198 e.SHA256 = hex.EncodeToString(sum[:])
199 kind, typ := sniff(body, resp.Header.Get("Content-Type"))
200 e.Type = typ
201 switch kind {
202 case KindImage:
203 out, w, h, reason := normaliseImage(typ, body)
204 if reason == "" && f.images+int64(len(out)) > MaxImageTotal {
205 reason = ReasonBudget
206 }
207 if reason != "" {
208 e.Reason = reason
209 return nil, websource.URL{}
210 }
211 file, err := f.out.addImage(j.id, out, w, h)
212 if err != nil {
213 f.err, e.Reason = err, ReasonRequest
214 return nil, websource.URL{}
215 }
216 f.images += file.Size
217 e.File = file.Name
218 return nil, websource.URL{}
219 case KindText:
220 content := string(body)
221 var pg *page
222 if typ == "text/html" {
223 p := extractHTML(body, final)
224 content, pg = pageText(p), &p
225 }
226 room := min(int64(MaxPageText), MaxTotalText-f.text)
227 if room <= 0 {
228 e.Reason = ReasonTextBudget
229 return nil, websource.URL{}
230 }
231 file, err := f.out.add(j.id, KindText, typ, []byte(clip(content, int(room))))
232 if err != nil {
233 f.err, e.Reason = err, ReasonRequest
234 return nil, websource.URL{}
235 }
236 f.text += file.Size
237 e.File = file.Name
238 if pg != nil && j.origin != OriginExpanded {
239 return pg, final
240 }
241 return nil, websource.URL{}
242 }
243 e.Reason = ReasonType
244 return nil, websource.URL{}
245}
246
247func isRedirect(code int) bool {
248 switch code {
249 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
250 return true
251 }
252 return false
253}
254
255// get requests u, following at most MaxRedirects redirects, each a fresh
256// request to a target checked as if approved. The caller closes the body
257// and calls cancel, which ends the final request's deadline.
258func (f *fetcher) get(ctx context.Context, u websource.URL, e *Entry) (*http.Response, context.CancelFunc, websource.URL, string) {
259 for hop := 0; ; hop++ {
260 e.Hops = append(e.Hops, Hop{URL: u.String()})
261 h := &e.Hops[len(e.Hops)-1]
262 if ctx.Err() != nil {
263 return nil, nil, u, ReasonTimeout
264 }
265 if f.refused[u.Host] {
266 return nil, nil, u, ReasonHostRefused
267 }
268 // Reserve before the request: it counts whether it succeeds or not.
269 if f.requests >= MaxRequests || f.used >= f.d.maxBytes {
270 return nil, nil, u, ReasonBudget
271 }
272 f.requests++
273 rctx, cancel := context.WithTimeout(ctx, f.d.request)
274 resp, addr, reason := f.roundTrip(rctx, u)
275 if addr.IsValid() {
276 h.Address, e.Address = addr.String(), addr.String()
277 }
278 if reason != "" {
279 cancel()
280 return nil, nil, u, reason
281 }
282 h.Status, e.Status = resp.StatusCode, resp.StatusCode
283 if !isRedirect(resp.StatusCode) {
284 if resp.StatusCode != http.StatusOK {
285 resp.Body.Close()
286 cancel()
287 return nil, nil, u, ReasonStatus
288 }
289 return resp, cancel, u, ""
290 }
291 location := resp.Header.Get("Location")
292 resp.Body.Close()
293 cancel()
294 if hop == MaxRedirects {
295 return nil, nil, u, ReasonRedirects
296 }
297 if location == "" {
298 return nil, nil, u, ReasonBadRedirect
299 }
300 next, err := websource.Resolve(u, location)
301 if err != nil {
302 e.Hops = append(e.Hops, Hop{URL: clipRaw(location)})
303 return nil, nil, u, websource.Reason(err)
304 }
305 if u.Scheme == "https" && next.Scheme != "https" {
306 e.Hops = append(e.Hops, Hop{URL: next.String()})
307 return nil, nil, u, ReasonDowngrade
308 }
309 u = next
310 }
311}
312
313// check is the address rule for every connection: public, in a family
314// whose egress the inventory knows, and not the site's own.
315func (f *fetcher) check(a netip.Addr) string {
316 a = a.Unmap()
317 if !egress.PublicAddress(a) {
318 return ReasonNotPublic
319 }
320 if a.Is4() && !f.known4 || a.Is6() && !f.known6 {
321 return ReasonFamilyUnknown
322 }
323 for _, p := range f.inventory {
324 if p.Contains(a) {
325 return ReasonInventory
326 }
327 }
328 return ""
329}
330
331// control runs on the socket before connect: the address actually dialled
332// must pass the same rule as the lookup's answer, on the scheme's port.
333func (f *fetcher) control(_, address string, _ syscall.RawConn) error {
334 ap, err := netip.ParseAddrPort(address)
335 if err != nil {
336 return refusal(ReasonNotPublic)
337 }
338 if r := f.check(ap.Addr()); r != "" {
339 return refusal(r)
340 }
341 if p := ap.Port(); p != 443 && p != 80 {
342 return refusal("port_refused")
343 }
344 return nil
345}
346
347func (f *fetcher) dialer() *net.Dialer {
348 return &net.Dialer{Timeout: f.d.connect, KeepAlive: -1, Control: f.control}
349}
350
351// roundTrip makes one request to u on one new connection: one lookup,
352// the whole answer checked, the first address dialled as a literal.
353func (f *fetcher) roundTrip(ctx context.Context, u websource.URL) (*http.Response, netip.Addr, string) {
354 var connected netip.Addr
355 var refused string
356 want := net.JoinHostPort(u.Host, strconv.Itoa(u.Port))
357 connect := func(ctx context.Context, network, addr string) (net.Conn, error) {
358 if addr != want || network != "tcp" {
359 refused = ReasonHostRefused
360 return nil, refusal(refused)
361 }
362 cctx, cancel := context.WithTimeout(ctx, f.d.connect)
363 defer cancel()
364 answer, err := f.d.lookup(cctx, u.Host)
365 if err != nil || len(answer) == 0 {
366 refused = ReasonLookup
367 if isTimeout(err) {
368 refused = ReasonTimeout
369 }
370 return nil, refusal(refused)
371 }
372 for _, a := range answer {
373 if r := f.check(a); r != "" {
374 refused = r
375 return nil, refusal(r)
376 }
377 }
378 a := answer[0].Unmap()
379 dial := f.d.dial
380 if dial == nil {
381 dial = f.dialer().DialContext
382 }
383 conn, err := dial(cctx, "tcp", netip.AddrPortFrom(a, uint16(u.Port)).String())
384 if err != nil {
385 refused = refusalOf(err)
386 if refused == "" {
387 refused = ReasonConnect
388 if isTimeout(err) {
389 refused = ReasonTimeout
390 }
391 }
392 return nil, err
393 }
394 connected = a
395 if u.Scheme != "https" {
396 return conn, nil
397 }
398 tc := tls.Client(conn, &tls.Config{ServerName: u.Host, RootCAs: f.d.roots, MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}})
399 if err = tc.HandshakeContext(cctx); err != nil {
400 conn.Close()
401 refused = "tls_failed"
402 if isTimeout(err) {
403 refused = ReasonTimeout
404 }
405 return nil, err
406 }
407 return tc, nil
408 }
409 tr := &http.Transport{
410 Proxy: nil,
411 DialContext: connect,
412 DialTLSContext: connect,
413 DisableKeepAlives: true,
414 DisableCompression: true,
415 MaxResponseHeaderBytes: MaxHeaderBytes,
416 ResponseHeaderTimeout: f.d.firstByte,
417 TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{},
418 }
419 defer tr.CloseIdleConnections()
420 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
421 if err != nil {
422 return nil, connected, websource.Reason(err)
423 }
424 req.Header = http.Header{"User-Agent": {UserAgent}, "Accept": {accept}, "Accept-Encoding": {"gzip"}}
425 resp, err := tr.RoundTrip(req)
426 if err != nil {
427 switch {
428 case refused != "":
429 return nil, connected, refused
430 case strings.Contains(err.Error(), "headers exceeded"):
431 return nil, connected, ReasonTooLarge
432 case isTimeout(err) || ctx.Err() != nil:
433 return nil, connected, ReasonTimeout
434 }
435 return nil, connected, ReasonRequest
436 }
437 return resp, connected, ""
438}
439
440func isTimeout(err error) bool {
441 if err == nil {
442 return false
443 }
444 var ne net.Error
445 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")
446}
447
448type countReader struct {
449 r io.Reader
450 n int64
451}
452
453func (c *countReader) Read(p []byte) (int, error) {
454 n, err := c.r.Read(p)
455 c.n += int64(n)
456 return n, err
457}
458
459// read takes the body, decompressing gzip itself. Content-Length is
460// checked before any byte is read; then the first bytes say whether this
461// is an image (8 MB cap) or anything else (2 MB), and bytes are counted
462// against that cap and the byte budget as they arrive. Bytes read are
463// charged to the budget whatever happens next.
464func (f *fetcher) read(resp *http.Response, e *Entry) ([]byte, string) {
465 remaining := f.d.maxBytes - f.used
466 if resp.ContentLength > MaxImageBytes {
467 return nil, ReasonTooLarge
468 }
469 if resp.ContentLength > remaining {
470 return nil, ReasonBudget
471 }
472 wireBound := min(int64(MaxImageBytes), remaining)
473 wire := &countReader{r: io.LimitReader(resp.Body, wireBound+1)}
474 var body []byte
475 defer func() { f.used += max(wire.n, int64(len(body))) }()
476 var r io.Reader = wire
477 switch strings.ToLower(strings.TrimSpace(resp.Header.Get("Content-Encoding"))) {
478 case "", "identity":
479 case "gzip", "x-gzip":
480 zr, err := gzip.NewReader(wire)
481 if err != nil {
482 if isTimeout(err) {
483 return nil, ReasonTimeout
484 }
485 return nil, ReasonEncoding
486 }
487 defer zr.Close()
488 r = zr
489 default:
490 return nil, ReasonEncoding
491 }
492 head := make([]byte, 512)
493 n, err := io.ReadFull(r, head)
494 body = head[:n]
495 if err == io.EOF || err == io.ErrUnexpectedEOF {
496 err = nil
497 } else if err == nil {
498 limit := int64(MaxTextBytes)
499 switch attach.Sniff(body) {
500 case attach.PNG, attach.JPEG, attach.GIF:
501 limit = MaxImageBytes
502 }
503 bound := min(limit, remaining)
504 var rest []byte
505 rest, err = io.ReadAll(io.LimitReader(r, bound+1-int64(n)))
506 body = append(body, rest...)
507 if int64(len(body)) > bound || wire.n > wireBound {
508 e.Bytes = int64(len(body))
509 if bound < limit {
510 return nil, ReasonBudget
511 }
512 return nil, ReasonTooLarge
513 }
514 }
515 e.Bytes = int64(len(body))
516 if wire.n > wireBound {
517 return nil, ReasonBudget
518 }
519 if err != nil {
520 if isTimeout(err) {
521 return nil, ReasonTimeout
522 }
523 return nil, ReasonRequest
524 }
525 return body, ""
526}
527
528// clipRaw makes a URL a page or a server wrote safe to log: valid UTF-8,
529// at most websource.MaxURL bytes.
530func clipRaw(s string) string { return clip(strings.ToValidUTF8(s, "?"), websource.MaxURL) }
531
532// pageText is what the bundle keeps of an HTML page.
533func pageText(p page) string {
534 var b strings.Builder
535 if p.title != "" {
536 b.WriteString("Title: " + p.title + "\n")
537 }
538 for _, m := range p.metas {
539 b.WriteString(m.name + ": " + m.content + "\n")
540 }
541 if p.text != "" {
542 b.WriteString("\n" + p.text + "\n")
543 }
544 var links []string
545 for _, r := range p.refs {
546 if r.err != nil {
547 continue
548 }
549 line := kindName[r.kind] + " " + r.url.String()
550 if r.logo {
551 line += " (logo)"
552 }
553 links = append(links, line)
554 }
555 if len(links) > 0 {
556 b.WriteString("\nLinks:\n" + strings.Join(links, "\n") + "\n")
557 }
558 if p.styles != "" {
559 b.WriteString("\nStyles:\n" + p.styles + "\n")
560 }
561 return b.String()
562}
563