Back to index

php5  5.3.10
fpm_main.c
Go to the documentation of this file.
00001 /*
00002    +----------------------------------------------------------------------+
00003    | PHP Version 5                                                        |
00004    +----------------------------------------------------------------------+
00005    | Copyright (c) 1997-2009 The PHP Group                                |
00006    +----------------------------------------------------------------------+
00007    | This source file is subject to version 3.01 of the PHP license,      |
00008    | that is bundled with this package in the file LICENSE, and is        |
00009    | available through the world-wide-web at the following url:           |
00010    | http://www.php.net/license/3_01.txt                                  |
00011    | If you did not receive a copy of the PHP license and are unable to   |
00012    | obtain it through the world-wide-web, please send a note to          |
00013    | license@php.net so we can mail you a copy immediately.               |
00014    +----------------------------------------------------------------------+
00015    | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
00016    |          Stig Bakken <ssb@php.net>                                   |
00017    |          Zeev Suraski <zeev@zend.com>                                |
00018    | FastCGI: Ben Mansell <php@slimyhorror.com>                           |
00019    |          Shane Caraveo <shane@caraveo.com>                           |
00020    |          Dmitry Stogov <dmitry@zend.com>                             |
00021    +----------------------------------------------------------------------+
00022 */
00023 
00024 /* $Id: cgi_main.c 291497 2009-11-30 14:43:22Z dmitry $ */
00025 
00026 #include "php.h"
00027 #include "php_globals.h"
00028 #include "php_variables.h"
00029 #include "zend_modules.h"
00030 #include "php.h"
00031 #include "zend_ini_scanner.h"
00032 #include "zend_globals.h"
00033 #include "zend_stream.h"
00034 
00035 #include "SAPI.h"
00036 
00037 #include <stdio.h>
00038 #include "php.h"
00039 
00040 #ifdef PHP_WIN32
00041 # include "win32/time.h"
00042 # include "win32/signal.h"
00043 # include <process.h>
00044 #endif
00045 
00046 #if HAVE_SYS_TIME_H
00047 # include <sys/time.h>
00048 #endif
00049 
00050 #if HAVE_UNISTD_H
00051 # include <unistd.h>
00052 #endif
00053 
00054 #if HAVE_SIGNAL_H
00055 # include <signal.h>
00056 #endif
00057 
00058 #if HAVE_SETLOCALE
00059 # include <locale.h>
00060 #endif
00061 
00062 #if HAVE_SYS_TYPES_H
00063 # include <sys/types.h>
00064 #endif
00065 
00066 #if HAVE_SYS_WAIT_H
00067 # include <sys/wait.h>
00068 #endif
00069 
00070 #if HAVE_FCNTL_H
00071 # include <fcntl.h>
00072 #endif
00073 
00074 #include "zend.h"
00075 #include "zend_extensions.h"
00076 #include "php_ini.h"
00077 #include "php_globals.h"
00078 #include "php_main.h"
00079 #include "fopen_wrappers.h"
00080 #include "ext/standard/php_standard.h"
00081 
00082 #ifdef PHP_WIN32
00083 # include <io.h>
00084 # include <fcntl.h>
00085 # include "win32/php_registry.h"
00086 #endif
00087 
00088 #ifdef __riscos__
00089 # include <unixlib/local.h>
00090 int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
00091 #endif
00092 
00093 #include "zend_compile.h"
00094 #include "zend_execute.h"
00095 #include "zend_highlight.h"
00096 #include "zend_indent.h"
00097 
00098 #include "php_getopt.h"
00099 
00100 #include "fastcgi.h"
00101 
00102 #include <php_config.h>
00103 #include "fpm.h"
00104 #include "fpm_request.h"
00105 #include "fpm_status.h"
00106 #include "fpm_conf.h"
00107 #include "fpm_php.h"
00108 #include "fpm_log.h"
00109 #include "zlog.h"
00110 
00111 #ifndef PHP_WIN32
00112 /* XXX this will need to change later when threaded fastcgi is implemented.  shane */
00113 struct sigaction act, old_term, old_quit, old_int;
00114 #endif
00115 
00116 static void (*php_php_import_environment_variables)(zval *array_ptr TSRMLS_DC);
00117 
00118 #ifndef PHP_WIN32
00119 /* these globals used for forking children on unix systems */
00120 
00124 static int parent = 1;
00125 #endif
00126 
00127 static int request_body_fd;
00128 static int fpm_is_running = 0;
00129 
00130 static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC);
00131 static void fastcgi_ini_parser(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg TSRMLS_DC);
00132 
00133 #define PHP_MODE_STANDARD   1
00134 #define PHP_MODE_HIGHLIGHT  2
00135 #define PHP_MODE_INDENT            3
00136 #define PHP_MODE_LINT              4
00137 #define PHP_MODE_STRIP             5
00138 
00139 static char *php_optarg = NULL;
00140 static int php_optind = 1;
00141 static zend_module_entry cgi_module_entry;
00142 
00143 static const opt_struct OPTIONS[] = {
00144        {'c', 1, "php-ini"},
00145        {'d', 1, "define"},
00146        {'e', 0, "profile-info"},
00147        {'h', 0, "help"},
00148        {'i', 0, "info"},
00149        {'m', 0, "modules"},
00150        {'n', 0, "no-php-ini"},
00151        {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
00152        {'v', 0, "version"},
00153        {'y', 1, "fpm-config"},
00154        {'t', 0, "test"},
00155        {'p', 1, "prefix"},
00156        {'g', 1, "pid"},
00157        {'-', 0, NULL} /* end of args */
00158 };
00159 
00160 typedef struct _php_cgi_globals_struct {
00161        zend_bool rfc2616_headers;
00162        zend_bool nph;
00163        zend_bool fix_pathinfo;
00164        zend_bool force_redirect;
00165        zend_bool discard_path;
00166        zend_bool fcgi_logging;
00167        char *redirect_status_env;
00168        HashTable user_config_cache;
00169        char *error_header;
00170        char *fpm_config;
00171 } php_cgi_globals_struct;
00172 
00173 /* {{{ user_config_cache
00174  *
00175  * Key for each cache entry is dirname(PATH_TRANSLATED).
00176  *
00177  * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
00178  *       the path starting from doc_root throught to dirname(PATH_TRANSLATED).  There is no point
00179  *       storing per-file entries as it would not be possible to detect added / deleted entries
00180  *       between separate files.
00181  */
00182 typedef struct _user_config_cache_entry {
00183        time_t expires;
00184        HashTable *user_config;
00185 } user_config_cache_entry;
00186 
00187 static void user_config_cache_entry_dtor(user_config_cache_entry *entry)
00188 {
00189        zend_hash_destroy(entry->user_config);
00190        free(entry->user_config);
00191 }
00192 /* }}} */
00193 
00194 #ifdef ZTS
00195 static int php_cgi_globals_id;
00196 #define CGIG(v) TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
00197 #else
00198 static php_cgi_globals_struct php_cgi_globals;
00199 #define CGIG(v) (php_cgi_globals.v)
00200 #endif
00201 
00202 #ifdef PHP_WIN32
00203 #define TRANSLATE_SLASHES(path) \
00204        { \
00205               char *tmp = path; \
00206               while (*tmp) { \
00207                      if (*tmp == '\\') *tmp = '/'; \
00208                      tmp++; \
00209               } \
00210        }
00211 #else
00212 #define TRANSLATE_SLASHES(path)
00213 #endif
00214 
00215 static int print_module_info(zend_module_entry *module, void *arg TSRMLS_DC)
00216 {
00217        php_printf("%s\n", module->name);
00218        return 0;
00219 }
00220 
00221 static int module_name_cmp(const void *a, const void *b TSRMLS_DC)
00222 {
00223        Bucket *f = *((Bucket **) a);
00224        Bucket *s = *((Bucket **) b);
00225 
00226        return strcasecmp(   ((zend_module_entry *)f->pData)->name,
00227                                           ((zend_module_entry *)s->pData)->name);
00228 }
00229 
00230 static void print_modules(TSRMLS_D)
00231 {
00232        HashTable sorted_registry;
00233        zend_module_entry tmp;
00234 
00235        zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
00236        zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
00237        zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
00238        zend_hash_apply_with_argument(&sorted_registry, (apply_func_arg_t) print_module_info, NULL TSRMLS_CC);
00239        zend_hash_destroy(&sorted_registry);
00240 }
00241 
00242 static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC)
00243 {
00244        php_printf("%s\n", ext->name);
00245        return 0;
00246 }
00247 
00248 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s TSRMLS_DC)
00249 {
00250        return strcmp(       ((zend_extension *)(*f)->data)->name,
00251                                    ((zend_extension *)(*s)->data)->name);
00252 }
00253 
00254 static void print_extensions(TSRMLS_D)
00255 {
00256        zend_llist sorted_exts;
00257 
00258        zend_llist_copy(&sorted_exts, &zend_extensions);
00259        sorted_exts.dtor = NULL;
00260        zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
00261        zend_llist_apply_with_argument(&sorted_exts, (llist_apply_with_arg_func_t) print_extension_info, NULL TSRMLS_CC);
00262        zend_llist_destroy(&sorted_exts);
00263 }
00264 
00265 #ifndef STDOUT_FILENO        
00266 #define STDOUT_FILENO 1      
00267 #endif
00268 
00269 static inline size_t sapi_cgibin_single_write(const char *str, uint str_length TSRMLS_DC)
00270 {
00271        ssize_t ret;
00272 
00273        /* sapi has started which means everyhting must be send through fcgi */
00274        if (fpm_is_running) {
00275               fcgi_request *request = (fcgi_request*) SG(server_context);
00276               ret = fcgi_write(request, FCGI_STDOUT, str, str_length);
00277               if (ret <= 0) {
00278                      return 0;
00279               }
00280               return (size_t)ret;
00281        }
00282 
00283        /* sapi has not started, output to stdout instead of fcgi */
00284 #ifdef PHP_WRITE_STDOUT      
00285        ret = write(STDOUT_FILENO, str, str_length);      
00286        if (ret <= 0) {
00287               return 0;
00288        }
00289        return (size_t)ret;
00290 #else
00291        return fwrite(str, 1, MIN(str_length, 16384), stdout);
00292 #endif
00293 }
00294 
00295 static int sapi_cgibin_ub_write(const char *str, uint str_length TSRMLS_DC)
00296 {
00297        const char *ptr = str;
00298        uint remaining = str_length;
00299        size_t ret;
00300 
00301        while (remaining > 0) {
00302               ret = sapi_cgibin_single_write(ptr, remaining TSRMLS_CC);
00303               if (!ret) {
00304                      php_handle_aborted_connection();
00305                      return str_length - remaining;
00306               }
00307               ptr += ret;
00308               remaining -= ret;
00309        }
00310 
00311        return str_length;
00312 }
00313 
00314 
00315 static void sapi_cgibin_flush(void *server_context)
00316 {
00317        /* fpm has started, let use fcgi instead of stdout */
00318        if (fpm_is_running) {
00319               fcgi_request *request = (fcgi_request*) server_context;
00320               if (
00321 #ifndef PHP_WIN32
00322              !parent &&
00323 #endif
00324              request && !fcgi_flush(request, 0)) {
00325                      php_handle_aborted_connection();
00326               }
00327               return;
00328        }
00329 
00330        /* fpm has not started yet, let use stdout instead of fcgi */
00331        if (fflush(stdout) == EOF) {
00332               php_handle_aborted_connection();
00333        }
00334 }
00335 
00336 #define SAPI_CGI_MAX_HEADER_LENGTH 1024
00337 
00338 typedef struct _http_error {
00339        int code;
00340        const char* msg;
00341 } http_error;
00342 
00343 static const http_error http_error_codes[] = {
00344        {100, "Continue"},
00345        {101, "Switching Protocols"},
00346        {200, "OK"},
00347        {201, "Created"},
00348        {202, "Accepted"},
00349        {203, "Non-Authoritative Information"},
00350        {204, "No Content"},
00351        {205, "Reset Content"},
00352        {206, "Partial Content"},
00353        {300, "Multiple Choices"},
00354        {301, "Moved Permanently"},
00355        {302, "Moved Temporarily"},
00356        {303, "See Other"},
00357        {304, "Not Modified"},
00358        {305, "Use Proxy"},
00359        {400, "Bad Request"},
00360        {401, "Unauthorized"},
00361        {402, "Payment Required"},
00362        {403, "Forbidden"},
00363        {404, "Not Found"},
00364        {405, "Method Not Allowed"},
00365        {406, "Not Acceptable"},
00366        {407, "Proxy Authentication Required"},
00367        {408, "Request Time-out"},
00368        {409, "Conflict"},
00369        {410, "Gone"},
00370        {411, "Length Required"},
00371        {412, "Precondition Failed"},
00372        {413, "Request Entity Too Large"},
00373        {414, "Request-URI Too Large"},
00374        {415, "Unsupported Media Type"},
00375        {500, "Internal Server Error"},
00376        {501, "Not Implemented"},
00377        {502, "Bad Gateway"},
00378        {503, "Service Unavailable"},
00379        {504, "Gateway Time-out"},
00380        {505, "HTTP Version not supported"},
00381        {0,   NULL}
00382 };
00383 
00384 static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
00385 {
00386        char buf[SAPI_CGI_MAX_HEADER_LENGTH];
00387        sapi_header_struct *h;
00388        zend_llist_position pos;
00389        zend_bool ignore_status = 0;
00390        int response_status = SG(sapi_headers).http_response_code;
00391 
00392        if (SG(request_info).no_headers == 1) {
00393               return  SAPI_HEADER_SENT_SUCCESSFULLY;
00394        }
00395 
00396        if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
00397        {
00398               int len;
00399               zend_bool has_status = 0;
00400 
00401               if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
00402                      char *s;
00403                      len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
00404                      if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
00405                             response_status = atoi((s + 1));
00406                      }
00407 
00408                      if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
00409                             len = SAPI_CGI_MAX_HEADER_LENGTH;
00410                      }
00411 
00412               } else {
00413                      char *s;
00414 
00415                      if (SG(sapi_headers).http_status_line &&
00416                             (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
00417                             (s - SG(sapi_headers).http_status_line) >= 5 &&
00418                             strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
00419                      ) {
00420                             len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
00421                             response_status = atoi((s + 1));
00422                      } else {
00423                             h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
00424                             while (h) {
00425                                    if (h->header_len > sizeof("Status:") - 1 &&
00426                                           strncasecmp(h->header, "Status:", sizeof("Status:") - 1) == 0
00427                                    ) {
00428                                           has_status = 1;
00429                                           break;
00430                                    }
00431                                    h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
00432                             }
00433                             if (!has_status) {
00434                                    http_error *err = (http_error*)http_error_codes;
00435 
00436                                    while (err->code != 0) {
00437                                           if (err->code == SG(sapi_headers).http_response_code) {
00438                                                  break;
00439                                           }
00440                                           err++;
00441                                    }
00442                                    if (err->msg) {
00443                                           len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->msg);
00444                                    } else {
00445                                           len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
00446                                    }
00447                             }
00448                      }
00449               }
00450 
00451               if (!has_status) {
00452                      PHPWRITE_H(buf, len);
00453                      ignore_status = 1;
00454               }
00455        }
00456 
00457        h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
00458        while (h) {
00459               /* prevent CRLFCRLF */
00460               if (h->header_len) {
00461                      if (h->header_len > sizeof("Status:") - 1 && 
00462                             strncasecmp(h->header, "Status:", sizeof("Status:") - 1) == 0
00463                      ) {
00464                             if (!ignore_status) {
00465                                    ignore_status = 1;
00466                                    PHPWRITE_H(h->header, h->header_len);
00467                                    PHPWRITE_H("\r\n", 2);
00468                             }
00469                      } else if (response_status == 304 && h->header_len > sizeof("Content-Type:") - 1 &&
00470                             strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:") - 1) == 0
00471                      ) {
00472                             h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
00473                             continue;
00474                      } else {
00475                             PHPWRITE_H(h->header, h->header_len);
00476                             PHPWRITE_H("\r\n", 2);
00477                      }
00478               }
00479               h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
00480        }
00481        PHPWRITE_H("\r\n", 2);
00482 
00483        return SAPI_HEADER_SENT_SUCCESSFULLY;
00484 }
00485 
00486 #ifndef STDIN_FILENO
00487 # define STDIN_FILENO 0
00488 #endif
00489 
00490 static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
00491 {
00492        uint read_bytes = 0;
00493        int tmp_read_bytes;
00494 
00495        count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
00496        while (read_bytes < count_bytes) {
00497               fcgi_request *request = (fcgi_request*) SG(server_context);
00498               if (request_body_fd == -1) {
00499                      char *request_body_filename = sapi_cgibin_getenv((char *) "REQUEST_BODY_FILE",
00500                                    sizeof("REQUEST_BODY_FILE") - 1 TSRMLS_CC);
00501 
00502                      if (request_body_filename && *request_body_filename) {
00503                             request_body_fd = open(request_body_filename, O_RDONLY);
00504 
00505                             if (0 > request_body_fd) {
00506                                    php_error(E_WARNING, "REQUEST_BODY_FILE: open('%s') failed: %s (%d)",
00507                                                  request_body_filename, strerror(errno), errno);
00508                                    return 0;
00509                             }
00510                      }
00511               }
00512 
00513               /* If REQUEST_BODY_FILE variable not available - read post body from fastcgi stream */
00514               if (request_body_fd < 0) {
00515                      tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes);
00516               } else {
00517                      tmp_read_bytes = read(request_body_fd, buffer + read_bytes, count_bytes - read_bytes);
00518               }
00519               if (tmp_read_bytes <= 0) {
00520                      break;
00521               }
00522               read_bytes += tmp_read_bytes;
00523        }
00524        return read_bytes;
00525 }
00526 
00527 static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC)
00528 {
00529        /* if fpm has started, use fcgi env */
00530        if (fpm_is_running) {
00531               fcgi_request *request = (fcgi_request*) SG(server_context);
00532               return fcgi_getenv(request, name, name_len);
00533        }
00534 
00535        /* if fpm has not started yet, use std env */
00536        return getenv(name);
00537 }
00538 
00539 static char *_sapi_cgibin_putenv(char *name, char *value TSRMLS_DC)
00540 {
00541        int name_len;
00542 
00543        if (!name) {
00544               return NULL;
00545        }
00546        name_len = strlen(name);
00547 
00548        fcgi_request *request = (fcgi_request*) SG(server_context);
00549        return fcgi_putenv(request, name, name_len, value);
00550 }
00551 
00552 static char *sapi_cgi_read_cookies(TSRMLS_D)
00553 {
00554        return sapi_cgibin_getenv((char *) "HTTP_COOKIE", sizeof("HTTP_COOKIE") - 1 TSRMLS_CC);
00555 }
00556 
00557 void cgi_php_import_environment_variables(zval *array_ptr TSRMLS_DC)
00558 {
00559        fcgi_request *request;
00560        HashPosition pos;
00561        int magic_quotes_gpc;;
00562        char *var, **val;
00563        uint var_len;
00564        ulong idx;
00565        int filter_arg;
00566 
00567 
00568        if (PG(http_globals)[TRACK_VARS_ENV] &&
00569               array_ptr != PG(http_globals)[TRACK_VARS_ENV] &&
00570               Z_TYPE_P(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
00571               zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_ENV])) > 0
00572        ) {
00573               zval_dtor(array_ptr);
00574               *array_ptr = *PG(http_globals)[TRACK_VARS_ENV];
00575               INIT_PZVAL(array_ptr);
00576               zval_copy_ctor(array_ptr);
00577               return;
00578        } else if (PG(http_globals)[TRACK_VARS_SERVER] &&
00579               array_ptr != PG(http_globals)[TRACK_VARS_SERVER] &&
00580               Z_TYPE_P(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
00581               zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER])) > 0
00582        ) {
00583               zval_dtor(array_ptr);
00584               *array_ptr = *PG(http_globals)[TRACK_VARS_SERVER];
00585               INIT_PZVAL(array_ptr);
00586               zval_copy_ctor(array_ptr);
00587               return;
00588        }
00589 
00590        /* call php's original import as a catch-all */
00591        php_php_import_environment_variables(array_ptr TSRMLS_CC);
00592 
00593        request = (fcgi_request*) SG(server_context);
00594        magic_quotes_gpc = PG(magic_quotes_gpc);
00595        filter_arg = (array_ptr == PG(http_globals)[TRACK_VARS_ENV])?PARSE_ENV:PARSE_SERVER;
00596 
00597        /* turn off magic_quotes while importing environment variables */
00598        PG(magic_quotes_gpc) = 0;
00599        for (zend_hash_internal_pointer_reset_ex(request->env, &pos);
00600             zend_hash_get_current_key_ex(request->env, &var, &var_len, &idx, 0, &pos) == HASH_KEY_IS_STRING &&
00601             zend_hash_get_current_data_ex(request->env, (void **) &val, &pos) == SUCCESS;
00602             zend_hash_move_forward_ex(request->env, &pos)
00603        ) {
00604               unsigned int new_val_len;
00605 
00606               if (sapi_module.input_filter(filter_arg, var, val, strlen(*val), &new_val_len TSRMLS_CC)) {
00607                      php_register_variable_safe(var, *val, new_val_len, array_ptr TSRMLS_CC);
00608               }
00609        }
00610        PG(magic_quotes_gpc) = magic_quotes_gpc;
00611 }
00612 
00613 static void sapi_cgi_register_variables(zval *track_vars_array TSRMLS_DC)
00614 {
00615        unsigned int php_self_len;
00616        char *php_self;
00617 
00618        /* In CGI mode, we consider the environment to be a part of the server
00619         * variables
00620         */
00621        php_import_environment_variables(track_vars_array TSRMLS_CC);
00622 
00623        if (CGIG(fix_pathinfo)) {
00624               char *script_name = SG(request_info).request_uri;
00625               unsigned int script_name_len = script_name ? strlen(script_name) : 0;
00626               char *path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO") - 1 TSRMLS_CC);
00627               unsigned int path_info_len = path_info ? strlen(path_info) : 0;
00628 
00629               php_self_len = script_name_len + path_info_len;
00630               php_self = emalloc(php_self_len + 1);
00631 
00632               /* Concat script_name and path_info into php_self */
00633               if (script_name) {
00634                      memcpy(php_self, script_name, script_name_len + 1);
00635               }
00636               if (path_info) {
00637                      memcpy(php_self + script_name_len, path_info, path_info_len + 1);
00638               }
00639 
00640               /* Build the special-case PHP_SELF variable for the CGI version */
00641               if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
00642                      php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
00643               }
00644               efree(php_self);
00645        } else {
00646               php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
00647               php_self_len = strlen(php_self);
00648               if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
00649                      php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
00650               }
00651        }
00652 }
00653 
00654 static void sapi_cgi_log_message(char *message)
00655 {
00656        TSRMLS_FETCH();
00657 
00658        if (CGIG(fcgi_logging)) {
00659               zlog(ZLOG_NOTICE, "PHP message: %s", message);
00660        }
00661 }
00662 
00663 /* {{{ php_cgi_ini_activate_user_config
00664  */
00665 static void php_cgi_ini_activate_user_config(char *path, int path_len, const char *doc_root, int doc_root_len, int start TSRMLS_DC)
00666 {
00667        char *ptr;
00668        user_config_cache_entry *new_entry, *entry;
00669        time_t request_time = sapi_get_request_time(TSRMLS_C);
00670 
00671        /* Find cached config entry: If not found, create one */
00672        if (zend_hash_find(&CGIG(user_config_cache), path, path_len + 1, (void **) &entry) == FAILURE) {
00673               new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
00674               new_entry->expires = 0;
00675               new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
00676               zend_hash_init(new_entry->user_config, 0, NULL, (dtor_func_t) config_zval_dtor, 1);
00677               zend_hash_update(&CGIG(user_config_cache), path, path_len + 1, new_entry, sizeof(user_config_cache_entry), (void **) &entry);
00678               free(new_entry);
00679        }
00680 
00681        /* Check whether cache entry has expired and rescan if it is */
00682        if (request_time > entry->expires) {
00683               char * real_path;
00684               int real_path_len;
00685               char *s1, *s2;
00686               int s_len;
00687 
00688               /* Clear the expired config */
00689               zend_hash_clean(entry->user_config);
00690 
00691               if (!IS_ABSOLUTE_PATH(path, path_len)) {
00692                      real_path = tsrm_realpath(path, NULL TSRMLS_CC);
00693                      if (real_path == NULL) {
00694                             return;
00695                      }
00696                      real_path_len = strlen(real_path);
00697                      path = real_path;
00698                      path_len = real_path_len;
00699               }
00700 
00701               if (path_len > doc_root_len) {
00702                      s1 = (char *) doc_root;
00703                      s2 = path;
00704                      s_len = doc_root_len;
00705               } else {
00706                      s1 = path;
00707                      s2 = (char *) doc_root;
00708                      s_len = path_len;
00709               }
00710 
00711               /* we have to test if path is part of DOCUMENT_ROOT.
00712                 if it is inside the docroot, we scan the tree up to the docroot 
00713                      to find more user.ini, if not we only scan the current path.
00714                 */
00715 #ifdef PHP_WIN32
00716               if (strnicmp(s1, s2, s_len) == 0) {
00717 #else 
00718               if (strncmp(s1, s2, s_len) == 0) {
00719 #endif
00720                      ptr = s2 + start;  /* start is the point where doc_root ends! */
00721                      while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
00722                             *ptr = 0;
00723                             php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
00724                             *ptr = '/';
00725                             ptr++;
00726                      }
00727               } else {
00728                      php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
00729               }
00730 
00731               entry->expires = request_time + PG(user_ini_cache_ttl);
00732        }
00733 
00734        /* Activate ini entries with values from the user config hash */
00735        php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS TSRMLS_CC);
00736 }
00737 /* }}} */
00738 
00739 static int sapi_cgi_activate(TSRMLS_D)
00740 {
00741        char *path, *doc_root, *server_name;
00742        uint path_len, doc_root_len, server_name_len;
00743 
00744        /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
00745        if (!SG(request_info).path_translated) {
00746               return FAILURE;
00747        }
00748 
00749        if (php_ini_has_per_host_config()) {
00750               /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
00751               server_name = sapi_cgibin_getenv("SERVER_NAME", sizeof("SERVER_NAME") - 1 TSRMLS_CC);
00752               /* SERVER_NAME should also be defined at this stage..but better check it anyway */
00753               if (server_name) {
00754                      server_name_len = strlen(server_name);
00755                      server_name = estrndup(server_name, server_name_len);
00756                      zend_str_tolower(server_name, server_name_len);
00757                      php_ini_activate_per_host_config(server_name, server_name_len + 1 TSRMLS_CC);
00758                      efree(server_name);
00759               }
00760        }
00761 
00762        if (php_ini_has_per_dir_config() ||
00763               (PG(user_ini_filename) && *PG(user_ini_filename))
00764        ) {
00765               /* Prepare search path */
00766               path_len = strlen(SG(request_info).path_translated);
00767 
00768               /* Make sure we have trailing slash! */
00769               if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
00770                      path = emalloc(path_len + 2);
00771                      memcpy(path, SG(request_info).path_translated, path_len + 1);
00772                      path_len = zend_dirname(path, path_len);
00773                      path[path_len++] = DEFAULT_SLASH;
00774               } else {
00775                      path = estrndup(SG(request_info).path_translated, path_len);
00776                      path_len = zend_dirname(path, path_len);
00777               }
00778               path[path_len] = 0;
00779 
00780               /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
00781               php_ini_activate_per_dir_config(path, path_len TSRMLS_CC); /* Note: for global settings sake we check from root to path */
00782 
00783               /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
00784               if (PG(user_ini_filename) && *PG(user_ini_filename)) {
00785                      doc_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT") - 1 TSRMLS_CC);
00786                      /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
00787                      if (doc_root) {
00788                             doc_root_len = strlen(doc_root);
00789                             if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
00790                                    --doc_root_len;
00791                             }
00792 #ifdef PHP_WIN32
00793                             /* paths on windows should be case-insensitive */
00794                             doc_root = estrndup(doc_root, doc_root_len);
00795                             zend_str_tolower(doc_root, doc_root_len);
00796 #endif
00797                             php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len, doc_root_len - 1 TSRMLS_CC);
00798                      }
00799               }
00800 
00801 #ifdef PHP_WIN32
00802               efree(doc_root);
00803 #endif
00804               efree(path);
00805        }
00806 
00807        return SUCCESS;
00808 }
00809 
00810 static int sapi_cgi_deactivate(TSRMLS_D)
00811 {
00812        /* flush only when SAPI was started. The reasons are:
00813               1. SAPI Deactivate is called from two places: module init and request shutdown
00814               2. When the first call occurs and the request is not set up, flush fails on FastCGI.
00815        */
00816        if (SG(sapi_started)) {
00817               if (
00818 #ifndef PHP_WIN32
00819                   !parent &&
00820 #endif
00821                   !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
00822                      php_handle_aborted_connection();
00823               }
00824        }
00825        return SUCCESS;
00826 }
00827 
00828 static int php_cgi_startup(sapi_module_struct *sapi_module)
00829 {
00830        if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
00831               return FAILURE;
00832        }
00833        return SUCCESS;
00834 }
00835 
00836 /* {{{ sapi_module_struct cgi_sapi_module
00837  */
00838 static sapi_module_struct cgi_sapi_module = {
00839        "fpm-fcgi",                                      /* name */
00840        "FPM/FastCGI",                                   /* pretty name */
00841 
00842        php_cgi_startup,                          /* startup */
00843        php_module_shutdown_wrapper,       /* shutdown */
00844 
00845        sapi_cgi_activate,                        /* activate */
00846        sapi_cgi_deactivate,               /* deactivate */
00847 
00848        sapi_cgibin_ub_write,                     /* unbuffered write */
00849        sapi_cgibin_flush,                        /* flush */
00850        NULL,                                            /* get uid */
00851        sapi_cgibin_getenv,                       /* getenv */
00852 
00853        php_error,                                       /* error handler */
00854 
00855        NULL,                                            /* header handler */
00856        sapi_cgi_send_headers,                    /* send headers handler */
00857        NULL,                                            /* send header handler */
00858 
00859        sapi_cgi_read_post,                       /* read POST data */
00860        sapi_cgi_read_cookies,                    /* read Cookies */
00861 
00862        sapi_cgi_register_variables,       /* register server variables */
00863        sapi_cgi_log_message,                     /* Log message */
00864        NULL,                                            /* Get request time */
00865        NULL,                                            /* Child terminate */
00866 
00867        STANDARD_SAPI_MODULE_PROPERTIES
00868 };
00869 /* }}} */
00870 
00871 /* {{{ arginfo ext/standard/dl.c */
00872 ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
00873        ZEND_ARG_INFO(0, extension_filename)
00874 ZEND_END_ARG_INFO()
00875 /* }}} */
00876 
00877 static const zend_function_entry additional_functions[] = {
00878        ZEND_FE(dl, arginfo_dl)
00879        {NULL, NULL, NULL}
00880 };
00881 
00882 /* {{{ php_cgi_usage
00883  */
00884 static void php_cgi_usage(char *argv0)
00885 {
00886        char *prog;
00887 
00888        prog = strrchr(argv0, '/');
00889        if (prog) {
00890               prog++;
00891        } else {
00892               prog = "php";
00893        }
00894 
00895        php_printf(   "Usage: %s [-n] [-e] [-h] [-i] [-m] [-v] [-t] [-p <prefix>] [-g <pid>] [-c <file>] [-d foo[=bar]] [-y <file>]\n"
00896                             "  -c <path>|<file> Look for php.ini file in this directory\n"
00897                             "  -n               No php.ini file will be used\n"
00898                             "  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
00899                             "  -e               Generate extended information for debugger/profiler\n"
00900                             "  -h               This help\n"
00901                             "  -i               PHP information\n"
00902                             "  -m               Show compiled in modules\n"
00903                             "  -v               Version number\n"
00904                             "  -p, --prefix <dir>\n"
00905                             "                   Specify alternative prefix path to FastCGI process manager (default: %s).\n"
00906                             "  -g, --pid <file>\n"
00907                             "                   Specify the PID file location.\n"
00908                             "  -y, --fpm-config <file>\n"
00909                             "                   Specify alternative path to FastCGI process manager config file.\n"
00910                             "  -t, --test       Test FPM configuration and exit\n",
00911                             prog, PHP_PREFIX);
00912 }
00913 /* }}} */
00914 
00915 /* {{{ is_valid_path
00916  *
00917  * some server configurations allow '..' to slip through in the
00918  * translated path.   We'll just refuse to handle such a path.
00919  */
00920 static int is_valid_path(const char *path)
00921 {
00922        const char *p;
00923 
00924        if (!path) {
00925               return 0;
00926        }
00927        p = strstr(path, "..");
00928        if (p) {
00929               if ((p == path || IS_SLASH(*(p-1))) &&
00930                      (*(p+2) == 0 || IS_SLASH(*(p+2)))
00931               ) {
00932                      return 0;
00933               }
00934               while (1) {
00935                      p = strstr(p+1, "..");
00936                      if (!p) {
00937                             break;
00938                      }
00939                      if (IS_SLASH(*(p-1)) &&
00940                             (*(p+2) == 0 || IS_SLASH(*(p+2)))
00941                      ) {
00942                                    return 0;
00943                      }
00944               }
00945        }
00946        return 1;
00947 }
00948 /* }}} */
00949 
00950 /* {{{ init_request_info
00951 
00952   initializes request_info structure
00953 
00954   specificly in this section we handle proper translations
00955   for:
00956 
00957   PATH_INFO
00958        derived from the portion of the URI path following
00959        the script name but preceding any query data
00960        may be empty
00961 
00962   PATH_TRANSLATED
00963     derived by taking any path-info component of the
00964        request URI and performing any virtual-to-physical
00965        translation appropriate to map it onto the server's
00966        document repository structure
00967 
00968        empty if PATH_INFO is empty
00969 
00970        The env var PATH_TRANSLATED **IS DIFFERENT** than the
00971        request_info.path_translated variable, the latter should
00972        match SCRIPT_FILENAME instead.
00973 
00974   SCRIPT_NAME
00975     set to a URL path that could identify the CGI script
00976        rather than the interpreter.  PHP_SELF is set to this
00977 
00978   REQUEST_URI
00979     uri section following the domain:port part of a URI
00980 
00981   SCRIPT_FILENAME
00982     The virtual-to-physical translation of SCRIPT_NAME (as per
00983        PATH_TRANSLATED)
00984 
00985   These settings are documented at
00986   http://cgi-spec.golux.com/
00987 
00988 
00989   Based on the following URL request:
00990 
00991   http://localhost/info.php/test?a=b
00992 
00993   should produce, which btw is the same as if
00994   we were running under mod_cgi on apache (ie. not
00995   using ScriptAlias directives):
00996 
00997   PATH_INFO=/test
00998   PATH_TRANSLATED=/docroot/test
00999   SCRIPT_NAME=/info.php
01000   REQUEST_URI=/info.php/test?a=b
01001   SCRIPT_FILENAME=/docroot/info.php
01002   QUERY_STRING=a=b
01003 
01004   but what we get is (cgi/mod_fastcgi under apache):
01005 
01006   PATH_INFO=/info.php/test
01007   PATH_TRANSLATED=/docroot/info.php/test
01008   SCRIPT_NAME=/php/php-cgi  (from the Action setting I suppose)
01009   REQUEST_URI=/info.php/test?a=b
01010   SCRIPT_FILENAME=/path/to/php/bin/php-cgi  (Action setting translated)
01011   QUERY_STRING=a=b
01012 
01013   Comments in the code below refer to using the above URL in a request
01014 
01015  */
01016 static void init_request_info(TSRMLS_D)
01017 {
01018        char *env_script_filename = sapi_cgibin_getenv("SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME") - 1 TSRMLS_CC);
01019        char *env_path_translated = sapi_cgibin_getenv("PATH_TRANSLATED", sizeof("PATH_TRANSLATED") - 1 TSRMLS_CC);
01020        char *script_path_translated = env_script_filename;
01021        char *ini;
01022        int apache_was_here = 0;
01023 
01024        /* some broken servers do not have script_filename or argv0
01025         * an example, IIS configured in some ways.  then they do more
01026         * broken stuff and set path_translated to the cgi script location */
01027        if (!script_path_translated && env_path_translated) {
01028               script_path_translated = env_path_translated;
01029        }
01030 
01031        /* initialize the defaults */
01032        SG(request_info).path_translated = NULL;
01033        SG(request_info).request_method = NULL;
01034        SG(request_info).proto_num = 1000;
01035        SG(request_info).query_string = NULL;
01036        SG(request_info).request_uri = NULL;
01037        SG(request_info).content_type = NULL;
01038        SG(request_info).content_length = 0;
01039        SG(sapi_headers).http_response_code = 200;
01040 
01041        /* script_path_translated being set is a good indication that
01042         * we are running in a cgi environment, since it is always
01043         * null otherwise.  otherwise, the filename
01044         * of the script will be retreived later via argc/argv */
01045        if (script_path_translated) {
01046               const char *auth;
01047               char *content_length = sapi_cgibin_getenv("CONTENT_LENGTH", sizeof("CONTENT_LENGTH") - 1 TSRMLS_CC);
01048               char *content_type = sapi_cgibin_getenv("CONTENT_TYPE", sizeof("CONTENT_TYPE") - 1 TSRMLS_CC);
01049               char *env_path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO") - 1 TSRMLS_CC);
01050               char *env_script_name = sapi_cgibin_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME") - 1 TSRMLS_CC);
01051 
01052               /* Hack for buggy IIS that sets incorrect PATH_INFO */
01053               char *env_server_software = sapi_cgibin_getenv("SERVER_SOFTWARE", sizeof("SERVER_SOFTWARE") - 1 TSRMLS_CC);
01054               if (env_server_software &&
01055                      env_script_name &&
01056                      env_path_info &&
01057                      strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS") - 1) == 0 &&
01058                      strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
01059               ) {
01060                      env_path_info = _sapi_cgibin_putenv("ORIG_PATH_INFO", env_path_info TSRMLS_CC);
01061                      env_path_info += strlen(env_script_name);
01062                      if (*env_path_info == 0) {
01063                             env_path_info = NULL;
01064                      }
01065                      env_path_info = _sapi_cgibin_putenv("PATH_INFO", env_path_info TSRMLS_CC);
01066               }
01067 
01068 #define APACHE_PROXY_FCGI_PREFIX "proxy:fcgi://"
01069               /* Fix proxy URLs in SCRIPT_FILENAME generated by Apache mod_proxy_fcgi:
01070                *     proxy:fcgi://localhost:9000/some-dir/info.php/test
01071                * should be changed to:
01072                *     /some-dir/info.php/test
01073                * See: http://bugs.php.net/bug.php?id=54152
01074                *      https://issues.apache.org/bugzilla/show_bug.cgi?id=50851
01075                */
01076               if (env_script_filename &&
01077                      strncasecmp(env_script_filename, APACHE_PROXY_FCGI_PREFIX, sizeof(APACHE_PROXY_FCGI_PREFIX) - 1) == 0) {
01078                      /* advance to first character of hostname */
01079                      char *p = env_script_filename + (sizeof(APACHE_PROXY_FCGI_PREFIX) - 1);
01080                      while (*p != '\0' && *p != '/') {
01081                             p++;   /* move past hostname and port */
01082                      }
01083                      if (*p != '\0') {
01084                             /* Copy path portion in place to avoid memory leak.  Note
01085                              * that this also affects what script_path_translated points
01086                              * to. */
01087                             memmove(env_script_filename, p, strlen(p) + 1);
01088                             apache_was_here = 1;
01089                      }
01090               }
01091 
01092               if (CGIG(fix_pathinfo)) {
01093                      struct stat st;
01094                      char *real_path = NULL;
01095                      char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL") - 1 TSRMLS_CC);
01096                      char *env_document_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT") - 1 TSRMLS_CC);
01097                      char *orig_path_translated = env_path_translated;
01098                      char *orig_path_info = env_path_info;
01099                      char *orig_script_name = env_script_name;
01100                      char *orig_script_filename = env_script_filename;
01101                      int script_path_translated_len;
01102 
01103                      if (!env_document_root && PG(doc_root)) {
01104                             env_document_root = _sapi_cgibin_putenv("DOCUMENT_ROOT", PG(doc_root) TSRMLS_CC);
01105                             /* fix docroot */
01106                             TRANSLATE_SLASHES(env_document_root);
01107                      }
01108 
01109                      if (env_path_translated != NULL && env_redirect_url != NULL &&
01110                          env_path_translated != script_path_translated &&
01111                          strcmp(env_path_translated, script_path_translated) != 0) {
01112                             /*
01113                              * pretty much apache specific.  If we have a redirect_url
01114                              * then our script_filename and script_name point to the
01115                              * php executable
01116                              */
01117                             script_path_translated = env_path_translated;
01118                             /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
01119                             env_script_name = env_redirect_url;
01120                      }
01121 
01122 #ifdef __riscos__
01123                      /* Convert path to unix format*/
01124                      __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
01125                      script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
01126 #endif
01127 
01128                      /*
01129                       * if the file doesn't exist, try to extract PATH_INFO out
01130                       * of it by stat'ing back through the '/'
01131                       * this fixes url's like /info.php/test
01132                       */
01133                      if (script_path_translated &&
01134                             (script_path_translated_len = strlen(script_path_translated)) > 0 &&
01135                             (script_path_translated[script_path_translated_len-1] == '/' ||
01136 #ifdef PHP_WIN32
01137                             script_path_translated[script_path_translated_len-1] == '\\' ||
01138 #endif
01139                             (real_path = tsrm_realpath(script_path_translated, NULL TSRMLS_CC)) == NULL)
01140                      ) {
01141                             char *pt = estrndup(script_path_translated, script_path_translated_len);
01142                             int len = script_path_translated_len;
01143                             char *ptr;
01144 
01145                             while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
01146                                    *ptr = 0;
01147                                    if (stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
01148                                           /*
01149                                            * okay, we found the base script!
01150                                            * work out how many chars we had to strip off;
01151                                            * then we can modify PATH_INFO
01152                                            * accordingly
01153                                            *
01154                                            * we now have the makings of
01155                                            * PATH_INFO=/test
01156                                            * SCRIPT_FILENAME=/docroot/info.php
01157                                            *
01158                                            * we now need to figure out what docroot is.
01159                                            * if DOCUMENT_ROOT is set, this is easy, otherwise,
01160                                            * we have to play the game of hide and seek to figure
01161                                            * out what SCRIPT_NAME should be
01162                                            */
01163                                           int ptlen = strlen(pt);
01164                                           int slen = len - ptlen;
01165                                           int pilen = env_path_info ? strlen(env_path_info) : 0;
01166                                           int tflag = 0;
01167                                           char *path_info;
01168                                           if (apache_was_here) {
01169                                                  /* recall that PATH_INFO won't exist */
01170                                                  path_info = script_path_translated + ptlen;
01171                                                  tflag = (slen != 0 && (!orig_path_info || strcmp(orig_path_info, path_info) != 0));
01172                                           } else {
01173                                                  path_info = env_path_info ? env_path_info + pilen - slen : NULL;
01174                                                  tflag = (orig_path_info != path_info);
01175                                           }
01176 
01177                                           if (tflag) {
01178                                                  if (orig_path_info) {
01179                                                         char old;
01180 
01181                                                         _sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
01182                                                         old = path_info[0];
01183                                                         path_info[0] = 0;
01184                                                         if (!orig_script_name ||
01185                                                                strcmp(orig_script_name, env_path_info) != 0) {
01186                                                                if (orig_script_name) {
01187                                                                       _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
01188                                                                }
01189                                                                SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_path_info TSRMLS_CC);
01190                                                         } else {
01191                                                                SG(request_info).request_uri = orig_script_name;
01192                                                         }
01193                                                         path_info[0] = old;
01194                                                  }
01195                                                  env_path_info = _sapi_cgibin_putenv("PATH_INFO", path_info TSRMLS_CC);
01196                                           }
01197                                           if (!orig_script_filename ||
01198                                                  strcmp(orig_script_filename, pt) != 0) {
01199                                                  if (orig_script_filename) {
01200                                                         _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
01201                                                  }
01202                                                  script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", pt TSRMLS_CC);
01203                                           }
01204                                           TRANSLATE_SLASHES(pt);
01205 
01206                                           /* figure out docroot
01207                                            * SCRIPT_FILENAME minus SCRIPT_NAME
01208                                            */
01209                                           if (env_document_root) {
01210                                                  int l = strlen(env_document_root);
01211                                                  int path_translated_len = 0;
01212                                                  char *path_translated = NULL;
01213 
01214                                                  if (l && env_document_root[l - 1] == '/') {
01215                                                         --l;
01216                                                  }
01217 
01218                                                  /* we have docroot, so we should have:
01219                                                   * DOCUMENT_ROOT=/docroot
01220                                                   * SCRIPT_FILENAME=/docroot/info.php
01221                                                   */
01222 
01223                                                  /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
01224                                                  path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
01225                                                  path_translated = (char *) emalloc(path_translated_len + 1);
01226                                                  memcpy(path_translated, env_document_root, l);
01227                                                  if (env_path_info) {
01228                                                         memcpy(path_translated + l, env_path_info, (path_translated_len - l));
01229                                                  }
01230                                                  path_translated[path_translated_len] = '\0';
01231                                                  if (orig_path_translated) {
01232                                                         _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
01233                                                  }
01234                                                  env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
01235                                                  efree(path_translated);
01236                                           } else if (   env_script_name &&
01237                                                                strstr(pt, env_script_name)
01238                                           ) {
01239                                                  /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
01240                                                  int ptlen = strlen(pt) - strlen(env_script_name);
01241                                                  int path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
01242                                                  char *path_translated = NULL;
01243 
01244                                                  path_translated = (char *) emalloc(path_translated_len + 1);
01245                                                  memcpy(path_translated, pt, ptlen);
01246                                                  if (env_path_info) {
01247                                                         memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
01248                                                  }
01249                                                  path_translated[path_translated_len] = '\0';
01250                                                  if (orig_path_translated) {
01251                                                         _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
01252                                                  }
01253                                                  env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
01254                                                  efree(path_translated);
01255                                           }
01256                                           break;
01257                                    }
01258                             }
01259                             if (!ptr) {
01260                                    /*
01261                                     * if we stripped out all the '/' and still didn't find
01262                                     * a valid path... we will fail, badly. of course we would
01263                                     * have failed anyway... we output 'no input file' now.
01264                                     */
01265                                    if (orig_script_filename) {
01266                                           _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
01267                                    }
01268                                    script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", NULL TSRMLS_CC);
01269                                    SG(sapi_headers).http_response_code = 404;
01270                             }
01271                             if (!SG(request_info).request_uri) {
01272                                    if (!orig_script_name ||
01273                                           strcmp(orig_script_name, env_script_name) != 0) {
01274                                           if (orig_script_name) {
01275                                                  _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
01276                                           }
01277                                           SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
01278                                    } else {
01279                                           SG(request_info).request_uri = orig_script_name;
01280                                    }
01281                             }
01282                             if (pt) {
01283                                    efree(pt);
01284                             }
01285                      } else {
01286                             /* make sure path_info/translated are empty */
01287                             if (!orig_script_filename ||
01288                                    (script_path_translated != orig_script_filename &&
01289                                    strcmp(script_path_translated, orig_script_filename) != 0)) {
01290                                    if (orig_script_filename) {
01291                                           _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
01292                                    }
01293                                    script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", script_path_translated TSRMLS_CC);
01294                             }
01295                             if (env_redirect_url) {
01296                                    if (orig_path_info) {
01297                                           _sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
01298                                           _sapi_cgibin_putenv("PATH_INFO", NULL TSRMLS_CC);
01299                                    }
01300                                    if (orig_path_translated) {
01301                                           _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
01302                                           _sapi_cgibin_putenv("PATH_TRANSLATED", NULL TSRMLS_CC);
01303                                    }
01304                             }
01305                             if (env_script_name != orig_script_name) {
01306                                    if (orig_script_name) {
01307                                           _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
01308                                    }
01309                                    SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
01310                             } else {
01311                                    SG(request_info).request_uri = env_script_name;
01312                             }
01313                             free(real_path);
01314                      }
01315               } else {
01316                      /* pre 4.3 behaviour, shouldn't be used but provides BC */
01317                      if (env_path_info) {
01318                             SG(request_info).request_uri = env_path_info;
01319                      } else {
01320                             SG(request_info).request_uri = env_script_name;
01321                      }
01322                      if (!CGIG(discard_path) && env_path_translated) {
01323                             script_path_translated = env_path_translated;
01324                      }
01325               }
01326 
01327               if (is_valid_path(script_path_translated)) {
01328                      SG(request_info).path_translated = estrdup(script_path_translated);
01329               }
01330 
01331               SG(request_info).request_method = sapi_cgibin_getenv("REQUEST_METHOD", sizeof("REQUEST_METHOD") - 1 TSRMLS_CC);
01332               /* FIXME - Work out proto_num here */
01333               SG(request_info).query_string = sapi_cgibin_getenv("QUERY_STRING", sizeof("QUERY_STRING") - 1 TSRMLS_CC);
01334               SG(request_info).content_type = (content_type ? content_type : "" );
01335               SG(request_info).content_length = (content_length ? atol(content_length) : 0);
01336 
01337               /* The CGI RFC allows servers to pass on unvalidated Authorization data */
01338               auth = sapi_cgibin_getenv("HTTP_AUTHORIZATION", sizeof("HTTP_AUTHORIZATION") - 1 TSRMLS_CC);
01339               php_handle_auth_data(auth TSRMLS_CC);
01340        }
01341 
01342        /* INI stuff */
01343        ini = sapi_cgibin_getenv("PHP_VALUE", sizeof("PHP_VALUE") - 1 TSRMLS_CC);
01344        if (ini) {
01345               int mode = ZEND_INI_USER;
01346               char *tmp;
01347               spprintf(&tmp, 0, "%s\n", ini);
01348               zend_parse_ini_string(tmp, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t)fastcgi_ini_parser, &mode TSRMLS_CC);
01349               efree(tmp);
01350        }
01351 
01352        ini = sapi_cgibin_getenv("PHP_ADMIN_VALUE", sizeof("PHP_ADMIN_VALUE") - 1 TSRMLS_CC);
01353        if (ini) {
01354               int mode = ZEND_INI_SYSTEM;
01355               char *tmp;
01356               spprintf(&tmp, 0, "%s\n", ini);
01357               zend_parse_ini_string(tmp, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t)fastcgi_ini_parser, &mode TSRMLS_CC);
01358               efree(tmp);
01359        }
01360 }
01361 /* }}} */
01362 
01363 static void fastcgi_ini_parser(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg TSRMLS_DC) /* {{{ */
01364 {
01365        int *mode = (int *)arg;
01366        char *key;
01367        char *value = NULL;
01368        struct key_value_s kv;
01369 
01370        if (!mode || !arg1) return;
01371 
01372        if (callback_type != ZEND_INI_PARSER_ENTRY) {
01373               zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: only classic entries are allowed");
01374               return;
01375        }
01376 
01377        key = Z_STRVAL_P(arg1);
01378 
01379        if (!key || strlen(key) < 1) {
01380               zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: empty key");
01381               return;
01382        }
01383 
01384        if (arg2) {
01385               value = Z_STRVAL_P(arg2);
01386        }
01387 
01388        if (!value) {
01389               zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: empty value for key '%s'", key);
01390               return;
01391        }
01392 
01393        kv.key = key;
01394        kv.value = value;
01395        kv.next = NULL;
01396        if (fpm_php_apply_defines_ex(&kv, *mode) == -1) {
01397               zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: unable to set '%s'", key);
01398        }
01399 }
01400 /* }}} */
01401 
01402 PHP_INI_BEGIN()
01403        STD_PHP_INI_ENTRY("cgi.rfc2616_headers",     "0",  PHP_INI_ALL,    OnUpdateBool,   rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
01404        STD_PHP_INI_ENTRY("cgi.nph",                 "0",  PHP_INI_ALL,    OnUpdateBool,   nph, php_cgi_globals_struct, php_cgi_globals)
01405        STD_PHP_INI_ENTRY("cgi.force_redirect",      "1",  PHP_INI_SYSTEM, OnUpdateBool,   force_redirect, php_cgi_globals_struct, php_cgi_globals)
01406        STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
01407        STD_PHP_INI_ENTRY("cgi.fix_pathinfo",        "1",  PHP_INI_SYSTEM, OnUpdateBool,   fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
01408        STD_PHP_INI_ENTRY("cgi.discard_path",        "0",  PHP_INI_SYSTEM, OnUpdateBool,   discard_path, php_cgi_globals_struct, php_cgi_globals)
01409        STD_PHP_INI_ENTRY("fastcgi.logging",         "1",  PHP_INI_SYSTEM, OnUpdateBool,   fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
01410        STD_PHP_INI_ENTRY("fastcgi.error_header",    NULL, PHP_INI_SYSTEM, OnUpdateString, error_header, php_cgi_globals_struct, php_cgi_globals)
01411        STD_PHP_INI_ENTRY("fpm.config",    NULL, PHP_INI_SYSTEM, OnUpdateString, fpm_config, php_cgi_globals_struct, php_cgi_globals)
01412 PHP_INI_END()
01413 
01414 /* {{{ php_cgi_globals_ctor
01415  */
01416 static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals TSRMLS_DC)
01417 {
01418        php_cgi_globals->rfc2616_headers = 0;
01419        php_cgi_globals->nph = 0;
01420        php_cgi_globals->force_redirect = 1;
01421        php_cgi_globals->redirect_status_env = NULL;
01422        php_cgi_globals->fix_pathinfo = 1;
01423        php_cgi_globals->discard_path = 0;
01424        php_cgi_globals->fcgi_logging = 1;
01425        zend_hash_init(&php_cgi_globals->user_config_cache, 0, NULL, (dtor_func_t) user_config_cache_entry_dtor, 1);
01426        php_cgi_globals->error_header = NULL;
01427        php_cgi_globals->fpm_config = NULL;
01428 }
01429 /* }}} */
01430 
01431 /* {{{ PHP_MINIT_FUNCTION
01432  */
01433 static PHP_MINIT_FUNCTION(cgi)
01434 {
01435 #ifdef ZTS
01436        ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
01437 #else
01438        php_cgi_globals_ctor(&php_cgi_globals TSRMLS_CC);
01439 #endif
01440        REGISTER_INI_ENTRIES();
01441        return SUCCESS;
01442 }
01443 /* }}} */
01444 
01445 /* {{{ PHP_MSHUTDOWN_FUNCTION
01446  */
01447 static PHP_MSHUTDOWN_FUNCTION(cgi)
01448 {
01449        zend_hash_destroy(&CGIG(user_config_cache));
01450 
01451        UNREGISTER_INI_ENTRIES();
01452        return SUCCESS;
01453 }
01454 /* }}} */
01455 
01456 /* {{{ PHP_MINFO_FUNCTION
01457  */
01458 static PHP_MINFO_FUNCTION(cgi)
01459 {
01460        php_info_print_table_start();
01461        php_info_print_table_row(2, "php-fpm", "active");
01462        php_info_print_table_end();
01463 
01464        DISPLAY_INI_ENTRIES();
01465 }
01466 /* }}} */
01467 
01468 PHP_FUNCTION(fastcgi_finish_request) /* {{{ */
01469 {
01470        fcgi_request *request = (fcgi_request*) SG(server_context);
01471 
01472        if (request->fd >= 0) {
01473 
01474               php_end_ob_buffers(1 TSRMLS_CC);
01475               php_header(TSRMLS_C);
01476 
01477               fcgi_flush(request, 1);
01478               fcgi_close(request, 0, 0);
01479               RETURN_TRUE;
01480        }
01481 
01482        RETURN_FALSE;
01483 
01484 }
01485 /* }}} */
01486 
01487 static const zend_function_entry cgi_fcgi_sapi_functions[] = {
01488        PHP_FE(fastcgi_finish_request,              NULL)
01489        {NULL, NULL, NULL}
01490 };
01491 
01492 static zend_module_entry cgi_module_entry = {
01493        STANDARD_MODULE_HEADER,
01494        "cgi-fcgi",
01495        cgi_fcgi_sapi_functions,
01496        PHP_MINIT(cgi),
01497        PHP_MSHUTDOWN(cgi),
01498        NULL,
01499        NULL,
01500        PHP_MINFO(cgi),
01501        NO_VERSION_YET,
01502        STANDARD_MODULE_PROPERTIES
01503 };
01504 
01505 /* {{{ main
01506  */
01507 int main(int argc, char *argv[])
01508 {
01509        int exit_status = SUCCESS;
01510        int cgi = 0, c;
01511        zend_file_handle file_handle;
01512 
01513        /* temporary locals */
01514        int orig_optind = php_optind;
01515        char *orig_optarg = php_optarg;
01516        int ini_entries_len = 0;
01517        /* end of temporary locals */
01518 
01519 #ifdef ZTS
01520        void ***tsrm_ls;
01521 #endif
01522 
01523        int max_requests = 500;
01524        int requests = 0;
01525        int fcgi_fd = 0;
01526        fcgi_request request;
01527        char *fpm_config = NULL;
01528        char *fpm_prefix = NULL;
01529        char *fpm_pid = NULL;
01530        int test_conf = 0;
01531        int php_information = 0;
01532 
01533        fcgi_init();
01534 
01535 #ifdef HAVE_SIGNAL_H
01536 #if defined(SIGPIPE) && defined(SIG_IGN)
01537        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
01538                                                         that sockets created via fsockopen()
01539                                                         don't kill PHP if the remote site
01540                                                         closes it.  in apache|apxs mode apache
01541                                                         does that for us!  thies@thieso.net
01542                                                         20000419 */
01543 #endif
01544 #endif
01545 
01546 #ifdef ZTS
01547        tsrm_startup(1, 1, 0, NULL);
01548        tsrm_ls = ts_resource(0);
01549 #endif
01550 
01551        sapi_startup(&cgi_sapi_module);
01552        cgi_sapi_module.php_ini_path_override = NULL;
01553 
01554 #ifdef PHP_WIN32
01555        _fmode = _O_BINARY; /* sets default for file streams to binary */
01556        setmode(_fileno(stdin),  O_BINARY);       /* make the stdio mode be binary */
01557        setmode(_fileno(stdout), O_BINARY);       /* make the stdio mode be binary */
01558        setmode(_fileno(stderr), O_BINARY);       /* make the stdio mode be binary */
01559 #endif
01560 
01561        while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
01562               switch (c) {
01563                      case 'c':
01564                             if (cgi_sapi_module.php_ini_path_override) {
01565                                    free(cgi_sapi_module.php_ini_path_override);
01566                             }
01567                             cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
01568                             break;
01569 
01570                      case 'n':
01571                             cgi_sapi_module.php_ini_ignore = 1;
01572                             break;
01573 
01574                      case 'd': {
01575                             /* define ini entries on command line */
01576                             int len = strlen(php_optarg);
01577                             char *val;
01578 
01579                             if ((val = strchr(php_optarg, '='))) {
01580                                    val++;
01581                                    if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
01582                                           cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
01583                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
01584                                           ini_entries_len += (val - php_optarg);
01585                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
01586                                           ini_entries_len++;
01587                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
01588                                           ini_entries_len += len - (val - php_optarg);
01589                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
01590                                           ini_entries_len += sizeof("\n\0\"") - 2;
01591                                    } else {
01592                                           cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
01593                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
01594                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
01595                                           ini_entries_len += len + sizeof("\n\0") - 2;
01596                                    }
01597                             } else {
01598                                    cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
01599                                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
01600                                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
01601                                    ini_entries_len += len + sizeof("=1\n\0") - 2;
01602                             }
01603                             break;
01604                      }
01605 
01606                      case 'y':
01607                             fpm_config = php_optarg;
01608                             break;
01609 
01610                      case 'p':
01611                             fpm_prefix = php_optarg;
01612                             break;
01613 
01614                      case 'g':
01615                             fpm_pid = php_optarg;
01616                             break;
01617 
01618                      case 'e': /* enable extended info output */
01619                             CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
01620                             break;
01621 
01622                      case 't': 
01623                             test_conf++;
01624                             break;
01625 
01626                      case 'm': /* list compiled in modules */
01627                             cgi_sapi_module.startup(&cgi_sapi_module);
01628                             php_output_startup();
01629                             php_output_activate(TSRMLS_C);
01630                             SG(headers_sent) = 1;
01631                             php_printf("[PHP Modules]\n");
01632                             print_modules(TSRMLS_C);
01633                             php_printf("\n[Zend Modules]\n");
01634                             print_extensions(TSRMLS_C);
01635                             php_printf("\n");
01636                             php_end_ob_buffers(1 TSRMLS_CC);
01637                             fcgi_shutdown();
01638                             exit_status = 0;
01639                             goto out;
01640 
01641                      case 'i': /* php info & quit */
01642                             php_information = 1;
01643                             break;
01644 
01645                      default:
01646                      case 'h':
01647                      case '?':
01648                             cgi_sapi_module.startup(&cgi_sapi_module);
01649                             php_output_startup();
01650                             php_output_activate(TSRMLS_C);
01651                             SG(headers_sent) = 1;
01652                             php_cgi_usage(argv[0]);
01653                             php_end_ob_buffers(1 TSRMLS_CC);
01654                             fcgi_shutdown();
01655                             exit_status = 0;
01656                             goto out;
01657 
01658                      case 'v': /* show php version & quit */
01659                             cgi_sapi_module.startup(&cgi_sapi_module);
01660                             if (php_request_startup(TSRMLS_C) == FAILURE) {
01661                                    SG(server_context) = NULL;
01662                                    php_module_shutdown(TSRMLS_C);
01663                                    return FAILURE;
01664                             }
01665                             SG(headers_sent) = 1;
01666                             SG(request_info).no_headers = 1;
01667 
01668 #if ZEND_DEBUG
01669                             php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2009 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__,        __TIME__, get_zend_version());
01670 #else
01671                             php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2009 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__,      get_zend_version());
01672 #endif
01673                             php_request_shutdown((void *) 0);
01674                             fcgi_shutdown();
01675                             exit_status = 0;
01676                             goto out;
01677               }
01678        }
01679 
01680        if (php_information) {
01681               cgi_sapi_module.phpinfo_as_text = 1;
01682               cgi_sapi_module.startup(&cgi_sapi_module);
01683               if (php_request_startup(TSRMLS_C) == FAILURE) {
01684                      SG(server_context) = NULL;
01685                      php_module_shutdown(TSRMLS_C);
01686                      return FAILURE;
01687               }
01688               SG(headers_sent) = 1;
01689               SG(request_info).no_headers = 1;
01690               php_print_info(0xFFFFFFFF TSRMLS_CC);
01691               php_request_shutdown((void *) 0);
01692               fcgi_shutdown();
01693               exit_status = 0;
01694               goto out;
01695        }
01696 
01697        /* No other args are permitted here as there is not interactive mode */
01698        if (argc != php_optind) {
01699               cgi_sapi_module.startup(&cgi_sapi_module);
01700               php_output_startup();
01701               php_output_activate(TSRMLS_C);
01702               SG(headers_sent) = 1;
01703               php_cgi_usage(argv[0]);
01704               php_end_ob_buffers(1 TSRMLS_CC);
01705               exit_status = 0;
01706               fcgi_shutdown();
01707               goto out;
01708        }
01709 
01710        php_optind = orig_optind;
01711        php_optarg = orig_optarg;
01712 
01713 #ifdef ZTS
01714        SG(request_info).path_translated = NULL;
01715 #endif
01716 
01717        cgi_sapi_module.additional_functions = additional_functions;
01718        cgi_sapi_module.executable_location = argv[0];
01719 
01720        /* startup after we get the above ini override se we get things right */
01721        if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
01722 #ifdef ZTS
01723               tsrm_shutdown();
01724 #endif
01725               return FAILURE;
01726        }
01727 
01728        /* check force_cgi after startup, so we have proper output */
01729        if (cgi && CGIG(force_redirect)) {
01730               /* Apache will generate REDIRECT_STATUS,
01731                * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
01732                * redirect.so and installation instructions available from
01733                * http://www.koehntopp.de/php.
01734                *   -- kk@netuse.de
01735                */
01736               if (!getenv("REDIRECT_STATUS") &&
01737                      !getenv ("HTTP_REDIRECT_STATUS") &&
01738                      /* this is to allow a different env var to be configured
01739                       * in case some server does something different than above */
01740                      (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
01741               ) {
01742                      zend_try {
01743                             SG(sapi_headers).http_response_code = 400;
01744                             PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
01745 <p>This PHP CGI binary was compiled with force-cgi-redirect enabled.  This\n\
01746 means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
01747 set, e.g. via an Apache Action directive.</p>\n\
01748 <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
01749 manual page for CGI security</a>.</p>\n\
01750 <p>For more information about changing this behaviour or re-enabling this webserver,\n\
01751 consult the installation file that came with this distribution, or visit \n\
01752 <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
01753                      } zend_catch {
01754                      } zend_end_try();
01755 #if defined(ZTS) && !defined(PHP_DEBUG)
01756                      /* XXX we're crashing here in msvc6 debug builds at
01757                       * php_message_handler_for_zend:839 because
01758                       * SG(request_info).path_translated is an invalid pointer.
01759                       * It still happens even though I set it to null, so something
01760                       * weird is going on.
01761                       */
01762                      tsrm_shutdown();
01763 #endif
01764                      return FAILURE;
01765               }
01766        }
01767 
01768        if (0 > fpm_init(argc, argv, fpm_config ? fpm_config : CGIG(fpm_config), fpm_prefix, fpm_pid, test_conf)) {
01769               return FAILURE;
01770        }
01771 
01772        fpm_is_running = 1;
01773 
01774        fcgi_fd = fpm_run(&max_requests);
01775        parent = 0;
01776 
01777        /* make php call us to get _ENV vars */
01778        php_php_import_environment_variables = php_import_environment_variables;
01779        php_import_environment_variables = cgi_php_import_environment_variables;
01780 
01781        /* library is already initialized, now init our request */
01782        fcgi_init_request(&request, fcgi_fd);
01783 
01784        zend_first_try {
01785               while (fcgi_accept_request(&request) >= 0) {
01786                      request_body_fd = -1;
01787                      SG(server_context) = (void *) &request;
01788                      init_request_info(TSRMLS_C);
01789                      CG(interactive) = 0;
01790                      char *primary_script = NULL;
01791 
01792                      fpm_request_info();
01793 
01794                      /* request startup only after we've done all we can to
01795                       *            get path_translated */
01796                      if (php_request_startup(TSRMLS_C) == FAILURE) {
01797                             fcgi_finish_request(&request, 1);
01798                             SG(server_context) = NULL;
01799                             php_module_shutdown(TSRMLS_C);
01800                             return FAILURE;
01801                      }
01802 
01803                      /* check if request_method has been sent.
01804                       * if not, it's certainly not an HTTP over fcgi request */
01805                      if (!SG(request_info).request_method) {
01806                             goto fastcgi_request_done;
01807                      }
01808 
01809                      if (fpm_status_handle_request(TSRMLS_C)) {
01810                             goto fastcgi_request_done;
01811                      }
01812 
01813                      /* If path_translated is NULL, terminate here with a 404 */
01814                      if (!SG(request_info).path_translated) {
01815                             zend_try {
01816                                    zlog(ZLOG_DEBUG, "Primary script unknown");
01817                                    SG(sapi_headers).http_response_code = 404;
01818                                    PUTS("File not found.\n");
01819                             } zend_catch {
01820                             } zend_end_try();
01821                             goto fastcgi_request_done;
01822                      }
01823 
01824                      if (fpm_php_limit_extensions(SG(request_info).path_translated)) {
01825                             SG(sapi_headers).http_response_code = 403;
01826                             PUTS("Access denied.\n");
01827                             goto fastcgi_request_done;
01828                      }
01829 
01830                      /* 
01831                       * have to duplicate SG(request_info).path_translated to be able to log errrors
01832                       * php_fopen_primary_script seems to delete SG(request_info).path_translated on failure
01833                       */
01834                      primary_script = estrdup(SG(request_info).path_translated);
01835 
01836                      /* path_translated exists, we can continue ! */
01837                      if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
01838                             zend_try {
01839                                    zlog(ZLOG_ERROR, "Unable to open primary script: %s (%s)", primary_script, strerror(errno));
01840                                    if (errno == EACCES) {
01841                                           SG(sapi_headers).http_response_code = 403;
01842                                           PUTS("Access denied.\n");
01843                                    } else {
01844                                           SG(sapi_headers).http_response_code = 404;
01845                                           PUTS("No input file specified.\n");
01846                                    }
01847                             } zend_catch {
01848                             } zend_end_try();
01849                             /* we want to serve more requests if this is fastcgi
01850                              * so cleanup and continue, request shutdown is
01851                              * handled later */
01852 
01853                             goto fastcgi_request_done;
01854                      }
01855 
01856                      fpm_request_executing();
01857 
01858                      php_execute_script(&file_handle TSRMLS_CC);
01859 
01860 fastcgi_request_done:
01861                      if (primary_script) {
01862                             efree(primary_script);
01863                      }
01864 
01865                      if (request_body_fd != -1) {
01866                             close(request_body_fd);
01867                      }
01868                      request_body_fd = -2;
01869 
01870                      if (EG(exit_status) == 255) {
01871                             if (CGIG(error_header) && *CGIG(error_header)) {
01872                                    sapi_header_line ctr = {0};
01873 
01874                                    ctr.line = CGIG(error_header);
01875                                    ctr.line_len = strlen(CGIG(error_header));
01876                                    sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
01877                             }
01878                      }
01879 
01880                      fpm_request_end(TSRMLS_C);
01881                      fpm_log_write(NULL TSRMLS_CC);
01882 
01883                      STR_FREE(SG(request_info).path_translated);
01884                      SG(request_info).path_translated = NULL;
01885 
01886                      php_request_shutdown((void *) 0);
01887 
01888                      if (exit_status == 0) {
01889                             exit_status = EG(exit_status);
01890                      }
01891 
01892                      requests++;
01893                      if (max_requests && (requests == max_requests)) {
01894                             fcgi_finish_request(&request, 1);
01895                             if (max_requests != 1) {
01896                                    /* no need to return exit_status of the last request */
01897                                    exit_status = 0;
01898                             }
01899                             break;
01900                      }
01901                      /* end of fastcgi loop */
01902               }
01903               fcgi_shutdown();
01904 
01905               if (cgi_sapi_module.php_ini_path_override) {
01906                      free(cgi_sapi_module.php_ini_path_override);
01907               }
01908               if (cgi_sapi_module.ini_entries) {
01909                      free(cgi_sapi_module.ini_entries);
01910               }
01911        } zend_catch {
01912               exit_status = 255;
01913        } zend_end_try();
01914 
01915 out:
01916 
01917        SG(server_context) = NULL;
01918        if (parent) {
01919               php_module_shutdown(TSRMLS_C);
01920               sapi_shutdown();
01921        }
01922 
01923 #ifdef ZTS
01924        tsrm_shutdown();
01925 #endif
01926 
01927 #if defined(PHP_WIN32) && ZEND_DEBUG && 0
01928        _CrtDumpMemoryLeaks();
01929 #endif
01930 
01931        return exit_status;
01932 }
01933 /* }}} */
01934 
01935 /*
01936  * Local variables:
01937  * tab-width: 4
01938  * c-basic-offset: 4
01939  * End:
01940  * vim600: sw=4 ts=4 fdm=marker
01941  * vim<600: sw=4 ts=4
01942  */