package websource import ( "bytes" "html" "net/url" "strings" ) // A small HTML reader, shared by Research's fetcher (internal/runner/ // webread) and the instance's lookups (Readable): enough for a page's // title, meta, readable text and the URLs it names, with every loop // bounded by the input. It never builds a tree and never runs anything a // page carries. // HTMLRefKind is what a URL a page names is for. type HTMLRefKind int // The kinds of URL a page names. const ( RefLink HTMLRefKind = iota RefStylesheet RefIcon RefOG RefImage ) // HTMLRef is a URL a page names, resolved against the page (or its base), or // the refusal resolving it met. logo marks an img whose src, alt, id or // class says "logo". type HTMLRef struct { Kind HTMLRefKind URL URL Raw string Err error Logo bool Alt string } // HTMLMeta is one of a page's meta tags. type HTMLMeta struct{ Name, Content string } // HTMLPage is what ExtractHTML read from a page. type HTMLPage struct { Title string Metas []HTMLMeta Text string Styles string Refs []HTMLRef } // Bounds on what one page contributes. const ( maxMetas = 32 maxMetaValue = 1024 maxStyles = 32 << 10 maxAttributes = 64 maxAttrValue = 4096 ) // rawText elements hold text that is not markup; their content runs to // the matching end tag. var rawText = map[string]bool{"script": true, "style": true, "title": true, "textarea": true, "noscript": true, "xmp": true, "template": true, "iframe": true, "noembed": true, "noframes": true, "plaintext": true} var blockTags = map[string]bool{"p": true, "div": true, "br": true, "li": true, "ul": true, "ol": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "tr": true, "td": true, "th": true, "table": true, "section": true, "article": true, "header": true, "footer": true, "nav": true, "main": true, "aside": true, "blockquote": true, "pre": true, "hr": true, "dt": true, "dd": true, "figcaption": true, "address": true} func asciiLower(b []byte) []byte { out := make([]byte, len(b)) for i, c := range b { if c >= 'A' && c <= 'Z' { c += 'a' - 'A' } out[i] = c } return out } func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' } type extractor struct { HTMLPage base URL based bool buf bytes.Buffer // maxText bounds the text, maxRefs the URLs named. maxText, maxRefs int } // maxRawText bounds a page's text before whitespace collapses. func (x *extractor) maxRawText() int { return 4 * x.maxText } // ExtractHTML reads src, an HTML page fetched from base: its title, // meta, readable text (at most maxText bytes) and up to maxRefs of the // URLs it names. Every loop is bounded by the input; it never builds a // tree and never runs anything a page carries. Scripts' and styles' // contents are never text. func ExtractHTML(src []byte, base URL, maxText, maxRefs int) HTMLPage { x := &extractor{base: base, maxText: maxText, maxRefs: maxRefs} lower := asciiLower(src) n := len(src) for i := 0; i < n; { if src[i] != '<' { j := bytes.IndexByte(src[i:], '<') if j < 0 { j = n - i } x.addText(src[i : i+j]) i += j continue } switch { case bytes.HasPrefix(lower[i:], []byte("")) if end < 0 { return x.finish() } i += 4 + end + 3 case i+1 < n && (src[i+1] == '!' || src[i+1] == '?'): end := bytes.IndexByte(src[i:], '>') if end < 0 { return x.finish() } i += end + 1 case i+1 < n && src[i+1] == '/': j := i + 2 for j < n && (isLetter(src[j]) || src[j] >= '0' && src[j] <= '9') { j++ } if blockTags[string(lower[i+2:j])] { x.buf.WriteByte('\n') } end := bytes.IndexByte(src[j:], '>') if end < 0 { return x.finish() } i = j + end + 1 case i+1 < n && isLetter(src[i+1]): name, attrs, next, ok := parseTag(src, lower, i+1) if !ok { return x.finish() } i = next x.start(name, attrs) if rawText[name] { end := bytes.Index(lower[i:], []byte("'); close >= 0 { i += close + 1 } else { i = n } } default: x.addText(src[i : i+1]) i++ } } return x.finish() } type attr struct{ name, value string } // parseTag reads a start tag from its name at i to its closing '>'. func parseTag(src, lower []byte, i int) (name string, attrs []attr, next int, ok bool) { n := len(src) j := i for j < n && !isSpace(src[j]) && src[j] != '>' && src[j] != '/' { j++ } name = string(lower[i:j]) for { for j < n && (isSpace(src[j]) || src[j] == '/') { j++ } if j >= n { return "", nil, n, false } if src[j] == '>' { return name, attrs, j + 1, true } k := j for k < n && !isSpace(src[k]) && src[k] != '=' && src[k] != '>' && src[k] != '/' { k++ } key := string(lower[j:k]) if k == j { k++ // a stray '=' with no name } j = k for j < n && isSpace(src[j]) { j++ } var value []byte if j < n && src[j] == '=' { j++ for j < n && isSpace(src[j]) { j++ } if j < n && (src[j] == '"' || src[j] == '\'') { q := src[j] end := bytes.IndexByte(src[j+1:], q) if end < 0 { return "", nil, n, false } value = src[j+1 : j+1+end] j += end + 2 } else { k = j for k < n && !isSpace(src[k]) && src[k] != '>' { k++ } value = src[j:k] j = k } } if key != "" && len(attrs) < maxAttributes { if len(value) > maxAttrValue { value = value[:maxAttrValue] } attrs = append(attrs, attr{key, html.UnescapeString(string(value))}) } } } func get(attrs []attr, name string) (string, bool) { for _, a := range attrs { if a.name == name { return a.value, true } } return "", false } func (x *extractor) addText(b []byte) { room := x.maxRawText() - x.buf.Len() if room <= 0 { return } if len(b) > room { b = b[:room] } // A run of text's own line breaks are layout; block tags make lines. space := false for _, r := range html.UnescapeString(string(b)) { if r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\f' || r == '\u00a0' { if !space { x.buf.WriteByte(' ') } space = true continue } space = false x.buf.WriteRune(r) } } func (x *extractor) addRef(kind HTMLRefKind, raw string, logo bool, alt string) { if len(x.Refs) >= x.maxRefs { return } raw = strings.TrimSpace(raw) if raw == "" { return } if p, err := url.Parse(raw); err == nil && p.Scheme != "" && p.Scheme != "http" && p.Scheme != "https" { return // data:, javascript:, mailto: name nothing to fetch } u, err := Resolve(x.base, raw) x.Refs = append(x.Refs, HTMLRef{Kind: kind, URL: u, Raw: raw, Err: err, Logo: logo, Alt: alt}) } func (x *extractor) start(name string, attrs []attr) { if blockTags[name] { x.buf.WriteByte('\n') } switch name { case "base": if href, ok := get(attrs, "href"); ok && !x.based { x.based = true if u, err := Resolve(x.base, strings.TrimSpace(href)); err == nil { x.base = u } } case "meta": key, ok := get(attrs, "name") if !ok { key, _ = get(attrs, "property") } key = strings.ToLower(strings.TrimSpace(key)) content, _ := get(attrs, "content") if key == "description" || key == "theme-color" || strings.HasPrefix(key, "og:") { if len(x.Metas) < maxMetas { x.Metas = append(x.Metas, HTMLMeta{key, clip(oneLine(content), maxMetaValue)}) } if key == "og:image" || key == "og:image:url" || key == "og:image:secure_url" { x.addRef(RefOG, content, false, "") } } case "link": href, _ := get(attrs, "href") rel, _ := get(attrs, "rel") for _, r := range strings.Fields(strings.ToLower(rel)) { switch r { case "stylesheet": x.addRef(RefStylesheet, href, false, "") return case "icon", "apple-touch-icon", "apple-touch-icon-precomposed", "mask-icon": x.addRef(RefIcon, href, false, "") return } } case "img": src, _ := get(attrs, "src") alt, _ := get(attrs, "alt") id, _ := get(attrs, "id") class, _ := get(attrs, "class") logo := strings.Contains(strings.ToLower(src+" "+alt+" "+id+" "+class), "logo") x.addRef(RefImage, src, logo, clip(oneLine(alt), 200)) if alt = oneLine(alt); alt != "" && x.buf.Len() < x.maxRawText() { x.buf.WriteString(" [image: " + clip(alt, 200) + "] ") } case "a": if href, ok := get(attrs, "href"); ok { x.addRef(RefLink, href, false, "") } } } func (x *extractor) raw(name string, content []byte) { switch name { case "title": if x.Title == "" { x.Title = clip(oneLine(html.UnescapeString(string(content))), maxMetaValue) } case "style": if room := maxStyles - len(x.Styles); room > 0 { x.Styles += clip(string(content), room) } case "textarea": x.addText(content) } } func (x *extractor) finish() HTMLPage { p := x.HTMLPage var lines []string for _, line := range strings.Split(x.buf.String(), "\n") { if line = oneLine(line); line != "" { lines = append(lines, line) } } p.Text = clip(strings.Join(lines, "\n"), x.maxText) p.Styles = strings.TrimSpace(p.Styles) return p } // oneLine collapses whitespace, including line breaks, to single spaces. func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") } // Clip cuts s to at most n bytes on a UTF-8 boundary. func Clip(s string, n int) string { return clip(s, n) } func clip(s string, n int) string { if len(s) <= n { return s } s = s[:n] for len(s) > 0 && !utf8Start(s[len(s)-1]) { s = s[:len(s)-1] } if len(s) > 0 && s[len(s)-1] >= 0x80 { s = s[:len(s)-1] // a lead byte whose continuation was cut } return s } func utf8Start(b byte) bool { return b < 0x80 || b >= 0xc0 }