1use alloc::string::String;
8use alloc::vec::Vec;
9
10const ENCODINGS: &[(&str, &[&str])] = &[
12 ("utf-8", &["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"]),
13 ("ibm866", &["866", "cp866", "csibm866", "ibm866"]),
14 ("iso-8859-2", &["csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2"]),
15 ("iso-8859-3", &["csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3"]),
16 ("iso-8859-4", &["csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4"]),
17 ("iso-8859-5", &["csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso8859-5", "iso88595", "iso_8859-5", "iso_8859-5:1988"]),
18 (
19 "iso-8859-6",
20 &[
21 "arabic", "asmo-708", "csiso88596e", "csiso88596i", "csisolatinarabic", "ecma-114", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-ir-127", "iso8859-6", "iso88596", "iso_8859-6",
22 "iso_8859-6:1987",
23 ],
24 ),
25 (
26 "iso-8859-7",
27 &["csisolatingreek", "ecma-118", "elot_928", "greek", "greek8", "iso-8859-7", "iso-ir-126", "iso8859-7", "iso88597", "iso_8859-7", "iso_8859-7:1987", "sun_eu_greek"],
28 ),
29 (
30 "iso-8859-8",
31 &["csiso88598e", "csisolatinhebrew", "hebrew", "iso-8859-8", "iso-8859-8-e", "iso-ir-138", "iso8859-8", "iso88598", "iso_8859-8", "iso_8859-8:1988", "visual"],
32 ),
33 ("iso-8859-8-i", &["csiso88598i", "iso-8859-8-i", "logical"]),
34 ("iso-8859-10", &["csisolatin6", "iso-8859-10", "iso-ir-157", "iso8859-10", "iso885910", "l6", "latin6"]),
35 ("iso-8859-13", &["iso-8859-13", "iso8859-13", "iso885913"]),
36 ("iso-8859-14", &["iso-8859-14", "iso8859-14", "iso885914"]),
37 ("iso-8859-15", &["csisolatin9", "iso-8859-15", "iso8859-15", "iso885915", "iso_8859-15", "l9"]),
38 ("iso-8859-16", &["iso-8859-16"]),
39 ("koi8-r", &["cskoi8r", "koi", "koi8", "koi8-r", "koi8_r"]),
40 ("koi8-u", &["koi8-ru", "koi8-u"]),
41 ("macintosh", &["csmacintosh", "mac", "macintosh", "x-mac-roman"]),
42 ("windows-874", &["dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874"]),
43 ("windows-1250", &["cp1250", "windows-1250", "x-cp1250"]),
44 ("windows-1251", &["cp1251", "windows-1251", "x-cp1251"]),
45 (
46 "windows-1252",
47 &[
48 "ansi_x3.4-1968", "ascii", "cp1252", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100", "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii",
49 "windows-1252", "x-cp1252",
50 ],
51 ),
52 ("windows-1253", &["cp1253", "windows-1253", "x-cp1253"]),
53 ("windows-1254", &["cp1254", "csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9", "iso_8859-9:1989", "l5", "latin5", "windows-1254", "x-cp1254"]),
54 ("windows-1255", &["cp1255", "windows-1255", "x-cp1255"]),
55 ("windows-1256", &["cp1256", "windows-1256", "x-cp1256"]),
56 ("windows-1257", &["cp1257", "windows-1257", "x-cp1257"]),
57 ("windows-1258", &["cp1258", "windows-1258", "x-cp1258"]),
58 ("x-mac-cyrillic", &["x-mac-cyrillic", "x-mac-ukrainian"]),
59 ("gbk", &["chinese", "csgb2312", "csiso58gb231280", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58", "x-gbk"]),
60 ("gb18030", &["gb18030"]),
61 ("big5", &["big5", "big5-hkscs", "cn-big5", "csbig5", "x-x-big5"]),
62 ("euc-jp", &["cseucpkdfmtjapanese", "euc-jp", "x-euc-jp"]),
63 ("iso-2022-jp", &["csiso2022jp", "iso-2022-jp"]),
64 ("shift_jis", &["csshiftjis", "ms932", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis"]),
65 ("euc-kr", &["cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "windows-949"]),
66 ("replacement", &["csiso2022kr", "hz-gb-2312", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-kr", "replacement"]),
67 ("utf-16be", &["unicodefffe", "utf-16be"]),
68 ("utf-16le", &["csunicode", "iso-10646-ucs-2", "ucs-2", "unicode", "unicodefeff", "utf-16", "utf-16le"]),
69 ("x-user-defined", &["x-user-defined"]),
70];
71
72fn is_ws(b: u8) -> bool {
73 matches!(b, 0x09 | 0x0a | 0x0c | 0x0d | 0x20)
74}
75
76pub fn resolve_encoding_label(label: &str) -> Option<&'static str> {
78 let l = label.trim_matches(|c| matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')).to_ascii_lowercase();
79 ENCODINGS.iter().find(|(_, labels)| labels.contains(&l.as_str())).map(|(n, _)| *n)
80}
81
82pub fn check_bom(bytes: &[u8]) -> Option<&'static str> {
84 if bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
85 Some("utf-8")
86 } else if bytes.starts_with(&[0xfe, 0xff]) {
87 Some("utf-16be")
88 } else if bytes.starts_with(&[0xff, 0xfe]) {
89 Some("utf-16le")
90 } else {
91 None
92 }
93}
94
95fn find_sub(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
96 if needle.is_empty() || hay.len() < needle.len() {
97 return None;
98 }
99 let mut i = from;
100 while i + needle.len() <= hay.len() {
101 if hay.get(i..i + needle.len()) == Some(needle) {
102 return Some(i);
103 }
104 i += 1;
105 }
106 None
107}
108
109fn starts_with_ci(hay: &[u8], pos: usize, pat: &[u8]) -> bool {
110 hay.get(pos..pos + pat.len()).is_some_and(|s| s.eq_ignore_ascii_case(pat))
111}
112
113fn extract_from_meta_content(v: &[u8]) -> Option<&'static str> {
115 let mut pos = 0usize;
116 loop {
117 let i = (pos..v.len()).find(|&i| starts_with_ci(v, i, b"charset"))?;
118 let mut p = i + 7;
119 while v.get(p).is_some_and(|&b| is_ws(b)) {
120 p += 1;
121 }
122 if v.get(p) != Some(&b'=') {
123 pos = i + 7;
124 continue;
125 }
126 p += 1;
127 while v.get(p).is_some_and(|&b| is_ws(b)) {
128 p += 1;
129 }
130 let val: &[u8] = match v.get(p) {
131 Some(&q) if q == b'"' || q == b'\'' => {
132 let rest = v.get(p + 1..)?;
133 let end = rest.iter().position(|&b| b == q)?;
134 rest.get(..end)?
135 }
136 Some(_) => {
137 let rest = v.get(p..)?;
138 let end = rest.iter().position(|&b| is_ws(b) || b == b';').unwrap_or(rest.len());
139 rest.get(..end)?
140 }
141 None => return None,
142 };
143 if val.is_empty() {
144 return None;
145 }
146 return resolve_encoding_label(&String::from_utf8_lossy(val));
147 }
148}
149
150fn get_attribute(b: &[u8], pos: &mut usize) -> Result<Option<(Vec<u8>, Vec<u8>)>, ()> {
152 while b.get(*pos).is_some_and(|&c| is_ws(c) || c == b'/') {
153 *pos += 1;
154 }
155 match b.get(*pos) {
156 None => return Err(()),
157 Some(&b'>') => return Ok(None),
158 _ => {}
159 }
160 let mut name: Vec<u8> = Vec::new();
161 let mut value: Vec<u8> = Vec::new();
162 loop {
164 let Some(&c) = b.get(*pos) else { return Err(()) };
165 if c == b'=' && !name.is_empty() {
166 break;
167 }
168 if is_ws(c) {
169 while b.get(*pos).is_some_and(|&x| is_ws(x)) {
171 *pos += 1;
172 }
173 match b.get(*pos) {
174 None => return Err(()),
175 Some(&b'=') => break,
176 Some(_) => return Ok(Some((name, value))),
177 }
178 }
179 if c == b'/' || c == b'>' {
180 return Ok(Some((name, value)));
181 }
182 name.push(c.to_ascii_lowercase());
183 *pos += 1;
184 }
185 *pos += 1;
187 while b.get(*pos).is_some_and(|&x| is_ws(x)) {
188 *pos += 1;
189 }
190 let Some(&c) = b.get(*pos) else { return Err(()) };
191 if c == b'"' || c == b'\'' {
192 *pos += 1;
193 loop {
194 let Some(&x) = b.get(*pos) else { return Err(()) };
195 *pos += 1;
196 if x == c {
197 return Ok(Some((name, value)));
198 }
199 value.push(x.to_ascii_lowercase());
200 }
201 }
202 if c == b'>' {
203 return Ok(Some((name, value)));
204 }
205 loop {
206 let Some(&x) = b.get(*pos) else { return Err(()) };
207 if is_ws(x) || x == b'>' {
208 return Ok(Some((name, value)));
209 }
210 value.push(x.to_ascii_lowercase());
211 *pos += 1;
212 }
213}
214
215pub fn prescan_meta_encoding(bytes: &[u8]) -> Option<&'static str> {
217 prescan_limited(bytes.get(..bytes.len().min(1024)).unwrap_or(bytes))
218}
219
220pub fn find_late_meta_encoding(bytes: &[u8]) -> Option<&'static str> {
223 prescan_limited(bytes)
224}
225
226fn prescan_limited(b: &[u8]) -> Option<&'static str> {
227 let mut pos = 0usize;
228 while pos < b.len() {
229 if b.get(pos..pos + 4) == Some(b"<!--") {
230 let end = find_sub(b, b"-->", pos + 2)?;
232 pos = end + 2;
233 } else if starts_with_ci(b, pos, b"<meta") && b.get(pos + 5).is_some_and(|&c| is_ws(c) || c == b'/') {
234 pos += 5;
235 let mut seen: Vec<Vec<u8>> = Vec::new();
236 let mut got_pragma = false;
237 let mut need_pragma: Option<bool> = None;
238 let mut charset: Option<Option<&'static str>> = None;
239 loop {
240 match get_attribute(b, &mut pos) {
241 Err(()) => return None,
242 Ok(None) => break,
243 Ok(Some((n, v))) => {
244 if seen.contains(&n) {
245 continue;
246 }
247 match n.as_slice() {
248 b"http-equiv" if v == b"content-type" => got_pragma = true,
249 b"content" if charset.is_none() => {
250 if let Some(e) = extract_from_meta_content(&v) {
251 charset = Some(Some(e));
252 need_pragma = Some(true);
253 }
254 }
255 b"charset" => {
256 charset = Some(resolve_encoding_label(&String::from_utf8_lossy(&v)));
257 need_pragma = Some(false);
258 }
259 _ => {}
260 }
261 seen.push(n);
262 }
263 }
264 }
265 match (need_pragma, charset) {
266 (Some(np), Some(Some(e))) if !np || got_pragma => {
267 return Some(match e {
268 "utf-16be" | "utf-16le" => "utf-8",
269 "x-user-defined" => "windows-1252",
270 e => e,
271 });
272 }
273 _ => {}
274 }
275 } else if (b.get(pos) == Some(&b'<') && b.get(pos + 1).is_some_and(|c| c.is_ascii_alphabetic()))
276 || (b.get(pos..pos + 2) == Some(b"</") && b.get(pos + 2).is_some_and(|c| c.is_ascii_alphabetic()))
277 {
278 pos += 1;
279 while b.get(pos).is_some_and(|&c| !is_ws(c) && c != b'>') {
280 pos += 1;
281 }
282 loop {
283 match get_attribute(b, &mut pos) {
284 Err(()) => return None,
285 Ok(None) => break,
286 Ok(Some(_)) => {}
287 }
288 }
289 } else if b.get(pos..pos + 2) == Some(b"<!") || b.get(pos..pos + 2) == Some(b"</") || b.get(pos..pos + 2) == Some(b"<?") {
290 pos = b.iter().skip(pos).position(|&c| c == b'>').map(|i| i + pos)?;
291 }
292 pos += 1;
293 }
294 None
295}
296
297pub fn sniff_html_encoding(bytes: &[u8], transport_charset: Option<&str>, default: &'static str) -> &'static str {
299 if let Some(e) = check_bom(bytes) {
300 return e;
301 }
302 if let Some(e) = transport_charset.and_then(resolve_encoding_label) {
303 return e;
304 }
305 prescan_meta_encoding(bytes).or_else(|| find_late_meta_encoding(bytes)).unwrap_or(default)
306}