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 hasHighBit := false
88 for _, c := range content {
89 if c >= 0x80 {
90 hasHighBit = true
91 break
92 }
93 }
94 if hasHighBit && utf8.Valid(content) {
95 return "utf-8"
96 }
97
98 // ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8.
99 if ascii(origContent) {
100 return "utf-8"
101 }
102
103 return latin(origContent)
104 }
105
106 func latin(content []byte) string {
107 hasControlBytes := false
108 for _, b := range content {
109 t := textChars[b]
110 if t != T && t != I {
111 return ""
112 }
113 if b >= 0x80 && b <= 0x9F {
114 hasControlBytes = true
115 }
116 }
117 // Code range 0x80 to 0x9F is reserved for control characters in ISO-8859-1
118 // (so-called C1 Controls). Windows 1252, however, has printable punctuation
119 // characters in this range.
120 if hasControlBytes {
121 return "windows-1252"
122 }
123 return "iso-8859-1"
124 }
125
126 func ascii(content []byte) bool {
127 for _, b := range content {
128 if textChars[b] != T {
129 return false
130 }
131 }
132 return true
133 }
134
135 // FromXML returns the charset of an XML document. It relies on the XML
136 // header <?xml version="1.0" encoding="UTF-8"?> and falls back on the plain
137 // text content.
138 func FromXML(content []byte) string {
139 if cset := fromXML(content); cset != "" {
140 return cset
141 }
142 return FromPlain(content)
143 }
144 func fromXML(s scan.Bytes) string {
145 xml := []byte("<?xml")
146 lxml := len(xml)
147 for {
148 s.TrimLWS()
149 if len(s) <= lxml {
150 return ""
151 }
152
153 i, k := s.Search(xml, 0)
154 if i == -1 {
155 return ""
156 }
157 s.Advance(i + k)
158 var aName, aVal []byte
159 hasMore := true
160 for hasMore {
161 aName, aVal, hasMore = markup.GetAnAttribute(&s)
162 if scan.Bytes(aName).Match([]byte("encoding"), 0) != -1 && len(aVal) != 0 {
163 return string(aVal)
164 }
165 }
166 }
167 }
168
169 // FromHTML returns the charset of an HTML document. It first looks if a BOM is
170 // present and if so uses it to determine the charset. If no BOM is present,
171 // it relies on the meta tag <meta charset="UTF-8"> and falls back on the
172 // plain text content.
173 func FromHTML(content []byte) string {
174 if cset := FromBOM(content); cset != "" {
175 return cset
176 }
177 if cset := fromHTML(content); cset != "" {
178 return cset
179 }
180 return FromPlain(content)
181 }
182
183 func fromHTML(s scan.Bytes) string {
184 const (
185 dontKnow = iota
186 doNeedPragma
187 doNotNeedPragma
188 )
189 meta := []byte("<META")
190 body := []byte("<BODY")
191 lmeta := len(meta)
192 for {
193 if markup.SkipAComment(&s) {
194 continue
195 }
196 if len(s) <= lmeta {
197 return ""
198 }
199 // Abort when <body is reached.
200 if s.Match(body, scan.IgnoreCase) != -1 {
201 return ""
202 }
203 if s.Match(meta, scan.IgnoreCase) == -1 {
204 s = s[1:] // safe to slice instead of s.Advance(1) because bounds are checked
205 continue
206 }
207 s = s[lmeta:]
208 c := s.Pop()
209 if c == 0 || (!scan.ByteIsWS(c) && c != '/') {
210 return ""
211 }
212 attrList := make(map[string]bool)
213 gotPragma := false
214 needPragma := dontKnow
215
216 charset := ""
217 var aNameB, aValB []byte
218 hasMore := true
219 for hasMore {
220 aNameB, aValB, hasMore = markup.GetAnAttribute(&s)
221 aName := strings.ToLower(string(aNameB))
222 if attrList[aName] {
223 continue
224 }
225 // processing step
226 if len(aName) == 0 && len(aValB) == 0 {
227 if needPragma == dontKnow {
228 continue
229 }
230 if needPragma == doNeedPragma && !gotPragma {
231 continue
232 }
233 }
234 attrList[aName] = true
235 switch aName {
236 case "http-equiv":
237 if scan.Bytes(aValB).Match([]byte("CONTENT-TYPE"), scan.IgnoreCase) != -1 {
238 gotPragma = true
239 }
240 case "content":
241 charset = string(extractCharsetFromMeta(scan.Bytes(aValB)))
242 if len(charset) != 0 {
243 needPragma = doNeedPragma
244 }
245 case "charset":
246 charset = string(aValB)
247 needPragma = doNotNeedPragma
248 }
249 }
250
251 if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma {
252 continue
253 }
254
255 return charset
256 }
257 }
258
259 // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#algorithm-for-extracting-a-character-encoding-from-a-meta-element
260 func extractCharsetFromMeta(s scan.Bytes) []byte {
261 for {
262 i := bytes.Index(s, []byte("charset"))
263 if i == -1 {
264 return nil
265 }
266 s.Advance(i + len("charset"))
267 for scan.ByteIsWS(s.Peek()) {
268 s.Advance(1)
269 }
270 if s.Pop() != '=' {
271 continue
272 }
273 for scan.ByteIsWS(s.Peek()) {
274 s.Advance(1)
275 }
276 quote := s.Peek()
277 if quote == 0 {
278 return nil
279 }
280 if quote == '"' || quote == '\'' {
281 s.Advance(1)
282 return bytes.TrimSpace(s.PopUntil(quote))
283 }
284
285 return bytes.TrimSpace(s.PopUntil(';', '\t', '\n', '\x0c', '\r', ' '))
286 }
287 }