1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 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   | Original design:  Shane Caraveo <shane@caraveo.com>                  |
16   | Authors: Andi Gutmans <andi@zend.com>                                |
17   |          Zeev Suraski <zeev@zend.com>                                |
18   +----------------------------------------------------------------------+
19*/
20
21/* $Id$ */
22
23#include <ctype.h>
24#include <sys/stat.h>
25
26#include "php.h"
27#include "SAPI.h"
28#include "php_variables.h"
29#include "php_ini.h"
30#include "ext/standard/php_string.h"
31#include "ext/standard/pageinfo.h"
32#if (HAVE_PCRE || HAVE_BUNDLED_PCRE) && !defined(COMPILE_DL_PCRE)
33#include "ext/pcre/php_pcre.h"
34#endif
35#ifdef ZTS
36#include "TSRM.h"
37#endif
38#ifdef HAVE_SYS_TIME_H
39#include <sys/time.h>
40#elif defined(PHP_WIN32)
41#include "win32/time.h"
42#endif
43
44#include "rfc1867.h"
45
46#ifdef PHP_WIN32
47#define STRCASECMP stricmp
48#else
49#define STRCASECMP strcasecmp
50#endif
51
52#include "php_content_types.h"
53
54#ifdef ZTS
55SAPI_API int sapi_globals_id;
56#else
57sapi_globals_struct sapi_globals;
58#endif
59
60static void _type_dtor(zval *zv)
61{
62    free(Z_PTR_P(zv));
63}
64
65static void sapi_globals_ctor(sapi_globals_struct *sapi_globals TSRMLS_DC)
66{
67    memset(sapi_globals, 0, sizeof(*sapi_globals));
68    zend_hash_init_ex(&sapi_globals->known_post_content_types, 8, NULL, _type_dtor, 1, 0);
69    php_setup_sapi_content_types(TSRMLS_C);
70}
71
72static void sapi_globals_dtor(sapi_globals_struct *sapi_globals TSRMLS_DC)
73{
74    zend_hash_destroy(&sapi_globals->known_post_content_types);
75}
76
77/* True globals (no need for thread safety) */
78SAPI_API sapi_module_struct sapi_module;
79
80
81SAPI_API void sapi_startup(sapi_module_struct *sf)
82{
83#ifdef ZEND_SIGNALS
84    zend_signal_startup();
85#endif
86
87    sf->ini_entries = NULL;
88    sapi_module = *sf;
89
90#ifdef ZTS
91    ts_allocate_id(&sapi_globals_id, sizeof(sapi_globals_struct), (ts_allocate_ctor) sapi_globals_ctor, (ts_allocate_dtor) sapi_globals_dtor);
92# ifdef PHP_WIN32
93    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
94# endif
95#else
96    sapi_globals_ctor(&sapi_globals);
97#endif
98
99#ifdef PHP_WIN32
100    tsrm_win32_startup();
101#endif
102
103    reentrancy_startup();
104}
105
106SAPI_API void sapi_shutdown(void)
107{
108#ifdef ZTS
109    ts_free_id(sapi_globals_id);
110#else
111    sapi_globals_dtor(&sapi_globals);
112#endif
113
114    reentrancy_shutdown();
115
116#ifdef PHP_WIN32
117    tsrm_win32_shutdown();
118#endif
119}
120
121
122SAPI_API void sapi_free_header(sapi_header_struct *sapi_header)
123{
124    efree(sapi_header->header);
125}
126
127/* {{{ proto bool header_register_callback(mixed callback)
128   call a header function */
129PHP_FUNCTION(header_register_callback)
130{
131    zval *callback_func;
132
133    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callback_func) == FAILURE) {
134        return;
135    }
136
137    if (!zend_is_callable(callback_func, 0, NULL TSRMLS_CC)) {
138        RETURN_FALSE;
139    }
140
141    if (Z_TYPE(SG(callback_func)) != IS_UNDEF) {
142        zval_ptr_dtor(&SG(callback_func));
143        SG(fci_cache) = empty_fcall_info_cache;
144    }
145
146    ZVAL_COPY(&SG(callback_func), callback_func);
147
148    RETURN_TRUE;
149}
150/* }}} */
151
152static void sapi_run_header_callback(TSRMLS_D)
153{
154    int   error;
155    zend_fcall_info fci;
156    char *callback_error = NULL;
157    zval retval;
158
159    if (zend_fcall_info_init(&SG(callback_func), 0, &fci, &SG(fci_cache), NULL, &callback_error TSRMLS_CC) == SUCCESS) {
160        fci.retval = &retval;
161
162        error = zend_call_function(&fci, &SG(fci_cache) TSRMLS_CC);
163        if (error == FAILURE) {
164            goto callback_failed;
165        } else {
166            zval_ptr_dtor(&retval);
167        }
168    } else {
169callback_failed:
170        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not call the sapi_header_callback");
171    }
172
173    if (callback_error) {
174        efree(callback_error);
175    }
176}
177
178SAPI_API void sapi_handle_post(void *arg TSRMLS_DC)
179{
180    if (SG(request_info).post_entry && SG(request_info).content_type_dup) {
181        SG(request_info).post_entry->post_handler(SG(request_info).content_type_dup, arg TSRMLS_CC);
182        efree(SG(request_info).content_type_dup);
183        SG(request_info).content_type_dup = NULL;
184    }
185}
186
187static void sapi_read_post_data(TSRMLS_D)
188{
189    sapi_post_entry *post_entry;
190    uint content_type_length = (uint)strlen(SG(request_info).content_type);
191    char *content_type = estrndup(SG(request_info).content_type, content_type_length);
192    char *p;
193    char oldchar=0;
194    void (*post_reader_func)(TSRMLS_D) = NULL;
195
196
197    /* dedicated implementation for increased performance:
198     * - Make the content type lowercase
199     * - Trim descriptive data, stay with the content-type only
200     */
201    for (p=content_type; p<content_type+content_type_length; p++) {
202        switch (*p) {
203            case ';':
204            case ',':
205            case ' ':
206                content_type_length = p-content_type;
207                oldchar = *p;
208                *p = 0;
209                break;
210            default:
211                *p = tolower(*p);
212                break;
213        }
214    }
215
216    /* now try to find an appropriate POST content handler */
217    if ((post_entry = zend_hash_str_find_ptr(&SG(known_post_content_types), content_type,
218            content_type_length)) != NULL) {
219        /* found one, register it for use */
220        SG(request_info).post_entry = post_entry;
221        post_reader_func = post_entry->post_reader;
222    } else {
223        /* fallback */
224        SG(request_info).post_entry = NULL;
225        if (!sapi_module.default_post_reader) {
226            /* no default reader ? */
227            SG(request_info).content_type_dup = NULL;
228            sapi_module.sapi_error(E_WARNING, "Unsupported content type:  '%s'", content_type);
229            return;
230        }
231    }
232    if (oldchar) {
233        *(p-1) = oldchar;
234    }
235
236    SG(request_info).content_type_dup = content_type;
237
238    if(post_reader_func) {
239        post_reader_func(TSRMLS_C);
240    }
241
242    if(sapi_module.default_post_reader) {
243        sapi_module.default_post_reader(TSRMLS_C);
244    }
245}
246
247SAPI_API int sapi_read_post_block(char *buffer, size_t buflen TSRMLS_DC)
248{
249    int read_bytes;
250
251    if (!sapi_module.read_post) {
252        return -1;
253    }
254
255    read_bytes = (int)sapi_module.read_post(buffer, buflen TSRMLS_CC);
256
257    if (read_bytes > 0) {
258        /* gogo */
259        SG(read_post_bytes) += read_bytes;
260    }
261    if (read_bytes < buflen) {
262        /* done */
263        SG(post_read) = 1;
264    }
265
266    return read_bytes;
267}
268
269SAPI_API SAPI_POST_READER_FUNC(sapi_read_standard_form_data)
270{
271    if ((SG(post_max_size) > 0) && (SG(request_info).content_length > SG(post_max_size))) {
272        php_error_docref(NULL TSRMLS_CC, E_WARNING, "POST Content-Length of %pd bytes exceeds the limit of %pd bytes",
273                    SG(request_info).content_length, SG(post_max_size));
274        return;
275    }
276
277
278    SG(request_info).request_body = php_stream_temp_create_ex(TEMP_STREAM_DEFAULT, SAPI_POST_BLOCK_SIZE, PG(upload_tmp_dir));
279
280    if (sapi_module.read_post) {
281        int read_bytes;
282
283        for (;;) {
284            char buffer[SAPI_POST_BLOCK_SIZE];
285
286            read_bytes = sapi_read_post_block(buffer, SAPI_POST_BLOCK_SIZE TSRMLS_CC);
287
288            if (read_bytes > 0) {
289                php_stream_write(SG(request_info).request_body, buffer, read_bytes);
290            }
291
292            if ((SG(post_max_size) > 0) && (SG(read_post_bytes) > SG(post_max_size))) {
293                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Actual POST length does not match Content-Length, and exceeds " ZEND_LONG_FMT " bytes", SG(post_max_size));
294                break;
295            }
296
297            if (read_bytes < SAPI_POST_BLOCK_SIZE) {
298                /* done */
299                break;
300            }
301        }
302        php_stream_rewind(SG(request_info).request_body);
303    }
304}
305
306
307static inline char *get_default_content_type(uint prefix_len, uint *len TSRMLS_DC)
308{
309    char *mimetype, *charset, *content_type;
310    uint mimetype_len, charset_len;
311
312    if (SG(default_mimetype)) {
313        mimetype = SG(default_mimetype);
314        mimetype_len = (uint)strlen(SG(default_mimetype));
315    } else {
316        mimetype = SAPI_DEFAULT_MIMETYPE;
317        mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1;
318    }
319    if (SG(default_charset)) {
320        charset = SG(default_charset);
321        charset_len = (uint)strlen(SG(default_charset));
322    } else {
323        charset = SAPI_DEFAULT_CHARSET;
324        charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1;
325    }
326
327    if (*charset && strncasecmp(mimetype, "text/", 5) == 0) {
328        char *p;
329
330        *len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len;
331        content_type = (char*)emalloc(*len + 1);
332        p = content_type + prefix_len;
333        memcpy(p, mimetype, mimetype_len);
334        p += mimetype_len;
335        memcpy(p, "; charset=", sizeof("; charset=") - 1);
336        p += sizeof("; charset=") - 1;
337        memcpy(p, charset, charset_len + 1);
338    } else {
339        *len = prefix_len + mimetype_len;
340        content_type = (char*)emalloc(*len + 1);
341        memcpy(content_type + prefix_len, mimetype, mimetype_len + 1);
342    }
343    return content_type;
344}
345
346
347SAPI_API char *sapi_get_default_content_type(TSRMLS_D)
348{
349    uint len;
350
351    return get_default_content_type(0, &len TSRMLS_CC);
352}
353
354
355SAPI_API void sapi_get_default_content_type_header(sapi_header_struct *default_header TSRMLS_DC)
356{
357    uint len;
358
359    default_header->header = get_default_content_type(sizeof("Content-type: ")-1, &len TSRMLS_CC);
360    default_header->header_len = len;
361    memcpy(default_header->header, "Content-type: ", sizeof("Content-type: ") - 1);
362}
363
364/*
365 * Add charset on content-type header if the MIME type starts with
366 * "text/", the default_charset directive is not empty and
367 * there is not already a charset option in there.
368 *
369 * If "mimetype" is non-NULL, it should point to a pointer allocated
370 * with emalloc().  If a charset is added, the string will be
371 * re-allocated and the new length is returned.  If mimetype is
372 * unchanged, 0 is returned.
373 *
374 */
375SAPI_API size_t sapi_apply_default_charset(char **mimetype, size_t len TSRMLS_DC)
376{
377    char *charset, *newtype;
378    size_t newlen;
379    charset = SG(default_charset) ? SG(default_charset) : SAPI_DEFAULT_CHARSET;
380
381    if (*mimetype != NULL) {
382        if (*charset && strncmp(*mimetype, "text/", 5) == 0 && strstr(*mimetype, "charset=") == NULL) {
383            newlen = len + (sizeof(";charset=")-1) + strlen(charset);
384            newtype = emalloc(newlen + 1);
385            PHP_STRLCPY(newtype, *mimetype, newlen + 1, len);
386            strlcat(newtype, ";charset=", newlen + 1);
387            strlcat(newtype, charset, newlen + 1);
388            efree(*mimetype);
389            *mimetype = newtype;
390            return newlen;
391        }
392    }
393    return 0;
394}
395
396SAPI_API void sapi_activate_headers_only(TSRMLS_D)
397{
398    if (SG(request_info).headers_read == 1)
399        return;
400    SG(request_info).headers_read = 1;
401    zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct),
402            (void (*)(void *)) sapi_free_header, 0);
403    SG(sapi_headers).send_default_content_type = 1;
404
405    /* SG(sapi_headers).http_response_code = 200; */
406    SG(sapi_headers).http_status_line = NULL;
407    SG(sapi_headers).mimetype = NULL;
408    SG(read_post_bytes) = 0;
409    SG(request_info).request_body = NULL;
410    SG(request_info).current_user = NULL;
411    SG(request_info).current_user_length = 0;
412    SG(request_info).no_headers = 0;
413    SG(request_info).post_entry = NULL;
414    SG(global_request_time) = 0;
415
416    /*
417     * It's possible to override this general case in the activate() callback,
418     * if necessary.
419     */
420    if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) {
421        SG(request_info).headers_only = 1;
422    } else {
423        SG(request_info).headers_only = 0;
424    }
425    if (SG(server_context)) {
426        SG(request_info).cookie_data = sapi_module.read_cookies(TSRMLS_C);
427        if (sapi_module.activate) {
428            sapi_module.activate(TSRMLS_C);
429        }
430    }
431    if (sapi_module.input_filter_init ) {
432        sapi_module.input_filter_init(TSRMLS_C);
433    }
434}
435
436/*
437 * Called from php_request_startup() for every request.
438 */
439
440SAPI_API void sapi_activate(TSRMLS_D)
441{
442    zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0);
443    SG(sapi_headers).send_default_content_type = 1;
444
445    /*
446    SG(sapi_headers).http_response_code = 200;
447    */
448    SG(sapi_headers).http_status_line = NULL;
449    SG(sapi_headers).mimetype = NULL;
450    SG(headers_sent) = 0;
451    SG(callback_run) = 0;
452    ZVAL_UNDEF(&SG(callback_func));
453    SG(read_post_bytes) = 0;
454    SG(request_info).request_body = NULL;
455    SG(request_info).current_user = NULL;
456    SG(request_info).current_user_length = 0;
457    SG(request_info).no_headers = 0;
458    SG(request_info).post_entry = NULL;
459    SG(request_info).proto_num = 1000; /* Default to HTTP 1.0 */
460    SG(global_request_time) = 0;
461    SG(post_read) = 0;
462    /* It's possible to override this general case in the activate() callback, if necessary. */
463    if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) {
464        SG(request_info).headers_only = 1;
465    } else {
466        SG(request_info).headers_only = 0;
467    }
468    SG(rfc1867_uploaded_files) = NULL;
469
470    /* Handle request method */
471    if (SG(server_context)) {
472        if (PG(enable_post_data_reading)
473        &&  SG(request_info).content_type
474        &&  SG(request_info).request_method
475        && !strcmp(SG(request_info).request_method, "POST")) {
476            /* HTTP POST may contain form data to be processed into variables
477             * depending on given content type */
478            sapi_read_post_data(TSRMLS_C);
479        } else {
480            SG(request_info).content_type_dup = NULL;
481        }
482
483        /* Cookies */
484        SG(request_info).cookie_data = sapi_module.read_cookies(TSRMLS_C);
485
486        if (sapi_module.activate) {
487            sapi_module.activate(TSRMLS_C);
488        }
489    }
490    if (sapi_module.input_filter_init) {
491        sapi_module.input_filter_init(TSRMLS_C);
492    }
493}
494
495
496static void sapi_send_headers_free(TSRMLS_D)
497{
498    if (SG(sapi_headers).http_status_line) {
499        efree(SG(sapi_headers).http_status_line);
500        SG(sapi_headers).http_status_line = NULL;
501    }
502}
503
504SAPI_API void sapi_deactivate(TSRMLS_D)
505{
506    zend_llist_destroy(&SG(sapi_headers).headers);
507    if (SG(request_info).request_body) {
508        SG(request_info).request_body = NULL;
509    } else if (SG(server_context)) {
510        if (!SG(post_read)) {
511            /* make sure we've consumed all request input data */
512            char dummy[SAPI_POST_BLOCK_SIZE];
513            int read_bytes;
514
515            do {
516                read_bytes = sapi_read_post_block(dummy, SAPI_POST_BLOCK_SIZE TSRMLS_CC);
517            } while (SAPI_POST_BLOCK_SIZE == read_bytes);
518        }
519    }
520    if (SG(request_info).auth_user) {
521        efree(SG(request_info).auth_user);
522    }
523    if (SG(request_info).auth_password) {
524        efree(SG(request_info).auth_password);
525    }
526    if (SG(request_info).auth_digest) {
527        efree(SG(request_info).auth_digest);
528    }
529    if (SG(request_info).content_type_dup) {
530        efree(SG(request_info).content_type_dup);
531    }
532    if (SG(request_info).current_user) {
533        efree(SG(request_info).current_user);
534    }
535    if (sapi_module.deactivate) {
536        sapi_module.deactivate(TSRMLS_C);
537    }
538    if (SG(rfc1867_uploaded_files)) {
539        destroy_uploaded_files_hash(TSRMLS_C);
540    }
541    if (SG(sapi_headers).mimetype) {
542        efree(SG(sapi_headers).mimetype);
543        SG(sapi_headers).mimetype = NULL;
544    }
545    sapi_send_headers_free(TSRMLS_C);
546    SG(sapi_started) = 0;
547    SG(headers_sent) = 0;
548    SG(callback_run) = 0;
549    zval_ptr_dtor(&SG(callback_func));
550    SG(request_info).headers_read = 0;
551    SG(global_request_time) = 0;
552}
553
554
555SAPI_API void sapi_initialize_empty_request(TSRMLS_D)
556{
557    SG(server_context) = NULL;
558    SG(request_info).request_method = NULL;
559    SG(request_info).auth_digest = SG(request_info).auth_user = SG(request_info).auth_password = NULL;
560    SG(request_info).content_type_dup = NULL;
561}
562
563
564static int sapi_extract_response_code(const char *header_line)
565{
566    int code = 200;
567    const char *ptr;
568
569    for (ptr = header_line; *ptr; ptr++) {
570        if (*ptr == ' ' && *(ptr + 1) != ' ') {
571            code = atoi(ptr + 1);
572            break;
573        }
574    }
575
576    return code;
577}
578
579
580static void sapi_update_response_code(int ncode TSRMLS_DC)
581{
582    /* if the status code did not change, we do not want
583       to change the status line, and no need to change the code */
584    if (SG(sapi_headers).http_response_code == ncode) {
585        return;
586    }
587
588    if (SG(sapi_headers).http_status_line) {
589        efree(SG(sapi_headers).http_status_line);
590        SG(sapi_headers).http_status_line = NULL;
591    }
592    SG(sapi_headers).http_response_code = ncode;
593}
594
595/*
596 * since zend_llist_del_element only remove one matched item once,
597 * we should remove them by ourself
598 */
599static void sapi_remove_header(zend_llist *l, char *name, uint len) {
600    sapi_header_struct *header;
601    zend_llist_element *next;
602    zend_llist_element *current=l->head;
603
604    while (current) {
605        header = (sapi_header_struct *)(current->data);
606        next = current->next;
607        if (header->header_len > len && header->header[len] == ':'
608                && !strncasecmp(header->header, name, len)) {
609            if (current->prev) {
610                current->prev->next = next;
611            } else {
612                l->head = next;
613            }
614            if (next) {
615                next->prev = current->prev;
616            } else {
617                l->tail = current->prev;
618            }
619            sapi_free_header(header);
620            efree(current);
621            --l->count;
622        }
623        current = next;
624    }
625}
626
627SAPI_API int sapi_add_header_ex(char *header_line, uint header_line_len, zend_bool duplicate, zend_bool replace TSRMLS_DC)
628{
629    sapi_header_line ctr = {0};
630    int r;
631
632    ctr.line = header_line;
633    ctr.line_len = header_line_len;
634
635    r = sapi_header_op(replace ? SAPI_HEADER_REPLACE : SAPI_HEADER_ADD,
636            &ctr TSRMLS_CC);
637
638    if (!duplicate)
639        efree(header_line);
640
641    return r;
642}
643
644static void sapi_header_add_op(sapi_header_op_enum op, sapi_header_struct *sapi_header TSRMLS_DC)
645{
646    if (!sapi_module.header_handler ||
647        (SAPI_HEADER_ADD & sapi_module.header_handler(sapi_header, op, &SG(sapi_headers) TSRMLS_CC))) {
648        if (op == SAPI_HEADER_REPLACE) {
649            char *colon_offset = strchr(sapi_header->header, ':');
650
651            if (colon_offset) {
652                char sav = *colon_offset;
653
654                *colon_offset = 0;
655                sapi_remove_header(&SG(sapi_headers).headers, sapi_header->header, (int)strlen(sapi_header->header));
656                *colon_offset = sav;
657            }
658        }
659        zend_llist_add_element(&SG(sapi_headers).headers, (void *) sapi_header);
660    } else {
661        sapi_free_header(sapi_header);
662    }
663}
664
665SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC)
666{
667    sapi_header_struct sapi_header;
668    char *colon_offset;
669    char *header_line;
670    uint header_line_len;
671    int http_response_code;
672
673    if (SG(headers_sent) && !SG(request_info).no_headers) {
674        const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
675        int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
676
677        if (output_start_filename) {
678            sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)",
679                output_start_filename, output_start_lineno);
680        } else {
681            sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent");
682        }
683        return FAILURE;
684    }
685
686    switch (op) {
687        case SAPI_HEADER_SET_STATUS:
688            sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC);
689            return SUCCESS;
690
691        case SAPI_HEADER_ADD:
692        case SAPI_HEADER_REPLACE:
693        case SAPI_HEADER_DELETE: {
694                sapi_header_line *p = arg;
695
696                if (!p->line || !p->line_len) {
697                    return FAILURE;
698                }
699                header_line = p->line;
700                header_line_len = p->line_len;
701                http_response_code = p->response_code;
702                break;
703            }
704
705        case SAPI_HEADER_DELETE_ALL:
706            if (sapi_module.header_handler) {
707                sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC);
708            }
709            zend_llist_clean(&SG(sapi_headers).headers);
710            return SUCCESS;
711
712        default:
713            return FAILURE;
714    }
715
716    header_line = estrndup(header_line, header_line_len);
717
718    /* cut off trailing spaces, linefeeds and carriage-returns */
719    if (header_line_len && isspace(header_line[header_line_len-1])) {
720        do {
721            header_line_len--;
722        } while(header_line_len && isspace(header_line[header_line_len-1]));
723        header_line[header_line_len]='\0';
724    }
725
726    if (op == SAPI_HEADER_DELETE) {
727        if (strchr(header_line, ':')) {
728            efree(header_line);
729            sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon.");
730            return FAILURE;
731        }
732        if (sapi_module.header_handler) {
733            sapi_header.header = header_line;
734            sapi_header.header_len = header_line_len;
735            sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC);
736        }
737        sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len);
738        efree(header_line);
739        return SUCCESS;
740    } else {
741        /* new line/NUL character safety check */
742        uint i;
743        for (i = 0; i < header_line_len; i++) {
744            /* RFC 2616 allows new lines if followed by SP or HT */
745            int illegal_break =
746                    (header_line[i+1] != ' ' && header_line[i+1] != '\t')
747                    && (
748                        header_line[i] == '\n'
749                        || (header_line[i] == '\r' && header_line[i+1] != '\n'));
750            if (illegal_break) {
751                efree(header_line);
752                sapi_module.sapi_error(E_WARNING, "Header may not contain "
753                        "more than a single header, new line detected");
754                return FAILURE;
755            }
756            if (header_line[i] == '\0') {
757                efree(header_line);
758                sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes");
759                return FAILURE;
760            }
761        }
762    }
763
764    sapi_header.header = header_line;
765    sapi_header.header_len = header_line_len;
766
767    /* Check the header for a few cases that we have special support for in SAPI */
768    if (header_line_len>=5
769        && !strncasecmp(header_line, "HTTP/", 5)) {
770        /* filter out the response code */
771        sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC);
772        /* sapi_update_response_code doesn't free the status line if the code didn't change */
773        if (SG(sapi_headers).http_status_line) {
774            efree(SG(sapi_headers).http_status_line);
775        }
776        SG(sapi_headers).http_status_line = header_line;
777        return SUCCESS;
778    } else {
779        colon_offset = strchr(header_line, ':');
780        if (colon_offset) {
781            *colon_offset = 0;
782            if (!STRCASECMP(header_line, "Content-Type")) {
783                char *ptr = colon_offset+1, *mimetype = NULL, *newheader;
784                size_t len = header_line_len - (ptr - header_line), newlen;
785                while (*ptr == ' ') {
786                    ptr++;
787                    len--;
788                }
789
790                /* Disable possible output compression for images */
791                if (!strncmp(ptr, "image/", sizeof("image/")-1)) {
792                    zend_string *key = zend_string_init("zlib.output_compression", sizeof("zlib.output_compression")-1, 0);
793                    zend_alter_ini_entry_chars(key, "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
794                    zend_string_release(key);
795                }
796
797                mimetype = estrdup(ptr);
798                newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC);
799                if (!SG(sapi_headers).mimetype){
800                    SG(sapi_headers).mimetype = estrdup(mimetype);
801                }
802
803                if (newlen != 0) {
804                    newlen += sizeof("Content-type: ");
805                    newheader = emalloc(newlen);
806                    PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1);
807                    strlcat(newheader, mimetype, newlen);
808                    sapi_header.header = newheader;
809                    sapi_header.header_len = (uint)(newlen - 1);
810                    efree(header_line);
811                }
812                efree(mimetype);
813                SG(sapi_headers).send_default_content_type = 0;
814            } else if (!STRCASECMP(header_line, "Content-Length")) {
815                /* Script is setting Content-length. The script cannot reasonably
816                 * know the size of the message body after compression, so it's best
817                 * do disable compression altogether. This contributes to making scripts
818                 * portable between setups that have and don't have zlib compression
819                 * enabled globally. See req #44164 */
820                zend_string *key = zend_string_init("zlib.output_compression", sizeof("zlib.output_compression")-1, 0);
821                zend_alter_ini_entry_chars(key,
822                    "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
823                zend_string_release(key);
824            } else if (!STRCASECMP(header_line, "Location")) {
825                if ((SG(sapi_headers).http_response_code < 300 ||
826                    SG(sapi_headers).http_response_code > 399) &&
827                    SG(sapi_headers).http_response_code != 201) {
828                    /* Return a Found Redirect if one is not already specified */
829                    if (http_response_code) { /* user specified redirect code */
830                        sapi_update_response_code(http_response_code TSRMLS_CC);
831                    } else if (SG(request_info).proto_num > 1000 &&
832                       SG(request_info).request_method &&
833                       strcmp(SG(request_info).request_method, "HEAD") &&
834                       strcmp(SG(request_info).request_method, "GET")) {
835                        sapi_update_response_code(303 TSRMLS_CC);
836                    } else {
837                        sapi_update_response_code(302 TSRMLS_CC);
838                    }
839                }
840            } else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */
841                sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */
842            }
843            if (sapi_header.header==header_line) {
844                *colon_offset = ':';
845            }
846        }
847    }
848    if (http_response_code) {
849        sapi_update_response_code(http_response_code TSRMLS_CC);
850    }
851    sapi_header_add_op(op, &sapi_header TSRMLS_CC);
852    return SUCCESS;
853}
854
855
856SAPI_API int sapi_send_headers(TSRMLS_D)
857{
858    int retval;
859    int ret = FAILURE;
860
861    if (SG(headers_sent) || SG(request_info).no_headers || SG(callback_run)) {
862        return SUCCESS;
863    }
864
865    /* Success-oriented.  We set headers_sent to 1 here to avoid an infinite loop
866     * in case of an error situation.
867     */
868    if (SG(sapi_headers).send_default_content_type && sapi_module.send_headers) {
869        sapi_header_struct default_header;
870        uint len;
871
872        SG(sapi_headers).mimetype = get_default_content_type(0, &len TSRMLS_CC);
873        default_header.header_len = sizeof("Content-type: ") - 1 + len;
874        default_header.header = emalloc(default_header.header_len + 1);
875        memcpy(default_header.header, "Content-type: ", sizeof("Content-type: ") - 1);
876        memcpy(default_header.header + sizeof("Content-type: ") - 1, SG(sapi_headers).mimetype, len + 1);
877        sapi_header_add_op(SAPI_HEADER_ADD, &default_header TSRMLS_CC);
878        SG(sapi_headers).send_default_content_type = 0;
879    }
880
881    if (Z_TYPE(SG(callback_func)) != IS_UNDEF && !SG(callback_run)) {
882        SG(callback_run) = 1;
883        sapi_run_header_callback(TSRMLS_C);
884    }
885
886    SG(headers_sent) = 1;
887
888    if (sapi_module.send_headers) {
889        retval = sapi_module.send_headers(&SG(sapi_headers) TSRMLS_CC);
890    } else {
891        retval = SAPI_HEADER_DO_SEND;
892    }
893
894    switch (retval) {
895        case SAPI_HEADER_SENT_SUCCESSFULLY:
896            ret = SUCCESS;
897            break;
898        case SAPI_HEADER_DO_SEND: {
899                sapi_header_struct http_status_line;
900                char buf[255];
901
902                if (SG(sapi_headers).http_status_line) {
903                    http_status_line.header = SG(sapi_headers).http_status_line;
904                    http_status_line.header_len = (uint)strlen(SG(sapi_headers).http_status_line);
905                } else {
906                    http_status_line.header = buf;
907                    http_status_line.header_len = slprintf(buf, sizeof(buf), "HTTP/1.0 %d X", SG(sapi_headers).http_response_code);
908                }
909                sapi_module.send_header(&http_status_line, SG(server_context) TSRMLS_CC);
910            }
911            zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t) sapi_module.send_header, SG(server_context) TSRMLS_CC);
912            if(SG(sapi_headers).send_default_content_type) {
913                sapi_header_struct default_header;
914
915                sapi_get_default_content_type_header(&default_header TSRMLS_CC);
916                sapi_module.send_header(&default_header, SG(server_context) TSRMLS_CC);
917                sapi_free_header(&default_header);
918            }
919            sapi_module.send_header(NULL, SG(server_context) TSRMLS_CC);
920            ret = SUCCESS;
921            break;
922        case SAPI_HEADER_SEND_FAILED:
923            SG(headers_sent) = 0;
924            ret = FAILURE;
925            break;
926    }
927
928    sapi_send_headers_free(TSRMLS_C);
929
930    return ret;
931}
932
933
934SAPI_API int sapi_register_post_entries(sapi_post_entry *post_entries TSRMLS_DC)
935{
936    sapi_post_entry *p=post_entries;
937
938    while (p->content_type) {
939        if (sapi_register_post_entry(p TSRMLS_CC) == FAILURE) {
940            return FAILURE;
941        }
942        p++;
943    }
944    return SUCCESS;
945}
946
947
948SAPI_API int sapi_register_post_entry(sapi_post_entry *post_entry TSRMLS_DC)
949{
950    if (SG(sapi_started) && EG(current_execute_data)) {
951        return FAILURE;
952    }
953    return zend_hash_str_add_mem(&SG(known_post_content_types),
954            post_entry->content_type, post_entry->content_type_len,
955            (void *) post_entry, sizeof(sapi_post_entry)) ? SUCCESS : FAILURE;
956}
957
958SAPI_API void sapi_unregister_post_entry(sapi_post_entry *post_entry TSRMLS_DC)
959{
960    if (SG(sapi_started) && EG(current_execute_data)) {
961        return;
962    }
963    zend_hash_str_del(&SG(known_post_content_types), post_entry->content_type,
964            post_entry->content_type_len);
965}
966
967
968SAPI_API int sapi_register_default_post_reader(void (*default_post_reader)(TSRMLS_D) TSRMLS_DC)
969{
970    if (SG(sapi_started) && EG(current_execute_data)) {
971        return FAILURE;
972    }
973    sapi_module.default_post_reader = default_post_reader;
974    return SUCCESS;
975}
976
977
978SAPI_API int sapi_register_treat_data(void (*treat_data)(int arg, char *str, zval *destArray TSRMLS_DC) TSRMLS_DC)
979{
980    if (SG(sapi_started) && EG(current_execute_data)) {
981        return FAILURE;
982    }
983    sapi_module.treat_data = treat_data;
984    return SUCCESS;
985}
986
987SAPI_API int sapi_register_input_filter(unsigned int (*input_filter)(int arg, char *var, char **val, size_t val_len, size_t *new_val_len TSRMLS_DC), unsigned int (*input_filter_init)(TSRMLS_D) TSRMLS_DC)
988{
989    if (SG(sapi_started) && EG(current_execute_data)) {
990        return FAILURE;
991    }
992    sapi_module.input_filter = input_filter;
993    sapi_module.input_filter_init = input_filter_init;
994    return SUCCESS;
995}
996
997SAPI_API int sapi_flush(TSRMLS_D)
998{
999    if (sapi_module.flush) {
1000        sapi_module.flush(SG(server_context) TSRMLS_CC);
1001        return SUCCESS;
1002    } else {
1003        return FAILURE;
1004    }
1005}
1006
1007SAPI_API zend_stat_t *sapi_get_stat(TSRMLS_D)
1008{
1009    if (sapi_module.get_stat) {
1010        return sapi_module.get_stat(TSRMLS_C);
1011    } else {
1012        if (!SG(request_info).path_translated || (VCWD_STAT(SG(request_info).path_translated, &SG(global_stat)) == -1)) {
1013            return NULL;
1014        }
1015        return &SG(global_stat);
1016    }
1017}
1018
1019SAPI_API char *sapi_getenv(char *name, size_t name_len TSRMLS_DC)
1020{
1021    if (sapi_module.getenv) {
1022        char *value, *tmp = sapi_module.getenv(name, name_len TSRMLS_CC);
1023        if (tmp) {
1024            value = estrdup(tmp);
1025        } else {
1026            return NULL;
1027        }
1028        if (sapi_module.input_filter) {
1029            sapi_module.input_filter(PARSE_STRING, name, &value, strlen(value), NULL TSRMLS_CC);
1030        }
1031        return value;
1032    }
1033    return NULL;
1034}
1035
1036SAPI_API int sapi_get_fd(int *fd TSRMLS_DC)
1037{
1038    if (sapi_module.get_fd) {
1039        return sapi_module.get_fd(fd TSRMLS_CC);
1040    } else {
1041        return FAILURE;
1042    }
1043}
1044
1045SAPI_API int sapi_force_http_10(TSRMLS_D)
1046{
1047    if (sapi_module.force_http_10) {
1048        return sapi_module.force_http_10(TSRMLS_C);
1049    } else {
1050        return FAILURE;
1051    }
1052}
1053
1054
1055SAPI_API int sapi_get_target_uid(uid_t *obj TSRMLS_DC)
1056{
1057    if (sapi_module.get_target_uid) {
1058        return sapi_module.get_target_uid(obj TSRMLS_CC);
1059    } else {
1060        return FAILURE;
1061    }
1062}
1063
1064SAPI_API int sapi_get_target_gid(gid_t *obj TSRMLS_DC)
1065{
1066    if (sapi_module.get_target_gid) {
1067        return sapi_module.get_target_gid(obj TSRMLS_CC);
1068    } else {
1069        return FAILURE;
1070    }
1071}
1072
1073SAPI_API double sapi_get_request_time(TSRMLS_D)
1074{
1075    if(SG(global_request_time)) return SG(global_request_time);
1076
1077    if (sapi_module.get_request_time && SG(server_context)) {
1078        SG(global_request_time) = sapi_module.get_request_time(TSRMLS_C);
1079    } else {
1080        struct timeval tp = {0};
1081        if (!gettimeofday(&tp, NULL)) {
1082            SG(global_request_time) = (double)(tp.tv_sec + tp.tv_usec / 1000000.00);
1083        } else {
1084            SG(global_request_time) = (double)time(0);
1085        }
1086    }
1087    return SG(global_request_time);
1088}
1089
1090SAPI_API void sapi_terminate_process(TSRMLS_D) {
1091    if (sapi_module.terminate_process) {
1092        sapi_module.terminate_process(TSRMLS_C);
1093    }
1094}
1095
1096/*
1097 * Local variables:
1098 * tab-width: 4
1099 * c-basic-offset: 4
1100 * End:
1101 * vim600: sw=4 ts=4 fdm=marker
1102 * vim<600: sw=4 ts=4
1103 */
1104