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