xref: /PHP-7.4/ext/standard/html.c (revision 3a5664fd)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Rasmus Lerdorf <rasmus@php.net>                             |
16    |          Jaakko Hyvätti <jaakko.hyvatti@iki.fi>                      |
17    |          Wez Furlong    <wez@thebrainroom.com>                       |
18    |          Gustavo Lopes  <cataphract@php.net>                         |
19    +----------------------------------------------------------------------+
20 */
21 
22 /*
23  * HTML entity resources:
24  *
25  * http://www.unicode.org/Public/MAPPINGS/OBSOLETE/UNI2SGML.TXT
26  *
27  * XHTML 1.0 DTD
28  * http://www.w3.org/TR/2002/REC-xhtml1-20020801/dtds.html#h-A2
29  *
30  * From HTML 4.01 strict DTD:
31  * http://www.w3.org/TR/html4/HTMLlat1.ent
32  * http://www.w3.org/TR/html4/HTMLsymbol.ent
33  * http://www.w3.org/TR/html4/HTMLspecial.ent
34  *
35  * HTML 5:
36  * http://dev.w3.org/html5/spec/Overview.html#named-character-references
37  */
38 
39 #include "php.h"
40 #ifdef PHP_WIN32
41 #include "config.w32.h"
42 #else
43 #include <php_config.h>
44 #endif
45 #include "php_standard.h"
46 #include "php_string.h"
47 #include "SAPI.h"
48 #include <locale.h>
49 #if HAVE_LANGINFO_H
50 #include <langinfo.h>
51 #endif
52 
53 #include <zend_hash.h>
54 #include "html_tables.h"
55 
56 /* Macro for disabling flag of translation of non-basic entities where this isn't supported.
57  * Not appropriate for html_entity_decode/htmlspecialchars_decode */
58 #define LIMIT_ALL(all, doctype, charset) do { \
59 	(all) = (all) && !CHARSET_PARTIAL_SUPPORT((charset)) && ((doctype) != ENT_HTML_DOC_XML1); \
60 } while (0)
61 
62 #define MB_FAILURE(pos, advance) do { \
63 	*cursor = pos + (advance); \
64 	*status = FAILURE; \
65 	return 0; \
66 } while (0)
67 
68 #define CHECK_LEN(pos, chars_need) ((str_len - (pos)) >= (chars_need))
69 
70 /* valid as single byte character or leading byte */
71 #define utf8_lead(c)  ((c) < 0x80 || ((c) >= 0xC2 && (c) <= 0xF4))
72 /* whether it's actually valid depends on other stuff;
73  * this macro cannot check for non-shortest forms, surrogates or
74  * code points above 0x10FFFF */
75 #define utf8_trail(c) ((c) >= 0x80 && (c) <= 0xBF)
76 
77 #define gb2312_lead(c) ((c) != 0x8E && (c) != 0x8F && (c) != 0xA0 && (c) != 0xFF)
78 #define gb2312_trail(c) ((c) >= 0xA1 && (c) <= 0xFE)
79 
80 #define sjis_lead(c) ((c) != 0x80 && (c) != 0xA0 && (c) < 0xFD)
81 #define sjis_trail(c) ((c) >= 0x40  && (c) != 0x7F && (c) < 0xFD)
82 
83 /* {{{ get_default_charset
84  */
get_default_charset(void)85 static char *get_default_charset(void) {
86 	if (PG(internal_encoding) && PG(internal_encoding)[0]) {
87 		return PG(internal_encoding);
88 	} else if (SG(default_charset) && SG(default_charset)[0] ) {
89 		return SG(default_charset);
90 	}
91 	return NULL;
92 }
93 /* }}} */
94 
95 /* {{{ get_next_char
96  */
get_next_char(enum entity_charset charset,const unsigned char * str,size_t str_len,size_t * cursor,int * status)97 static inline unsigned int get_next_char(
98 		enum entity_charset charset,
99 		const unsigned char *str,
100 		size_t str_len,
101 		size_t *cursor,
102 		int *status)
103 {
104 	size_t pos = *cursor;
105 	unsigned int this_char = 0;
106 
107 	*status = SUCCESS;
108 	assert(pos <= str_len);
109 
110 	if (!CHECK_LEN(pos, 1))
111 		MB_FAILURE(pos, 1);
112 
113 	switch (charset) {
114 	case cs_utf_8:
115 		{
116 			/* We'll follow strategy 2. from section 3.6.1 of UTR #36:
117 			 * "In a reported illegal byte sequence, do not include any
118 			 *  non-initial byte that encodes a valid character or is a leading
119 			 *  byte for a valid sequence." */
120 			unsigned char c;
121 			c = str[pos];
122 			if (c < 0x80) {
123 				this_char = c;
124 				pos++;
125 			} else if (c < 0xc2) {
126 				MB_FAILURE(pos, 1);
127 			} else if (c < 0xe0) {
128 				if (!CHECK_LEN(pos, 2))
129 					MB_FAILURE(pos, 1);
130 
131 				if (!utf8_trail(str[pos + 1])) {
132 					MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2);
133 				}
134 				this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f);
135 				if (this_char < 0x80) { /* non-shortest form */
136 					MB_FAILURE(pos, 2);
137 				}
138 				pos += 2;
139 			} else if (c < 0xf0) {
140 				size_t avail = str_len - pos;
141 
142 				if (avail < 3 ||
143 						!utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) {
144 					if (avail < 2 || utf8_lead(str[pos + 1]))
145 						MB_FAILURE(pos, 1);
146 					else if (avail < 3 || utf8_lead(str[pos + 2]))
147 						MB_FAILURE(pos, 2);
148 					else
149 						MB_FAILURE(pos, 3);
150 				}
151 
152 				this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f);
153 				if (this_char < 0x800) { /* non-shortest form */
154 					MB_FAILURE(pos, 3);
155 				} else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */
156 					MB_FAILURE(pos, 3);
157 				}
158 				pos += 3;
159 			} else if (c < 0xf5) {
160 				size_t avail = str_len - pos;
161 
162 				if (avail < 4 ||
163 						!utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) ||
164 						!utf8_trail(str[pos + 3])) {
165 					if (avail < 2 || utf8_lead(str[pos + 1]))
166 						MB_FAILURE(pos, 1);
167 					else if (avail < 3 || utf8_lead(str[pos + 2]))
168 						MB_FAILURE(pos, 2);
169 					else if (avail < 4 || utf8_lead(str[pos + 3]))
170 						MB_FAILURE(pos, 3);
171 					else
172 						MB_FAILURE(pos, 4);
173 				}
174 
175 				this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f);
176 				if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */
177 					MB_FAILURE(pos, 4);
178 				}
179 				pos += 4;
180 			} else {
181 				MB_FAILURE(pos, 1);
182 			}
183 		}
184 		break;
185 
186 	case cs_big5:
187 		/* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */
188 		{
189 			unsigned char c = str[pos];
190 			if (c >= 0x81 && c <= 0xFE) {
191 				unsigned char next;
192 				if (!CHECK_LEN(pos, 2))
193 					MB_FAILURE(pos, 1);
194 
195 				next = str[pos + 1];
196 
197 				if ((next >= 0x40 && next <= 0x7E) ||
198 						(next >= 0xA1 && next <= 0xFE)) {
199 					this_char = (c << 8) | next;
200 				} else {
201 					MB_FAILURE(pos, 1);
202 				}
203 				pos += 2;
204 			} else {
205 				this_char = c;
206 				pos += 1;
207 			}
208 		}
209 		break;
210 
211 	case cs_big5hkscs:
212 		{
213 			unsigned char c = str[pos];
214 			if (c >= 0x81 && c <= 0xFE) {
215 				unsigned char next;
216 				if (!CHECK_LEN(pos, 2))
217 					MB_FAILURE(pos, 1);
218 
219 				next = str[pos + 1];
220 
221 				if ((next >= 0x40 && next <= 0x7E) ||
222 						(next >= 0xA1 && next <= 0xFE)) {
223 					this_char = (c << 8) | next;
224 				} else if (next != 0x80 && next != 0xFF) {
225 					MB_FAILURE(pos, 1);
226 				} else {
227 					MB_FAILURE(pos, 2);
228 				}
229 				pos += 2;
230 			} else {
231 				this_char = c;
232 				pos += 1;
233 			}
234 		}
235 		break;
236 
237 	case cs_gb2312: /* EUC-CN */
238 		{
239 			unsigned char c = str[pos];
240 			if (c >= 0xA1 && c <= 0xFE) {
241 				unsigned char next;
242 				if (!CHECK_LEN(pos, 2))
243 					MB_FAILURE(pos, 1);
244 
245 				next = str[pos + 1];
246 
247 				if (gb2312_trail(next)) {
248 					this_char = (c << 8) | next;
249 				} else if (gb2312_lead(next)) {
250 					MB_FAILURE(pos, 1);
251 				} else {
252 					MB_FAILURE(pos, 2);
253 				}
254 				pos += 2;
255 			} else if (gb2312_lead(c)) {
256 				this_char = c;
257 				pos += 1;
258 			} else {
259 				MB_FAILURE(pos, 1);
260 			}
261 		}
262 		break;
263 
264 	case cs_sjis:
265 		{
266 			unsigned char c = str[pos];
267 			if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) {
268 				unsigned char next;
269 				if (!CHECK_LEN(pos, 2))
270 					MB_FAILURE(pos, 1);
271 
272 				next = str[pos + 1];
273 
274 				if (sjis_trail(next)) {
275 					this_char = (c << 8) | next;
276 				} else if (sjis_lead(next)) {
277 					MB_FAILURE(pos, 1);
278 				} else {
279 					MB_FAILURE(pos, 2);
280 				}
281 				pos += 2;
282 			} else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) {
283 				this_char = c;
284 				pos += 1;
285 			} else {
286 				MB_FAILURE(pos, 1);
287 			}
288 		}
289 		break;
290 
291 	case cs_eucjp:
292 		{
293 			unsigned char c = str[pos];
294 
295 			if (c >= 0xA1 && c <= 0xFE) {
296 				unsigned next;
297 				if (!CHECK_LEN(pos, 2))
298 					MB_FAILURE(pos, 1);
299 				next = str[pos + 1];
300 
301 				if (next >= 0xA1 && next <= 0xFE) {
302 					/* this a jis kanji char */
303 					this_char = (c << 8) | next;
304 				} else {
305 					MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2);
306 				}
307 				pos += 2;
308 			} else if (c == 0x8E) {
309 				unsigned next;
310 				if (!CHECK_LEN(pos, 2))
311 					MB_FAILURE(pos, 1);
312 
313 				next = str[pos + 1];
314 				if (next >= 0xA1 && next <= 0xDF) {
315 					/* JIS X 0201 kana */
316 					this_char = (c << 8) | next;
317 				} else {
318 					MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2);
319 				}
320 				pos += 2;
321 			} else if (c == 0x8F) {
322 				size_t avail = str_len - pos;
323 
324 				if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) ||
325 						!(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) {
326 					if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF))
327 						MB_FAILURE(pos, 1);
328 					else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF))
329 						MB_FAILURE(pos, 2);
330 					else
331 						MB_FAILURE(pos, 3);
332 				} else {
333 					/* JIS X 0212 hojo-kanji */
334 					this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2];
335 				}
336 				pos += 3;
337 			} else if (c != 0xA0 && c != 0xFF) {
338 				/* character encoded in 1 code unit */
339 				this_char = c;
340 				pos += 1;
341 			} else {
342 				MB_FAILURE(pos, 1);
343 			}
344 		}
345 		break;
346 	default:
347 		/* single-byte charsets */
348 		this_char = str[pos++];
349 		break;
350 	}
351 
352 	*cursor = pos;
353   	return this_char;
354 }
355 /* }}} */
356 
357 /* {{{ php_next_utf8_char
358  * Public interface for get_next_char used with UTF-8 */
php_next_utf8_char(const unsigned char * str,size_t str_len,size_t * cursor,int * status)359  PHPAPI unsigned int php_next_utf8_char(
360 		const unsigned char *str,
361 		size_t str_len,
362 		size_t *cursor,
363 		int *status)
364 {
365 	return get_next_char(cs_utf_8, str, str_len, cursor, status);
366 }
367 /* }}} */
368 
369 /* {{{ entity_charset determine_charset
370  * returns the charset identifier based on current locale or a hint.
371  * defaults to UTF-8 */
determine_charset(char * charset_hint)372 static enum entity_charset determine_charset(char *charset_hint)
373 {
374 	size_t i;
375 	enum entity_charset charset = cs_utf_8;
376 	size_t len = 0;
377 	const zend_encoding *zenc;
378 
379 	/* Default is now UTF-8 */
380 	if (charset_hint == NULL)
381 		return cs_utf_8;
382 
383 	if ((len = strlen(charset_hint)) != 0) {
384 		goto det_charset;
385 	}
386 
387 	zenc = zend_multibyte_get_internal_encoding();
388 	if (zenc != NULL) {
389 		charset_hint = (char *)zend_multibyte_get_encoding_name(zenc);
390 		if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
391 			if ((len == 4) /* sizeof (auto|pass) */ &&
392 					/* XXX should the "wchar" be ignored as well?? */
393 					(!memcmp("pass", charset_hint, 4) ||
394 					 !memcmp("auto", charset_hint, 4))) {
395 				charset_hint = NULL;
396 				len = 0;
397 			} else {
398 				goto det_charset;
399 			}
400 		}
401 	}
402 
403 	charset_hint = SG(default_charset);
404 	if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
405 		goto det_charset;
406 	}
407 
408 	/* try to detect the charset for the locale */
409 #if HAVE_NL_LANGINFO && defined(CODESET)
410 	charset_hint = nl_langinfo(CODESET);
411 	if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
412 		goto det_charset;
413 	}
414 #endif
415 
416 	/* try to figure out the charset from the locale */
417 	{
418 		char *localename;
419 		char *dot, *at;
420 
421 		/* lang[_territory][.codeset][@modifier] */
422 		localename = setlocale(LC_CTYPE, NULL);
423 
424 		dot = strchr(localename, '.');
425 		if (dot) {
426 			dot++;
427 			/* locale specifies a codeset */
428 			at = strchr(dot, '@');
429 			if (at)
430 				len = at - dot;
431 			else
432 				len = strlen(dot);
433 			charset_hint = dot;
434 		} else {
435 			/* no explicit name; see if the name itself
436 			 * is the charset */
437 			charset_hint = localename;
438 			len = strlen(charset_hint);
439 		}
440 	}
441 
442 det_charset:
443 
444 	if (charset_hint) {
445 		int found = 0;
446 
447 		/* now walk the charset map and look for the codeset */
448 		for (i = 0; i < sizeof(charset_map)/sizeof(charset_map[0]); i++) {
449 			if (len == charset_map[i].codeset_len &&
450 			    zend_binary_strcasecmp(charset_hint, len, charset_map[i].codeset, len) == 0) {
451 				charset = charset_map[i].charset;
452 				found = 1;
453 				break;
454 			}
455 		}
456 		if (!found) {
457 			php_error_docref(NULL, E_WARNING, "charset `%s' not supported, assuming utf-8",
458 					charset_hint);
459 		}
460 	}
461 	return charset;
462 }
463 /* }}} */
464 
465 /* {{{ php_utf32_utf8 */
php_utf32_utf8(unsigned char * buf,unsigned k)466 static inline size_t php_utf32_utf8(unsigned char *buf, unsigned k)
467 {
468 	size_t retval = 0;
469 
470 	/* assert(0x0 <= k <= 0x10FFFF); */
471 
472 	if (k < 0x80) {
473 		buf[0] = k;
474 		retval = 1;
475 	} else if (k < 0x800) {
476 		buf[0] = 0xc0 | (k >> 6);
477 		buf[1] = 0x80 | (k & 0x3f);
478 		retval = 2;
479 	} else if (k < 0x10000) {
480 		buf[0] = 0xe0 | (k >> 12);
481 		buf[1] = 0x80 | ((k >> 6) & 0x3f);
482 		buf[2] = 0x80 | (k & 0x3f);
483 		retval = 3;
484 	} else {
485 		buf[0] = 0xf0 | (k >> 18);
486 		buf[1] = 0x80 | ((k >> 12) & 0x3f);
487 		buf[2] = 0x80 | ((k >> 6) & 0x3f);
488 		buf[3] = 0x80 | (k & 0x3f);
489 		retval = 4;
490 	}
491 	/* UTF-8 has been restricted to max 4 bytes since RFC 3629 */
492 
493 	return retval;
494 }
495 /* }}} */
496 
497 /* {{{ unimap_bsearc_cmp
498  * Binary search of unicode code points in unicode <--> charset mapping.
499  * Returns the code point in the target charset (whose mapping table was given) or 0 if
500  * the unicode code point is not in the table.
501  */
unimap_bsearch(const uni_to_enc * table,unsigned code_key_a,size_t num)502 static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
503 {
504 	const uni_to_enc *l = table,
505 					 *h = &table[num-1],
506 					 *m;
507 	unsigned short code_key;
508 
509 	/* we have no mappings outside the BMP */
510 	if (code_key_a > 0xFFFFU)
511 		return 0;
512 
513 	code_key = (unsigned short) code_key_a;
514 
515 	while (l <= h) {
516 		m = l + (h - l) / 2;
517 		if (code_key < m->un_code_point)
518 			h = m - 1;
519 		else if (code_key > m->un_code_point)
520 			l = m + 1;
521 		else
522 			return m->cs_code;
523 	}
524 	return 0;
525 }
526 /* }}} */
527 
528 /* {{{ map_from_unicode */
map_from_unicode(unsigned code,enum entity_charset charset,unsigned * res)529 static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res)
530 {
531 	unsigned char found;
532 	const uni_to_enc *table;
533 	size_t table_size;
534 
535 	switch (charset) {
536 	case cs_8859_1:
537 		/* identity mapping of code points to unicode */
538 		if (code > 0xFF) {
539 			return FAILURE;
540 		}
541 		*res = code;
542 		break;
543 
544 	case cs_8859_5:
545 		if (code <= 0xA0 || code == 0xAD /* soft hyphen */) {
546 			*res = code;
547 		} else if (code == 0x2116) {
548 			*res = 0xF0; /* numero sign */
549 		} else if (code == 0xA7) {
550 			*res = 0xFD; /* section sign */
551 		} else if (code >= 0x0401 && code <= 0x044F) {
552 			if (code == 0x040D || code == 0x0450 || code == 0x045D)
553 				return FAILURE;
554 			*res = code - 0x360;
555 		} else {
556 			return FAILURE;
557 		}
558 		break;
559 
560 	case cs_8859_15:
561 		if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) {
562 			*res = code;
563 		} else { /* between A4 and 0xBE */
564 			found = unimap_bsearch(unimap_iso885915,
565 				code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915));
566 			if (found)
567 				*res = found;
568 			else
569 				return FAILURE;
570 		}
571 		break;
572 
573 	case cs_cp1252:
574 		if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) {
575 			*res = code;
576 		} else {
577 			found = unimap_bsearch(unimap_win1252,
578 				code, sizeof(unimap_win1252) / sizeof(*unimap_win1252));
579 			if (found)
580 				*res = found;
581 			else
582 				return FAILURE;
583 		}
584 		break;
585 
586 	case cs_macroman:
587 		if (code == 0x7F)
588 			return FAILURE;
589 		table = unimap_macroman;
590 		table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman);
591 		goto table_over_7F;
592 	case cs_cp1251:
593 		table = unimap_win1251;
594 		table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251);
595 		goto table_over_7F;
596 	case cs_koi8r:
597 		table = unimap_koi8r;
598 		table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r);
599 		goto table_over_7F;
600 	case cs_cp866:
601 		table = unimap_cp866;
602 		table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866);
603 
604 table_over_7F:
605 		if (code <= 0x7F) {
606 			*res = code;
607 		} else {
608 			found = unimap_bsearch(table, code, table_size);
609 			if (found)
610 				*res = found;
611 			else
612 				return FAILURE;
613 		}
614 		break;
615 
616 	/* from here on, only map the possible characters in the ASCII range.
617 	 * to improve support here, it's a matter of building the unicode mappings.
618 	 * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */
619 	case cs_sjis:
620 	case cs_eucjp:
621 		/* we interpret 0x5C as the Yen symbol. This is not universal.
622 		 * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */
623 		if (code >= 0x20 && code <= 0x7D) {
624 			if (code == 0x5C)
625 				return FAILURE;
626 			*res = code;
627 		} else {
628 			return FAILURE;
629 		}
630 		break;
631 
632 	case cs_big5:
633 	case cs_big5hkscs:
634 	case cs_gb2312:
635 		if (code >= 0x20 && code <= 0x7D) {
636 			*res = code;
637 		} else {
638 			return FAILURE;
639 		}
640 		break;
641 
642 	default:
643 		return FAILURE;
644 	}
645 
646 	return SUCCESS;
647 }
648 /* }}} */
649 
650 /* {{{ */
map_to_unicode(unsigned code,const enc_to_uni * table,unsigned * res)651 static inline void map_to_unicode(unsigned code, const enc_to_uni *table, unsigned *res)
652 {
653 	/* only single byte encodings are currently supported; assumed code <= 0xFF */
654 	*res = table->inner[ENT_ENC_TO_UNI_STAGE1(code)]->uni_cp[ENT_ENC_TO_UNI_STAGE2(code)];
655 }
656 /* }}} */
657 
658 /* {{{ unicode_cp_is_allowed */
unicode_cp_is_allowed(unsigned uni_cp,int document_type)659 static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type)
660 {
661 	/* XML 1.0				HTML 4.01			HTML 5
662 	 * 0x09..0x0A			0x09..0x0A			0x09..0x0A
663 	 * 0x0D					0x0D				0x0C..0x0D
664 	 * 0x0020..0xD7FF		0x20..0x7E			0x20..0x7E
665 	 *						0x00A0..0xD7FF		0x00A0..0xD7FF
666 	 * 0xE000..0xFFFD		0xE000..0x10FFFF	0xE000..0xFDCF
667 	 * 0x010000..0x10FFFF						0xFDF0..0x10FFFF (*)
668 	 *
669 	 * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE)
670 	 *
671 	 * References:
672 	 * XML 1.0:   <http://www.w3.org/TR/REC-xml/#charsets>
673 	 * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html>
674 	 * HTML 5:    <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream>
675 	 *
676 	 * Not sure this is the relevant part for HTML 5, though. I opted to
677 	 * disallow the characters that would result in a parse error when
678 	 * preprocessing of the input stream. See also section 8.1.3.
679 	 *
680 	 * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to
681 	 * XHTML 1.0 the same rules as for XML 1.0.
682 	 * See <http://cmsmcq.com/2007/C1.xml>.
683 	 */
684 
685 	switch (document_type) {
686 	case ENT_HTML_DOC_HTML401:
687 		return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
688 			(uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||
689 			(uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||
690 			(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF);
691 	case ENT_HTML_DOC_HTML5:
692 		return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
693 			(uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */
694 			(uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||
695 			(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF &&
696 				((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */
697 				(uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */
698 	case ENT_HTML_DOC_XHTML:
699 	case ENT_HTML_DOC_XML1:
700 		return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) ||
701 			(uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||
702 			(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF);
703 	default:
704 		return 1;
705 	}
706 }
707 /* }}} */
708 
709 /* {{{ unicode_cp_is_allowed */
numeric_entity_is_allowed(unsigned uni_cp,int document_type)710 static inline int numeric_entity_is_allowed(unsigned uni_cp, int document_type)
711 {
712 	/* less restrictive than unicode_cp_is_allowed */
713 	switch (document_type) {
714 	case ENT_HTML_DOC_HTML401:
715 		/* all non-SGML characters (those marked with UNUSED in DESCSET) should be
716 		 * representable with numeric entities */
717 		return uni_cp <= 0x10FFFF;
718 	case ENT_HTML_DOC_HTML5:
719 		/* 8.1.4. The numeric character reference forms described above are allowed to
720 		 * reference any Unicode code point other than U+0000, U+000D, permanently
721 		 * undefined Unicode characters (noncharacters), and control characters other
722 		 * than space characters (U+0009, U+000A, U+000C and U+000D) */
723 		/* seems to allow surrogate characters, then */
724 		return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
725 			(uni_cp >= 0x09 && uni_cp <= 0x0C && uni_cp != 0x0B) || /* form feed U+0C allowed, but not U+0D */
726 			(uni_cp >= 0xA0 && uni_cp <= 0x10FFFF &&
727 				((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */
728 				(uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */
729 	case ENT_HTML_DOC_XHTML:
730 	case ENT_HTML_DOC_XML1:
731 		/* OTOH, XML 1.0 requires "character references to match the production for Char
732 		 * See <http://www.w3.org/TR/REC-xml/#NT-CharRef> */
733 		return unicode_cp_is_allowed(uni_cp, document_type);
734 	default:
735 		return 1;
736 	}
737 }
738 /* }}} */
739 
740 /* {{{ process_numeric_entity
741  * Auxiliary function to traverse_for_entities.
742  * On input, *buf should point to the first character after # and on output, it's the last
743  * byte read, no matter if there was success or insuccess.
744  */
process_numeric_entity(const char ** buf,unsigned * code_point)745 static inline int process_numeric_entity(const char **buf, unsigned *code_point)
746 {
747 	zend_long code_l;
748 	int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */
749 	char *endptr;
750 
751 	if (hexadecimal && (**buf != '\0'))
752 		(*buf)++;
753 
754 	/* strtol allows whitespace and other stuff in the beginning
755 		* we're not interested */
756 	if ((hexadecimal && !isxdigit(**buf)) ||
757 			(!hexadecimal && !isdigit(**buf))) {
758 		return FAILURE;
759 	}
760 
761 	code_l = ZEND_STRTOL(*buf, &endptr, hexadecimal ? 16 : 10);
762 	/* we're guaranteed there were valid digits, so *endptr > buf */
763 	*buf = endptr;
764 
765 	if (**buf != ';')
766 		return FAILURE;
767 
768 	/* many more are invalid, but that depends on whether it's HTML
769 	 * (and which version) or XML. */
770 	if (code_l > Z_L(0x10FFFF))
771 		return FAILURE;
772 
773 	if (code_point != NULL)
774 		*code_point = (unsigned)code_l;
775 
776 	return SUCCESS;
777 }
778 /* }}} */
779 
780 /* {{{ process_named_entity */
process_named_entity_html(const char ** buf,const char ** start,size_t * length)781 static inline int process_named_entity_html(const char **buf, const char **start, size_t *length)
782 {
783 	*start = *buf;
784 
785 	/* "&" is represented by a 0x26 in all supported encodings. That means
786 	 * the byte after represents a character or is the leading byte of an
787 	 * sequence of 8-bit code units. If in the ranges below, it represents
788 	 * necessarily a alpha character because none of the supported encodings
789 	 * has an overlap with ASCII in the leading byte (only on the second one) */
790 	while ((**buf >= 'a' && **buf <= 'z') ||
791 			(**buf >= 'A' && **buf <= 'Z') ||
792 			(**buf >= '0' && **buf <= '9')) {
793 		(*buf)++;
794 	}
795 
796 	if (**buf != ';')
797 		return FAILURE;
798 
799 	/* cast to size_t OK as the quantity is always non-negative */
800 	*length = *buf - *start;
801 
802 	if (*length == 0)
803 		return FAILURE;
804 
805 	return SUCCESS;
806 }
807 /* }}} */
808 
809 /* {{{ resolve_named_entity_html */
resolve_named_entity_html(const char * start,size_t length,const entity_ht * ht,unsigned * uni_cp1,unsigned * uni_cp2)810 static inline int resolve_named_entity_html(const char *start, size_t length, const entity_ht *ht, unsigned *uni_cp1, unsigned *uni_cp2)
811 {
812 	const entity_cp_map *s;
813 	zend_ulong hash = zend_inline_hash_func(start, length);
814 
815 	s = ht->buckets[hash % ht->num_elems];
816 	while (s->entity) {
817 		if (s->entity_len == length) {
818 			if (memcmp(start, s->entity, length) == 0) {
819 				*uni_cp1 = s->codepoint1;
820 				*uni_cp2 = s->codepoint2;
821 				return SUCCESS;
822 			}
823 		}
824 		s++;
825 	}
826 	return FAILURE;
827 }
828 /* }}} */
829 
write_octet_sequence(unsigned char * buf,enum entity_charset charset,unsigned code)830 static inline size_t write_octet_sequence(unsigned char *buf, enum entity_charset charset, unsigned code) {
831 	/* code is not necessarily a unicode code point */
832 	switch (charset) {
833 	case cs_utf_8:
834 		return php_utf32_utf8(buf, code);
835 
836 	case cs_8859_1:
837 	case cs_cp1252:
838 	case cs_8859_15:
839 	case cs_koi8r:
840 	case cs_cp1251:
841 	case cs_8859_5:
842 	case cs_cp866:
843 	case cs_macroman:
844 		/* single byte stuff */
845 		*buf = code;
846 		return 1;
847 
848 	case cs_big5:
849 	case cs_big5hkscs:
850 	case cs_sjis:
851 	case cs_gb2312:
852 		/* we don't have complete unicode mappings for these yet in entity_decode,
853 		 * and we opt to pass through the octet sequences for these in htmlentities
854 		 * instead of converting to an int and then converting back. */
855 #if 0
856 		return php_mb2_int_to_char(buf, code);
857 #else
858 #if ZEND_DEBUG
859 		assert(code <= 0xFFU);
860 #endif
861 		*buf = code;
862 		return 1;
863 #endif
864 
865 	case cs_eucjp:
866 #if 0 /* idem */
867 		return php_mb2_int_to_char(buf, code);
868 #else
869 #if ZEND_DEBUG
870 		assert(code <= 0xFFU);
871 #endif
872 		*buf = code;
873 		return 1;
874 #endif
875 
876 	default:
877 		assert(0);
878 		return 0;
879 	}
880 }
881 
882 /* {{{ traverse_for_entities
883  * Auxiliary function to php_unescape_html_entities().
884  * - The argument "all" determines if all numeric entities are decode or only those
885  *   that correspond to quotes (depending on quote_style).
886  */
887 /* maximum expansion (factor 1.2) for HTML 5 with &nGt; and &nLt; */
888 /* +2 is 1 because of rest (probably unnecessary), 1 because of terminating 0 */
889 #define TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen) ((oldlen) + (oldlen) / 5 + 2)
traverse_for_entities(const char * old,size_t oldlen,zend_string * ret,int all,int flags,const entity_ht * inv_map,enum entity_charset charset)890 static void traverse_for_entities(
891 	const char *old,
892 	size_t oldlen,
893 	zend_string *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
894 	int all,
895 	int flags,
896 	const entity_ht *inv_map,
897 	enum entity_charset charset)
898 {
899 	const char *p,
900 			   *lim;
901 	char	   *q;
902 	int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
903 
904 	lim = old + oldlen; /* terminator address */
905 	assert(*lim == '\0');
906 
907 	for (p = old, q = ZSTR_VAL(ret); p < lim;) {
908 		unsigned code, code2 = 0;
909 		const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
910 
911 		/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
912 		 * ASCII range byte can be part of a multi-byte sequence.
913 		 * However, they start at 0x40, therefore if we find a 0x26 byte,
914 		 * we're sure it represents the '&' character. */
915 
916 		/* assumes there are no single-char entities */
917 		if (p[0] != '&' || (p + 3 >= lim)) {
918 			*(q++) = *(p++);
919 			continue;
920 		}
921 
922 		/* now p[3] is surely valid and is no terminator */
923 
924 		/* numerical entity */
925 		if (p[1] == '#') {
926 			next = &p[2];
927 			if (process_numeric_entity(&next, &code) == FAILURE)
928 				goto invalid_code;
929 
930 			/* If we're in htmlspecialchars_decode, we're only decoding entities
931 			 * that represent &, <, >, " and '. Is this one of them? */
932 			if (!all && (code > 63U ||
933 					stage3_table_be_apos_00000[code].data.ent.entity == NULL))
934 				goto invalid_code;
935 
936 			/* are we allowed to decode this entity in this document type?
937 			 * HTML 5 is the only that has a character that cannot be used in
938 			 * a numeric entity but is allowed literally (U+000D). The
939 			 * unoptimized version would be ... || !numeric_entity_is_allowed(code) */
940 			if (!unicode_cp_is_allowed(code, doctype) ||
941 					(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
942 				goto invalid_code;
943 		} else {
944 			const char *start;
945 			size_t ent_len;
946 
947 			next = &p[1];
948 			start = next;
949 
950 			if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
951 				goto invalid_code;
952 
953 			if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
954 				if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
955 							&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
956 					/* uses html4 inv_map, which doesn't include apos;. This is a
957 					 * hack to support it */
958 					code = (unsigned) '\'';
959 				} else {
960 					goto invalid_code;
961 				}
962 			}
963 		}
964 
965 		assert(*next == ';');
966 
967 		if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
968 				(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
969 				/* && code2 == '\0' always true for current maps */)
970 			goto invalid_code;
971 
972 		/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
973 		 * the call is needed to ensure the codepoint <= U+00FF)  */
974 		if (charset != cs_utf_8) {
975 			/* replace unicode code point */
976 			if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
977 				goto invalid_code; /* not representable in target charset */
978 		}
979 
980 		q += write_octet_sequence((unsigned char*)q, charset, code);
981 		if (code2) {
982 			q += write_octet_sequence((unsigned char*)q, charset, code2);
983 		}
984 
985 		/* jump over the valid entity; may go beyond size of buffer; np */
986 		p = next + 1;
987 		continue;
988 
989 invalid_code:
990 		for (; p < next; p++) {
991 			*(q++) = *p;
992 		}
993 	}
994 
995 	*q = '\0';
996 	ZSTR_LEN(ret) = (size_t)(q - ZSTR_VAL(ret));
997 }
998 /* }}} */
999 
1000 /* {{{ unescape_inverse_map */
unescape_inverse_map(int all,int flags)1001 static const entity_ht *unescape_inverse_map(int all, int flags)
1002 {
1003 	int document_type = flags & ENT_HTML_DOC_TYPE_MASK;
1004 
1005 	if (all) {
1006 		switch (document_type) {
1007 		case ENT_HTML_DOC_HTML401:
1008 		case ENT_HTML_DOC_XHTML: /* but watch out for &apos;...*/
1009 			return &ent_ht_html4;
1010 		case ENT_HTML_DOC_HTML5:
1011 			return &ent_ht_html5;
1012 		default:
1013 			return &ent_ht_be_apos;
1014 		}
1015 	} else {
1016 		switch (document_type) {
1017 		case ENT_HTML_DOC_HTML401:
1018 			return &ent_ht_be_noapos;
1019 		default:
1020 			return &ent_ht_be_apos;
1021 		}
1022 	}
1023 }
1024 /* }}} */
1025 
1026 /* {{{ determine_entity_table
1027  * Entity table to use. Note that entity tables are defined in terms of
1028  * unicode code points */
determine_entity_table(int all,int doctype)1029 static entity_table_opt determine_entity_table(int all, int doctype)
1030 {
1031 	entity_table_opt retval = {NULL};
1032 
1033 	assert(!(doctype == ENT_HTML_DOC_XML1 && all));
1034 
1035 	if (all) {
1036 		retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
1037 			entity_ms_table_html5 : entity_ms_table_html4;
1038 	} else {
1039 		retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
1040 			stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
1041 	}
1042 	return retval;
1043 }
1044 /* }}} */
1045 
1046 /* {{{ php_unescape_html_entities
1047  * The parameter "all" should be true to decode all possible entities, false to decode
1048  * only the basic ones, i.e., those in basic_entities_ex + the numeric entities
1049  * that correspond to quotes.
1050  */
php_unescape_html_entities(zend_string * str,int all,int flags,char * hint_charset)1051 PHPAPI zend_string *php_unescape_html_entities(zend_string *str, int all, int flags, char *hint_charset)
1052 {
1053 	zend_string *ret;
1054 	enum entity_charset charset;
1055 	const entity_ht *inverse_map;
1056 	size_t new_size;
1057 
1058 	if (!memchr(ZSTR_VAL(str), '&', ZSTR_LEN(str))) {
1059 		return zend_string_copy(str);
1060 	}
1061 
1062 	if (all) {
1063 		charset = determine_charset(hint_charset);
1064 	} else {
1065 		charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */
1066 	}
1067 
1068 	/* don't use LIMIT_ALL! */
1069 
1070 	new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(ZSTR_LEN(str));
1071 	if (ZSTR_LEN(str) > new_size) {
1072 		/* overflow, refuse to do anything */
1073 		return zend_string_copy(str);
1074 	}
1075 
1076 	ret = zend_string_alloc(new_size, 0);
1077 
1078 	inverse_map = unescape_inverse_map(all, flags);
1079 
1080 	/* replace numeric entities */
1081 	traverse_for_entities(ZSTR_VAL(str), ZSTR_LEN(str), ret, all, flags, inverse_map, charset);
1082 
1083 	return ret;
1084 }
1085 /* }}} */
1086 
php_escape_html_entities(unsigned char * old,size_t oldlen,int all,int flags,char * hint_charset)1087 PHPAPI zend_string *php_escape_html_entities(unsigned char *old, size_t oldlen, int all, int flags, char *hint_charset)
1088 {
1089 	return php_escape_html_entities_ex(old, oldlen, all, flags, hint_charset, 1);
1090 }
1091 
1092 /* {{{ find_entity_for_char */
find_entity_for_char(unsigned int k,enum entity_charset charset,const entity_stage1_row * table,const unsigned char ** entity,size_t * entity_len,unsigned char * old,size_t oldlen,size_t * cursor)1093 static inline void find_entity_for_char(
1094 	unsigned int k,
1095 	enum entity_charset charset,
1096 	const entity_stage1_row *table,
1097 	const unsigned char **entity,
1098 	size_t *entity_len,
1099 	unsigned char *old,
1100 	size_t oldlen,
1101 	size_t *cursor)
1102 {
1103 	unsigned stage1_idx = ENT_STAGE1_INDEX(k);
1104 	const entity_stage3_row *c;
1105 
1106 	if (stage1_idx > 0x1D) {
1107 		*entity     = NULL;
1108 		*entity_len = 0;
1109 		return;
1110 	}
1111 
1112 	c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
1113 
1114 	if (!c->ambiguous) {
1115 		*entity     = (const unsigned char *)c->data.ent.entity;
1116 		*entity_len = c->data.ent.entity_len;
1117 	} else {
1118 		/* peek at next char */
1119 		size_t	 cursor_before	= *cursor;
1120 		int		 status			= SUCCESS;
1121 		unsigned next_char;
1122 
1123 		if (!(*cursor < oldlen))
1124 			goto no_suitable_2nd;
1125 
1126 		next_char = get_next_char(charset, old, oldlen, cursor, &status);
1127 
1128 		if (status == FAILURE)
1129 			goto no_suitable_2nd;
1130 
1131 		{
1132 			const entity_multicodepoint_row *s, *e;
1133 
1134 			s = &c->data.multicodepoint_table[1];
1135 			e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
1136 			/* we could do a binary search but it's not worth it since we have
1137 			 * at most two entries... */
1138 			for ( ; s <= e; s++) {
1139 				if (s->normal_entry.second_cp == next_char) {
1140 					*entity     = (const unsigned char *) s->normal_entry.entity;
1141 					*entity_len = s->normal_entry.entity_len;
1142 					return;
1143 				}
1144 			}
1145 		}
1146 no_suitable_2nd:
1147 		*cursor = cursor_before;
1148 		*entity = (const unsigned char *)
1149 			c->data.multicodepoint_table[0].leading_entry.default_entity;
1150 		*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
1151 	}
1152 }
1153 /* }}} */
1154 
1155 /* {{{ find_entity_for_char_basic */
find_entity_for_char_basic(unsigned int k,const entity_stage3_row * table,const unsigned char ** entity,size_t * entity_len)1156 static inline void find_entity_for_char_basic(
1157 	unsigned int k,
1158 	const entity_stage3_row *table,
1159 	const unsigned char **entity,
1160 	size_t *entity_len)
1161 {
1162 	if (k >= 64U) {
1163 		*entity     = NULL;
1164 		*entity_len = 0;
1165 		return;
1166 	}
1167 
1168 	*entity     = (const unsigned char *) table[k].data.ent.entity;
1169 	*entity_len = table[k].data.ent.entity_len;
1170 }
1171 /* }}} */
1172 
1173 /* {{{ php_escape_html_entities
1174  */
php_escape_html_entities_ex(unsigned char * old,size_t oldlen,int all,int flags,char * hint_charset,zend_bool double_encode)1175 PHPAPI zend_string *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, int all, int flags, char *hint_charset, zend_bool double_encode)
1176 {
1177 	size_t cursor, maxlen, len;
1178 	zend_string *replaced;
1179 	enum entity_charset charset = determine_charset(hint_charset);
1180 	int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
1181 	entity_table_opt entity_table;
1182 	const enc_to_uni *to_uni_table = NULL;
1183 	const entity_ht *inv_map = NULL; /* used for !double_encode */
1184 	/* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
1185 	const unsigned char *replacement = NULL;
1186 	size_t replacement_len = 0;
1187 
1188 	if (all) { /* replace with all named entities */
1189 		if (CHARSET_PARTIAL_SUPPORT(charset)) {
1190 			php_error_docref(NULL, E_NOTICE, "Only basic entities "
1191 				"substitution is supported for multi-byte encodings other than UTF-8; "
1192 				"functionality is equivalent to htmlspecialchars");
1193 		}
1194 		LIMIT_ALL(all, doctype, charset);
1195 	}
1196 	entity_table = determine_entity_table(all, doctype);
1197 	if (all && !CHARSET_UNICODE_COMPAT(charset)) {
1198 		to_uni_table = enc_to_uni_index[charset];
1199 	}
1200 
1201 	if (!double_encode) {
1202 		/* first arg is 1 because we want to identify valid named entities
1203 		 * even if we are only encoding the basic ones */
1204 		inv_map = unescape_inverse_map(1, flags);
1205 	}
1206 
1207 	if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
1208 		if (charset == cs_utf_8) {
1209 			replacement = (const unsigned char*)"\xEF\xBF\xBD";
1210 			replacement_len = sizeof("\xEF\xBF\xBD") - 1;
1211 		} else {
1212 			replacement = (const unsigned char*)"&#xFFFD;";
1213 			replacement_len = sizeof("&#xFFFD;") - 1;
1214 		}
1215 	}
1216 
1217 	/* initial estimate */
1218 	if (oldlen < 64) {
1219 		maxlen = 128;
1220 	} else {
1221 		maxlen = zend_safe_addmult(oldlen, 2, 0, "html_entities");
1222 	}
1223 
1224 	replaced = zend_string_alloc(maxlen, 0);
1225 	len = 0;
1226 	cursor = 0;
1227 	while (cursor < oldlen) {
1228 		const unsigned char *mbsequence = NULL;
1229 		size_t mbseqlen					= 0,
1230 		       cursor_before			= cursor;
1231 		int status						= SUCCESS;
1232 		unsigned int this_char			= get_next_char(charset, old, oldlen, &cursor, &status);
1233 
1234 		/* guarantee we have at least 40 bytes to write.
1235 		 * In HTML5, entities may take up to 33 bytes */
1236 		if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
1237 			replaced = zend_string_safe_realloc(replaced, maxlen, 1, 128, 0);
1238 			maxlen += 128;
1239 		}
1240 
1241 		if (status == FAILURE) {
1242 			/* invalid MB sequence */
1243 			if (flags & ENT_HTML_IGNORE_ERRORS) {
1244 				continue;
1245 			} else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
1246 				memcpy(&ZSTR_VAL(replaced)[len], replacement, replacement_len);
1247 				len += replacement_len;
1248 				continue;
1249 			} else {
1250 				zend_string_efree(replaced);
1251 				return ZSTR_EMPTY_ALLOC();
1252 			}
1253 		} else { /* SUCCESS */
1254 			mbsequence = &old[cursor_before];
1255 			mbseqlen = cursor - cursor_before;
1256 		}
1257 
1258 		if (this_char != '&') { /* no entity on this position */
1259 			const unsigned char *rep	= NULL;
1260 			size_t				rep_len	= 0;
1261 
1262 			if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1263 					(this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1264 				goto pass_char_through;
1265 
1266 			if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
1267 				if (to_uni_table != NULL) {
1268 					/* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
1269 					 * is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
1270 					 * we're using a single byte encoding */
1271 					map_to_unicode(this_char, to_uni_table, &this_char);
1272 					if (this_char == 0xFFFF) /* no mapping; pass through */
1273 						goto pass_char_through;
1274 				}
1275 				/* the cursor may advance */
1276 				find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
1277 					&rep_len, old, oldlen, &cursor);
1278 			} else {
1279 				find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
1280 			}
1281 
1282 			if (rep != NULL) {
1283 				ZSTR_VAL(replaced)[len++] = '&';
1284 				memcpy(&ZSTR_VAL(replaced)[len], rep, rep_len);
1285 				len += rep_len;
1286 				ZSTR_VAL(replaced)[len++] = ';';
1287 			} else {
1288 				/* we did not find an entity for this char.
1289 				 * check for its validity, if its valid pass it unchanged */
1290 				if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
1291 					if (CHARSET_UNICODE_COMPAT(charset)) {
1292 						if (!unicode_cp_is_allowed(this_char, doctype)) {
1293 							mbsequence = replacement;
1294 							mbseqlen = replacement_len;
1295 						}
1296 					} else if (to_uni_table) {
1297 						if (!all) /* otherwise we already did this */
1298 							map_to_unicode(this_char, to_uni_table, &this_char);
1299 						if (!unicode_cp_is_allowed(this_char, doctype)) {
1300 							mbsequence = replacement;
1301 							mbseqlen = replacement_len;
1302 						}
1303 					} else {
1304 						/* not a unicode code point, unless, coincidentally, it's in
1305 						 * the 0x20..0x7D range (except 0x5C in sjis). We know nothing
1306 						 * about other code points, because we have no tables. Since
1307 						 * Unicode code points in that range are not disallowed in any
1308 						 * document type, we could do nothing. However, conversion
1309 						 * tables frequently map 0x00-0x1F to the respective C0 code
1310 						 * points. Let's play it safe and admit that's the case */
1311 						if (this_char <= 0x7D &&
1312 								!unicode_cp_is_allowed(this_char, doctype)) {
1313 							mbsequence = replacement;
1314 							mbseqlen = replacement_len;
1315 						}
1316 					}
1317 				}
1318 pass_char_through:
1319 				if (mbseqlen > 1) {
1320 					memcpy(ZSTR_VAL(replaced) + len, mbsequence, mbseqlen);
1321 					len += mbseqlen;
1322 				} else {
1323 					ZSTR_VAL(replaced)[len++] = mbsequence[0];
1324 				}
1325 			}
1326 		} else { /* this_char == '&' */
1327 			if (double_encode) {
1328 encode_amp:
1329 				memcpy(&ZSTR_VAL(replaced)[len], "&amp;", sizeof("&amp;") - 1);
1330 				len += sizeof("&amp;") - 1;
1331 			} else { /* no double encode */
1332 				/* check if entity is valid */
1333 				size_t ent_len; /* not counting & or ; */
1334 				/* peek at next char */
1335 				if (old[cursor] == '#') { /* numeric entity */
1336 					unsigned code_point;
1337 					int valid;
1338 					char *pos = (char*)&old[cursor+1];
1339 					valid = process_numeric_entity((const char **)&pos, &code_point);
1340 					if (valid == FAILURE)
1341 						goto encode_amp;
1342 					if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
1343 						if (!numeric_entity_is_allowed(code_point, doctype))
1344 							goto encode_amp;
1345 					}
1346 					ent_len = pos - (char*)&old[cursor];
1347 				} else { /* named entity */
1348 					/* check for vality of named entity */
1349 					const char *start = (const char *) &old[cursor],
1350 							   *next = start;
1351 					unsigned   dummy1, dummy2;
1352 
1353 					if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
1354 						goto encode_amp;
1355 					if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
1356 						if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
1357 									&& start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
1358 							/* uses html4 inv_map, which doesn't include apos;. This is a
1359 							 * hack to support it */
1360 							goto encode_amp;
1361 						}
1362 					}
1363 				}
1364 				/* checks passed; copy entity to result */
1365 				/* entity size is unbounded, we may need more memory */
1366 				/* at this point maxlen - len >= 40 */
1367 				if (maxlen - len < ent_len + 2 /* & and ; */) {
1368 					/* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
1369 					replaced = zend_string_safe_realloc(replaced, maxlen, 1, ent_len + 128, 0);
1370 					maxlen += ent_len + 128;
1371 				}
1372 				ZSTR_VAL(replaced)[len++] = '&';
1373 				memcpy(&ZSTR_VAL(replaced)[len], &old[cursor], ent_len);
1374 				len += ent_len;
1375 				ZSTR_VAL(replaced)[len++] = ';';
1376 				cursor += ent_len + 1;
1377 			}
1378 		}
1379 	}
1380 	ZSTR_VAL(replaced)[len] = '\0';
1381 	ZSTR_LEN(replaced) = len;
1382 
1383 	return replaced;
1384 }
1385 /* }}} */
1386 
1387 /* {{{ php_html_entities
1388  */
php_html_entities(INTERNAL_FUNCTION_PARAMETERS,int all)1389 static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
1390 {
1391 	zend_string *str, *hint_charset = NULL;
1392 	char *default_charset;
1393 	zend_long flags = ENT_COMPAT;
1394 	zend_string *replaced;
1395 	zend_bool double_encode = 1;
1396 
1397 	ZEND_PARSE_PARAMETERS_START(1, 4)
1398 		Z_PARAM_STR(str)
1399 		Z_PARAM_OPTIONAL
1400 		Z_PARAM_LONG(flags)
1401 		Z_PARAM_STR_EX(hint_charset, 1, 0)
1402 		Z_PARAM_BOOL(double_encode);
1403 	ZEND_PARSE_PARAMETERS_END();
1404 
1405 	if (!hint_charset) {
1406 		default_charset = get_default_charset();
1407 	}
1408 	replaced = php_escape_html_entities_ex((unsigned char*)ZSTR_VAL(str), ZSTR_LEN(str), all, (int) flags, (hint_charset ? ZSTR_VAL(hint_charset) : default_charset), double_encode);
1409 	RETVAL_STR(replaced);
1410 }
1411 /* }}} */
1412 
1413 #define HTML_SPECIALCHARS 	0
1414 #define HTML_ENTITIES	 	1
1415 
1416 /* {{{ register_html_constants
1417  */
register_html_constants(INIT_FUNC_ARGS)1418 void register_html_constants(INIT_FUNC_ARGS)
1419 {
1420 	REGISTER_LONG_CONSTANT("HTML_SPECIALCHARS", HTML_SPECIALCHARS, CONST_PERSISTENT|CONST_CS);
1421 	REGISTER_LONG_CONSTANT("HTML_ENTITIES", HTML_ENTITIES, CONST_PERSISTENT|CONST_CS);
1422 	REGISTER_LONG_CONSTANT("ENT_COMPAT", ENT_COMPAT, CONST_PERSISTENT|CONST_CS);
1423 	REGISTER_LONG_CONSTANT("ENT_QUOTES", ENT_QUOTES, CONST_PERSISTENT|CONST_CS);
1424 	REGISTER_LONG_CONSTANT("ENT_NOQUOTES", ENT_NOQUOTES, CONST_PERSISTENT|CONST_CS);
1425 	REGISTER_LONG_CONSTANT("ENT_IGNORE", ENT_IGNORE, CONST_PERSISTENT|CONST_CS);
1426 	REGISTER_LONG_CONSTANT("ENT_SUBSTITUTE", ENT_SUBSTITUTE, CONST_PERSISTENT|CONST_CS);
1427 	REGISTER_LONG_CONSTANT("ENT_DISALLOWED", ENT_DISALLOWED, CONST_PERSISTENT|CONST_CS);
1428 	REGISTER_LONG_CONSTANT("ENT_HTML401", ENT_HTML401, CONST_PERSISTENT|CONST_CS);
1429 	REGISTER_LONG_CONSTANT("ENT_XML1", ENT_XML1, CONST_PERSISTENT|CONST_CS);
1430 	REGISTER_LONG_CONSTANT("ENT_XHTML", ENT_XHTML, CONST_PERSISTENT|CONST_CS);
1431 	REGISTER_LONG_CONSTANT("ENT_HTML5", ENT_HTML5, CONST_PERSISTENT|CONST_CS);
1432 }
1433 /* }}} */
1434 
1435 /* {{{ proto string htmlspecialchars(string string [, int quote_style[, string encoding[, bool double_encode]]])
1436    Convert special characters to HTML entities */
PHP_FUNCTION(htmlspecialchars)1437 PHP_FUNCTION(htmlspecialchars)
1438 {
1439 	php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1440 }
1441 /* }}} */
1442 
1443 /* {{{ proto string htmlspecialchars_decode(string string [, int quote_style])
1444    Convert special HTML entities back to characters */
PHP_FUNCTION(htmlspecialchars_decode)1445 PHP_FUNCTION(htmlspecialchars_decode)
1446 {
1447 	zend_string *str;
1448 	zend_long quote_style = ENT_COMPAT;
1449 	zend_string *replaced;
1450 
1451 	ZEND_PARSE_PARAMETERS_START(1, 2)
1452 		Z_PARAM_STR(str)
1453 		Z_PARAM_OPTIONAL
1454 		Z_PARAM_LONG(quote_style)
1455 	ZEND_PARSE_PARAMETERS_END();
1456 
1457 	replaced = php_unescape_html_entities(str, 0 /*!all*/, (int)quote_style, NULL);
1458 	if (replaced) {
1459 		RETURN_STR(replaced);
1460 	}
1461 	RETURN_FALSE;
1462 }
1463 /* }}} */
1464 
1465 /* {{{ proto string html_entity_decode(string string [, int quote_style][, string encoding])
1466    Convert all HTML entities to their applicable characters */
PHP_FUNCTION(html_entity_decode)1467 PHP_FUNCTION(html_entity_decode)
1468 {
1469 	zend_string *str, *hint_charset = NULL;
1470 	char *default_charset;
1471 	zend_long quote_style = ENT_COMPAT;
1472 	zend_string *replaced;
1473 
1474 	ZEND_PARSE_PARAMETERS_START(1, 3)
1475 		Z_PARAM_STR(str)
1476 		Z_PARAM_OPTIONAL
1477 		Z_PARAM_LONG(quote_style)
1478 		Z_PARAM_STR(hint_charset)
1479 	ZEND_PARSE_PARAMETERS_END();
1480 
1481 	if (!hint_charset) {
1482 		default_charset = get_default_charset();
1483 	}
1484 	replaced = php_unescape_html_entities(str, 1 /*all*/, (int)quote_style, (hint_charset ? ZSTR_VAL(hint_charset) : default_charset));
1485 
1486 	if (replaced) {
1487 		RETURN_STR(replaced);
1488 	}
1489 	RETURN_FALSE;
1490 }
1491 /* }}} */
1492 
1493 
1494 /* {{{ proto string htmlentities(string string [, int quote_style[, string encoding[, bool double_encode]]])
1495    Convert all applicable characters to HTML entities */
PHP_FUNCTION(htmlentities)1496 PHP_FUNCTION(htmlentities)
1497 {
1498 	php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1499 }
1500 /* }}} */
1501 
1502 /* {{{ write_s3row_data */
write_s3row_data(const entity_stage3_row * r,unsigned orig_cp,enum entity_charset charset,zval * arr)1503 static inline void write_s3row_data(
1504 	const entity_stage3_row *r,
1505 	unsigned orig_cp,
1506 	enum entity_charset charset,
1507 	zval *arr)
1508 {
1509 	char key[9] = ""; /* two unicode code points in UTF-8 */
1510 	char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'};
1511 	size_t written_k1;
1512 
1513 	written_k1 = write_octet_sequence((unsigned char*)key, charset, orig_cp);
1514 
1515 	if (!r->ambiguous) {
1516 		size_t l = r->data.ent.entity_len;
1517 		memcpy(&entity[1], r->data.ent.entity, l);
1518 		entity[l + 1] = ';';
1519 		add_assoc_stringl_ex(arr, key, written_k1, entity, l + 2);
1520 	} else {
1521 		unsigned i,
1522 			     num_entries;
1523 		const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table;
1524 
1525 		if (mcpr[0].leading_entry.default_entity != NULL) {
1526 			size_t l = mcpr[0].leading_entry.default_entity_len;
1527 			memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l);
1528 			entity[l + 1] = ';';
1529 			add_assoc_stringl_ex(arr, key, written_k1, entity, l + 2);
1530 		}
1531 		num_entries = mcpr[0].leading_entry.size;
1532 		for (i = 1; i <= num_entries; i++) {
1533 			size_t   l,
1534 				     written_k2;
1535 			unsigned uni_cp,
1536 					 spe_cp;
1537 
1538 			uni_cp = mcpr[i].normal_entry.second_cp;
1539 			l = mcpr[i].normal_entry.entity_len;
1540 
1541 			if (!CHARSET_UNICODE_COMPAT(charset)) {
1542 				if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE)
1543 					continue; /* non representable in this charset */
1544 			} else {
1545 				spe_cp = uni_cp;
1546 			}
1547 
1548 			written_k2 = write_octet_sequence((unsigned char*)&key[written_k1], charset, spe_cp);
1549 			memcpy(&entity[1], mcpr[i].normal_entry.entity, l);
1550 			entity[l + 1] = ';';
1551 			add_assoc_stringl_ex(arr, key, written_k1 + written_k2, entity, l + 2);
1552 		}
1553 	}
1554 }
1555 /* }}} */
1556 
1557 /* {{{ proto array get_html_translation_table([int table [, int flags [, string encoding]]])
1558    Returns the internal translation table used by htmlspecialchars and htmlentities */
PHP_FUNCTION(get_html_translation_table)1559 PHP_FUNCTION(get_html_translation_table)
1560 {
1561 	zend_long all = HTML_SPECIALCHARS,
1562 		 flags = ENT_COMPAT;
1563 	int doctype;
1564 	entity_table_opt entity_table;
1565 	const enc_to_uni *to_uni_table = NULL;
1566 	char *charset_hint = NULL;
1567 	size_t charset_hint_len;
1568 	enum entity_charset charset;
1569 
1570 	/* in this function we have to jump through some loops because we're
1571 	 * getting the translated table from data structures that are optimized for
1572 	 * random access, not traversal */
1573 
1574 	ZEND_PARSE_PARAMETERS_START(0, 3)
1575 		Z_PARAM_OPTIONAL
1576 		Z_PARAM_LONG(all)
1577 		Z_PARAM_LONG(flags)
1578 		Z_PARAM_STRING(charset_hint, charset_hint_len)
1579 	ZEND_PARSE_PARAMETERS_END();
1580 
1581 	charset = determine_charset(charset_hint);
1582 	doctype = flags & ENT_HTML_DOC_TYPE_MASK;
1583 	LIMIT_ALL(all, doctype, charset);
1584 
1585 	array_init(return_value);
1586 
1587 	entity_table = determine_entity_table((int)all, doctype);
1588 	if (all && !CHARSET_UNICODE_COMPAT(charset)) {
1589 		to_uni_table = enc_to_uni_index[charset];
1590 	}
1591 
1592 	if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */
1593 		const entity_stage1_row *ms_table = entity_table.ms_table;
1594 
1595 		if (CHARSET_UNICODE_COMPAT(charset)) {
1596 			unsigned i, j, k,
1597 					 max_i, max_j, max_k;
1598 			/* no mapping to unicode required */
1599 			if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
1600 				max_i = 1; max_j = 4; max_k = 64;
1601 			} else {
1602 				max_i = 0x1E; max_j = 64; max_k = 64;
1603 			}
1604 
1605 			for (i = 0; i < max_i; i++) {
1606 				if (ms_table[i] == empty_stage2_table)
1607 					continue;
1608 				for (j = 0; j < max_j; j++) {
1609 					if (ms_table[i][j] == empty_stage3_table)
1610 						continue;
1611 					for (k = 0; k < max_k; k++) {
1612 						const entity_stage3_row *r = &ms_table[i][j][k];
1613 						unsigned code;
1614 
1615 						if (r->data.ent.entity == NULL)
1616 							continue;
1617 
1618 						code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
1619 						if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1620 								(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1621 							continue;
1622 						write_s3row_data(r, code, charset, return_value);
1623 					}
1624 				}
1625 			}
1626 		} else {
1627 			/* we have to iterate through the set of code points for this
1628 			 * encoding and map them to unicode code points */
1629 			unsigned i;
1630 			for (i = 0; i <= 0xFF; i++) {
1631 				const entity_stage3_row *r;
1632 				unsigned uni_cp;
1633 
1634 				/* can be done before mapping, they're invariant */
1635 				if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1636 						(i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1637 					continue;
1638 
1639 				map_to_unicode(i, to_uni_table, &uni_cp);
1640 				r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
1641 				if (r->data.ent.entity == NULL)
1642 					continue;
1643 
1644 				write_s3row_data(r, i, charset, return_value);
1645 			}
1646 		}
1647 	} else {
1648 		/* we could use sizeof(stage3_table_be_apos_00000) as well */
1649 		unsigned	  j,
1650 					  numelems = sizeof(stage3_table_be_noapos_00000) /
1651 							sizeof(*stage3_table_be_noapos_00000);
1652 
1653 		for (j = 0; j < numelems; j++) {
1654 			const entity_stage3_row *r = &entity_table.table[j];
1655 			if (r->data.ent.entity == NULL)
1656 				continue;
1657 
1658 			if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1659 					(j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1660 				continue;
1661 
1662 			/* charset is indifferent, used cs_8859_1 for efficiency */
1663 			write_s3row_data(r, j, cs_8859_1, return_value);
1664 		}
1665 	}
1666 }
1667 /* }}} */
1668