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 | http://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 "ext/standard/php_string.h"
32 #include "zend_smart_string.h"
33
34 #ifndef DEBUG_FILE_UPLOAD
35 # define DEBUG_FILE_UPLOAD 0
36 #endif
37
dummy_encoding_translation(void)38 static int dummy_encoding_translation(void)
39 {
40 return 0;
41 }
42
43 static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop);
44 static char *php_ap_getword_conf(const zend_encoding *encoding, char *str);
45
46 static php_rfc1867_encoding_translation_t php_rfc1867_encoding_translation = dummy_encoding_translation;
47 static php_rfc1867_get_detect_order_t php_rfc1867_get_detect_order = NULL;
48 static php_rfc1867_set_input_encoding_t php_rfc1867_set_input_encoding = NULL;
49 static php_rfc1867_getword_t php_rfc1867_getword = php_ap_getword;
50 static php_rfc1867_getword_conf_t php_rfc1867_getword_conf = php_ap_getword_conf;
51 static php_rfc1867_basename_t php_rfc1867_basename = NULL;
52
53 PHPAPI int (*php_rfc1867_callback)(unsigned int event, void *event_data, void **extra) = NULL;
54
55 static void safe_php_register_variable(char *var, char *strval, size_t val_len, zval *track_vars_array, zend_bool override_protection);
56
57 /* The longest property name we use in an uploaded file array */
58 #define MAX_SIZE_OF_INDEX sizeof("[tmp_name]")
59
60 /* The longest anonymous name */
61 #define MAX_SIZE_ANONNAME 33
62
63 /* Errors */
64 #define UPLOAD_ERROR_OK 0 /* File upload successful */
65 #define UPLOAD_ERROR_A 1 /* Uploaded file exceeded upload_max_filesize */
66 #define UPLOAD_ERROR_B 2 /* Uploaded file exceeded MAX_FILE_SIZE */
67 #define UPLOAD_ERROR_C 3 /* Partially uploaded */
68 #define UPLOAD_ERROR_D 4 /* No file uploaded */
69 #define UPLOAD_ERROR_E 6 /* Missing /tmp or similar directory */
70 #define UPLOAD_ERROR_F 7 /* Failed to write file to disk */
71 #define UPLOAD_ERROR_X 8 /* File upload stopped by extension */
72
php_rfc1867_register_constants(void)73 void php_rfc1867_register_constants(void) /* {{{ */
74 {
75 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_OK", UPLOAD_ERROR_OK, CONST_CS | CONST_PERSISTENT);
76 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_INI_SIZE", UPLOAD_ERROR_A, CONST_CS | CONST_PERSISTENT);
77 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_FORM_SIZE", UPLOAD_ERROR_B, CONST_CS | CONST_PERSISTENT);
78 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_PARTIAL", UPLOAD_ERROR_C, CONST_CS | CONST_PERSISTENT);
79 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_NO_FILE", UPLOAD_ERROR_D, CONST_CS | CONST_PERSISTENT);
80 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_NO_TMP_DIR", UPLOAD_ERROR_E, CONST_CS | CONST_PERSISTENT);
81 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_CANT_WRITE", UPLOAD_ERROR_F, CONST_CS | CONST_PERSISTENT);
82 REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_EXTENSION", UPLOAD_ERROR_X, CONST_CS | CONST_PERSISTENT);
83 }
84 /* }}} */
85
normalize_protected_variable(char * varname)86 static void normalize_protected_variable(char *varname) /* {{{ */
87 {
88 char *s = varname, *index = NULL, *indexend = NULL, *p;
89
90 /* overjump leading space */
91 while (*s == ' ') {
92 s++;
93 }
94
95 /* and remove it */
96 if (s != varname) {
97 memmove(varname, s, strlen(s)+1);
98 }
99
100 for (p = varname; *p && *p != '['; p++) {
101 switch(*p) {
102 case ' ':
103 case '.':
104 *p = '_';
105 break;
106 }
107 }
108
109 /* find index */
110 index = strchr(varname, '[');
111 if (index) {
112 index++;
113 s = index;
114 } else {
115 return;
116 }
117
118 /* done? */
119 while (index) {
120 while (*index == ' ' || *index == '\r' || *index == '\n' || *index=='\t') {
121 index++;
122 }
123 indexend = strchr(index, ']');
124 indexend = indexend ? indexend + 1 : index + strlen(index);
125
126 if (s != index) {
127 memmove(s, index, strlen(index)+1);
128 s += indexend-index;
129 } else {
130 s = indexend;
131 }
132
133 if (*s == '[') {
134 s++;
135 index = s;
136 } else {
137 index = NULL;
138 }
139 }
140 *s = '\0';
141 }
142 /* }}} */
143
add_protected_variable(char * varname)144 static void add_protected_variable(char *varname) /* {{{ */
145 {
146 normalize_protected_variable(varname);
147 zend_hash_str_add_empty_element(&PG(rfc1867_protected_variables), varname, strlen(varname));
148 }
149 /* }}} */
150
is_protected_variable(char * varname)151 static zend_bool is_protected_variable(char *varname) /* {{{ */
152 {
153 normalize_protected_variable(varname);
154 return zend_hash_str_exists(&PG(rfc1867_protected_variables), varname, strlen(varname));
155 }
156 /* }}} */
157
safe_php_register_variable(char * var,char * strval,size_t val_len,zval * track_vars_array,zend_bool override_protection)158 static void safe_php_register_variable(char *var, char *strval, size_t val_len, zval *track_vars_array, zend_bool override_protection) /* {{{ */
159 {
160 if (override_protection || !is_protected_variable(var)) {
161 php_register_variable_safe(var, strval, val_len, track_vars_array);
162 }
163 }
164 /* }}} */
165
safe_php_register_variable_ex(char * var,zval * val,zval * track_vars_array,zend_bool override_protection)166 static void safe_php_register_variable_ex(char *var, zval *val, zval *track_vars_array, zend_bool override_protection) /* {{{ */
167 {
168 if (override_protection || !is_protected_variable(var)) {
169 php_register_variable_ex(var, val, track_vars_array);
170 }
171 }
172 /* }}} */
173
register_http_post_files_variable(char * strvar,char * val,zval * http_post_files,zend_bool override_protection)174 static void register_http_post_files_variable(char *strvar, char *val, zval *http_post_files, zend_bool override_protection) /* {{{ */
175 {
176 safe_php_register_variable(strvar, val, strlen(val), http_post_files, override_protection);
177 }
178 /* }}} */
179
register_http_post_files_variable_ex(char * var,zval * val,zval * http_post_files,zend_bool override_protection)180 static void register_http_post_files_variable_ex(char *var, zval *val, zval *http_post_files, zend_bool override_protection) /* {{{ */
181 {
182 safe_php_register_variable_ex(var, val, http_post_files, override_protection);
183 }
184 /* }}} */
185
free_filename(zval * el)186 static void free_filename(zval *el) {
187 zend_string *filename = Z_STR_P(el);
188 zend_string_release_ex(filename, 0);
189 }
190
destroy_uploaded_files_hash(void)191 PHPAPI void destroy_uploaded_files_hash(void) /* {{{ */
192 {
193 zval *el;
194
195 ZEND_HASH_FOREACH_VAL(SG(rfc1867_uploaded_files), el) {
196 zend_string *filename = Z_STR_P(el);
197 VCWD_UNLINK(ZSTR_VAL(filename));
198 } ZEND_HASH_FOREACH_END();
199 zend_hash_destroy(SG(rfc1867_uploaded_files));
200 FREE_HASHTABLE(SG(rfc1867_uploaded_files));
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, anonindex = 0, is_anonymous;
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 php_strtolower(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 /* Initialize the buffer */
756 if (!(mbuff = multipart_buffer_new(boundary, boundary_len))) {
757 sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer");
758 return;
759 }
760
761 /* Initialize $_FILES[] */
762 zend_hash_init(&PG(rfc1867_protected_variables), 8, NULL, NULL, 0);
763
764 ALLOC_HASHTABLE(uploaded_files);
765 zend_hash_init(uploaded_files, 8, NULL, free_filename, 0);
766 SG(rfc1867_uploaded_files) = uploaded_files;
767
768 if (Z_TYPE(PG(http_globals)[TRACK_VARS_FILES]) != IS_ARRAY) {
769 /* php_auto_globals_create_files() might have already done that */
770 array_init(&PG(http_globals)[TRACK_VARS_FILES]);
771 }
772
773 zend_llist_init(&header, sizeof(mime_header_entry), (llist_dtor_func_t) php_free_hdr_entry, 0);
774
775 if (php_rfc1867_callback != NULL) {
776 multipart_event_start event_start;
777
778 event_start.content_length = SG(request_info).content_length;
779 if (php_rfc1867_callback(MULTIPART_EVENT_START, &event_start, &event_extra_data) == FAILURE) {
780 goto fileupload_done;
781 }
782 }
783
784 while (!multipart_buffer_eof(mbuff))
785 {
786 char buff[FILLUNIT];
787 char *cd = NULL, *param = NULL, *filename = NULL, *tmp = NULL;
788 size_t blen = 0, wlen = 0;
789 zend_off_t offset;
790
791 zend_llist_clean(&header);
792
793 if (!multipart_buffer_headers(mbuff, &header)) {
794 goto fileupload_done;
795 }
796
797 if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) {
798 char *pair = NULL;
799 int end = 0;
800
801 if (--body_parts_cnt < 0) {
802 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);
803 goto fileupload_done;
804 }
805
806 while (isspace(*cd)) {
807 ++cd;
808 }
809
810 while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';')))
811 {
812 char *key = NULL, *word = pair;
813
814 while (isspace(*cd)) {
815 ++cd;
816 }
817
818 if (strchr(pair, '=')) {
819 key = getword(mbuff->input_encoding, &pair, '=');
820
821 if (!strcasecmp(key, "name")) {
822 if (param) {
823 efree(param);
824 }
825 param = getword_conf(mbuff->input_encoding, pair);
826 if (mbuff->input_encoding && internal_encoding) {
827 unsigned char *new_param;
828 size_t new_param_len;
829 if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding)) {
830 efree(param);
831 param = (char *)new_param;
832 }
833 }
834 } else if (!strcasecmp(key, "filename")) {
835 if (filename) {
836 efree(filename);
837 }
838 filename = getword_conf(mbuff->input_encoding, pair);
839 if (mbuff->input_encoding && internal_encoding) {
840 unsigned char *new_filename;
841 size_t new_filename_len;
842 if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff->input_encoding)) {
843 efree(filename);
844 filename = (char *)new_filename;
845 }
846 }
847 }
848 }
849 if (key) {
850 efree(key);
851 }
852 efree(word);
853 }
854
855 /* Normal form variable, safe to read all data into memory */
856 if (!filename && param) {
857 size_t value_len;
858 char *value = multipart_buffer_read_body(mbuff, &value_len);
859 size_t new_val_len; /* Dummy variable */
860
861 if (!value) {
862 value = estrdup("");
863 value_len = 0;
864 }
865
866 if (mbuff->input_encoding && internal_encoding) {
867 unsigned char *new_value;
868 size_t new_value_len;
869 if ((size_t)-1 != zend_multibyte_encoding_converter(&new_value, &new_value_len, (unsigned char *)value, value_len, internal_encoding, mbuff->input_encoding)) {
870 efree(value);
871 value = (char *)new_value;
872 value_len = new_value_len;
873 }
874 }
875
876 if (++count <= PG(max_input_vars) && sapi_module.input_filter(PARSE_POST, param, &value, value_len, &new_val_len)) {
877 if (php_rfc1867_callback != NULL) {
878 multipart_event_formdata event_formdata;
879 size_t newlength = new_val_len;
880
881 event_formdata.post_bytes_processed = SG(read_post_bytes);
882 event_formdata.name = param;
883 event_formdata.value = &value;
884 event_formdata.length = new_val_len;
885 event_formdata.newlength = &newlength;
886 if (php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data) == FAILURE) {
887 efree(param);
888 efree(value);
889 continue;
890 }
891 new_val_len = newlength;
892 }
893 safe_php_register_variable(param, value, new_val_len, array_ptr, 0);
894 } else {
895 if (count == PG(max_input_vars) + 1) {
896 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));
897 }
898
899 if (php_rfc1867_callback != NULL) {
900 multipart_event_formdata event_formdata;
901
902 event_formdata.post_bytes_processed = SG(read_post_bytes);
903 event_formdata.name = param;
904 event_formdata.value = &value;
905 event_formdata.length = value_len;
906 event_formdata.newlength = NULL;
907 php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data);
908 }
909 }
910
911 if (!strcasecmp(param, "MAX_FILE_SIZE")) {
912 max_file_size = strtoll(value, NULL, 10);
913 }
914
915 efree(param);
916 efree(value);
917 continue;
918 }
919
920 /* If file_uploads=off, skip the file part */
921 if (!PG(file_uploads)) {
922 skip_upload = 1;
923 } else if (upload_cnt <= 0) {
924 skip_upload = 1;
925 if (upload_cnt == 0) {
926 --upload_cnt;
927 sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded");
928 }
929 }
930
931 /* Return with an error if the posted data is garbled */
932 if (!param && !filename) {
933 sapi_module.sapi_error(E_WARNING, "File Upload Mime headers garbled");
934 goto fileupload_done;
935 }
936
937 if (!param) {
938 is_anonymous = 1;
939 param = emalloc(MAX_SIZE_ANONNAME);
940 snprintf(param, MAX_SIZE_ANONNAME, "%u", anonindex++);
941 } else {
942 is_anonymous = 0;
943 }
944
945 /* New Rule: never repair potential malicious user input */
946 if (!skip_upload) {
947 long c = 0;
948 tmp = param;
949
950 while (*tmp) {
951 if (*tmp == '[') {
952 c++;
953 } else if (*tmp == ']') {
954 c--;
955 if (tmp[1] && tmp[1] != '[') {
956 skip_upload = 1;
957 break;
958 }
959 }
960 if (c < 0) {
961 skip_upload = 1;
962 break;
963 }
964 tmp++;
965 }
966 /* Brackets should always be closed */
967 if(c != 0) {
968 skip_upload = 1;
969 }
970 }
971
972 total_bytes = cancel_upload = 0;
973 temp_filename = NULL;
974 fd = -1;
975
976 if (!skip_upload && php_rfc1867_callback != NULL) {
977 multipart_event_file_start event_file_start;
978
979 event_file_start.post_bytes_processed = SG(read_post_bytes);
980 event_file_start.name = param;
981 event_file_start.filename = &filename;
982 if (php_rfc1867_callback(MULTIPART_EVENT_FILE_START, &event_file_start, &event_extra_data) == FAILURE) {
983 temp_filename = NULL;
984 efree(param);
985 efree(filename);
986 continue;
987 }
988 }
989
990 if (skip_upload) {
991 efree(param);
992 efree(filename);
993 continue;
994 }
995
996 if (filename[0] == '\0') {
997 #if DEBUG_FILE_UPLOAD
998 sapi_module.sapi_error(E_NOTICE, "No file uploaded");
999 #endif
1000 cancel_upload = UPLOAD_ERROR_D;
1001 }
1002
1003 offset = 0;
1004 end = 0;
1005
1006 if (!cancel_upload) {
1007 /* only bother to open temp file if we have data */
1008 blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
1009 #if DEBUG_FILE_UPLOAD
1010 if (blen > 0) {
1011 #else
1012 /* in non-debug mode we have no problem with 0-length files */
1013 {
1014 #endif
1015 fd = php_open_temporary_fd_ex(PG(upload_tmp_dir), "php", &temp_filename, PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ON_FALLBACK);
1016 upload_cnt--;
1017 if (fd == -1) {
1018 sapi_module.sapi_error(E_WARNING, "File upload error - unable to create a temporary file");
1019 cancel_upload = UPLOAD_ERROR_E;
1020 }
1021 }
1022 }
1023
1024 while (!cancel_upload && (blen > 0))
1025 {
1026 if (php_rfc1867_callback != NULL) {
1027 multipart_event_file_data event_file_data;
1028
1029 event_file_data.post_bytes_processed = SG(read_post_bytes);
1030 event_file_data.offset = offset;
1031 event_file_data.data = buff;
1032 event_file_data.length = blen;
1033 event_file_data.newlength = &blen;
1034 if (php_rfc1867_callback(MULTIPART_EVENT_FILE_DATA, &event_file_data, &event_extra_data) == FAILURE) {
1035 cancel_upload = UPLOAD_ERROR_X;
1036 continue;
1037 }
1038 }
1039
1040 if (PG(upload_max_filesize) > 0 && (zend_long)(total_bytes+blen) > PG(upload_max_filesize)) {
1041 #if DEBUG_FILE_UPLOAD
1042 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);
1043 #endif
1044 cancel_upload = UPLOAD_ERROR_A;
1045 } else if (max_file_size && ((zend_long)(total_bytes+blen) > max_file_size)) {
1046 #if DEBUG_FILE_UPLOAD
1047 sapi_module.sapi_error(E_NOTICE, "MAX_FILE_SIZE of %" PRId64 " bytes exceeded - file [%s=%s] not saved", max_file_size, param, filename);
1048 #endif
1049 cancel_upload = UPLOAD_ERROR_B;
1050 } else if (blen > 0) {
1051 #ifdef PHP_WIN32
1052 wlen = write(fd, buff, (unsigned int)blen);
1053 #else
1054 wlen = write(fd, buff, blen);
1055 #endif
1056
1057 if (wlen == (size_t)-1) {
1058 /* write failed */
1059 #if DEBUG_FILE_UPLOAD
1060 sapi_module.sapi_error(E_NOTICE, "write() failed - %s", strerror(errno));
1061 #endif
1062 cancel_upload = UPLOAD_ERROR_F;
1063 } else if (wlen < blen) {
1064 #if DEBUG_FILE_UPLOAD
1065 sapi_module.sapi_error(E_NOTICE, "Only %zd bytes were written, expected to write %zd", wlen, blen);
1066 #endif
1067 cancel_upload = UPLOAD_ERROR_F;
1068 } else {
1069 total_bytes += wlen;
1070 }
1071 offset += wlen;
1072 }
1073
1074 /* read data for next iteration */
1075 blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
1076 }
1077
1078 if (fd != -1) { /* may not be initialized if file could not be created */
1079 close(fd);
1080 }
1081
1082 if (!cancel_upload && !end) {
1083 #if DEBUG_FILE_UPLOAD
1084 sapi_module.sapi_error(E_NOTICE, "Missing mime boundary at the end of the data for file %s", filename[0] != '\0' ? filename : "");
1085 #endif
1086 cancel_upload = UPLOAD_ERROR_C;
1087 }
1088 #if DEBUG_FILE_UPLOAD
1089 if (filename[0] != '\0' && total_bytes == 0 && !cancel_upload) {
1090 sapi_module.sapi_error(E_WARNING, "Uploaded file size 0 - file [%s=%s] not saved", param, filename);
1091 cancel_upload = 5;
1092 }
1093 #endif
1094 if (php_rfc1867_callback != NULL) {
1095 multipart_event_file_end event_file_end;
1096
1097 event_file_end.post_bytes_processed = SG(read_post_bytes);
1098 event_file_end.temp_filename = temp_filename ? ZSTR_VAL(temp_filename) : NULL;
1099 event_file_end.cancel_upload = cancel_upload;
1100 if (php_rfc1867_callback(MULTIPART_EVENT_FILE_END, &event_file_end, &event_extra_data) == FAILURE) {
1101 cancel_upload = UPLOAD_ERROR_X;
1102 }
1103 }
1104
1105 if (cancel_upload) {
1106 if (temp_filename) {
1107 if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */
1108 unlink(ZSTR_VAL(temp_filename));
1109 }
1110 zend_string_release_ex(temp_filename, 0);
1111 }
1112 temp_filename = NULL;
1113 } else {
1114 zend_hash_add_ptr(SG(rfc1867_uploaded_files), temp_filename, temp_filename);
1115 }
1116
1117 /* is_arr_upload is true when name of file upload field
1118 * ends in [.*]
1119 * start_arr is set to point to 1st [ */
1120 is_arr_upload = (start_arr = strchr(param,'[')) && (param[strlen(param)-1] == ']');
1121
1122 if (is_arr_upload) {
1123 array_len = strlen(start_arr);
1124 if (array_index) {
1125 efree(array_index);
1126 }
1127 array_index = estrndup(start_arr + 1, array_len - 2);
1128 }
1129
1130 /* Add $foo_name */
1131 if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) {
1132 llen = (int)strlen(param);
1133 lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1);
1134 llen += MAX_SIZE_OF_INDEX + 1;
1135 }
1136
1137 if (is_arr_upload) {
1138 if (abuf) efree(abuf);
1139 abuf = estrndup(param, strlen(param)-array_len);
1140 snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index);
1141 } else {
1142 snprintf(lbuf, llen, "%s_name", param);
1143 }
1144
1145 /* Pursuant to RFC 7578, strip any path components in the
1146 * user-supplied file name:
1147 * > If a "filename" parameter is supplied ... do not use
1148 * > directory path information that may be present."
1149 */
1150 s = _basename(internal_encoding, filename);
1151 if (!s) {
1152 s = filename;
1153 }
1154
1155 if (!is_anonymous) {
1156 safe_php_register_variable(lbuf, s, strlen(s), NULL, 0);
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 efree(filename);
1167 s = NULL;
1168
1169 /* Possible Content-Type: */
1170 if (cancel_upload || !(cd = php_mime_get_hdr_value(header, "Content-Type"))) {
1171 cd = "";
1172 } else {
1173 /* fix for Opera 6.01 */
1174 s = strchr(cd, ';');
1175 if (s != NULL) {
1176 *s = '\0';
1177 }
1178 }
1179
1180 /* Add $foo_type */
1181 if (is_arr_upload) {
1182 snprintf(lbuf, llen, "%s_type[%s]", abuf, array_index);
1183 } else {
1184 snprintf(lbuf, llen, "%s_type", param);
1185 }
1186 if (!is_anonymous) {
1187 safe_php_register_variable(lbuf, cd, strlen(cd), NULL, 0);
1188 }
1189
1190 /* Add $foo[type] */
1191 if (is_arr_upload) {
1192 snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index);
1193 } else {
1194 snprintf(lbuf, llen, "%s[type]", param);
1195 }
1196 register_http_post_files_variable(lbuf, cd, &PG(http_globals)[TRACK_VARS_FILES], 0);
1197
1198 /* Restore Content-Type Header */
1199 if (s != NULL) {
1200 *s = ';';
1201 }
1202 s = "";
1203
1204 {
1205 /* store temp_filename as-is (in case upload_tmp_dir
1206 * contains escapable characters. escape only the variable name.) */
1207 zval zfilename;
1208
1209 /* Initialize variables */
1210 add_protected_variable(param);
1211
1212 /* if param is of form xxx[.*] this will cut it to xxx */
1213 if (!is_anonymous) {
1214 if (temp_filename) {
1215 ZVAL_STR_COPY(&zfilename, temp_filename);
1216 } else {
1217 ZVAL_EMPTY_STRING(&zfilename);
1218 }
1219 safe_php_register_variable_ex(param, &zfilename, NULL, 1);
1220 }
1221
1222 /* Add $foo[tmp_name] */
1223 if (is_arr_upload) {
1224 snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index);
1225 } else {
1226 snprintf(lbuf, llen, "%s[tmp_name]", param);
1227 }
1228 add_protected_variable(lbuf);
1229 if (temp_filename) {
1230 ZVAL_STR_COPY(&zfilename, temp_filename);
1231 } else {
1232 ZVAL_EMPTY_STRING(&zfilename);
1233 }
1234 register_http_post_files_variable_ex(lbuf, &zfilename, &PG(http_globals)[TRACK_VARS_FILES], 1);
1235 }
1236
1237 {
1238 zval file_size, error_type;
1239 int size_overflow = 0;
1240 char file_size_buf[65];
1241
1242 ZVAL_LONG(&error_type, cancel_upload);
1243
1244 /* Add $foo[error] */
1245 if (cancel_upload) {
1246 ZVAL_LONG(&file_size, 0);
1247 } else {
1248 if (total_bytes > ZEND_LONG_MAX) {
1249 #ifdef PHP_WIN32
1250 if (_i64toa_s(total_bytes, file_size_buf, 65, 10)) {
1251 file_size_buf[0] = '0';
1252 file_size_buf[1] = '\0';
1253 }
1254 #else
1255 {
1256 int __len = snprintf(file_size_buf, 65, "%" PRId64, total_bytes);
1257 file_size_buf[__len] = '\0';
1258 }
1259 #endif
1260 size_overflow = 1;
1261
1262 } else {
1263 ZVAL_LONG(&file_size, total_bytes);
1264 }
1265 }
1266
1267 if (is_arr_upload) {
1268 snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index);
1269 } else {
1270 snprintf(lbuf, llen, "%s[error]", param);
1271 }
1272 register_http_post_files_variable_ex(lbuf, &error_type, &PG(http_globals)[TRACK_VARS_FILES], 0);
1273
1274 /* Add $foo_size */
1275 if (is_arr_upload) {
1276 snprintf(lbuf, llen, "%s_size[%s]", abuf, array_index);
1277 } else {
1278 snprintf(lbuf, llen, "%s_size", param);
1279 }
1280 if (!is_anonymous) {
1281 if (size_overflow) {
1282 ZVAL_STRING(&file_size, file_size_buf);
1283 }
1284 safe_php_register_variable_ex(lbuf, &file_size, NULL, size_overflow);
1285 }
1286
1287 /* Add $foo[size] */
1288 if (is_arr_upload) {
1289 snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index);
1290 } else {
1291 snprintf(lbuf, llen, "%s[size]", param);
1292 }
1293 if (size_overflow) {
1294 ZVAL_STRING(&file_size, file_size_buf);
1295 }
1296 register_http_post_files_variable_ex(lbuf, &file_size, &PG(http_globals)[TRACK_VARS_FILES], size_overflow);
1297 }
1298 efree(param);
1299 }
1300 }
1301
1302 fileupload_done:
1303 if (php_rfc1867_callback != NULL) {
1304 multipart_event_end event_end;
1305
1306 event_end.post_bytes_processed = SG(read_post_bytes);
1307 php_rfc1867_callback(MULTIPART_EVENT_END, &event_end, &event_extra_data);
1308 }
1309
1310 if (lbuf) efree(lbuf);
1311 if (abuf) efree(abuf);
1312 if (array_index) efree(array_index);
1313 zend_hash_destroy(&PG(rfc1867_protected_variables));
1314 zend_llist_destroy(&header);
1315 if (mbuff->boundary_next) efree(mbuff->boundary_next);
1316 if (mbuff->boundary) efree(mbuff->boundary);
1317 if (mbuff->buffer) efree(mbuff->buffer);
1318 if (mbuff) efree(mbuff);
1319 }
1320 /* }}} */
1321
1322 SAPI_API void php_rfc1867_set_multibyte_callbacks(
1323 php_rfc1867_encoding_translation_t encoding_translation,
1324 php_rfc1867_get_detect_order_t get_detect_order,
1325 php_rfc1867_set_input_encoding_t set_input_encoding,
1326 php_rfc1867_getword_t getword,
1327 php_rfc1867_getword_conf_t getword_conf,
1328 php_rfc1867_basename_t basename) /* {{{ */
1329 {
1330 php_rfc1867_encoding_translation = encoding_translation;
1331 php_rfc1867_get_detect_order = get_detect_order;
1332 php_rfc1867_set_input_encoding = set_input_encoding;
1333 php_rfc1867_getword = getword;
1334 php_rfc1867_getword_conf = getword_conf;
1335 php_rfc1867_basename = basename;
1336 }
1337 /* }}} */
1338