xref: /php-src/ext/standard/html.c (revision 25a51461)
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 int 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 int 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 int 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 int 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 #if ZEND_DEBUG
784 		assert(code <= 0xFFU);
785 #endif
786 		*buf = code;
787 		return 1;
788 #endif
789 
790 	case cs_eucjp:
791 #if 0 /* idem */
792 		return php_mb2_int_to_char(buf, code);
793 #else
794 #if ZEND_DEBUG
795 		assert(code <= 0xFFU);
796 #endif
797 		*buf = code;
798 		return 1;
799 #endif
800 
801 	default:
802 		assert(0);
803 		return 0;
804 	}
805 }
806 
807 /* {{{ traverse_for_entities
808  * Auxiliary function to php_unescape_html_entities().
809  * - The argument "all" determines if all numeric entities are decode or only those
810  *   that correspond to quotes (depending on quote_style).
811  */
812 /* maximum expansion (factor 1.2) for HTML 5 with &nGt; and &nLt; */
813 /* +2 is 1 because of rest (probably unnecessary), 1 because of terminating 0 */
814 #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)815 static void traverse_for_entities(
816 	const char *old,
817 	size_t oldlen,
818 	zend_string *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
819 	int all,
820 	int flags,
821 	const entity_ht *inv_map,
822 	enum entity_charset charset)
823 {
824 	const char *p,
825 			   *lim;
826 	char	   *q;
827 	int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
828 
829 	lim = old + oldlen; /* terminator address */
830 	assert(*lim == '\0');
831 
832 	for (p = old, q = ZSTR_VAL(ret); p < lim;) {
833 		unsigned code, code2 = 0;
834 		const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
835 
836 		/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
837 		 * ASCII range byte can be part of a multi-byte sequence.
838 		 * However, they start at 0x40, therefore if we find a 0x26 byte,
839 		 * we're sure it represents the '&' character. */
840 
841 		/* assumes there are no single-char entities */
842 		if (p[0] != '&' || (p + 3 >= lim)) {
843 			*(q++) = *(p++);
844 			continue;
845 		}
846 
847 		/* now p[3] is surely valid and is no terminator */
848 
849 		/* numerical entity */
850 		if (p[1] == '#') {
851 			next = &p[2];
852 			if (process_numeric_entity(&next, &code) == FAILURE)
853 				goto invalid_code;
854 
855 			/* If we're in htmlspecialchars_decode, we're only decoding entities
856 			 * that represent &, <, >, " and '. Is this one of them? */
857 			if (!all && (code > 63U ||
858 					stage3_table_be_apos_00000[code].data.ent.entity == NULL))
859 				goto invalid_code;
860 
861 			/* are we allowed to decode this entity in this document type?
862 			 * HTML 5 is the only that has a character that cannot be used in
863 			 * a numeric entity but is allowed literally (U+000D). The
864 			 * unoptimized version would be ... || !numeric_entity_is_allowed(code) */
865 			if (!unicode_cp_is_allowed(code, doctype) ||
866 					(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
867 				goto invalid_code;
868 		} else {
869 			const char *start;
870 			size_t ent_len;
871 
872 			next = &p[1];
873 			start = next;
874 
875 			if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
876 				goto invalid_code;
877 
878 			if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
879 				if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
880 							&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
881 					/* uses html4 inv_map, which doesn't include apos;. This is a
882 					 * hack to support it */
883 					code = (unsigned) '\'';
884 				} else {
885 					goto invalid_code;
886 				}
887 			}
888 		}
889 
890 		assert(*next == ';');
891 
892 		if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
893 				(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
894 				/* && code2 == '\0' always true for current maps */)
895 			goto invalid_code;
896 
897 		/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
898 		 * the call is needed to ensure the codepoint <= U+00FF)  */
899 		if (charset != cs_utf_8) {
900 			/* replace unicode code point */
901 			if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
902 				goto invalid_code; /* not representable in target charset */
903 		}
904 
905 		q += write_octet_sequence((unsigned char*)q, charset, code);
906 		if (code2) {
907 			q += write_octet_sequence((unsigned char*)q, charset, code2);
908 		}
909 
910 		/* jump over the valid entity; may go beyond size of buffer; np */
911 		p = next + 1;
912 		continue;
913 
914 invalid_code:
915 		for (; p < next; p++) {
916 			*(q++) = *p;
917 		}
918 	}
919 
920 	*q = '\0';
921 	ZSTR_LEN(ret) = (size_t)(q - ZSTR_VAL(ret));
922 }
923 /* }}} */
924 
925 /* {{{ unescape_inverse_map */
unescape_inverse_map(int all,int flags)926 static const entity_ht *unescape_inverse_map(int all, int flags)
927 {
928 	int document_type = flags & ENT_HTML_DOC_TYPE_MASK;
929 
930 	if (all) {
931 		switch (document_type) {
932 		case ENT_HTML_DOC_HTML401:
933 		case ENT_HTML_DOC_XHTML: /* but watch out for &apos;...*/
934 			return &ent_ht_html4;
935 		case ENT_HTML_DOC_HTML5:
936 			return &ent_ht_html5;
937 		default:
938 			return &ent_ht_be_apos;
939 		}
940 	} else {
941 		switch (document_type) {
942 		case ENT_HTML_DOC_HTML401:
943 			return &ent_ht_be_noapos;
944 		default:
945 			return &ent_ht_be_apos;
946 		}
947 	}
948 }
949 /* }}} */
950 
951 /* {{{ determine_entity_table
952  * Entity table to use. Note that entity tables are defined in terms of
953  * unicode code points */
determine_entity_table(int all,int doctype)954 static entity_table_opt determine_entity_table(int all, int doctype)
955 {
956 	entity_table_opt retval = {0};
957 
958 	assert(!(doctype == ENT_HTML_DOC_XML1 && all));
959 
960 	if (all) {
961 		retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
962 			entity_ms_table_html5 : entity_ms_table_html4;
963 	} else {
964 		retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
965 			stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
966 	}
967 	return retval;
968 }
969 /* }}} */
970 
971 /* {{{ php_unescape_html_entities
972  * The parameter "all" should be true to decode all possible entities, false to decode
973  * only the basic ones, i.e., those in basic_entities_ex + the numeric entities
974  * that correspond to quotes.
975  */
php_unescape_html_entities(zend_string * str,int all,int flags,const char * hint_charset)976 PHPAPI zend_string *php_unescape_html_entities(zend_string *str, int all, int flags, const char *hint_charset)
977 {
978 	zend_string *ret;
979 	enum entity_charset charset;
980 	const entity_ht *inverse_map;
981 	size_t new_size;
982 
983 	if (!memchr(ZSTR_VAL(str), '&', ZSTR_LEN(str))) {
984 		return zend_string_copy(str);
985 	}
986 
987 	if (all) {
988 		charset = determine_charset(hint_charset, /* quiet */ 0);
989 	} else {
990 		charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */
991 	}
992 
993 	/* don't use LIMIT_ALL! */
994 
995 	new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(ZSTR_LEN(str));
996 	if (ZSTR_LEN(str) > new_size) {
997 		/* overflow, refuse to do anything */
998 		return zend_string_copy(str);
999 	}
1000 
1001 	ret = zend_string_alloc(new_size, 0);
1002 
1003 	inverse_map = unescape_inverse_map(all, flags);
1004 
1005 	/* replace numeric entities */
1006 	traverse_for_entities(ZSTR_VAL(str), ZSTR_LEN(str), ret, all, flags, inverse_map, charset);
1007 
1008 	return ret;
1009 }
1010 /* }}} */
1011 
php_escape_html_entities(const unsigned char * old,size_t oldlen,int all,int flags,const char * hint_charset)1012 PHPAPI zend_string *php_escape_html_entities(const unsigned char *old, size_t oldlen, int all, int flags, const char *hint_charset)
1013 {
1014 	return php_escape_html_entities_ex(old, oldlen, all, flags, hint_charset, 1, /* quiet */ 0);
1015 }
1016 
1017 /* {{{ 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)1018 static inline void find_entity_for_char(
1019 	unsigned int k,
1020 	enum entity_charset charset,
1021 	const entity_stage1_row *table,
1022 	const unsigned char **entity,
1023 	size_t *entity_len,
1024 	const unsigned char *old,
1025 	size_t oldlen,
1026 	size_t *cursor)
1027 {
1028 	unsigned stage1_idx = ENT_STAGE1_INDEX(k);
1029 	const entity_stage3_row *c;
1030 
1031 	if (stage1_idx > 0x1D) {
1032 		*entity     = NULL;
1033 		*entity_len = 0;
1034 		return;
1035 	}
1036 
1037 	c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
1038 
1039 	if (!c->ambiguous) {
1040 		*entity     = (const unsigned char *)c->data.ent.entity;
1041 		*entity_len = c->data.ent.entity_len;
1042 	} else {
1043 		/* peek at next char */
1044 		size_t cursor_before = *cursor;
1045 		zend_result status = SUCCESS;
1046 		unsigned next_char;
1047 
1048 		if (!(*cursor < oldlen))
1049 			goto no_suitable_2nd;
1050 
1051 		next_char = get_next_char(charset, old, oldlen, cursor, &status);
1052 
1053 		if (status == FAILURE)
1054 			goto no_suitable_2nd;
1055 
1056 		{
1057 			const entity_multicodepoint_row *s, *e;
1058 
1059 			s = &c->data.multicodepoint_table[1];
1060 			e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
1061 			/* we could do a binary search but it's not worth it since we have
1062 			 * at most two entries... */
1063 			for ( ; s <= e; s++) {
1064 				if (s->normal_entry.second_cp == next_char) {
1065 					*entity     = (const unsigned char *) s->normal_entry.entity;
1066 					*entity_len = s->normal_entry.entity_len;
1067 					return;
1068 				}
1069 			}
1070 		}
1071 no_suitable_2nd:
1072 		*cursor = cursor_before;
1073 		*entity = (const unsigned char *)
1074 			c->data.multicodepoint_table[0].leading_entry.default_entity;
1075 		*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
1076 	}
1077 }
1078 /* }}} */
1079 
1080 /* {{{ 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)1081 static inline void find_entity_for_char_basic(
1082 	unsigned int k,
1083 	const entity_stage3_row *table,
1084 	const unsigned char **entity,
1085 	size_t *entity_len)
1086 {
1087 	if (k >= 64U) {
1088 		*entity     = NULL;
1089 		*entity_len = 0;
1090 		return;
1091 	}
1092 
1093 	*entity     = (const unsigned char *) table[k].data.ent.entity;
1094 	*entity_len = table[k].data.ent.entity_len;
1095 }
1096 /* }}} */
1097 
1098 /* {{{ 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)1099 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)
1100 {
1101 	size_t cursor, maxlen, len;
1102 	zend_string *replaced;
1103 	enum entity_charset charset = determine_charset(hint_charset, quiet);
1104 	int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
1105 	entity_table_opt entity_table;
1106 	const enc_to_uni *to_uni_table = NULL;
1107 	const entity_ht *inv_map = NULL; /* used for !double_encode */
1108 	/* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
1109 	const unsigned char *replacement = NULL;
1110 	size_t replacement_len = 0;
1111 
1112 	if (all) { /* replace with all named entities */
1113 		if (!quiet && CHARSET_PARTIAL_SUPPORT(charset)) {
1114 			php_error_docref(NULL, E_NOTICE, "Only basic entities "
1115 				"substitution is supported for multi-byte encodings other than UTF-8; "
1116 				"functionality is equivalent to htmlspecialchars");
1117 		}
1118 		LIMIT_ALL(all, doctype, charset);
1119 	}
1120 	entity_table = determine_entity_table(all, doctype);
1121 	if (all && !CHARSET_UNICODE_COMPAT(charset)) {
1122 		to_uni_table = enc_to_uni_index[charset];
1123 	}
1124 
1125 	if (!double_encode) {
1126 		/* first arg is 1 because we want to identify valid named entities
1127 		 * even if we are only encoding the basic ones */
1128 		inv_map = unescape_inverse_map(1, flags);
1129 	}
1130 
1131 	if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
1132 		if (charset == cs_utf_8) {
1133 			replacement = (const unsigned char*)"\xEF\xBF\xBD";
1134 			replacement_len = sizeof("\xEF\xBF\xBD") - 1;
1135 		} else {
1136 			replacement = (const unsigned char*)"&#xFFFD;";
1137 			replacement_len = sizeof("&#xFFFD;") - 1;
1138 		}
1139 	}
1140 
1141 	/* initial estimate */
1142 	if (oldlen < 64) {
1143 		maxlen = 128;
1144 	} else {
1145 		maxlen = zend_safe_addmult(oldlen, 2, 0, "html_entities");
1146 	}
1147 
1148 	replaced = zend_string_alloc(maxlen, 0);
1149 	len = 0;
1150 	cursor = 0;
1151 	while (cursor < oldlen) {
1152 		const unsigned char *mbsequence = NULL;
1153 		size_t mbseqlen					= 0,
1154 		       cursor_before			= cursor;
1155 		zend_result status				= SUCCESS;
1156 		unsigned int this_char			= get_next_char(charset, old, oldlen, &cursor, &status);
1157 
1158 		/* guarantee we have at least 40 bytes to write.
1159 		 * In HTML5, entities may take up to 33 bytes */
1160 		if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
1161 			replaced = zend_string_safe_realloc(replaced, maxlen, 1, 128, 0);
1162 			maxlen += 128;
1163 		}
1164 
1165 		if (status == FAILURE) {
1166 			/* invalid MB sequence */
1167 			if (flags & ENT_HTML_IGNORE_ERRORS) {
1168 				continue;
1169 			} else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
1170 				memcpy(&ZSTR_VAL(replaced)[len], replacement, replacement_len);
1171 				len += replacement_len;
1172 				continue;
1173 			} else {
1174 				zend_string_efree(replaced);
1175 				return ZSTR_EMPTY_ALLOC();
1176 			}
1177 		} else { /* SUCCESS */
1178 			mbsequence = &old[cursor_before];
1179 			mbseqlen = cursor - cursor_before;
1180 		}
1181 
1182 		if (this_char != '&') { /* no entity on this position */
1183 			const unsigned char *rep	= NULL;
1184 			size_t				rep_len	= 0;
1185 
1186 			if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1187 					(this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1188 				goto pass_char_through;
1189 
1190 			if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
1191 				if (to_uni_table != NULL) {
1192 					/* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
1193 					 * is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
1194 					 * we're using a single byte encoding */
1195 					map_to_unicode(this_char, to_uni_table, &this_char);
1196 					if (this_char == 0xFFFF) /* no mapping; pass through */
1197 						goto pass_char_through;
1198 				}
1199 				/* the cursor may advance */
1200 				find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
1201 					&rep_len, old, oldlen, &cursor);
1202 			} else {
1203 				find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
1204 			}
1205 
1206 			if (rep != NULL) {
1207 				ZSTR_VAL(replaced)[len++] = '&';
1208 				memcpy(&ZSTR_VAL(replaced)[len], rep, rep_len);
1209 				len += rep_len;
1210 				ZSTR_VAL(replaced)[len++] = ';';
1211 			} else {
1212 				/* we did not find an entity for this char.
1213 				 * check for its validity, if its valid pass it unchanged */
1214 				if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
1215 					if (CHARSET_UNICODE_COMPAT(charset)) {
1216 						if (!unicode_cp_is_allowed(this_char, doctype)) {
1217 							mbsequence = replacement;
1218 							mbseqlen = replacement_len;
1219 						}
1220 					} else if (to_uni_table) {
1221 						if (!all) /* otherwise we already did this */
1222 							map_to_unicode(this_char, to_uni_table, &this_char);
1223 						if (!unicode_cp_is_allowed(this_char, doctype)) {
1224 							mbsequence = replacement;
1225 							mbseqlen = replacement_len;
1226 						}
1227 					} else {
1228 						/* not a unicode code point, unless, coincidentally, it's in
1229 						 * the 0x20..0x7D range (except 0x5C in sjis). We know nothing
1230 						 * about other code points, because we have no tables. Since
1231 						 * Unicode code points in that range are not disallowed in any
1232 						 * document type, we could do nothing. However, conversion
1233 						 * tables frequently map 0x00-0x1F to the respective C0 code
1234 						 * points. Let's play it safe and admit that's the case */
1235 						if (this_char <= 0x7D &&
1236 								!unicode_cp_is_allowed(this_char, doctype)) {
1237 							mbsequence = replacement;
1238 							mbseqlen = replacement_len;
1239 						}
1240 					}
1241 				}
1242 pass_char_through:
1243 				if (mbseqlen > 1) {
1244 					memcpy(ZSTR_VAL(replaced) + len, mbsequence, mbseqlen);
1245 					len += mbseqlen;
1246 				} else {
1247 					ZSTR_VAL(replaced)[len++] = mbsequence[0];
1248 				}
1249 			}
1250 		} else { /* this_char == '&' */
1251 			if (double_encode) {
1252 encode_amp:
1253 				memcpy(&ZSTR_VAL(replaced)[len], "&amp;", sizeof("&amp;") - 1);
1254 				len += sizeof("&amp;") - 1;
1255 			} else { /* no double encode */
1256 				/* check if entity is valid */
1257 				size_t ent_len; /* not counting & or ; */
1258 				/* peek at next char */
1259 				if (old[cursor] == '#') { /* numeric entity */
1260 					unsigned code_point;
1261 					int valid;
1262 					char *pos = (char*)&old[cursor+1];
1263 					valid = process_numeric_entity((const char **)&pos, &code_point);
1264 					if (valid == FAILURE)
1265 						goto encode_amp;
1266 					if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
1267 						if (!numeric_entity_is_allowed(code_point, doctype))
1268 							goto encode_amp;
1269 					}
1270 					ent_len = pos - (char*)&old[cursor];
1271 				} else { /* named entity */
1272 					/* check for vality of named entity */
1273 					const char *start = (const char *) &old[cursor],
1274 							   *next = start;
1275 					unsigned   dummy1, dummy2;
1276 
1277 					if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
1278 						goto encode_amp;
1279 					if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
1280 						if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
1281 									&& start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
1282 							/* uses html4 inv_map, which doesn't include apos;. This is a
1283 							 * hack to support it */
1284 							goto encode_amp;
1285 						}
1286 					}
1287 				}
1288 				/* checks passed; copy entity to result */
1289 				/* entity size is unbounded, we may need more memory */
1290 				/* at this point maxlen - len >= 40 */
1291 				if (maxlen - len < ent_len + 2 /* & and ; */) {
1292 					/* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
1293 					replaced = zend_string_safe_realloc(replaced, maxlen, 1, ent_len + 128, 0);
1294 					maxlen += ent_len + 128;
1295 				}
1296 				ZSTR_VAL(replaced)[len++] = '&';
1297 				memcpy(&ZSTR_VAL(replaced)[len], &old[cursor], ent_len);
1298 				len += ent_len;
1299 				ZSTR_VAL(replaced)[len++] = ';';
1300 				cursor += ent_len + 1;
1301 			}
1302 		}
1303 	}
1304 	ZSTR_VAL(replaced)[len] = '\0';
1305 	ZSTR_LEN(replaced) = len;
1306 
1307 	return replaced;
1308 }
1309 /* }}} */
1310 
1311 /* {{{ php_html_entities */
php_html_entities(INTERNAL_FUNCTION_PARAMETERS,int all)1312 static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
1313 {
1314 	zend_string *str, *hint_charset = NULL;
1315 	zend_long flags = ENT_QUOTES|ENT_SUBSTITUTE;
1316 	zend_string *replaced;
1317 	bool double_encode = 1;
1318 
1319 	ZEND_PARSE_PARAMETERS_START(1, 4)
1320 		Z_PARAM_STR(str)
1321 		Z_PARAM_OPTIONAL
1322 		Z_PARAM_LONG(flags)
1323 		Z_PARAM_STR_OR_NULL(hint_charset)
1324 		Z_PARAM_BOOL(double_encode);
1325 	ZEND_PARSE_PARAMETERS_END();
1326 
1327 	replaced = php_escape_html_entities_ex(
1328 		(unsigned char*)ZSTR_VAL(str), ZSTR_LEN(str), all, (int) flags,
1329 		hint_charset ? ZSTR_VAL(hint_charset) : NULL, double_encode, /* quiet */ 0);
1330 	RETVAL_STR(replaced);
1331 }
1332 /* }}} */
1333 
1334 /* {{{ Convert special characters to HTML entities */
PHP_FUNCTION(htmlspecialchars)1335 PHP_FUNCTION(htmlspecialchars)
1336 {
1337 	php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1338 }
1339 /* }}} */
1340 
1341 /* {{{ Convert special HTML entities back to characters */
PHP_FUNCTION(htmlspecialchars_decode)1342 PHP_FUNCTION(htmlspecialchars_decode)
1343 {
1344 	zend_string *str;
1345 	zend_long quote_style = ENT_QUOTES|ENT_SUBSTITUTE;
1346 	zend_string *replaced;
1347 
1348 	ZEND_PARSE_PARAMETERS_START(1, 2)
1349 		Z_PARAM_STR(str)
1350 		Z_PARAM_OPTIONAL
1351 		Z_PARAM_LONG(quote_style)
1352 	ZEND_PARSE_PARAMETERS_END();
1353 
1354 	replaced = php_unescape_html_entities(str, 0 /*!all*/, (int)quote_style, NULL);
1355 	RETURN_STR(replaced);
1356 }
1357 /* }}} */
1358 
1359 /* {{{ Convert all HTML entities to their applicable characters */
PHP_FUNCTION(html_entity_decode)1360 PHP_FUNCTION(html_entity_decode)
1361 {
1362 	zend_string *str, *hint_charset = NULL;
1363 	zend_long quote_style = ENT_QUOTES|ENT_SUBSTITUTE;
1364 	zend_string *replaced;
1365 
1366 	ZEND_PARSE_PARAMETERS_START(1, 3)
1367 		Z_PARAM_STR(str)
1368 		Z_PARAM_OPTIONAL
1369 		Z_PARAM_LONG(quote_style)
1370 		Z_PARAM_STR_OR_NULL(hint_charset)
1371 	ZEND_PARSE_PARAMETERS_END();
1372 
1373 	replaced = php_unescape_html_entities(
1374 		str, 1 /*all*/, (int)quote_style, hint_charset ? ZSTR_VAL(hint_charset) : NULL);
1375 	RETURN_STR(replaced);
1376 }
1377 /* }}} */
1378 
1379 
1380 /* {{{ Convert all applicable characters to HTML entities */
PHP_FUNCTION(htmlentities)1381 PHP_FUNCTION(htmlentities)
1382 {
1383 	php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1384 }
1385 /* }}} */
1386 
1387 /* {{{ write_s3row_data */
write_s3row_data(const entity_stage3_row * r,unsigned orig_cp,enum entity_charset charset,zval * arr)1388 static inline void write_s3row_data(
1389 	const entity_stage3_row *r,
1390 	unsigned orig_cp,
1391 	enum entity_charset charset,
1392 	zval *arr)
1393 {
1394 	char key[9] = ""; /* two unicode code points in UTF-8 */
1395 	char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'};
1396 	size_t written_k1;
1397 
1398 	written_k1 = write_octet_sequence((unsigned char*)key, charset, orig_cp);
1399 
1400 	if (!r->ambiguous) {
1401 		size_t l = r->data.ent.entity_len;
1402 		memcpy(&entity[1], r->data.ent.entity, l);
1403 		entity[l + 1] = ';';
1404 		add_assoc_stringl_ex(arr, key, written_k1, entity, l + 2);
1405 	} else {
1406 		unsigned i,
1407 			     num_entries;
1408 		const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table;
1409 
1410 		if (mcpr[0].leading_entry.default_entity != NULL) {
1411 			size_t l = mcpr[0].leading_entry.default_entity_len;
1412 			memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l);
1413 			entity[l + 1] = ';';
1414 			add_assoc_stringl_ex(arr, key, written_k1, entity, l + 2);
1415 		}
1416 		num_entries = mcpr[0].leading_entry.size;
1417 		for (i = 1; i <= num_entries; i++) {
1418 			size_t   l,
1419 				     written_k2;
1420 			unsigned uni_cp,
1421 					 spe_cp;
1422 
1423 			uni_cp = mcpr[i].normal_entry.second_cp;
1424 			l = mcpr[i].normal_entry.entity_len;
1425 
1426 			if (!CHARSET_UNICODE_COMPAT(charset)) {
1427 				if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE)
1428 					continue; /* non representable in this charset */
1429 			} else {
1430 				spe_cp = uni_cp;
1431 			}
1432 
1433 			written_k2 = write_octet_sequence((unsigned char*)&key[written_k1], charset, spe_cp);
1434 			memcpy(&entity[1], mcpr[i].normal_entry.entity, l);
1435 			entity[l + 1] = ';';
1436 			add_assoc_stringl_ex(arr, key, written_k1 + written_k2, entity, l + 2);
1437 		}
1438 	}
1439 }
1440 /* }}} */
1441 
1442 /* {{{ Returns the internal translation table used by htmlspecialchars and htmlentities */
PHP_FUNCTION(get_html_translation_table)1443 PHP_FUNCTION(get_html_translation_table)
1444 {
1445 	zend_long all = PHP_HTML_SPECIALCHARS,
1446 		 flags = ENT_QUOTES|ENT_SUBSTITUTE;
1447 	int doctype;
1448 	entity_table_opt entity_table;
1449 	const enc_to_uni *to_uni_table = NULL;
1450 	char *charset_hint = NULL;
1451 	size_t charset_hint_len;
1452 	enum entity_charset charset;
1453 
1454 	/* in this function we have to jump through some loops because we're
1455 	 * getting the translated table from data structures that are optimized for
1456 	 * random access, not traversal */
1457 
1458 	ZEND_PARSE_PARAMETERS_START(0, 3)
1459 		Z_PARAM_OPTIONAL
1460 		Z_PARAM_LONG(all)
1461 		Z_PARAM_LONG(flags)
1462 		Z_PARAM_STRING(charset_hint, charset_hint_len)
1463 	ZEND_PARSE_PARAMETERS_END();
1464 
1465 	charset = determine_charset(charset_hint, /* quiet */ 0);
1466 	doctype = flags & ENT_HTML_DOC_TYPE_MASK;
1467 	LIMIT_ALL(all, doctype, charset);
1468 
1469 	array_init(return_value);
1470 
1471 	entity_table = determine_entity_table((int)all, doctype);
1472 	if (all && !CHARSET_UNICODE_COMPAT(charset)) {
1473 		to_uni_table = enc_to_uni_index[charset];
1474 	}
1475 
1476 	if (all) { /* PHP_HTML_ENTITIES (actually, any non-zero value for 1st param) */
1477 		const entity_stage1_row *ms_table = entity_table.ms_table;
1478 
1479 		if (CHARSET_UNICODE_COMPAT(charset)) {
1480 			unsigned i, j, k,
1481 					 max_i, max_j, max_k;
1482 			/* no mapping to unicode required */
1483 			if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
1484 				max_i = 1; max_j = 4; max_k = 64;
1485 			} else {
1486 				max_i = 0x1E; max_j = 64; max_k = 64;
1487 			}
1488 
1489 			for (i = 0; i < max_i; i++) {
1490 				if (ms_table[i] == empty_stage2_table)
1491 					continue;
1492 				for (j = 0; j < max_j; j++) {
1493 					if (ms_table[i][j] == empty_stage3_table)
1494 						continue;
1495 					for (k = 0; k < max_k; k++) {
1496 						const entity_stage3_row *r = &ms_table[i][j][k];
1497 						unsigned code;
1498 
1499 						if (r->data.ent.entity == NULL)
1500 							continue;
1501 
1502 						code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
1503 						if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1504 								(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1505 							continue;
1506 						write_s3row_data(r, code, charset, return_value);
1507 					}
1508 				}
1509 			}
1510 		} else {
1511 			/* we have to iterate through the set of code points for this
1512 			 * encoding and map them to unicode code points */
1513 			unsigned i;
1514 			for (i = 0; i <= 0xFF; i++) {
1515 				const entity_stage3_row *r;
1516 				unsigned uni_cp;
1517 
1518 				/* can be done before mapping, they're invariant */
1519 				if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1520 						(i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1521 					continue;
1522 
1523 				map_to_unicode(i, to_uni_table, &uni_cp);
1524 				r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
1525 				if (r->data.ent.entity == NULL)
1526 					continue;
1527 
1528 				write_s3row_data(r, i, charset, return_value);
1529 			}
1530 		}
1531 	} else {
1532 		/* we could use sizeof(stage3_table_be_apos_00000) as well */
1533 		unsigned	  j,
1534 					  numelems = sizeof(stage3_table_be_noapos_00000) /
1535 							sizeof(*stage3_table_be_noapos_00000);
1536 
1537 		for (j = 0; j < numelems; j++) {
1538 			const entity_stage3_row *r = &entity_table.table[j];
1539 			if (r->data.ent.entity == NULL)
1540 				continue;
1541 
1542 			if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
1543 					(j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
1544 				continue;
1545 
1546 			/* charset is indifferent, used cs_8859_1 for efficiency */
1547 			write_s3row_data(r, j, cs_8859_1, return_value);
1548 		}
1549 	}
1550 }
1551 /* }}} */
1552