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