Debian Codegraph @

internal/charset/charset.go

raw symbols SCIP
1 package charset
2
3 import (
4 "bytes"
5 "strings"
6 "unicode/utf8"
7
8 "github.com/gabriel-vasile/mimetype/internal/markup"
9 "github.com/gabriel-vasile/mimetype/internal/scan"
10 )
11
12 const (
13 F = 0 /* character never appears in text */
14 T = 1 /* character appears in plain ASCII text */
15 I = 2 /* character appears in ISO-8859 text */
16 X = 3 /* character appears in non-ISO extended ASCII (Mac, IBM PC) */
17 )
18
19 var (
20 boms = []struct {
21 bom []byte
22 enc string
23 }{
24 {[]byte{0xEF, 0xBB, 0xBF}, "utf-8"},
25 {[]byte{0x00, 0x00, 0xFE, 0xFF}, "utf-32be"},
26 {[]byte{0xFF, 0xFE, 0x00, 0x00}, "utf-32le"},
27 {[]byte{0xFE, 0xFF}, "utf-16be"},
28 {[]byte{0xFF, 0xFE}, "utf-16le"},
29 }
30
31 // https://github.com/file/file/blob/fa93fb9f7d21935f1c7644c47d2975d31f12b812/src/encoding.c#L241
32 textChars = [256]byte{
33 /* BEL BS HT LF VT FF CR */
34 F, F, F, F, F, F, F, T, T, T, T, T, T, T, F, F, /* 0x0X */
35 /* ESC */
36 F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, F, /* 0x1X */
37 T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x2X */
38 T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x3X */
39 T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x4X */
40 T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x5X */
41 T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x6X */
42 T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, /* 0x7X */
43 /* NEL */
44 X, X, X, X, X, T, X, X, X, X, X, X, X, X, X, X, /* 0x8X */
45 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 0x9X */
46 I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xaX */
47 I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xbX */
48 I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xcX */
49 I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xdX */
50 I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xeX */
51 I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xfX */
52 }
53 )
54
55 // FromBOM returns the charset declared in the BOM of content.
56 func FromBOM(content []byte) string {
57 for _, b := range boms {
58 if bytes.HasPrefix(content, b.bom) {
59 return b.enc
60 }
61 }
62 return ""
63 }
64
65 // FromPlain returns the charset of a plain text. It relies on BOM presence
66 // and it falls back on checking each byte in content.
67 func FromPlain(content []byte) string {
68 if len(content) == 0 {
69 return ""
70 }
71 if cset := FromBOM(content); cset != "" {
72 return cset
73 }
74 origContent := content
75 // Try to detect UTF-8.
76 // First eliminate any partial rune at the end.
77 for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- {
78 b := content[i]
79 if b < 0x80 {
80 break
81 }
82 if utf8.RuneStart(b) {
83 content = content[:i]
84 break
85 }
86 }
87 // ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8.
88 if utf8.Valid(content) {
89 return "utf-8"
90 }
91
92 return latin(origContent)
93 }
94
95 func latin(content []byte) string {
96 hasControlBytes := false
97 for _, b := range content {
98 t := textChars[b]
99 if t != T && t != I {
100 return ""
101 }
102 if b >= 0x80 && b <= 0x9F {
103 hasControlBytes = true
104 }
105 }
106 // Code range 0x80 to 0x9F is reserved for control characters in ISO-8859-1
107 // (so-called C1 Controls). Windows 1252, however, has printable punctuation
108 // characters in this range.
109 if hasControlBytes {
110 return "windows-1252"
111 }
112 return "iso-8859-1"
113 }
114
115 // FromXML returns the charset of an XML document. It relies on the XML
116 // header <?xml version="1.0" encoding="UTF-8"?> and falls back on the plain
117 // text content.
118 func FromXML(content []byte) string {
119 if cset := fromXML(content); cset != "" {
120 return cset
121 }
122 return FromPlain(content)
123 }
124 func fromXML(s scan.Bytes) string {
125 xml := []byte("<?xml")
126 lxml := len(xml)
127 for {
128 s.TrimLWS()
129 if len(s) <= lxml {
130 return ""
131 }
132
133 i, k := s.Search(xml, 0)
134 if i == -1 {
135 return ""
136 }
137 s.Advance(i + k)
138 var aName, aVal []byte
139 hasMore := true
140 for hasMore {
141 aName, aVal, hasMore = markup.GetAnAttribute(&s)
142 if scan.Bytes(aName).Match([]byte("encoding"), 0) != -1 && len(aVal) != 0 {
143 return string(aVal)
144 }
145 }
146 }
147 }
148
149 // FromHTML returns the charset of an HTML document. It first looks if a BOM is
150 // present and if so uses it to determine the charset. If no BOM is present,
151 // it relies on the meta tag <meta charset="UTF-8"> and falls back on the
152 // plain text content.
153 func FromHTML(content []byte) string {
154 if cset := FromBOM(content); cset != "" {
155 return cset
156 }
157 if cset := fromHTML(content); cset != "" {
158 return cset
159 }
160 return FromPlain(content)
161 }
162
163 func fromHTML(s scan.Bytes) string {
164 const (
165 dontKnow = iota
166 doNeedPragma
167 doNotNeedPragma
168 )
169 meta := []byte("<META")
170 body := []byte("<BODY")
171 lmeta := len(meta)
172 for {
173 if markup.SkipAComment(&s) {
174 continue
175 }
176 if len(s) <= lmeta {
177 return ""
178 }
179 // Abort when <body is reached.
180 if s.Match(body, scan.IgnoreCase) != -1 {
181 return ""
182 }
183 if s.Match(meta, scan.IgnoreCase) == -1 {
184 s = s[1:] // safe to slice instead of s.Advance(1) because bounds are checked
185 continue
186 }
187 s = s[lmeta:]
188 c := s.Pop()
189 if c == 0 || (!scan.ByteIsWS(c) && c != '/') {
190 return ""
191 }
192 attrList := make(map[string]bool)
193 gotPragma := false
194 needPragma := dontKnow
195
196 charset := ""
197 var aNameB, aValB []byte
198 hasMore := true
199 for hasMore {
200 aNameB, aValB, hasMore = markup.GetAnAttribute(&s)
201 aName := strings.ToLower(string(aNameB))
202 if attrList[aName] {
203 continue
204 }
205 // processing step
206 if len(aName) == 0 && len(aValB) == 0 {
207 if needPragma == dontKnow {
208 continue
209 }
210 if needPragma == doNeedPragma && !gotPragma {
211 continue
212 }
213 }
214 attrList[aName] = true
215 switch aName {
216 case "http-equiv":
217 if scan.Bytes(aValB).Match([]byte("CONTENT-TYPE"), scan.IgnoreCase) != -1 {
218 gotPragma = true
219 }
220 case "content":
221 charset = string(extractCharsetFromMeta(scan.Bytes(aValB)))
222 if len(charset) != 0 {
223 needPragma = doNeedPragma
224 }
225 case "charset":
226 charset = string(aValB)
227 needPragma = doNotNeedPragma
228 }
229 }
230
231 if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {
232 continue
233 }
234
235 return charset
236 }
237 }
238
239 // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#algorithm-for-extracting-a-character-encoding-from-a-meta-element
240 func extractCharsetFromMeta(s scan.Bytes) []byte {
241 for {
242 i := bytes.Index(s, []byte("charset"))
243 if i == -1 {
244 return nil
245 }
246 s.Advance(i + len("charset"))
247 for scan.ByteIsWS(s.Peek()) {
248 s.Advance(1)
249 }
250 if s.Pop() != '=' {
251 continue
252 }
253 for scan.ByteIsWS(s.Peek()) {
254 s.Advance(1)
255 }
256 quote := s.Peek()
257 if quote == 0 {
258 return nil
259 }
260 if quote == '"' || quote == '\'' {
261 s.Advance(1)
262 return bytes.TrimSpace(s.PopUntil(quote))
263 }
264
265 return bytes.TrimSpace(s.PopUntil(';', '\t', '\n', '\x0c', '\r', ' '))
266 }
267 }