charset.go 5.0 KB

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