charset.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package charset provides common text encodings for HTML documents.
  5. //
  6. // The mapping from encoding labels to encodings is defined at
  7. // https://encoding.spec.whatwg.org/.
  8. package charset // import "golang.org/x/net/html/charset"
  9. import (
  10. "bytes"
  11. "fmt"
  12. "io"
  13. "mime"
  14. "strings"
  15. "unicode/utf8"
  16. "golang.org/x/net/html"
  17. "golang.org/x/text/encoding"
  18. "golang.org/x/text/encoding/charmap"
  19. "golang.org/x/text/transform"
  20. )
  21. // Lookup returns the encoding with the specified label, and its canonical
  22. // name. It returns nil and the empty string if label is not one of the
  23. // standard encodings for HTML. Matching is case-insensitive and ignores
  24. // leading and trailing whitespace.
  25. func Lookup(label string) (e encoding.Encoding, name string) {
  26. label = strings.ToLower(strings.Trim(label, "\t\n\r\f "))
  27. enc := encodings[label]
  28. return enc.e, enc.name
  29. }
  30. // DetermineEncoding determines the encoding of an HTML document by examining
  31. // up to the first 1024 bytes of content and the declared Content-Type.
  32. //
  33. // See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding
  34. func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) {
  35. if len(content) > 1024 {
  36. content = content[:1024]
  37. }
  38. for _, b := range boms {
  39. if bytes.HasPrefix(content, b.bom) {
  40. e, name = Lookup(b.enc)
  41. return e, name, true
  42. }
  43. }
  44. if _, params, err := mime.ParseMediaType(contentType); err == nil {
  45. if cs, ok := params["charset"]; ok {
  46. if e, name = Lookup(cs); e != nil {
  47. return e, name, true
  48. }
  49. }
  50. }
  51. if len(content) > 0 {
  52. e, name = prescan(content)
  53. if e != nil {
  54. return e, name, false
  55. }
  56. }
  57. // Try to detect UTF-8.
  58. // First eliminate any partial rune at the end.
  59. for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {
  60. b := content[i]
  61. if b < 0x80 {
  62. break
  63. }
  64. if utf8.RuneStart(b) {
  65. content = content[:i]
  66. break
  67. }
  68. }
  69. hasHighBit := false
  70. for _, c := range content {
  71. if c >= 0x80 {
  72. hasHighBit = true
  73. break
  74. }
  75. }
  76. if hasHighBit && utf8.Valid(content) {
  77. return encoding.Nop, "utf-8", false
  78. }
  79. // TODO: change default depending on user's locale?
  80. return charmap.Windows1252, "windows-1252", false
  81. }
  82. // NewReader returns an io.Reader that converts the content of r to UTF-8.
  83. // It calls DetermineEncoding to find out what r's encoding is.
  84. func NewReader(r io.Reader, contentType string) (io.Reader, error) {
  85. preview := make([]byte, 1024)
  86. n, err := io.ReadFull(r, preview)
  87. switch {
  88. case err == io.ErrUnexpectedEOF:
  89. preview = preview[:n]
  90. r = bytes.NewReader(preview)
  91. case err != nil:
  92. return nil, err
  93. default:
  94. r = io.MultiReader(bytes.NewReader(preview), r)
  95. }
  96. if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop {
  97. r = transform.NewReader(r, e.NewDecoder())
  98. }
  99. return r, nil
  100. }
  101. // NewReaderLabel returns a reader that converts from the specified charset to
  102. // UTF-8. It uses Lookup to find the encoding that corresponds to label, and
  103. // returns an error if Lookup returns nil. It is suitable for use as
  104. // encoding/xml.Decoder's CharsetReader function.
  105. func NewReaderLabel(label string, input io.Reader) (io.Reader, error) {
  106. e, _ := Lookup(label)
  107. if e == nil {
  108. return nil, fmt.Errorf("unsupported charset: %q", label)
  109. }
  110. return transform.NewReader(input, e.NewDecoder()), nil
  111. }
  112. func prescan(content []byte) (e encoding.Encoding, name string) {
  113. z := html.NewTokenizer(bytes.NewReader(content))
  114. for {
  115. switch z.Next() {
  116. case html.ErrorToken:
  117. return nil, ""
  118. case html.StartTagToken, html.SelfClosingTagToken:
  119. tagName, hasAttr := z.TagName()
  120. if !bytes.Equal(tagName, []byte("meta")) {
  121. continue
  122. }
  123. attrList := make(map[string]bool)
  124. gotPragma := false
  125. const (
  126. dontKnow = iota
  127. doNeedPragma
  128. doNotNeedPragma
  129. )
  130. needPragma := dontKnow
  131. name = ""
  132. e = nil
  133. for hasAttr {
  134. var key, val []byte
  135. key, val, hasAttr = z.TagAttr()
  136. ks := string(key)
  137. if attrList[ks] {
  138. continue
  139. }
  140. attrList[ks] = true
  141. for i, c := range val {
  142. if 'A' <= c && c <= 'Z' {
  143. val[i] = c + 0x20
  144. }
  145. }
  146. switch ks {
  147. case "http-equiv":
  148. if bytes.Equal(val, []byte("content-type")) {
  149. gotPragma = true
  150. }
  151. case "content":
  152. if e == nil {
  153. name = fromMetaElement(string(val))
  154. if name != "" {
  155. e, name = Lookup(name)
  156. if e != nil {
  157. needPragma = doNeedPragma
  158. }
  159. }
  160. }
  161. case "charset":
  162. e, name = Lookup(string(val))
  163. needPragma = doNotNeedPragma
  164. }
  165. }
  166. if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {
  167. continue
  168. }
  169. if strings.HasPrefix(name, "utf-16") {
  170. name = "utf-8"
  171. e = encoding.Nop
  172. }
  173. if e != nil {
  174. return e, name
  175. }
  176. }
  177. }
  178. }
  179. func fromMetaElement(s string) string {
  180. for s != "" {
  181. csLoc := strings.Index(s, "charset")
  182. if csLoc == -1 {
  183. return ""
  184. }
  185. s = s[csLoc+len("charset"):]
  186. s = strings.TrimLeft(s, " \t\n\f\r")
  187. if !strings.HasPrefix(s, "=") {
  188. continue
  189. }
  190. s = s[1:]
  191. s = strings.TrimLeft(s, " \t\n\f\r")
  192. if s == "" {
  193. return ""
  194. }
  195. if q := s[0]; q == '"' || q == '\'' {
  196. s = s[1:]
  197. closeQuote := strings.IndexRune(s, rune(q))
  198. if closeQuote == -1 {
  199. return ""
  200. }
  201. return s[:closeQuote]
  202. }
  203. end := strings.IndexAny(s, "; \t\n\f\r")
  204. if end == -1 {
  205. end = len(s)
  206. }
  207. return s[:end]
  208. }
  209. return ""
  210. }
  211. var boms = []struct {
  212. bom []byte
  213. enc string
  214. }{
  215. {[]byte{0xfe, 0xff}, "utf-16be"},
  216. {[]byte{0xff, 0xfe}, "utf-16le"},
  217. {[]byte{0xef, 0xbb, 0xbf}, "utf-8"},
  218. }