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 }
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 bool throw_exceptions = SG(request_parse_body_context).throw_exceptions;
663 int fd = -1;
664 zend_llist header;
665 void *event_extra_data = NULL;
666 unsigned int llen = 0;
667 zend_long upload_cnt = REQUEST_PARSE_BODY_OPTION_GET(max_file_uploads, INI_INT("max_file_uploads"));
668 zend_long body_parts_cnt = REQUEST_PARSE_BODY_OPTION_GET(max_multipart_body_parts, INI_INT("max_multipart_body_parts"));
669 zend_long post_max_size = REQUEST_PARSE_BODY_OPTION_GET(post_max_size, SG(post_max_size));
670 zend_long max_input_vars = REQUEST_PARSE_BODY_OPTION_GET(max_input_vars, PG(max_input_vars));
671 zend_long upload_max_filesize = REQUEST_PARSE_BODY_OPTION_GET(upload_max_filesize, PG(upload_max_filesize));
672 const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding();
673 php_rfc1867_getword_t getword;
674 php_rfc1867_getword_conf_t getword_conf;
675 php_rfc1867_basename_t _basename;
676 zend_long count = 0;
677
678 #define EMIT_WARNING_OR_ERROR(...) do { \
679 if (throw_exceptions) { \
680 zend_throw_exception_ex(zend_ce_request_parse_body_exception, 0, __VA_ARGS__); \
681 } else { \
682 php_error_docref(NULL, E_WARNING, __VA_ARGS__); \
683 } \
684 } while (0)
685
686 if (php_rfc1867_encoding_translation() && internal_encoding) {
687 getword = php_rfc1867_getword;
688 getword_conf = php_rfc1867_getword_conf;
689 _basename = php_rfc1867_basename;
690 } else {
691 getword = php_ap_getword;
692 getword_conf = php_ap_getword_conf;
693 _basename = php_ap_basename;
694 }
695
696 if (post_max_size > 0 && SG(request_info).content_length > post_max_size) {
697 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);
698 return;
699 }
700
701 if (body_parts_cnt < 0) {
702 body_parts_cnt = max_input_vars + upload_cnt;
703 }
704 int body_parts_limit = body_parts_cnt;
705
706 /* Get the boundary */
707 boundary = strstr(content_type_dup, "boundary");
708 if (!boundary) {
709 int content_type_len = (int)strlen(content_type_dup);
710 char *content_type_lcase = estrndup(content_type_dup, content_type_len);
711
712 zend_str_tolower(content_type_lcase, content_type_len);
713 boundary = strstr(content_type_lcase, "boundary");
714 if (boundary) {
715 boundary = content_type_dup + (boundary - content_type_lcase);
716 }
717 efree(content_type_lcase);
718 }
719
720 if (!boundary || !(boundary = strchr(boundary, '='))) {
721 EMIT_WARNING_OR_ERROR("Missing boundary in multipart/form-data POST data");
722 return;
723 }
724
725 boundary++;
726 boundary_len = (int)strlen(boundary);
727
728 if (boundary[0] == '"') {
729 boundary++;
730 boundary_end = strchr(boundary, '"');
731 if (!boundary_end) {
732 EMIT_WARNING_OR_ERROR("Invalid boundary in multipart/form-data POST data");
733 return;
734 }
735 } else {
736 /* search for the end of the boundary */
737 boundary_end = strpbrk(boundary, ",;");
738 }
739 if (boundary_end) {
740 boundary_end[0] = '\0';
741 boundary_len = boundary_end-boundary;
742 }
743
744 /* Initialize the buffer */
745 mbuff = multipart_buffer_new(boundary, boundary_len);
746
747 /* Initialize $_FILES[] */
748 zend_hash_init(&PG(rfc1867_protected_variables), 8, NULL, NULL, 0);
749
750 ALLOC_HASHTABLE(uploaded_files);
751 zend_hash_init(uploaded_files, 8, NULL, free_filename, 0);
752 SG(rfc1867_uploaded_files) = uploaded_files;
753
754 if (Z_TYPE(PG(http_globals)[TRACK_VARS_FILES]) != IS_ARRAY) {
755 /* php_auto_globals_create_files() might have already done that */
756 array_init(&PG(http_globals)[TRACK_VARS_FILES]);
757 }
758
759 zend_llist_init(&header, sizeof(mime_header_entry), (llist_dtor_func_t) php_free_hdr_entry, 0);
760
761 if (php_rfc1867_callback != NULL) {
762 multipart_event_start event_start;
763
764 event_start.content_length = SG(request_info).content_length;
765 if (php_rfc1867_callback(MULTIPART_EVENT_START, &event_start, &event_extra_data) == FAILURE) {
766 goto fileupload_done;
767 }
768 }
769
770 while (!multipart_buffer_eof(mbuff))
771 {
772 char buff[FILLUNIT];
773 char *cd = NULL, *param = NULL, *filename = NULL, *tmp = NULL;
774 size_t blen = 0, wlen = 0;
775 zend_off_t offset;
776
777 zend_llist_clean(&header);
778
779 if (!multipart_buffer_headers(mbuff, &header)) {
780 goto fileupload_done;
781 }
782
783 if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) {
784 char *pair = NULL;
785 int end = 0;
786
787 if (--body_parts_cnt < 0) {
788 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);
789 goto fileupload_done;
790 }
791
792 while (isspace(*cd)) {
793 ++cd;
794 }
795
796 while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';')))
797 {
798 char *key = NULL, *word = pair;
799
800 while (isspace(*cd)) {
801 ++cd;
802 }
803
804 if (strchr(pair, '=')) {
805 key = getword(mbuff->input_encoding, &pair, '=');
806
807 if (!strcasecmp(key, "name")) {
808 if (param) {
809 efree(param);
810 }
811 param = getword_conf(mbuff->input_encoding, pair);
812 if (mbuff->input_encoding && internal_encoding) {
813 unsigned char *new_param;
814 size_t new_param_len;
815 if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding)) {
816 efree(param);
817 param = (char *)new_param;
818 }
819 }
820 } else if (!strcasecmp(key, "filename")) {
821 if (filename) {
822 efree(filename);
823 }
824 filename = getword_conf(mbuff->input_encoding, pair);
825 if (mbuff->input_encoding && internal_encoding) {
826 unsigned char *new_filename;
827 size_t new_filename_len;
828 if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff->input_encoding)) {
829 efree(filename);
830 filename = (char *)new_filename;
831 }
832 }
833 }
834 }
835 if (key) {
836 efree(key);
837 }
838 efree(word);
839 }
840
841 /* Normal form variable, safe to read all data into memory */
842 if (!filename && param) {
843 size_t value_len;
844 char *value = multipart_buffer_read_body(mbuff, &value_len);
845 size_t new_val_len; /* Dummy variable */
846
847 if (!value) {
848 value = estrdup("");
849 value_len = 0;
850 }
851
852 if (mbuff->input_encoding && internal_encoding) {
853 unsigned char *new_value;
854 size_t new_value_len;
855 if ((size_t)-1 != zend_multibyte_encoding_converter(&new_value, &new_value_len, (unsigned char *)value, value_len, internal_encoding, mbuff->input_encoding)) {
856 efree(value);
857 value = (char *)new_value;
858 value_len = new_value_len;
859 }
860 }
861
862 if (++count <= max_input_vars && sapi_module.input_filter(PARSE_POST, param, &value, value_len, &new_val_len)) {
863 if (php_rfc1867_callback != NULL) {
864 multipart_event_formdata event_formdata;
865 size_t newlength = new_val_len;
866
867 event_formdata.post_bytes_processed = SG(read_post_bytes);
868 event_formdata.name = param;
869 event_formdata.value = &value;
870 event_formdata.length = new_val_len;
871 event_formdata.newlength = &newlength;
872 if (php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data) == FAILURE) {
873 efree(param);
874 efree(value);
875 continue;
876 }
877 new_val_len = newlength;
878 }
879 safe_php_register_variable(param, value, new_val_len, array_ptr, 0);
880 } else {
881 if (count == max_input_vars + 1) {
882 EMIT_WARNING_OR_ERROR("Input variables exceeded " ZEND_LONG_FMT ". To increase the limit change max_input_vars in php.ini.", max_input_vars);
883 }
884
885 if (php_rfc1867_callback != NULL) {
886 multipart_event_formdata event_formdata;
887
888 event_formdata.post_bytes_processed = SG(read_post_bytes);
889 event_formdata.name = param;
890 event_formdata.value = &value;
891 event_formdata.length = value_len;
892 event_formdata.newlength = NULL;
893 php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data);
894 }
895 }
896
897 if (!strcasecmp(param, "MAX_FILE_SIZE")) {
898 max_file_size = strtoll(value, NULL, 10);
899 }
900
901 efree(param);
902 efree(value);
903 continue;
904 }
905
906 /* If file_uploads=off, skip the file part */
907 if (!PG(file_uploads)) {
908 skip_upload = 1;
909 } else if (upload_cnt <= 0) {
910 skip_upload = 1;
911 if (upload_cnt == 0) {
912 --upload_cnt;
913 EMIT_WARNING_OR_ERROR("Maximum number of allowable file uploads has been exceeded");
914 }
915 }
916
917 /* Return with an error if the posted data is garbled */
918 if (!param && !filename) {
919 EMIT_WARNING_OR_ERROR("File Upload Mime headers garbled");
920 goto fileupload_done;
921 }
922
923 if (!param) {
924 param = emalloc(MAX_SIZE_ANONNAME);
925 snprintf(param, MAX_SIZE_ANONNAME, "%u", anonymous_index++);
926 }
927
928 /* New Rule: never repair potential malicious user input */
929 if (!skip_upload) {
930 long c = 0;
931 tmp = param;
932
933 while (*tmp) {
934 if (*tmp == '[') {
935 c++;
936 } else if (*tmp == ']') {
937 c--;
938 if (tmp[1] && tmp[1] != '[') {
939 skip_upload = 1;
940 break;
941 }
942 }
943 if (c < 0) {
944 skip_upload = 1;
945 break;
946 }
947 tmp++;
948 }
949 /* Brackets should always be closed */
950 if(c != 0) {
951 skip_upload = 1;
952 }
953 }
954
955 total_bytes = cancel_upload = 0;
956 temp_filename = NULL;
957 fd = -1;
958
959 if (!skip_upload && php_rfc1867_callback != NULL) {
960 multipart_event_file_start event_file_start;
961
962 event_file_start.post_bytes_processed = SG(read_post_bytes);
963 event_file_start.name = param;
964 event_file_start.filename = &filename;
965 if (php_rfc1867_callback(MULTIPART_EVENT_FILE_START, &event_file_start, &event_extra_data) == FAILURE) {
966 temp_filename = NULL;
967 efree(param);
968 efree(filename);
969 continue;
970 }
971 }
972
973 if (skip_upload) {
974 efree(param);
975 efree(filename);
976 continue;
977 }
978
979 if (filename[0] == '\0') {
980 #if DEBUG_FILE_UPLOAD
981 sapi_module.sapi_error(E_NOTICE, "No file uploaded");
982 #endif
983 cancel_upload = PHP_UPLOAD_ERROR_D;
984 }
985
986 offset = 0;
987 end = 0;
988
989 if (!cancel_upload) {
990 /* only bother to open temp file if we have data */
991 blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
992 #if DEBUG_FILE_UPLOAD
993 if (blen > 0) {
994 #else
995 /* in non-debug mode we have no problem with 0-length files */
996 {
997 #endif
998 fd = php_open_temporary_fd_ex(PG(upload_tmp_dir), "php", &temp_filename, PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK);
999 upload_cnt--;
1000 if (fd == -1) {
1001 EMIT_WARNING_OR_ERROR("File upload error - unable to create a temporary file");
1002 cancel_upload = PHP_UPLOAD_ERROR_E;
1003 }
1004 }
1005 }
1006
1007 while (!cancel_upload && (blen > 0))
1008 {
1009 if (php_rfc1867_callback != NULL) {
1010 multipart_event_file_data event_file_data;
1011
1012 event_file_data.post_bytes_processed = SG(read_post_bytes);
1013 event_file_data.offset = offset;
1014 event_file_data.data = buff;
1015 event_file_data.length = blen;
1016 event_file_data.newlength = &blen;
1017 if (php_rfc1867_callback(MULTIPART_EVENT_FILE_DATA, &event_file_data, &event_extra_data) == FAILURE) {
1018 cancel_upload = PHP_UPLOAD_ERROR_X;
1019 continue;
1020 }
1021 }
1022
1023 if (upload_max_filesize > 0 && (zend_long)(total_bytes+blen) > upload_max_filesize) {
1024 #if DEBUG_FILE_UPLOAD
1025 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);
1026 #endif
1027 cancel_upload = PHP_UPLOAD_ERROR_A;
1028 } else if (max_file_size && ((zend_long)(total_bytes+blen) > max_file_size)) {
1029 #if DEBUG_FILE_UPLOAD
1030 sapi_module.sapi_error(E_NOTICE, "MAX_FILE_SIZE of %" PRId64 " bytes exceeded - file [%s=%s] not saved", max_file_size, param, filename);
1031 #endif
1032 cancel_upload = PHP_UPLOAD_ERROR_B;
1033 } else if (blen > 0) {
1034 #ifdef PHP_WIN32
1035 wlen = write(fd, buff, (unsigned int)blen);
1036 #else
1037 wlen = write(fd, buff, blen);
1038 #endif
1039
1040 if (wlen == (size_t)-1) {
1041 /* write failed */
1042 #if DEBUG_FILE_UPLOAD
1043 sapi_module.sapi_error(E_NOTICE, "write() failed - %s", strerror(errno));
1044 #endif
1045 cancel_upload = PHP_UPLOAD_ERROR_F;
1046 } else if (wlen < blen) {
1047 #if DEBUG_FILE_UPLOAD
1048 sapi_module.sapi_error(E_NOTICE, "Only %zd bytes were written, expected to write %zd", wlen, blen);
1049 #endif
1050 cancel_upload = PHP_UPLOAD_ERROR_F;
1051 } else {
1052 total_bytes += wlen;
1053 }
1054 offset += wlen;
1055 }
1056
1057 /* read data for next iteration */
1058 blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
1059 }
1060
1061 if (fd != -1) { /* may not be initialized if file could not be created */
1062 close(fd);
1063 }
1064
1065 if (!cancel_upload && !end) {
1066 #if DEBUG_FILE_UPLOAD
1067 sapi_module.sapi_error(E_NOTICE, "Missing mime boundary at the end of the data for file %s", filename[0] != '\0' ? filename : "");
1068 #endif
1069 cancel_upload = PHP_UPLOAD_ERROR_C;
1070 }
1071 #if DEBUG_FILE_UPLOAD
1072 if (filename[0] != '\0' && total_bytes == 0 && !cancel_upload) {
1073 EMIT_WARNING_OR_ERROR("Uploaded file size 0 - file [%s=%s] not saved", param, filename);
1074 cancel_upload = 5;
1075 }
1076 #endif
1077 if (php_rfc1867_callback != NULL) {
1078 multipart_event_file_end event_file_end;
1079
1080 event_file_end.post_bytes_processed = SG(read_post_bytes);
1081 event_file_end.temp_filename = temp_filename ? ZSTR_VAL(temp_filename) : NULL;
1082 event_file_end.cancel_upload = cancel_upload;
1083 if (php_rfc1867_callback(MULTIPART_EVENT_FILE_END, &event_file_end, &event_extra_data) == FAILURE) {
1084 cancel_upload = PHP_UPLOAD_ERROR_X;
1085 }
1086 }
1087
1088 if (cancel_upload) {
1089 if (temp_filename) {
1090 if (cancel_upload != PHP_UPLOAD_ERROR_E) { /* file creation failed */
1091 unlink(ZSTR_VAL(temp_filename));
1092 }
1093 zend_string_release_ex(temp_filename, 0);
1094 }
1095 temp_filename = NULL;
1096 } else {
1097 zend_hash_add_ptr(SG(rfc1867_uploaded_files), temp_filename, temp_filename);
1098 }
1099
1100 /* is_arr_upload is true when name of file upload field
1101 * ends in [.*]
1102 * start_arr is set to point to 1st [ */
1103 is_arr_upload = (start_arr = strchr(param,'[')) && (param[strlen(param)-1] == ']');
1104
1105 if (is_arr_upload) {
1106 array_len = strlen(start_arr);
1107 if (array_index) {
1108 efree(array_index);
1109 }
1110 array_index = estrndup(start_arr + 1, array_len - 2);
1111 }
1112
1113 /* Add $foo_name */
1114 if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) {
1115 llen = (int)strlen(param);
1116 lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1);
1117 llen += MAX_SIZE_OF_INDEX + 1;
1118 }
1119
1120 if (is_arr_upload) {
1121 if (abuf) efree(abuf);
1122 abuf = estrndup(param, strlen(param)-array_len);
1123 snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index);
1124 } else {
1125 snprintf(lbuf, llen, "%s_name", param);
1126 }
1127
1128 /* Pursuant to RFC 7578, strip any path components in the
1129 * user-supplied file name:
1130 * > If a "filename" parameter is supplied ... do not use
1131 * > directory path information that may be present."
1132 */
1133 s = _basename(internal_encoding, filename);
1134 if (!s) {
1135 s = filename;
1136 }
1137
1138 /* Add $foo[name] */
1139 if (is_arr_upload) {
1140 snprintf(lbuf, llen, "%s[name][%s]", abuf, array_index);
1141 } else {
1142 snprintf(lbuf, llen, "%s[name]", param);
1143 }
1144 register_http_post_files_variable(lbuf, s, &PG(http_globals)[TRACK_VARS_FILES], 0);
1145 s = NULL;
1146
1147 /* Add full path of supplied file for folder uploads via
1148 * <input type="file" name="files" multiple webkitdirectory>
1149 */
1150 /* Add $foo[full_path] */
1151 if (is_arr_upload) {
1152 snprintf(lbuf, llen, "%s[full_path][%s]", abuf, array_index);
1153 } else {
1154 snprintf(lbuf, llen, "%s[full_path]", param);
1155 }
1156 register_http_post_files_variable(lbuf, filename, &PG(http_globals)[TRACK_VARS_FILES], 0);
1157 efree(filename);
1158
1159 /* Possible Content-Type: */
1160 if (cancel_upload || !(cd = php_mime_get_hdr_value(header, "Content-Type"))) {
1161 cd = "";
1162 } else {
1163 /* fix for Opera 6.01 */
1164 s = strchr(cd, ';');
1165 if (s != NULL) {
1166 *s = '\0';
1167 }
1168 }
1169
1170 /* Add $foo[type] */
1171 if (is_arr_upload) {
1172 snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index);
1173 } else {
1174 snprintf(lbuf, llen, "%s[type]", param);
1175 }
1176 register_http_post_files_variable(lbuf, cd, &PG(http_globals)[TRACK_VARS_FILES], 0);
1177
1178 /* Restore Content-Type Header */
1179 if (s != NULL) {
1180 *s = ';';
1181 }
1182 s = "";
1183
1184 {
1185 /* store temp_filename as-is (in case upload_tmp_dir
1186 * contains escapable characters. escape only the variable name.) */
1187 zval zfilename;
1188
1189 /* Initialize variables */
1190 add_protected_variable(param);
1191
1192 /* Add $foo[tmp_name] */
1193 if (is_arr_upload) {
1194 snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index);
1195 } else {
1196 snprintf(lbuf, llen, "%s[tmp_name]", param);
1197 }
1198 add_protected_variable(lbuf);
1199 if (temp_filename) {
1200 ZVAL_STR_COPY(&zfilename, temp_filename);
1201 } else {
1202 ZVAL_EMPTY_STRING(&zfilename);
1203 }
1204 register_http_post_files_variable_ex(lbuf, &zfilename, &PG(http_globals)[TRACK_VARS_FILES], 1);
1205 }
1206
1207 {
1208 zval file_size, error_type;
1209 int size_overflow = 0;
1210 char file_size_buf[65];
1211
1212 ZVAL_LONG(&error_type, cancel_upload);
1213
1214 /* Add $foo[error] */
1215 if (cancel_upload) {
1216 ZVAL_LONG(&file_size, 0);
1217 } else {
1218 if (total_bytes > ZEND_LONG_MAX) {
1219 #ifdef PHP_WIN32
1220 if (_i64toa_s(total_bytes, file_size_buf, 65, 10)) {
1221 file_size_buf[0] = '0';
1222 file_size_buf[1] = '\0';
1223 }
1224 #else
1225 {
1226 int __len = snprintf(file_size_buf, 65, "%" PRId64, total_bytes);
1227 file_size_buf[__len] = '\0';
1228 }
1229 #endif
1230 size_overflow = 1;
1231
1232 } else {
1233 ZVAL_LONG(&file_size, total_bytes);
1234 }
1235 }
1236
1237 if (is_arr_upload) {
1238 snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index);
1239 } else {
1240 snprintf(lbuf, llen, "%s[error]", param);
1241 }
1242 register_http_post_files_variable_ex(lbuf, &error_type, &PG(http_globals)[TRACK_VARS_FILES], 0);
1243
1244 /* Add $foo[size] */
1245 if (is_arr_upload) {
1246 snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index);
1247 } else {
1248 snprintf(lbuf, llen, "%s[size]", param);
1249 }
1250 if (size_overflow) {
1251 ZVAL_STRING(&file_size, file_size_buf);
1252 }
1253 register_http_post_files_variable_ex(lbuf, &file_size, &PG(http_globals)[TRACK_VARS_FILES], size_overflow);
1254 }
1255 efree(param);
1256 }
1257 }
1258
1259 fileupload_done:
1260 if (php_rfc1867_callback != NULL) {
1261 multipart_event_end event_end;
1262
1263 event_end.post_bytes_processed = SG(read_post_bytes);
1264 php_rfc1867_callback(MULTIPART_EVENT_END, &event_end, &event_extra_data);
1265 }
1266
1267 if (lbuf) efree(lbuf);
1268 if (abuf) efree(abuf);
1269 if (array_index) efree(array_index);
1270 zend_hash_destroy(&PG(rfc1867_protected_variables));
1271 zend_llist_destroy(&header);
1272 if (mbuff->boundary_next) efree(mbuff->boundary_next);
1273 if (mbuff->boundary) efree(mbuff->boundary);
1274 if (mbuff->buffer) efree(mbuff->buffer);
1275 if (mbuff) efree(mbuff);
1276
1277 #undef EMIT_WARNING_OR_ERROR
1278 }
1279 /* }}} */
1280
1281 SAPI_API void php_rfc1867_set_multibyte_callbacks(
1282 php_rfc1867_encoding_translation_t encoding_translation,
1283 php_rfc1867_get_detect_order_t get_detect_order,
1284 php_rfc1867_set_input_encoding_t set_input_encoding,
1285 php_rfc1867_getword_t getword,
1286 php_rfc1867_getword_conf_t getword_conf,
1287 php_rfc1867_basename_t basename) /* {{{ */
1288 {
1289 php_rfc1867_encoding_translation = encoding_translation;
1290 php_rfc1867_get_detect_order = get_detect_order;
1291 php_rfc1867_set_input_encoding = set_input_encoding;
1292 php_rfc1867_getword = getword;
1293 php_rfc1867_getword_conf = getword_conf;
1294 php_rfc1867_basename = basename;
1295 }
1296 /* }}} */
1297