charset.go 5.1 KB

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