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