1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
|
/*
* htmlcs.c - implement the charset_from_html_prefix function.
*
* Uses, hopefully exactly, the algorithm described at
* https://html.spec.whatwg.org/multipage/syntax.html#prescan-a-byte-stream-to-determine-its-encoding
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include "charset.h"
struct file {
const char *data; /* data from start of stream */
size_t pos; /* how many bytes in data have we stepped past */
size_t len; /* how many bytes in data are meaningful */
size_t cs_start; /* start pos of charset name, if we've found one */
size_t cs_len; /* length of charset name, if we've found one */
};
static void file_init(struct file *f, const void *data, size_t len)
{
f->data = data;
f->pos = 0;
f->len = len;
f->cs_start = f->cs_len = 0;
}
static bool looking_at(struct file *f, ...)
{
size_t ourpos;
va_list ap;
bool to_return;
ourpos = f->pos;
va_start(ap, f);
while (1) {
const char *validchars = va_arg(ap, const char *);
if (!*validchars) {
to_return = true;
break;
}
if (ourpos == f->len) {
to_return = false;
break;
}
if (!strchr(validchars, f->data[ourpos])) {
to_return = false;
break;
}
ourpos++;
}
va_end(ap);
return to_return;
}
static bool looking_at_eof(struct file *f)
{
if (f->pos < f->len)
return false;
return true;
}
static char this_char(struct file *f)
{
assert(f->pos < f->len);
return f->data[f->pos];
}
static bool advance(struct file *f)
{
if (f->pos == f->len)
return false;
f->pos++;
return true;
}
static bool string_match(const char *a, const char *b)
{
while (1) {
char ac = *a++, bc = *b++;
if (ac >= 'A' && ac <= 'Z')
ac += 0x20;
if (bc >= 'A' && bc <= 'Z')
bc += 0x20;
if (ac != bc)
return false;
if (!ac)
return true;
}
}
static int get_charset_from(const char *string)
{
int charset;
if (string_match(string, "x-user-defined"))
return CS_CP1252;
charset = charset_from_mimeenc(string);
if (charset == CS_UTF16 || charset == CS_UTF16BE || charset == CS_UTF16LE)
charset = CS_UTF8;
return charset;
}
#define WHITESPACE " \t\n\f\r"
#define UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define LOWER "abcdefghijklmnopqrstuvwxyz"
#define LETTER UPPER LOWER
struct attr_str {
/* Fixed-size buffer large enough to hold any attribute name or
* value that we will translate into anything other than
* 'unrecognised'. */
char str[128];
int len;
size_t filepos; /* starting location in the file we got it from */
};
static void attr_str_init(struct attr_str *as)
{
if (!as)
return;
as->len = 0;
as->str[as->len] = '\0';
}
static void attr_str_append_file_char(struct attr_str *as,
struct file *f, bool lowercase)
{
char c;
if (!as)
return;
if (as->len == sizeof(as->str)-1 || /* too long */
as->str[0] == 0x7F || /* string already marked invalid */
looking_at_eof(f) || /* end of file */
(unsigned char)(c = this_char(f)) >= 0x80) /* non-ASCII character */
{
/* Set the string to something that definitely won't match
* anything we will want to compare it against. */
as->str[0] = 0x7F;
as->str[1] = '\0';
as->len = 1;
} else {
if (lowercase && strchr(UPPER, c))
c += 0x20;
if (as->len == 0) {
as->filepos = f->pos;
} else {
assert(as->filepos + as->len == f->pos);
}
as->str[as->len++] = c;
as->str[as->len] = '\0';
}
}
static int get_charset_from_meta(struct file *f)
{
const char *end;
bool end_mandatory;
struct attr_str csname;
int i;
while (!looking_at(f, "Cc", "Hh", "Aa", "Rr", "Ss", "Ee", "Tt", "")) {
if (!advance(f))
return CS_NONE;
}
for (i = 0; i < 7; i++) {
/* Skip past the word "charset" */
if (!advance(f))
assert(0 && "Should still be in the word 'charset'!");
}
while (looking_at(f, WHITESPACE, "")) {
if (!advance(f))
assert(0 && "But there's whitespace ahead!");
}
if (!looking_at(f, "=", ""))
return CS_NONE;
if (!advance(f))
assert(0 && "But we just saw an = ahead of us!");
while (looking_at(f, WHITESPACE, "")) {
if (!advance(f))
assert(0 && "But there's whitespace ahead!");
}
if (looking_at(f, "\"'", "")) {
end = looking_at(f, "\"", "") ? "\"" : "'";
end_mandatory = true;
if (!advance(f))
assert(0 && "But we just saw a quote character!");
} else {
end = WHITESPACE ";";
end_mandatory = false;
}
attr_str_init(&csname);
while (1) {
if (looking_at(f, end, ""))
break;
if (looking_at_eof(f)) {
if (end_mandatory)
return CS_NONE;
else
break;
}
attr_str_append_file_char(&csname, f, false);
if (!advance(f))
assert(0 && "But we just found we weren't looking at EOF!");
}
f->cs_start = csname.filepos;
f->cs_len = csname.len;
return get_charset_from(csname.str);
}
static bool get_attribute(struct file *f, struct attr_str *attr_name,
struct attr_str *attr_value)
{
bool attr_name_nonempty;
while (looking_at(f, WHITESPACE "/", "")) {
if (!advance(f))
assert(0 && "But there's whitespace (or a slash) ahead!");
}
if (looking_at(f, ">", ""))
return false;
attr_str_init(attr_name);
attr_str_init(attr_value);
attr_name_nonempty = false;
while (1) {
if (looking_at(f, WHITESPACE "=", "") && attr_name_nonempty) {
break;
} else if (looking_at(f, "/>", "")) {
return true;
} else {
attr_str_append_file_char(attr_name, f, false);
attr_name_nonempty = true;
}
if (!advance(f))
return false;
}
while (looking_at(f, WHITESPACE, "")) {
if (!advance(f))
assert(0 && "But there's whitespace ahead!");
}
if (!looking_at(f, "=", ""))
return true;
if (!advance(f))
assert(0 && "But we just saw an = ahead!");
while (looking_at(f, WHITESPACE, "")) {
if (!advance(f))
assert(0 && "But there's whitespace ahead!");
}
if (looking_at(f, "\"'", "")) {
const char *close_quote = looking_at(f, "\"", "") ? "\"" : "'";;
while (1) {
if (!advance(f))
return false;
if (looking_at(f, close_quote, "")) {
if (!advance(f))
assert(0 && "But we just saw a closing quote!");
return true;
}
attr_str_append_file_char(attr_value, f, true);
}
} else if (looking_at(f, ">", "")) {
return true;
} else {
attr_str_append_file_char(attr_value, f, true);
if (!advance(f))
return true;
}
while (1) {
if (looking_at(f, WHITESPACE ">", "")) {
return true;
} else {
attr_str_append_file_char(attr_value, f, true);
}
if (!advance(f))
return true;
}
}
static int get_charset(struct file *f)
{
while (1) {
if (looking_at(f, "<", "!", "-", "-", "")) {
while (!looking_at(f, "-", "-", ">", "")) {
if (!advance(f))
return CS_NONE;
}
} else if (looking_at(f, "<", "Mm", "Ee", "Tt", "Aa",
WHITESPACE "/", "")) {
struct attr_str attr_name, attr_value;
int attributes_seen_mask = 0;
bool got_pragma = false;
enum { NP_NULL, NP_FALSE, NP_TRUE } need_pragma = NP_NULL;
int charset = CS_NONE;
while (!looking_at(f, WHITESPACE "/", "")) {
if (!advance(f))
return CS_NONE;
}
while (get_attribute(f, &attr_name, &attr_value)) {
enum { HTTP_EQUIV, CONTENT, CHARSET } attr;
if (string_match(attr_name.str, "http-equiv")) {
attr = HTTP_EQUIV;
} else if (string_match(attr_name.str, "content")) {
attr = CONTENT;
} else if (string_match(attr_name.str, "charset")) {
attr = CHARSET;
} else {
continue; /* ignore attributes we don't recognise */
}
if (attributes_seen_mask & (1 << attr))
continue; /* ignore attributes we've already seen one of */
attributes_seen_mask |= (1 << attr);
switch (attr) {
case HTTP_EQUIV:
if (string_match(attr_value.str, "content-type"))
got_pragma = true;
break;
case CONTENT:
{
struct file fvalue;
int new_charset;
file_init(&fvalue, attr_value.str, attr_value.len);
new_charset = get_charset_from_meta(&fvalue);
if (charset == CS_NONE && new_charset != CS_NONE) {
charset = new_charset;
f->cs_start = attr_value.filepos + fvalue.cs_start;
f->cs_len = fvalue.cs_len;
need_pragma = NP_TRUE;
}
}
break;
case CHARSET:
charset = get_charset_from(attr_value.str);
f->cs_start = attr_value.filepos;
f->cs_len = attr_value.len;
need_pragma = NP_FALSE;
}
}
if (need_pragma == NP_NULL)
continue;
if (need_pragma == NP_TRUE && !got_pragma)
continue;
if (charset == CS_NONE)
continue;
return charset;
} else if (looking_at(f, "<", LETTER, "") ||
looking_at(f, "<", "/", LETTER, "")) {
while (!looking_at(f, WHITESPACE ">", "")) {
if (!advance(f))
return CS_NONE;
}
while (get_attribute(f, NULL, NULL))
/* do nothing */;
} else if (looking_at(f, "<", "!/?", "")) {
while (!looking_at(f, ">", "")) {
if (!advance(f))
return CS_NONE;
}
} else {
if (!advance(f))
return CS_NONE;
}
}
}
int charset_from_html_prefix(const char *data, size_t len,
size_t *namepos, size_t *namelen)
{
struct file f;
int cs;
file_init(&f, data, len);
cs = get_charset(&f);
if (cs != CS_NONE) {
if (namepos)
*namepos = f.cs_start;
if (namelen)
*namelen = f.cs_len;
}
return cs;
}
#ifdef TEST_HTMLCS
/*
gcc -DTEST_HTMLCS -g -O0 -o htmlcs htmlcs.c libcharset.a
*/
struct testcase {
const char *string;
size_t len;
int expected_charset;
size_t expected_namepos, expected_namelen;
int line;
};
#define TESTCASE_POS(before, name, after, charset) \
{ before name after, sizeof(before name after)-1, \
charset, sizeof(before)-1, sizeof(name)-1, __LINE__ }
#define TESTCASE_NEG(string) \
{ string, sizeof(string)-1, CS_NONE, 0, 0, __LINE__ }
const struct testcase testcases[] = {
TESTCASE_POS("<html> <head> <meta http-equiv=\"content-type\" content=\"text/html; charset=", "US-ASCII", "\">", CS_ASCII),
TESTCASE_POS("<meta http-equiv=\"content-type\" content=\"text/html; charset=", "US-ASCII", "\"/>", CS_ASCII),
TESTCASE_NEG("<meta http-equiv=\"content-type\" content=\"text/html; charset=US-ASCII\'>"), /* mismatched quotes around content */
TESTCASE_NEG("<!--<meta http-equiv=\"content-type\" content=\"text/html; charset=US-ASCII\">-->"), /* meta tag is commented out */
TESTCASE_NEG("<tag attr='<meta http-equiv=\"content-type\" content=\"text/html; charset=US-ASCII\">'>"), /* meta tag is inside another tag's attribute! */
TESTCASE_NEG("</tag attr='<meta http-equiv=\"content-type\" content=\"text/html; charset=US-ASCII\">'>"), /* even closing tags count as having attributes */
TESTCASE_NEG("<meta content=\"text/html; charset=US-ASCII\">"), /* missing http-equiv when it is mandatory */
TESTCASE_NEG("<meta http-equiv=dummy http-equiv=\"content-type\" content=\"text/html; charset=US-ASCII\">"), /* only the first http-equiv attribute is considered */
TESTCASE_POS("<!--<meta http-equiv=\"content-type\" content=\"text/html; charset=US-ASCII\">--><meta http-equiv=\"content-type\" content=\"text/html; charset=", "ISO8859-1", "\">", CS_ISO8859_1),
TESTCASE_POS("<meta charset=\"", "ISO8859-1", "\">", CS_ISO8859_1),
TESTCASE_POS("<meta charset=\"", "ISO8859-1", "\"/>", CS_ISO8859_1),
TESTCASE_POS("<meta charset='", "ISO8859-1", "'/>", CS_ISO8859_1),
TESTCASE_POS("<meta charset=", "ISO8859-1", " />", CS_ISO8859_1),
TESTCASE_POS("<meta charset=", "ISO8859-1", ">", CS_ISO8859_1),
TESTCASE_POS("<meta charset = \"", "ISO8859-1", "\">", CS_ISO8859_1),
TESTCASE_POS("<meta charset = ", "ISO8859-1", ">", CS_ISO8859_1),
TESTCASE_NEG("<meta charset = \" ISO8859-1\">"), /* spaces between = and attribute value must be outside quotes, if there are quotes */
TESTCASE_NEG("<meta charset=ISO8859-1/>"), /* an unquoted attribute must be terminated by space or >, not / */
TESTCASE_POS("<meta http-equiv=\"content-type\" charset=\"", "ISO8859-1", "\"/>", CS_ISO8859_1),
TESTCASE_POS("<META Charset=\"", "ISO8859-1", "\"/>", CS_ISO8859_1),
TESTCASE_POS("<meta HTTP-Equiv=\"Content-Type\" conTent=\"text/html; chArset=", "us-Ascii", "\">", CS_ASCII),
TESTCASE_POS("<meta charset='", "x-user-defined", "'/>", CS_CP1252),
TESTCASE_POS("<meta charset='", "utf-16", "'/>", CS_UTF8),
TESTCASE_POS("<meta charset='", "utf-16be", "'/>", CS_UTF8),
TESTCASE_POS("<meta charset='", "utf-16le", "'/>", CS_UTF8),
TESTCASE_NEG("<meta charset='****************************************************************************************************************************************************************************************************************************************************************'/>"), /* unrecognised string long enough to overflow the buffer in attr_str */
};
#define lenof(x) ( sizeof((x)) / sizeof(*(x)) )
int run_unit_tests(void)
{
size_t i;
int npass, nfail;
npass = nfail = 0;
for (i = 0; i < lenof(testcases); i++) {
const struct testcase *tc = &testcases[i];
int cs;
size_t namepos, namelen;
cs = charset_from_html_prefix(tc->string, tc->len, &namepos, &namelen);
if (cs != tc->expected_charset) {
printf("%s:%d: expected charset %s, got %s\n",
__FILE__, tc->line,
charset_to_localenc(tc->expected_charset),
charset_to_localenc(cs));
nfail++;
continue;
}
if (cs != CS_NONE) {
if (namepos != tc->expected_namepos) {
printf("%s:%d: expected namepos %d, got %d\n",
__FILE__, tc->line,
(int)tc->expected_namepos, (int)namepos);
nfail++;
continue;
}
if (namelen != tc->expected_namelen) {
printf("%s:%d: expected namelen %d, got %d\n",
__FILE__, tc->line,
(int)tc->expected_namelen, (int)namelen);
nfail++;
continue;
}
}
npass++;
}
printf("passed %d failed %d total %d\n", npass, nfail, npass+nfail);
return nfail != 0;
}
void test_file(FILE *fp)
{
char buf[1024];
size_t got;
int cs;
size_t namepos, namelen;
got = fread(buf, 1, 1024, fp);
cs = charset_from_html_prefix(buf, got, &namepos, &namelen);
if (cs == CS_NONE)
printf("No charset\n");
else
printf("Got charset %s (at %d, len %d)\n",
charset_to_localenc(cs), (int)namepos, (int)namelen);
}
int main(int argc, char **argv)
{
if (argc <= 1) {
return run_unit_tests();
} else {
FILE *fp = fopen(argv[1], "rb");
if (!fp) {
perror(argv[1]);
exit(1);
}
test_file(fp);
fclose(fp);
}
return 0;
}
#endif /* TEST_HTMLCS */
|