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