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