xref: /PHP-8.3/main/rfc1867.c (revision c47d357d)
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    |          Jani Taskinen <jani@php.net>                                |
15    +----------------------------------------------------------------------+
16  */
17 
18 /*
19  *  This product includes software developed by the Apache Group
20  *  for use in the Apache HTTP server project (http://www.apache.org/).
21  *
22  */
23 
24 #include <stdio.h>
25 #include "php.h"
26 #include "php_open_temporary_file.h"
27 #include "zend_globals.h"
28 #include "php_globals.h"
29 #include "php_variables.h"
30 #include "rfc1867.h"
31 #include "zend_smart_string.h"
32 
33 #ifndef DEBUG_FILE_UPLOAD
34 # define DEBUG_FILE_UPLOAD 0
35 #endif
36 
dummy_encoding_translation(void)37 static int dummy_encoding_translation(void)
38 {
39 	return 0;
40 }
41 
42 static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop);
43 static char *php_ap_getword_conf(const zend_encoding *encoding, char *str);
44 
45 static php_rfc1867_encoding_translation_t php_rfc1867_encoding_translation = dummy_encoding_translation;
46 static php_rfc1867_get_detect_order_t php_rfc1867_get_detect_order = NULL;
47 static php_rfc1867_set_input_encoding_t php_rfc1867_set_input_encoding = NULL;
48 static php_rfc1867_getword_t php_rfc1867_getword = php_ap_getword;
49 static php_rfc1867_getword_conf_t php_rfc1867_getword_conf = php_ap_getword_conf;
50 static php_rfc1867_basename_t php_rfc1867_basename = NULL;
51 
52 PHPAPI zend_result (*php_rfc1867_callback)(unsigned int event, void *event_data, void **extra) = NULL;
53 
54 static void safe_php_register_variable(char *var, char *strval, size_t val_len, zval *track_vars_array, bool override_protection);
55 
56 /* The longest property name we use in an uploaded file array */
57 #define MAX_SIZE_OF_INDEX sizeof("[full_path]")
58 
59 /* The longest anonymous name */
60 #define MAX_SIZE_ANONNAME 33
61 
normalize_protected_variable(char * varname)62 static void normalize_protected_variable(char *varname) /* {{{ */
63 {
64 	char *s = varname, *index = NULL, *indexend = NULL, *p;
65 
66 	/* skip leading space */
67 	while (*s == ' ') {
68 		s++;
69 	}
70 
71 	/* and remove it */
72 	if (s != varname) {
73 		memmove(varname, s, strlen(s)+1);
74 	}
75 
76 	for (p = varname; *p && *p != '['; p++) {
77 		switch(*p) {
78 			case ' ':
79 			case '.':
80 				*p = '_';
81 				break;
82 		}
83 	}
84 
85 	/* find index */
86 	index = strchr(varname, '[');
87 	if (index) {
88 		index++;
89 		s = index;
90 	} else {
91 		return;
92 	}
93 
94 	/* done? */
95 	while (index) {
96 		while (*index == ' ' || *index == '\r' || *index == '\n' || *index=='\t') {
97 			index++;
98 		}
99 		indexend = strchr(index, ']');
100 		indexend = indexend ? indexend + 1 : index + strlen(index);
101 
102 		if (s != index) {
103 			memmove(s, index, strlen(index)+1);
104 			s += indexend-index;
105 		} else {
106 			s = indexend;
107 		}
108 
109 		if (*s == '[') {
110 			s++;
111 			index = s;
112 		} else {
113 			index = NULL;
114 		}
115 	}
116 	*s = '\0';
117 }
118 /* }}} */
119 
add_protected_variable(char * varname)120 static void add_protected_variable(char *varname) /* {{{ */
121 {
122 	normalize_protected_variable(varname);
123 	zend_hash_str_add_empty_element(&PG(rfc1867_protected_variables), varname, strlen(varname));
124 }
125 /* }}} */
126 
is_protected_variable(char * varname)127 static bool is_protected_variable(char *varname) /* {{{ */
128 {
129 	normalize_protected_variable(varname);
130 	return zend_hash_str_exists(&PG(rfc1867_protected_variables), varname, strlen(varname));
131 }
132 /* }}} */
133 
safe_php_register_variable(char * var,char * strval,size_t val_len,zval * track_vars_array,bool override_protection)134 static void safe_php_register_variable(char *var, char *strval, size_t val_len, zval *track_vars_array, bool override_protection) /* {{{ */
135 {
136 	if (override_protection || !is_protected_variable(var)) {
137 		php_register_variable_safe(var, strval, val_len, track_vars_array);
138 	}
139 }
140 /* }}} */
141 
safe_php_register_variable_ex(char * var,zval * val,zval * track_vars_array,bool override_protection)142 static void safe_php_register_variable_ex(char *var, zval *val, zval *track_vars_array, bool override_protection) /* {{{ */
143 {
144 	if (override_protection || !is_protected_variable(var)) {
145 		php_register_variable_ex(var, val, track_vars_array);
146 	}
147 }
148 /* }}} */
149 
register_http_post_files_variable(char * strvar,char * val,zval * http_post_files,bool override_protection)150 static void register_http_post_files_variable(char *strvar, char *val, zval *http_post_files, bool override_protection) /* {{{ */
151 {
152 	safe_php_register_variable(strvar, val, strlen(val), http_post_files, override_protection);
153 }
154 /* }}} */
155 
register_http_post_files_variable_ex(char * var,zval * val,zval * http_post_files,bool override_protection)156 static void register_http_post_files_variable_ex(char *var, zval *val, zval *http_post_files, bool override_protection) /* {{{ */
157 {
158 	safe_php_register_variable_ex(var, val, http_post_files, override_protection);
159 }
160 /* }}} */
161 
free_filename(zval * el)162 static void free_filename(zval *el) {
163 	zend_string *filename = Z_STR_P(el);
164 	zend_string_release_ex(filename, 0);
165 }
166 
destroy_uploaded_files_hash(void)167 PHPAPI void destroy_uploaded_files_hash(void) /* {{{ */
168 {
169 	zval *el;
170 
171 	ZEND_HASH_MAP_FOREACH_VAL(SG(rfc1867_uploaded_files), el) {
172 		zend_string *filename = Z_STR_P(el);
173 		VCWD_UNLINK(ZSTR_VAL(filename));
174 	} ZEND_HASH_FOREACH_END();
175 	zend_hash_destroy(SG(rfc1867_uploaded_files));
176 	FREE_HASHTABLE(SG(rfc1867_uploaded_files));
177 	SG(rfc1867_uploaded_files) = NULL;
178 }
179 /* }}} */
180 
181 /* {{{ Following code is based on apache_multipart_buffer.c from libapreq-0.33 package. */
182 
183 #define FILLUNIT (1024 * 5)
184 
185 typedef struct {
186 
187 	/* read buffer */
188 	char *buffer;
189 	char *buf_begin;
190 	int  bufsize;
191 	int  bytes_in_buffer;
192 
193 	/* boundary info */
194 	char *boundary;
195 	char *boundary_next;
196 	int  boundary_next_len;
197 
198 	const zend_encoding *input_encoding;
199 	const zend_encoding **detect_order;
200 	size_t detect_order_size;
201 } multipart_buffer;
202 
203 typedef struct {
204 	char *key;
205 	char *value;
206 } mime_header_entry;
207 
208 /*
209  * Fill up the buffer with client data.
210  * Returns number of bytes added to buffer.
211  */
fill_buffer(multipart_buffer * self)212 static int fill_buffer(multipart_buffer *self)
213 {
214 	int bytes_to_read, total_read = 0, actual_read = 0;
215 
216 	/* shift the existing data if necessary */
217 	if (self->bytes_in_buffer > 0 && self->buf_begin != self->buffer) {
218 		memmove(self->buffer, self->buf_begin, self->bytes_in_buffer);
219 	}
220 
221 	self->buf_begin = self->buffer;
222 
223 	/* calculate the free space in the buffer */
224 	bytes_to_read = self->bufsize - self->bytes_in_buffer;
225 
226 	/* read the required number of bytes */
227 	while (bytes_to_read > 0) {
228 
229 		char *buf = self->buffer + self->bytes_in_buffer;
230 
231 		actual_read = (int)sapi_module.read_post(buf, bytes_to_read);
232 
233 		/* update the buffer length */
234 		if (actual_read > 0) {
235 			self->bytes_in_buffer += actual_read;
236 			SG(read_post_bytes) += actual_read;
237 			total_read += actual_read;
238 			bytes_to_read -= actual_read;
239 		} else {
240 			break;
241 		}
242 	}
243 
244 	return total_read;
245 }
246 
247 /* eof if we are out of bytes, or if we hit the final boundary */
multipart_buffer_eof(multipart_buffer * self)248 static int multipart_buffer_eof(multipart_buffer *self)
249 {
250 	return self->bytes_in_buffer == 0 && fill_buffer(self) < 1;
251 }
252 
253 /* create new multipart_buffer structure */
multipart_buffer_new(char * boundary,int boundary_len)254 static multipart_buffer *multipart_buffer_new(char *boundary, int boundary_len)
255 {
256 	multipart_buffer *self = (multipart_buffer *) ecalloc(1, sizeof(multipart_buffer));
257 
258 	int minsize = boundary_len + 6;
259 	if (minsize < FILLUNIT) minsize = FILLUNIT;
260 
261 	self->buffer = (char *) ecalloc(1, minsize + 1);
262 	self->bufsize = minsize;
263 
264 	spprintf(&self->boundary, 0, "--%s", boundary);
265 
266 	self->boundary_next_len = (int)spprintf(&self->boundary_next, 0, "\n--%s", boundary);
267 
268 	self->buf_begin = self->buffer;
269 	self->bytes_in_buffer = 0;
270 
271 	if (php_rfc1867_encoding_translation()) {
272 		php_rfc1867_get_detect_order(&self->detect_order, &self->detect_order_size);
273 	} else {
274 		self->detect_order = NULL;
275 		self->detect_order_size = 0;
276 	}
277 
278 	self->input_encoding = NULL;
279 
280 	return self;
281 }
282 
283 /*
284  * Gets the next CRLF terminated line from the input buffer.
285  * If it doesn't find a CRLF, and the buffer isn't completely full, returns
286  * NULL; otherwise, returns the beginning of the null-terminated line,
287  * minus the CRLF.
288  *
289  * Note that we really just look for LF terminated lines. This works
290  * around a bug in internet explorer for the macintosh which sends mime
291  * boundaries that are only LF terminated when you use an image submit
292  * button in a multipart/form-data form.
293  */
next_line(multipart_buffer * self)294 static char *next_line(multipart_buffer *self)
295 {
296 	/* look for LF in the data */
297 	char* line = self->buf_begin;
298 	char* ptr = memchr(self->buf_begin, '\n', self->bytes_in_buffer);
299 
300 	if (ptr) {	/* LF found */
301 
302 		/* terminate the string, remove CRLF */
303 		if ((ptr - line) > 0 && *(ptr-1) == '\r') {
304 			*(ptr-1) = 0;
305 		} else {
306 			*ptr = 0;
307 		}
308 
309 		/* bump the pointer */
310 		self->buf_begin = ptr + 1;
311 		self->bytes_in_buffer -= (self->buf_begin - line);
312 
313 	} else {	/* no LF found */
314 
315 		/* buffer isn't completely full, fail */
316 		if (self->bytes_in_buffer < self->bufsize) {
317 			return NULL;
318 		}
319 		/* return entire buffer as a partial line */
320 		line[self->bufsize] = 0;
321 		self->buf_begin = ptr;
322 		self->bytes_in_buffer = 0;
323 	}
324 
325 	return line;
326 }
327 
328 /* Returns the next CRLF terminated line from the client */
get_line(multipart_buffer * self)329 static char *get_line(multipart_buffer *self)
330 {
331 	char* ptr = next_line(self);
332 
333 	if (!ptr) {
334 		fill_buffer(self);
335 		ptr = next_line(self);
336 	}
337 
338 	return ptr;
339 }
340 
341 /* Free header entry */
php_free_hdr_entry(mime_header_entry * h)342 static void php_free_hdr_entry(mime_header_entry *h)
343 {
344 	if (h->key) {
345 		efree(h->key);
346 	}
347 	if (h->value) {
348 		efree(h->value);
349 	}
350 }
351 
352 /* finds a boundary */
find_boundary(multipart_buffer * self,char * boundary)353 static int find_boundary(multipart_buffer *self, char *boundary)
354 {
355 	char *line;
356 
357 	/* loop through lines */
358 	while( (line = get_line(self)) )
359 	{
360 		/* finished if we found the boundary */
361 		if (!strcmp(line, boundary)) {
362 			return 1;
363 		}
364 	}
365 
366 	/* didn't find the boundary */
367 	return 0;
368 }
369 
370 /* parse headers */
multipart_buffer_headers(multipart_buffer * self,zend_llist * header)371 static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header)
372 {
373 	char *line;
374 	mime_header_entry entry = {0};
375 	smart_string buf_value = {0};
376 	char *key = NULL;
377 
378 	/* didn't find boundary, abort */
379 	if (!find_boundary(self, self->boundary)) {
380 		return 0;
381 	}
382 
383 	/* get lines of text, or CRLF_CRLF */
384 
385 	while ((line = get_line(self)) && line[0] != '\0') {
386 		/* add header to table */
387 		char *value = NULL;
388 
389 		if (php_rfc1867_encoding_translation()) {
390 			self->input_encoding = zend_multibyte_encoding_detector((const unsigned char *) line, strlen(line), self->detect_order, self->detect_order_size);
391 		}
392 
393 		/* space in the beginning means same header */
394 		if (!isspace(line[0])) {
395 			value = strchr(line, ':');
396 		}
397 
398 		if (value) {
399 			if (buf_value.c && key) {
400 				/* new entry, add the old one to the list */
401 				smart_string_0(&buf_value);
402 				entry.key = key;
403 				entry.value = buf_value.c;
404 				zend_llist_add_element(header, &entry);
405 				buf_value.c = NULL;
406 				key = NULL;
407 			}
408 
409 			*value = '\0';
410 			do { value++; } while (isspace(*value));
411 
412 			key = estrdup(line);
413 			smart_string_appends(&buf_value, value);
414 		} else if (buf_value.c) { /* If no ':' on the line, add to previous line */
415 			smart_string_appends(&buf_value, line);
416 		} else {
417 			continue;
418 		}
419 	}
420 
421 	if (buf_value.c && key) {
422 		/* add the last one to the list */
423 		smart_string_0(&buf_value);
424 		entry.key = key;
425 		entry.value = buf_value.c;
426 		zend_llist_add_element(header, &entry);
427 	}
428 
429 	return 1;
430 }
431 
php_mime_get_hdr_value(zend_llist header,char * key)432 static char *php_mime_get_hdr_value(zend_llist header, char *key)
433 {
434 	mime_header_entry *entry;
435 
436 	if (key == NULL) {
437 		return NULL;
438 	}
439 
440 	entry = zend_llist_get_first(&header);
441 	while (entry) {
442 		if (!strcasecmp(entry->key, key)) {
443 			return entry->value;
444 		}
445 		entry = zend_llist_get_next(&header);
446 	}
447 
448 	return NULL;
449 }
450 
php_ap_getword(const zend_encoding * encoding,char ** line,char stop)451 static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop)
452 {
453 	char *pos = *line, quote;
454 	char *res;
455 
456 	while (*pos && *pos != stop) {
457 		if ((quote = *pos) == '"' || quote == '\'') {
458 			++pos;
459 			while (*pos && *pos != quote) {
460 				if (*pos == '\\' && pos[1] && pos[1] == quote) {
461 					pos += 2;
462 				} else {
463 					++pos;
464 				}
465 			}
466 			if (*pos) {
467 				++pos;
468 			}
469 		} else ++pos;
470 	}
471 	if (*pos == '\0') {
472 		res = estrdup(*line);
473 		*line += strlen(*line);
474 		return res;
475 	}
476 
477 	res = estrndup(*line, pos - *line);
478 
479 	while (*pos == stop) {
480 		++pos;
481 	}
482 
483 	*line = pos;
484 	return res;
485 }
486 
substring_conf(char * start,int len,char quote)487 static char *substring_conf(char *start, int len, char quote)
488 {
489 	char *result = emalloc(len + 1);
490 	char *resp = result;
491 	int i;
492 
493 	for (i = 0; i < len && start[i] != quote; ++i) {
494 		if (start[i] == '\\' && (start[i + 1] == '\\' || (quote && start[i + 1] == quote))) {
495 			*resp++ = start[++i];
496 		} else {
497 			*resp++ = start[i];
498 		}
499 	}
500 
501 	*resp = '\0';
502 	return result;
503 }
504 
php_ap_getword_conf(const zend_encoding * encoding,char * str)505 static char *php_ap_getword_conf(const zend_encoding *encoding, char *str)
506 {
507 	while (*str && isspace(*str)) {
508 		++str;
509 	}
510 
511 	if (!*str) {
512 		return estrdup("");
513 	}
514 
515 	if (*str == '"' || *str == '\'') {
516 		char quote = *str;
517 
518 		str++;
519 		return substring_conf(str, (int)strlen(str), quote);
520 	} else {
521 		char *strend = str;
522 
523 		while (*strend && !isspace(*strend)) {
524 			++strend;
525 		}
526 		return substring_conf(str, strend - str, 0);
527 	}
528 }
529 
php_ap_basename(const zend_encoding * encoding,char * path)530 static char *php_ap_basename(const zend_encoding *encoding, char *path)
531 {
532 	char *s = strrchr(path, '\\');
533 	char *s2 = strrchr(path, '/');
534 
535 	if (s && s2) {
536 		if (s > s2) {
537 			++s;
538 		} else {
539 			s = ++s2;
540 		}
541 		return s;
542 	} else if (s) {
543 		return ++s;
544 	} else if (s2) {
545 		return ++s2;
546 	}
547 	return path;
548 }
549 
550 /*
551  * Search for a string in a fixed-length byte string.
552  * If partial is true, partial matches are allowed at the end of the buffer.
553  * Returns NULL if not found, or a pointer to the start of the first match.
554  */
php_ap_memstr(char * haystack,int haystacklen,char * needle,int needlen,int partial)555 static void *php_ap_memstr(char *haystack, int haystacklen, char *needle, int needlen, int partial)
556 {
557 	int len = haystacklen;
558 	char *ptr = haystack;
559 
560 	/* iterate through first character matches */
561 	while( (ptr = memchr(ptr, needle[0], len)) ) {
562 
563 		/* calculate length after match */
564 		len = haystacklen - (ptr - (char *)haystack);
565 
566 		/* done if matches up to capacity of buffer */
567 		if (memcmp(needle, ptr, needlen < len ? needlen : len) == 0 && (partial || len >= needlen)) {
568 			break;
569 		}
570 
571 		/* next character */
572 		ptr++; len--;
573 	}
574 
575 	return ptr;
576 }
577 
578 /* read until a boundary condition */
multipart_buffer_read(multipart_buffer * self,char * buf,size_t bytes,int * end)579 static size_t multipart_buffer_read(multipart_buffer *self, char *buf, size_t bytes, int *end)
580 {
581 	size_t len, max;
582 	char *bound;
583 
584 	/* fill buffer if needed */
585 	if (bytes > (size_t)self->bytes_in_buffer) {
586 		fill_buffer(self);
587 	}
588 
589 	/* look for a potential boundary match, only read data up to that point */
590 	if ((bound = php_ap_memstr(self->buf_begin, self->bytes_in_buffer, self->boundary_next, self->boundary_next_len, 1))) {
591 		max = bound - self->buf_begin;
592 		if (end && php_ap_memstr(self->buf_begin, self->bytes_in_buffer, self->boundary_next, self->boundary_next_len, 0)) {
593 			*end = 1;
594 		}
595 	} else {
596 		max = self->bytes_in_buffer;
597 	}
598 
599 	/* maximum number of bytes we are reading */
600 	len = max < bytes-1 ? max : bytes-1;
601 
602 	/* if we read any data... */
603 	if (len > 0) {
604 
605 		/* copy the data */
606 		memcpy(buf, self->buf_begin, len);
607 		buf[len] = 0;
608 
609 		if (bound && len > 0 && buf[len-1] == '\r') {
610 			buf[--len] = 0;
611 		}
612 
613 		/* update the buffer */
614 		self->bytes_in_buffer -= (int)len;
615 		self->buf_begin += len;
616 	}
617 
618 	return len;
619 }
620 
621 /*
622   XXX: this is horrible memory-usage-wise, but we only expect
623   to do this on small pieces of form data.
624 */
multipart_buffer_read_body(multipart_buffer * self,size_t * len)625 static char *multipart_buffer_read_body(multipart_buffer *self, size_t *len)
626 {
627 	char buf[FILLUNIT], *out=NULL;
628 	size_t total_bytes=0, read_bytes=0;
629 
630 	while((read_bytes = multipart_buffer_read(self, buf, sizeof(buf), NULL))) {
631 		out = erealloc(out, total_bytes + read_bytes + 1);
632 		memcpy(out + total_bytes, buf, read_bytes);
633 		total_bytes += read_bytes;
634 	}
635 
636 	if (out) {
637 		out[total_bytes] = '\0';
638 	}
639 	*len = total_bytes;
640 
641 	return out;
642 }
643 /* }}} */
644 
645 /*
646  * The combined READER/HANDLER
647  *
648  */
649 
SAPI_POST_HANDLER_FUNC(rfc1867_post_handler)650 SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */
651 {
652 	char *boundary, *s = NULL, *boundary_end = NULL, *start_arr = NULL, *array_index = NULL;
653 	char *lbuf = NULL, *abuf = NULL;
654 	zend_string *temp_filename = NULL;
655 	int boundary_len = 0, cancel_upload = 0, is_arr_upload = 0;
656 	size_t array_len = 0;
657 	int64_t total_bytes = 0, max_file_size = 0;
658 	int skip_upload = 0, anonymous_index = 0;
659 	HashTable *uploaded_files = NULL;
660 	multipart_buffer *mbuff;
661 	zval *array_ptr = (zval *) arg;
662 	int fd = -1;
663 	zend_llist header;
664 	void *event_extra_data = NULL;
665 	unsigned int llen = 0;
666 	int upload_cnt = INI_INT("max_file_uploads");
667 	int body_parts_cnt = INI_INT("max_multipart_body_parts");
668 	const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding();
669 	php_rfc1867_getword_t getword;
670 	php_rfc1867_getword_conf_t getword_conf;
671 	php_rfc1867_basename_t _basename;
672 	zend_long count = 0;
673 
674 	if (php_rfc1867_encoding_translation() && internal_encoding) {
675 		getword = php_rfc1867_getword;
676 		getword_conf = php_rfc1867_getword_conf;
677 		_basename = php_rfc1867_basename;
678 	} else {
679 		getword = php_ap_getword;
680 		getword_conf = php_ap_getword_conf;
681 		_basename = php_ap_basename;
682 	}
683 
684 	if (SG(post_max_size) > 0 && SG(request_info).content_length > SG(post_max_size)) {
685 		sapi_module.sapi_error(E_WARNING, "POST Content-Length of " ZEND_LONG_FMT " bytes exceeds the limit of " ZEND_LONG_FMT " bytes", SG(request_info).content_length, SG(post_max_size));
686 		return;
687 	}
688 
689 	if (body_parts_cnt < 0) {
690 		body_parts_cnt = PG(max_input_vars) + upload_cnt;
691 	}
692 	int body_parts_limit = body_parts_cnt;
693 
694 	/* Get the boundary */
695 	boundary = strstr(content_type_dup, "boundary");
696 	if (!boundary) {
697 		int content_type_len = (int)strlen(content_type_dup);
698 		char *content_type_lcase = estrndup(content_type_dup, content_type_len);
699 
700 		zend_str_tolower(content_type_lcase, content_type_len);
701 		boundary = strstr(content_type_lcase, "boundary");
702 		if (boundary) {
703 			boundary = content_type_dup + (boundary - content_type_lcase);
704 		}
705 		efree(content_type_lcase);
706 	}
707 
708 	if (!boundary || !(boundary = strchr(boundary, '='))) {
709 		sapi_module.sapi_error(E_WARNING, "Missing boundary in multipart/form-data POST data");
710 		return;
711 	}
712 
713 	boundary++;
714 	boundary_len = (int)strlen(boundary);
715 
716 	if (boundary[0] == '"') {
717 		boundary++;
718 		boundary_end = strchr(boundary, '"');
719 		if (!boundary_end) {
720 			sapi_module.sapi_error(E_WARNING, "Invalid boundary in multipart/form-data POST data");
721 			return;
722 		}
723 	} else {
724 		/* search for the end of the boundary */
725 		boundary_end = strpbrk(boundary, ",;");
726 	}
727 	if (boundary_end) {
728 		boundary_end[0] = '\0';
729 		boundary_len = boundary_end-boundary;
730 	}
731 
732 	/* Initialize the buffer */
733 	if (!(mbuff = multipart_buffer_new(boundary, boundary_len))) {
734 		sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer");
735 		return;
736 	}
737 
738 	/* Initialize $_FILES[] */
739 	zend_hash_init(&PG(rfc1867_protected_variables), 8, NULL, NULL, 0);
740 
741 	ALLOC_HASHTABLE(uploaded_files);
742 	zend_hash_init(uploaded_files, 8, NULL, free_filename, 0);
743 	SG(rfc1867_uploaded_files) = uploaded_files;
744 
745 	if (Z_TYPE(PG(http_globals)[TRACK_VARS_FILES]) != IS_ARRAY) {
746 		/* php_auto_globals_create_files() might have already done that */
747 		array_init(&PG(http_globals)[TRACK_VARS_FILES]);
748 	}
749 
750 	zend_llist_init(&header, sizeof(mime_header_entry), (llist_dtor_func_t) php_free_hdr_entry, 0);
751 
752 	if (php_rfc1867_callback != NULL) {
753 		multipart_event_start event_start;
754 
755 		event_start.content_length = SG(request_info).content_length;
756 		if (php_rfc1867_callback(MULTIPART_EVENT_START, &event_start, &event_extra_data) == FAILURE) {
757 			goto fileupload_done;
758 		}
759 	}
760 
761 	while (!multipart_buffer_eof(mbuff))
762 	{
763 		char buff[FILLUNIT];
764 		char *cd = NULL, *param = NULL, *filename = NULL, *tmp = NULL;
765 		size_t blen = 0, wlen = 0;
766 		zend_off_t offset;
767 
768 		zend_llist_clean(&header);
769 
770 		if (!multipart_buffer_headers(mbuff, &header)) {
771 			goto fileupload_done;
772 		}
773 
774 		if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) {
775 			char *pair = NULL;
776 			int end = 0;
777 
778 			if (--body_parts_cnt < 0) {
779 				php_error_docref(NULL, E_WARNING, "Multipart body parts limit exceeded %d. To increase the limit change max_multipart_body_parts in php.ini.", body_parts_limit);
780 				goto fileupload_done;
781 			}
782 
783 			while (isspace(*cd)) {
784 				++cd;
785 			}
786 
787 			while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';')))
788 			{
789 				char *key = NULL, *word = pair;
790 
791 				while (isspace(*cd)) {
792 					++cd;
793 				}
794 
795 				if (strchr(pair, '=')) {
796 					key = getword(mbuff->input_encoding, &pair, '=');
797 
798 					if (!strcasecmp(key, "name")) {
799 						if (param) {
800 							efree(param);
801 						}
802 						param = getword_conf(mbuff->input_encoding, pair);
803 						if (mbuff->input_encoding && internal_encoding) {
804 							unsigned char *new_param;
805 							size_t new_param_len;
806 							if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding)) {
807 								efree(param);
808 								param = (char *)new_param;
809 							}
810 						}
811 					} else if (!strcasecmp(key, "filename")) {
812 						if (filename) {
813 							efree(filename);
814 						}
815 						filename = getword_conf(mbuff->input_encoding, pair);
816 						if (mbuff->input_encoding && internal_encoding) {
817 							unsigned char *new_filename;
818 							size_t new_filename_len;
819 							if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff->input_encoding)) {
820 								efree(filename);
821 								filename = (char *)new_filename;
822 							}
823 						}
824 					}
825 				}
826 				if (key) {
827 					efree(key);
828 				}
829 				efree(word);
830 			}
831 
832 			/* Normal form variable, safe to read all data into memory */
833 			if (!filename && param) {
834 				size_t value_len;
835 				char *value = multipart_buffer_read_body(mbuff, &value_len);
836 				size_t new_val_len; /* Dummy variable */
837 
838 				if (!value) {
839 					value = estrdup("");
840 					value_len = 0;
841 				}
842 
843 				if (mbuff->input_encoding && internal_encoding) {
844 					unsigned char *new_value;
845 					size_t new_value_len;
846 					if ((size_t)-1 != zend_multibyte_encoding_converter(&new_value, &new_value_len, (unsigned char *)value, value_len, internal_encoding, mbuff->input_encoding)) {
847 						efree(value);
848 						value = (char *)new_value;
849 						value_len = new_value_len;
850 					}
851 				}
852 
853 				if (++count <= PG(max_input_vars) && sapi_module.input_filter(PARSE_POST, param, &value, value_len, &new_val_len)) {
854 					if (php_rfc1867_callback != NULL) {
855 						multipart_event_formdata event_formdata;
856 						size_t newlength = new_val_len;
857 
858 						event_formdata.post_bytes_processed = SG(read_post_bytes);
859 						event_formdata.name = param;
860 						event_formdata.value = &value;
861 						event_formdata.length = new_val_len;
862 						event_formdata.newlength = &newlength;
863 						if (php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data) == FAILURE) {
864 							efree(param);
865 							efree(value);
866 							continue;
867 						}
868 						new_val_len = newlength;
869 					}
870 					safe_php_register_variable(param, value, new_val_len, array_ptr, 0);
871 				} else {
872 					if (count == PG(max_input_vars) + 1) {
873 						php_error_docref(NULL, E_WARNING, "Input variables exceeded " ZEND_LONG_FMT ". To increase the limit change max_input_vars in php.ini.", PG(max_input_vars));
874 					}
875 
876 					if (php_rfc1867_callback != NULL) {
877 						multipart_event_formdata event_formdata;
878 
879 						event_formdata.post_bytes_processed = SG(read_post_bytes);
880 						event_formdata.name = param;
881 						event_formdata.value = &value;
882 						event_formdata.length = value_len;
883 						event_formdata.newlength = NULL;
884 						php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data);
885 					}
886 				}
887 
888 				if (!strcasecmp(param, "MAX_FILE_SIZE")) {
889 					max_file_size = strtoll(value, NULL, 10);
890 				}
891 
892 				efree(param);
893 				efree(value);
894 				continue;
895 			}
896 
897 			/* If file_uploads=off, skip the file part */
898 			if (!PG(file_uploads)) {
899 				skip_upload = 1;
900 			} else if (upload_cnt <= 0) {
901 				skip_upload = 1;
902 				if (upload_cnt == 0) {
903 					--upload_cnt;
904 					sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded");
905 				}
906 			}
907 
908 			/* Return with an error if the posted data is garbled */
909 			if (!param && !filename) {
910 				sapi_module.sapi_error(E_WARNING, "File Upload Mime headers garbled");
911 				goto fileupload_done;
912 			}
913 
914 			if (!param) {
915 				param = emalloc(MAX_SIZE_ANONNAME);
916 				snprintf(param, MAX_SIZE_ANONNAME, "%u", anonymous_index++);
917 			}
918 
919 			/* New Rule: never repair potential malicious user input */
920 			if (!skip_upload) {
921 				long c = 0;
922 				tmp = param;
923 
924 				while (*tmp) {
925 					if (*tmp == '[') {
926 						c++;
927 					} else if (*tmp == ']') {
928 						c--;
929 						if (tmp[1] && tmp[1] != '[') {
930 							skip_upload = 1;
931 							break;
932 						}
933 					}
934 					if (c < 0) {
935 						skip_upload = 1;
936 						break;
937 					}
938 					tmp++;
939 				}
940 				/* Brackets should always be closed */
941 				if(c != 0) {
942 					skip_upload = 1;
943 				}
944 			}
945 
946 			total_bytes = cancel_upload = 0;
947 			temp_filename = NULL;
948 			fd = -1;
949 
950 			if (!skip_upload && php_rfc1867_callback != NULL) {
951 				multipart_event_file_start event_file_start;
952 
953 				event_file_start.post_bytes_processed = SG(read_post_bytes);
954 				event_file_start.name = param;
955 				event_file_start.filename = &filename;
956 				if (php_rfc1867_callback(MULTIPART_EVENT_FILE_START, &event_file_start, &event_extra_data) == FAILURE) {
957 					temp_filename = NULL;
958 					efree(param);
959 					efree(filename);
960 					continue;
961 				}
962 			}
963 
964 			if (skip_upload) {
965 				efree(param);
966 				efree(filename);
967 				continue;
968 			}
969 
970 			if (filename[0] == '\0') {
971 #if DEBUG_FILE_UPLOAD
972 				sapi_module.sapi_error(E_NOTICE, "No file uploaded");
973 #endif
974 				cancel_upload = PHP_UPLOAD_ERROR_D;
975 			}
976 
977 			offset = 0;
978 			end = 0;
979 
980 			if (!cancel_upload) {
981 				/* only bother to open temp file if we have data */
982 				blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
983 #if DEBUG_FILE_UPLOAD
984 				if (blen > 0) {
985 #else
986 				/* in non-debug mode we have no problem with 0-length files */
987 				{
988 #endif
989 					fd = php_open_temporary_fd_ex(PG(upload_tmp_dir), "php", &temp_filename, PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK);
990 					upload_cnt--;
991 					if (fd == -1) {
992 						sapi_module.sapi_error(E_WARNING, "File upload error - unable to create a temporary file");
993 						cancel_upload = PHP_UPLOAD_ERROR_E;
994 					}
995 				}
996 			}
997 
998 			while (!cancel_upload && (blen > 0))
999 			{
1000 				if (php_rfc1867_callback != NULL) {
1001 					multipart_event_file_data event_file_data;
1002 
1003 					event_file_data.post_bytes_processed = SG(read_post_bytes);
1004 					event_file_data.offset = offset;
1005 					event_file_data.data = buff;
1006 					event_file_data.length = blen;
1007 					event_file_data.newlength = &blen;
1008 					if (php_rfc1867_callback(MULTIPART_EVENT_FILE_DATA, &event_file_data, &event_extra_data) == FAILURE) {
1009 						cancel_upload = PHP_UPLOAD_ERROR_X;
1010 						continue;
1011 					}
1012 				}
1013 
1014 				if (PG(upload_max_filesize) > 0 && (zend_long)(total_bytes+blen) > PG(upload_max_filesize)) {
1015 #if DEBUG_FILE_UPLOAD
1016 					sapi_module.sapi_error(E_NOTICE, "upload_max_filesize of " ZEND_LONG_FMT " bytes exceeded - file [%s=%s] not saved", PG(upload_max_filesize), param, filename);
1017 #endif
1018 					cancel_upload = PHP_UPLOAD_ERROR_A;
1019 				} else if (max_file_size && ((zend_long)(total_bytes+blen) > max_file_size)) {
1020 #if DEBUG_FILE_UPLOAD
1021 					sapi_module.sapi_error(E_NOTICE, "MAX_FILE_SIZE of %" PRId64 " bytes exceeded - file [%s=%s] not saved", max_file_size, param, filename);
1022 #endif
1023 					cancel_upload = PHP_UPLOAD_ERROR_B;
1024 				} else if (blen > 0) {
1025 #ifdef PHP_WIN32
1026 					wlen = write(fd, buff, (unsigned int)blen);
1027 #else
1028 					wlen = write(fd, buff, blen);
1029 #endif
1030 
1031 					if (wlen == (size_t)-1) {
1032 						/* write failed */
1033 #if DEBUG_FILE_UPLOAD
1034 						sapi_module.sapi_error(E_NOTICE, "write() failed - %s", strerror(errno));
1035 #endif
1036 						cancel_upload = PHP_UPLOAD_ERROR_F;
1037 					} else if (wlen < blen) {
1038 #if DEBUG_FILE_UPLOAD
1039 						sapi_module.sapi_error(E_NOTICE, "Only %zd bytes were written, expected to write %zd", wlen, blen);
1040 #endif
1041 						cancel_upload = PHP_UPLOAD_ERROR_F;
1042 					} else {
1043 						total_bytes += wlen;
1044 					}
1045 					offset += wlen;
1046 				}
1047 
1048 				/* read data for next iteration */
1049 				blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
1050 			}
1051 
1052 			if (fd != -1) { /* may not be initialized if file could not be created */
1053 				close(fd);
1054 			}
1055 
1056 			if (!cancel_upload && !end) {
1057 #if DEBUG_FILE_UPLOAD
1058 				sapi_module.sapi_error(E_NOTICE, "Missing mime boundary at the end of the data for file %s", filename[0] != '\0' ? filename : "");
1059 #endif
1060 				cancel_upload = PHP_UPLOAD_ERROR_C;
1061 			}
1062 #if DEBUG_FILE_UPLOAD
1063 			if (filename[0] != '\0' && total_bytes == 0 && !cancel_upload) {
1064 				sapi_module.sapi_error(E_WARNING, "Uploaded file size 0 - file [%s=%s] not saved", param, filename);
1065 				cancel_upload = 5;
1066 			}
1067 #endif
1068 			if (php_rfc1867_callback != NULL) {
1069 				multipart_event_file_end event_file_end;
1070 
1071 				event_file_end.post_bytes_processed = SG(read_post_bytes);
1072 				event_file_end.temp_filename = temp_filename ? ZSTR_VAL(temp_filename) : NULL;
1073 				event_file_end.cancel_upload = cancel_upload;
1074 				if (php_rfc1867_callback(MULTIPART_EVENT_FILE_END, &event_file_end, &event_extra_data) == FAILURE) {
1075 					cancel_upload = PHP_UPLOAD_ERROR_X;
1076 				}
1077 			}
1078 
1079 			if (cancel_upload) {
1080 				if (temp_filename) {
1081 					if (cancel_upload != PHP_UPLOAD_ERROR_E) { /* file creation failed */
1082 						unlink(ZSTR_VAL(temp_filename));
1083 					}
1084 					zend_string_release_ex(temp_filename, 0);
1085 				}
1086 				temp_filename = NULL;
1087 			} else {
1088 				zend_hash_add_ptr(SG(rfc1867_uploaded_files), temp_filename, temp_filename);
1089 			}
1090 
1091 			/* is_arr_upload is true when name of file upload field
1092 			 * ends in [.*]
1093 			 * start_arr is set to point to 1st [ */
1094 			is_arr_upload =	(start_arr = strchr(param,'[')) && (param[strlen(param)-1] == ']');
1095 
1096 			if (is_arr_upload) {
1097 				array_len = strlen(start_arr);
1098 				if (array_index) {
1099 					efree(array_index);
1100 				}
1101 				array_index = estrndup(start_arr + 1, array_len - 2);
1102 			}
1103 
1104 			/* Add $foo_name */
1105 			if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) {
1106 				llen = (int)strlen(param);
1107 				lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1);
1108 				llen += MAX_SIZE_OF_INDEX + 1;
1109 			}
1110 
1111 			if (is_arr_upload) {
1112 				if (abuf) efree(abuf);
1113 				abuf = estrndup(param, strlen(param)-array_len);
1114 				snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index);
1115 			} else {
1116 				snprintf(lbuf, llen, "%s_name", param);
1117 			}
1118 
1119 			/* Pursuant to RFC 7578, strip any path components in the
1120 			 * user-supplied file name:
1121 			 *  > If a "filename" parameter is supplied ... do not use
1122 			 *  > directory path information that may be present."
1123 			 */
1124 			s = _basename(internal_encoding, filename);
1125 			if (!s) {
1126 				s = filename;
1127 			}
1128 
1129 			/* Add $foo[name] */
1130 			if (is_arr_upload) {
1131 				snprintf(lbuf, llen, "%s[name][%s]", abuf, array_index);
1132 			} else {
1133 				snprintf(lbuf, llen, "%s[name]", param);
1134 			}
1135 			register_http_post_files_variable(lbuf, s, &PG(http_globals)[TRACK_VARS_FILES], 0);
1136 			s = NULL;
1137 
1138 			/* Add full path of supplied file for folder uploads via
1139 			 * <input type="file" name="files" multiple webkitdirectory>
1140 			 */
1141 			/* Add $foo[full_path] */
1142 			if (is_arr_upload) {
1143 				snprintf(lbuf, llen, "%s[full_path][%s]", abuf, array_index);
1144 			} else {
1145 				snprintf(lbuf, llen, "%s[full_path]", param);
1146 			}
1147 			register_http_post_files_variable(lbuf, filename, &PG(http_globals)[TRACK_VARS_FILES], 0);
1148 			efree(filename);
1149 
1150 			/* Possible Content-Type: */
1151 			if (cancel_upload || !(cd = php_mime_get_hdr_value(header, "Content-Type"))) {
1152 				cd = "";
1153 			} else {
1154 				/* fix for Opera 6.01 */
1155 				s = strchr(cd, ';');
1156 				if (s != NULL) {
1157 					*s = '\0';
1158 				}
1159 			}
1160 
1161 			/* Add $foo[type] */
1162 			if (is_arr_upload) {
1163 				snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index);
1164 			} else {
1165 				snprintf(lbuf, llen, "%s[type]", param);
1166 			}
1167 			register_http_post_files_variable(lbuf, cd, &PG(http_globals)[TRACK_VARS_FILES], 0);
1168 
1169 			/* Restore Content-Type Header */
1170 			if (s != NULL) {
1171 				*s = ';';
1172 			}
1173 			s = "";
1174 
1175 			{
1176 				/* store temp_filename as-is (in case upload_tmp_dir
1177 				 * contains escapable characters. escape only the variable name.) */
1178 				zval zfilename;
1179 
1180 				/* Initialize variables */
1181 				add_protected_variable(param);
1182 
1183 				/* Add $foo[tmp_name] */
1184 				if (is_arr_upload) {
1185 					snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index);
1186 				} else {
1187 					snprintf(lbuf, llen, "%s[tmp_name]", param);
1188 				}
1189 				add_protected_variable(lbuf);
1190 				if (temp_filename) {
1191 					ZVAL_STR_COPY(&zfilename, temp_filename);
1192 				} else {
1193 					ZVAL_EMPTY_STRING(&zfilename);
1194 				}
1195 				register_http_post_files_variable_ex(lbuf, &zfilename, &PG(http_globals)[TRACK_VARS_FILES], 1);
1196 			}
1197 
1198 			{
1199 				zval file_size, error_type;
1200 				int size_overflow = 0;
1201 				char file_size_buf[65];
1202 
1203 				ZVAL_LONG(&error_type, cancel_upload);
1204 
1205 				/* Add $foo[error] */
1206 				if (cancel_upload) {
1207 					ZVAL_LONG(&file_size, 0);
1208 				} else {
1209 					if (total_bytes > ZEND_LONG_MAX) {
1210 #ifdef PHP_WIN32
1211 						if (_i64toa_s(total_bytes, file_size_buf, 65, 10)) {
1212 							file_size_buf[0] = '0';
1213 							file_size_buf[1] = '\0';
1214 						}
1215 #else
1216 						{
1217 							int __len = snprintf(file_size_buf, 65, "%" PRId64, total_bytes);
1218 							file_size_buf[__len] = '\0';
1219 						}
1220 #endif
1221 						size_overflow = 1;
1222 
1223 					} else {
1224 						ZVAL_LONG(&file_size, total_bytes);
1225 					}
1226 				}
1227 
1228 				if (is_arr_upload) {
1229 					snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index);
1230 				} else {
1231 					snprintf(lbuf, llen, "%s[error]", param);
1232 				}
1233 				register_http_post_files_variable_ex(lbuf, &error_type, &PG(http_globals)[TRACK_VARS_FILES], 0);
1234 
1235 				/* Add $foo[size] */
1236 				if (is_arr_upload) {
1237 					snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index);
1238 				} else {
1239 					snprintf(lbuf, llen, "%s[size]", param);
1240 				}
1241 				if (size_overflow) {
1242 					ZVAL_STRING(&file_size, file_size_buf);
1243 				}
1244 				register_http_post_files_variable_ex(lbuf, &file_size, &PG(http_globals)[TRACK_VARS_FILES], size_overflow);
1245 			}
1246 			efree(param);
1247 		}
1248 	}
1249 
1250 fileupload_done:
1251 	if (php_rfc1867_callback != NULL) {
1252 		multipart_event_end event_end;
1253 
1254 		event_end.post_bytes_processed = SG(read_post_bytes);
1255 		php_rfc1867_callback(MULTIPART_EVENT_END, &event_end, &event_extra_data);
1256 	}
1257 
1258 	if (lbuf) efree(lbuf);
1259 	if (abuf) efree(abuf);
1260 	if (array_index) efree(array_index);
1261 	zend_hash_destroy(&PG(rfc1867_protected_variables));
1262 	zend_llist_destroy(&header);
1263 	if (mbuff->boundary_next) efree(mbuff->boundary_next);
1264 	if (mbuff->boundary) efree(mbuff->boundary);
1265 	if (mbuff->buffer) efree(mbuff->buffer);
1266 	if (mbuff) efree(mbuff);
1267 }
1268 /* }}} */
1269 
1270 SAPI_API void php_rfc1867_set_multibyte_callbacks(
1271 					php_rfc1867_encoding_translation_t encoding_translation,
1272 					php_rfc1867_get_detect_order_t get_detect_order,
1273 					php_rfc1867_set_input_encoding_t set_input_encoding,
1274 					php_rfc1867_getword_t getword,
1275 					php_rfc1867_getword_conf_t getword_conf,
1276 					php_rfc1867_basename_t basename) /* {{{ */
1277 {
1278 	php_rfc1867_encoding_translation = encoding_translation;
1279 	php_rfc1867_get_detect_order = get_detect_order;
1280 	php_rfc1867_set_input_encoding = set_input_encoding;
1281 	php_rfc1867_getword = getword;
1282 	php_rfc1867_getword_conf = getword_conf;
1283 	php_rfc1867_basename = basename;
1284 }
1285 /* }}} */
1286