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