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