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