Path: blob/main/vendor/golang.org/x/net/html/charset/charset.go
2893 views
// Copyright 2013 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// Package charset provides common text encodings for HTML documents.5//6// The mapping from encoding labels to encodings is defined at7// https://encoding.spec.whatwg.org/.8package charset // import "golang.org/x/net/html/charset"910import (11"bytes"12"fmt"13"io"14"mime"15"strings"16"unicode/utf8"1718"golang.org/x/net/html"19"golang.org/x/text/encoding"20"golang.org/x/text/encoding/charmap"21"golang.org/x/text/encoding/htmlindex"22"golang.org/x/text/transform"23)2425// Lookup returns the encoding with the specified label, and its canonical26// name. It returns nil and the empty string if label is not one of the27// standard encodings for HTML. Matching is case-insensitive and ignores28// leading and trailing whitespace. Encoders will use HTML escape sequences for29// runes that are not supported by the character set.30func Lookup(label string) (e encoding.Encoding, name string) {31e, err := htmlindex.Get(label)32if err != nil {33return nil, ""34}35name, _ = htmlindex.Name(e)36return &htmlEncoding{e}, name37}3839type htmlEncoding struct{ encoding.Encoding }4041func (h *htmlEncoding) NewEncoder() *encoding.Encoder {42// HTML requires a non-terminating legacy encoder. We use HTML escapes to43// substitute unsupported code points.44return encoding.HTMLEscapeUnsupported(h.Encoding.NewEncoder())45}4647// DetermineEncoding determines the encoding of an HTML document by examining48// up to the first 1024 bytes of content and the declared Content-Type.49//50// See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding51func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) {52if len(content) > 1024 {53content = content[:1024]54}5556for _, b := range boms {57if bytes.HasPrefix(content, b.bom) {58e, name = Lookup(b.enc)59return e, name, true60}61}6263if _, params, err := mime.ParseMediaType(contentType); err == nil {64if cs, ok := params["charset"]; ok {65if e, name = Lookup(cs); e != nil {66return e, name, true67}68}69}7071if len(content) > 0 {72e, name = prescan(content)73if e != nil {74return e, name, false75}76}7778// Try to detect UTF-8.79// First eliminate any partial rune at the end.80for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {81b := content[i]82if b < 0x80 {83break84}85if utf8.RuneStart(b) {86content = content[:i]87break88}89}90hasHighBit := false91for _, c := range content {92if c >= 0x80 {93hasHighBit = true94break95}96}97if hasHighBit && utf8.Valid(content) {98return encoding.Nop, "utf-8", false99}100101// TODO: change default depending on user's locale?102return charmap.Windows1252, "windows-1252", false103}104105// NewReader returns an io.Reader that converts the content of r to UTF-8.106// It calls DetermineEncoding to find out what r's encoding is.107func NewReader(r io.Reader, contentType string) (io.Reader, error) {108preview := make([]byte, 1024)109n, err := io.ReadFull(r, preview)110switch {111case err == io.ErrUnexpectedEOF:112preview = preview[:n]113r = bytes.NewReader(preview)114case err != nil:115return nil, err116default:117r = io.MultiReader(bytes.NewReader(preview), r)118}119120if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop {121r = transform.NewReader(r, e.NewDecoder())122}123return r, nil124}125126// NewReaderLabel returns a reader that converts from the specified charset to127// UTF-8. It uses Lookup to find the encoding that corresponds to label, and128// returns an error if Lookup returns nil. It is suitable for use as129// encoding/xml.Decoder's CharsetReader function.130func NewReaderLabel(label string, input io.Reader) (io.Reader, error) {131e, _ := Lookup(label)132if e == nil {133return nil, fmt.Errorf("unsupported charset: %q", label)134}135return transform.NewReader(input, e.NewDecoder()), nil136}137138func prescan(content []byte) (e encoding.Encoding, name string) {139z := html.NewTokenizer(bytes.NewReader(content))140for {141switch z.Next() {142case html.ErrorToken:143return nil, ""144145case html.StartTagToken, html.SelfClosingTagToken:146tagName, hasAttr := z.TagName()147if !bytes.Equal(tagName, []byte("meta")) {148continue149}150attrList := make(map[string]bool)151gotPragma := false152153const (154dontKnow = iota155doNeedPragma156doNotNeedPragma157)158needPragma := dontKnow159160name = ""161e = nil162for hasAttr {163var key, val []byte164key, val, hasAttr = z.TagAttr()165ks := string(key)166if attrList[ks] {167continue168}169attrList[ks] = true170for i, c := range val {171if 'A' <= c && c <= 'Z' {172val[i] = c + 0x20173}174}175176switch ks {177case "http-equiv":178if bytes.Equal(val, []byte("content-type")) {179gotPragma = true180}181182case "content":183if e == nil {184name = fromMetaElement(string(val))185if name != "" {186e, name = Lookup(name)187if e != nil {188needPragma = doNeedPragma189}190}191}192193case "charset":194e, name = Lookup(string(val))195needPragma = doNotNeedPragma196}197}198199if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {200continue201}202203if strings.HasPrefix(name, "utf-16") {204name = "utf-8"205e = encoding.Nop206}207208if e != nil {209return e, name210}211}212}213}214215func fromMetaElement(s string) string {216for s != "" {217csLoc := strings.Index(s, "charset")218if csLoc == -1 {219return ""220}221s = s[csLoc+len("charset"):]222s = strings.TrimLeft(s, " \t\n\f\r")223if !strings.HasPrefix(s, "=") {224continue225}226s = s[1:]227s = strings.TrimLeft(s, " \t\n\f\r")228if s == "" {229return ""230}231if q := s[0]; q == '"' || q == '\'' {232s = s[1:]233closeQuote := strings.IndexRune(s, rune(q))234if closeQuote == -1 {235return ""236}237return s[:closeQuote]238}239240end := strings.IndexAny(s, "; \t\n\f\r")241if end == -1 {242end = len(s)243}244return s[:end]245}246return ""247}248249var boms = []struct {250bom []byte251enc string252}{253{[]byte{0xfe, 0xff}, "utf-16be"},254{[]byte{0xff, 0xfe}, "utf-16le"},255{[]byte{0xef, 0xbb, 0xbf}, "utf-8"},256}257258259