Back to index

php5  5.3.10
cgi_main.c
Go to the documentation of this file.
00001 /*
00002    +----------------------------------------------------------------------+
00003    | PHP Version 5                                                        |
00004    +----------------------------------------------------------------------+
00005    | Copyright (c) 1997-2012 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 321634 2012-01-01 13:15:04Z felipe $ */
00025 
00026 #include "php.h"
00027 #include "php_globals.h"
00028 #include "php_variables.h"
00029 #include "zend_modules.h"
00030 
00031 #include "SAPI.h"
00032 
00033 #include <stdio.h>
00034 #include "php.h"
00035 
00036 #ifdef PHP_WIN32
00037 # include "win32/time.h"
00038 # include "win32/signal.h"
00039 # include <process.h>
00040 #endif
00041 
00042 #if HAVE_SYS_TIME_H
00043 # include <sys/time.h>
00044 #endif
00045 
00046 #if HAVE_UNISTD_H
00047 # include <unistd.h>
00048 #endif
00049 
00050 #if HAVE_SIGNAL_H
00051 # include <signal.h>
00052 #endif
00053 
00054 #if HAVE_SETLOCALE
00055 # include <locale.h>
00056 #endif
00057 
00058 #if HAVE_SYS_TYPES_H
00059 # include <sys/types.h>
00060 #endif
00061 
00062 #if HAVE_SYS_WAIT_H
00063 # include <sys/wait.h>
00064 #endif
00065 
00066 #include "zend.h"
00067 #include "zend_extensions.h"
00068 #include "php_ini.h"
00069 #include "php_globals.h"
00070 #include "php_main.h"
00071 #include "fopen_wrappers.h"
00072 #include "ext/standard/php_standard.h"
00073 
00074 #ifdef PHP_WIN32
00075 # include <io.h>
00076 # include <fcntl.h>
00077 # include "win32/php_registry.h"
00078 #endif
00079 
00080 #ifdef __riscos__
00081 # include <unixlib/local.h>
00082 int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
00083 #endif
00084 
00085 #include "zend_compile.h"
00086 #include "zend_execute.h"
00087 #include "zend_highlight.h"
00088 #include "zend_indent.h"
00089 
00090 #include "php_getopt.h"
00091 
00092 #include "fastcgi.h"
00093 
00094 #ifndef PHP_WIN32
00095 /* XXX this will need to change later when threaded fastcgi is implemented.  shane */
00096 struct sigaction act, old_term, old_quit, old_int;
00097 #endif
00098 
00099 static void (*php_php_import_environment_variables)(zval *array_ptr TSRMLS_DC);
00100 
00101 #ifndef PHP_WIN32
00102 /* these globals used for forking children on unix systems */
00106 static int children = 0;
00107 
00111 static int parent = 1;
00112 
00113 /* Did parent received exit signals SIG_TERM/SIG_INT/SIG_QUIT */
00114 static int exit_signal = 0;
00115 
00116 /* Is Parent waiting for children to exit */
00117 static int parent_waiting = 0;
00118 
00122 static pid_t pgroup;
00123 #endif
00124 
00125 #define PHP_MODE_STANDARD   1
00126 #define PHP_MODE_HIGHLIGHT  2
00127 #define PHP_MODE_INDENT            3
00128 #define PHP_MODE_LINT              4
00129 #define PHP_MODE_STRIP             5
00130 
00131 static char *php_optarg = NULL;
00132 static int php_optind = 1;
00133 static zend_module_entry cgi_module_entry;
00134 
00135 static const opt_struct OPTIONS[] = {
00136        {'a', 0, "interactive"},
00137        {'b', 1, "bindpath"},
00138        {'C', 0, "no-chdir"},
00139        {'c', 1, "php-ini"},
00140        {'d', 1, "define"},
00141        {'e', 0, "profile-info"},
00142        {'f', 1, "file"},
00143        {'h', 0, "help"},
00144        {'i', 0, "info"},
00145        {'l', 0, "syntax-check"},
00146        {'m', 0, "modules"},
00147        {'n', 0, "no-php-ini"},
00148        {'q', 0, "no-header"},
00149        {'s', 0, "syntax-highlight"},
00150        {'s', 0, "syntax-highlighting"},
00151        {'w', 0, "strip"},
00152        {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
00153        {'v', 0, "version"},
00154        {'z', 1, "zend-extension"},
00155        {'T', 1, "timing"},
00156        {'-', 0, NULL} /* end of args */
00157 };
00158 
00159 typedef struct _php_cgi_globals_struct {
00160        zend_bool rfc2616_headers;
00161        zend_bool nph;
00162        zend_bool check_shebang_line;
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 #ifdef PHP_WIN32
00169        zend_bool impersonate;
00170 #endif
00171        HashTable user_config_cache;
00172 } php_cgi_globals_struct;
00173 
00174 /* {{{ user_config_cache
00175  *
00176  * Key for each cache entry is dirname(PATH_TRANSLATED).
00177  *
00178  * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
00179  *       the path starting from doc_root throught to dirname(PATH_TRANSLATED).  There is no point
00180  *       storing per-file entries as it would not be possible to detect added / deleted entries
00181  *       between separate files.
00182  */
00183 typedef struct _user_config_cache_entry {
00184        time_t expires;
00185        HashTable *user_config;
00186 } user_config_cache_entry;
00187 
00188 static void user_config_cache_entry_dtor(user_config_cache_entry *entry)
00189 {
00190        zend_hash_destroy(entry->user_config);
00191        free(entry->user_config);
00192 }
00193 /* }}} */
00194 
00195 #ifdef ZTS
00196 static int php_cgi_globals_id;
00197 #define CGIG(v) TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
00198 #else
00199 static php_cgi_globals_struct php_cgi_globals;
00200 #define CGIG(v) (php_cgi_globals.v)
00201 #endif
00202 
00203 #ifdef PHP_WIN32
00204 #define TRANSLATE_SLASHES(path) \
00205        { \
00206               char *tmp = path; \
00207               while (*tmp) { \
00208                      if (*tmp == '\\') *tmp = '/'; \
00209                      tmp++; \
00210               } \
00211        }
00212 #else
00213 #define TRANSLATE_SLASHES(path)
00214 #endif
00215 
00216 static int print_module_info(zend_module_entry *module, void *arg TSRMLS_DC)
00217 {
00218        php_printf("%s\n", module->name);
00219        return 0;
00220 }
00221 
00222 static int module_name_cmp(const void *a, const void *b TSRMLS_DC)
00223 {
00224        Bucket *f = *((Bucket **) a);
00225        Bucket *s = *((Bucket **) b);
00226 
00227        return strcasecmp(   ((zend_module_entry *)f->pData)->name,
00228                                           ((zend_module_entry *)s->pData)->name);
00229 }
00230 
00231 static void print_modules(TSRMLS_D)
00232 {
00233        HashTable sorted_registry;
00234        zend_module_entry tmp;
00235 
00236        zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
00237        zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
00238        zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
00239        zend_hash_apply_with_argument(&sorted_registry, (apply_func_arg_t) print_module_info, NULL TSRMLS_CC);
00240        zend_hash_destroy(&sorted_registry);
00241 }
00242 
00243 static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC)
00244 {
00245        php_printf("%s\n", ext->name);
00246        return 0;
00247 }
00248 
00249 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s TSRMLS_DC)
00250 {
00251        return strcmp(       ((zend_extension *)(*f)->data)->name,
00252                                    ((zend_extension *)(*s)->data)->name);
00253 }
00254 
00255 static void print_extensions(TSRMLS_D)
00256 {
00257        zend_llist sorted_exts;
00258 
00259        zend_llist_copy(&sorted_exts, &zend_extensions);
00260        sorted_exts.dtor = NULL;
00261        zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
00262        zend_llist_apply_with_argument(&sorted_exts, (llist_apply_with_arg_func_t) print_extension_info, NULL TSRMLS_CC);
00263        zend_llist_destroy(&sorted_exts);
00264 }
00265 
00266 #ifndef STDOUT_FILENO
00267 #define STDOUT_FILENO 1
00268 #endif
00269 
00270 static inline size_t sapi_cgibin_single_write(const char *str, uint str_length TSRMLS_DC)
00271 {
00272 #ifdef PHP_WRITE_STDOUT
00273        long ret;
00274 #else
00275        size_t ret;
00276 #endif
00277 
00278        if (fcgi_is_fastcgi()) {
00279               fcgi_request *request = (fcgi_request*) SG(server_context);
00280               long ret = fcgi_write(request, FCGI_STDOUT, str, str_length);
00281               if (ret <= 0) {
00282                      return 0;
00283               }
00284               return ret;
00285        }
00286 
00287 #ifdef PHP_WRITE_STDOUT
00288        ret = write(STDOUT_FILENO, str, str_length);
00289        if (ret <= 0) return 0;
00290        return ret;
00291 #else
00292        ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
00293        return ret;
00294 #endif
00295 }
00296 
00297 static int sapi_cgibin_ub_write(const char *str, uint str_length TSRMLS_DC)
00298 {
00299        const char *ptr = str;
00300        uint remaining = str_length;
00301        size_t ret;
00302 
00303        while (remaining > 0) {
00304               ret = sapi_cgibin_single_write(ptr, remaining TSRMLS_CC);
00305               if (!ret) {
00306                      php_handle_aborted_connection();
00307                      return str_length - remaining;
00308               }
00309               ptr += ret;
00310               remaining -= ret;
00311        }
00312 
00313        return str_length;
00314 }
00315 
00316 
00317 static void sapi_cgibin_flush(void *server_context)
00318 {
00319        if (fcgi_is_fastcgi()) {
00320               fcgi_request *request = (fcgi_request*) server_context;
00321               if (
00322 #ifndef PHP_WIN32
00323               !parent &&
00324 #endif
00325               request && !fcgi_flush(request, 0)) {
00326                      php_handle_aborted_connection();
00327               }
00328               return;
00329        }
00330        if (fflush(stdout) == EOF) {
00331               php_handle_aborted_connection();
00332        }
00333 }
00334 
00335 #define SAPI_CGI_MAX_HEADER_LENGTH 1024
00336 
00337 typedef struct _http_error {
00338   int code;
00339   const char* msg;
00340 } http_error;
00341 
00342 static const http_error http_error_codes[] = {
00343        {100, "Continue"},
00344        {101, "Switching Protocols"},
00345        {200, "OK"},
00346        {201, "Created"},
00347        {202, "Accepted"},
00348        {203, "Non-Authoritative Information"},
00349        {204, "No Content"},
00350        {205, "Reset Content"},
00351        {206, "Partial Content"},
00352        {300, "Multiple Choices"},
00353        {301, "Moved Permanently"},
00354        {302, "Moved Temporarily"},
00355        {303, "See Other"},
00356        {304, "Not Modified"},
00357        {305, "Use Proxy"},
00358        {400, "Bad Request"},
00359        {401, "Unauthorized"},
00360        {402, "Payment Required"},
00361        {403, "Forbidden"},
00362        {404, "Not Found"},
00363        {405, "Method Not Allowed"},
00364        {406, "Not Acceptable"},
00365        {407, "Proxy Authentication Required"},
00366        {408, "Request Time-out"},
00367        {409, "Conflict"},
00368        {410, "Gone"},
00369        {411, "Length Required"},
00370        {412, "Precondition Failed"},
00371        {413, "Request Entity Too Large"},
00372        {414, "Request-URI Too Large"},
00373        {415, "Unsupported Media Type"},
00374        {500, "Internal Server Error"},
00375        {501, "Not Implemented"},
00376        {502, "Bad Gateway"},
00377        {503, "Service Unavailable"},
00378        {504, "Gateway Time-out"},
00379        {505, "HTTP Version not supported"},
00380        {0,   NULL}
00381 };
00382 
00383 static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
00384 {
00385        char buf[SAPI_CGI_MAX_HEADER_LENGTH];
00386        sapi_header_struct *h;
00387        zend_llist_position pos;
00388        zend_bool ignore_status = 0;
00389        int response_status = SG(sapi_headers).http_response_code;
00390 
00391        if (SG(request_info).no_headers == 1) {
00392               return  SAPI_HEADER_SENT_SUCCESSFULLY;
00393        }
00394 
00395        if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
00396        {
00397               int len;
00398               zend_bool has_status = 0;
00399 
00400               if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
00401                      char *s;
00402                      len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
00403                      if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
00404                             response_status = atoi((s + 1));
00405                      }
00406 
00407                      if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
00408                             len = SAPI_CGI_MAX_HEADER_LENGTH;
00409                      }
00410 
00411               } else {
00412                      char *s;
00413 
00414                      if (SG(sapi_headers).http_status_line &&
00415                             (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
00416                             (s - SG(sapi_headers).http_status_line) >= 5 &&
00417                             strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
00418                      ) {
00419                             len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
00420                             response_status = atoi((s + 1));
00421                      } else {
00422                             h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
00423                             while (h) {
00424                                    if (h->header_len > sizeof("Status:")-1 &&
00425                                           strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
00426                                    ) {
00427                                           has_status = 1;
00428                                           break;
00429                                    }
00430                                    h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
00431                             }
00432                             if (!has_status) {
00433                                    http_error *err = (http_error*)http_error_codes;
00434 
00435                                    while (err->code != 0) {
00436                                           if (err->code == SG(sapi_headers).http_response_code) {
00437                                                  break;
00438                                           }
00439                                           err++;
00440                                    }
00441                                    if (err->msg) {
00442                                           len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->msg);
00443                                    } else {
00444                                           len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
00445                                    }
00446                             }
00447                      }
00448               }
00449 
00450               if (!has_status) {
00451                      PHPWRITE_H(buf, len);
00452                      ignore_status = 1;
00453               }
00454        }
00455 
00456        h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
00457        while (h) {
00458               /* prevent CRLFCRLF */
00459               if (h->header_len) {
00460                      if (h->header_len > sizeof("Status:")-1 && 
00461                             strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
00462                      ) {
00463                             if (!ignore_status) {
00464                                    ignore_status = 1;
00465                                    PHPWRITE_H(h->header, h->header_len);
00466                                    PHPWRITE_H("\r\n", 2);
00467                             }
00468                      } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
00469                             strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
00470                      ) {
00471                             h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
00472                             continue;
00473                      } else {
00474                             PHPWRITE_H(h->header, h->header_len);
00475                             PHPWRITE_H("\r\n", 2);
00476                      }
00477               }
00478               h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
00479        }
00480        PHPWRITE_H("\r\n", 2);
00481 
00482        return SAPI_HEADER_SENT_SUCCESSFULLY;
00483 }
00484 
00485 #ifndef STDIN_FILENO
00486 # define STDIN_FILENO 0
00487 #endif
00488 
00489 static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
00490 {
00491        uint read_bytes = 0;
00492        int tmp_read_bytes;
00493 
00494        count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
00495        while (read_bytes < count_bytes) {
00496               if (fcgi_is_fastcgi()) {
00497                      fcgi_request *request = (fcgi_request*) SG(server_context);
00498                      tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes);
00499               } else {
00500                      tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes);
00501               }
00502               if (tmp_read_bytes <= 0) {
00503                      break;
00504               }
00505               read_bytes += tmp_read_bytes;
00506        }
00507        return read_bytes;
00508 }
00509 
00510 static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC)
00511 {
00512        /* when php is started by mod_fastcgi, no regular environment
00513         * is provided to PHP.  It is always sent to PHP at the start
00514         * of a request.  So we have to do our own lookup to get env
00515         * vars.  This could probably be faster somehow.  */
00516        if (fcgi_is_fastcgi()) {
00517               fcgi_request *request = (fcgi_request*) SG(server_context);
00518               return fcgi_getenv(request, name, name_len);
00519        }
00520        /*  if cgi, or fastcgi and not found in fcgi env
00521               check the regular environment */
00522        return getenv(name);
00523 }
00524 
00525 static char *_sapi_cgibin_putenv(char *name, char *value TSRMLS_DC)
00526 {
00527        int name_len;
00528 #if !HAVE_SETENV || !HAVE_UNSETENV
00529        int len;
00530        char *buf;
00531 #endif
00532 
00533        if (!name) {
00534               return NULL;
00535        }
00536        name_len = strlen(name);
00537 
00538        /* when php is started by mod_fastcgi, no regular environment
00539         * is provided to PHP.  It is always sent to PHP at the start
00540         * of a request.  So we have to do our own lookup to get env
00541         * vars.  This could probably be faster somehow.  */
00542        if (fcgi_is_fastcgi()) {
00543               fcgi_request *request = (fcgi_request*) SG(server_context);
00544               return fcgi_putenv(request, name, name_len, value);
00545        }
00546 
00547 #if HAVE_SETENV
00548        if (value) {
00549               setenv(name, value, 1);
00550        }
00551 #endif
00552 #if HAVE_UNSETENV
00553        if (!value) {
00554               unsetenv(name);
00555        }
00556 #endif
00557 
00558 #if !HAVE_SETENV || !HAVE_UNSETENV
00559        /*  if cgi, or fastcgi and not found in fcgi env
00560               check the regular environment
00561               this leaks, but it's only cgi anyway, we'll fix
00562               it for 5.0
00563        */
00564        len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
00565        buf = (char *) malloc(len);
00566        if (buf == NULL) {
00567               return getenv(name);
00568        }
00569 #endif
00570 #if !HAVE_SETENV
00571        if (value) {
00572               len = slprintf(buf, len - 1, "%s=%s", name, value);
00573               putenv(buf);
00574        }
00575 #endif
00576 #if !HAVE_UNSETENV
00577        if (!value) {
00578               len = slprintf(buf, len - 1, "%s=", name);
00579               putenv(buf);
00580        }
00581 #endif
00582        return getenv(name);
00583 }
00584 
00585 static char *sapi_cgi_read_cookies(TSRMLS_D)
00586 {
00587        return sapi_cgibin_getenv((char *) "HTTP_COOKIE", sizeof("HTTP_COOKIE")-1 TSRMLS_CC);
00588 }
00589 
00590 void cgi_php_import_environment_variables(zval *array_ptr TSRMLS_DC)
00591 {
00592        if (PG(http_globals)[TRACK_VARS_ENV] &&
00593               array_ptr != PG(http_globals)[TRACK_VARS_ENV] &&
00594               Z_TYPE_P(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
00595               zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_ENV])) > 0
00596        ) {
00597               zval_dtor(array_ptr);
00598               *array_ptr = *PG(http_globals)[TRACK_VARS_ENV];
00599               INIT_PZVAL(array_ptr);
00600               zval_copy_ctor(array_ptr);
00601               return;
00602        } else if (PG(http_globals)[TRACK_VARS_SERVER] &&
00603               array_ptr != PG(http_globals)[TRACK_VARS_SERVER] &&
00604               Z_TYPE_P(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
00605               zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER])) > 0
00606        ) {
00607               zval_dtor(array_ptr);
00608               *array_ptr = *PG(http_globals)[TRACK_VARS_SERVER];
00609               INIT_PZVAL(array_ptr);
00610               zval_copy_ctor(array_ptr);
00611               return;
00612        }
00613 
00614        /* call php's original import as a catch-all */
00615        php_php_import_environment_variables(array_ptr TSRMLS_CC);
00616 
00617        if (fcgi_is_fastcgi()) {
00618               fcgi_request *request = (fcgi_request*) SG(server_context);
00619               HashPosition pos;
00620               int magic_quotes_gpc = PG(magic_quotes_gpc);
00621               char *var, **val;
00622               uint var_len;
00623               ulong idx;
00624               int filter_arg = (array_ptr == PG(http_globals)[TRACK_VARS_ENV])?PARSE_ENV:PARSE_SERVER;
00625 
00626               /* turn off magic_quotes while importing environment variables */
00627               PG(magic_quotes_gpc) = 0;
00628               for (zend_hash_internal_pointer_reset_ex(request->env, &pos);
00629                      zend_hash_get_current_key_ex(request->env, &var, &var_len, &idx, 0, &pos) == HASH_KEY_IS_STRING &&
00630                      zend_hash_get_current_data_ex(request->env, (void **) &val, &pos) == SUCCESS;
00631                      zend_hash_move_forward_ex(request->env, &pos)
00632               ) {
00633                      unsigned int new_val_len;
00634 
00635                      if (sapi_module.input_filter(filter_arg, var, val, strlen(*val), &new_val_len TSRMLS_CC)) {
00636                             php_register_variable_safe(var, *val, new_val_len, array_ptr TSRMLS_CC);
00637                      }
00638               }
00639               PG(magic_quotes_gpc) = magic_quotes_gpc;
00640        }
00641 }
00642 
00643 static void sapi_cgi_register_variables(zval *track_vars_array TSRMLS_DC)
00644 {
00645        unsigned int php_self_len;
00646        char *php_self;
00647 
00648        /* In CGI mode, we consider the environment to be a part of the server
00649         * variables
00650         */
00651        php_import_environment_variables(track_vars_array TSRMLS_CC);
00652 
00653        if (CGIG(fix_pathinfo)) {
00654               char *script_name = SG(request_info).request_uri;
00655               unsigned int script_name_len = script_name ? strlen(script_name) : 0;
00656               char *path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
00657               unsigned int path_info_len = path_info ? strlen(path_info) : 0;
00658 
00659               php_self_len = script_name_len + path_info_len;
00660               php_self = emalloc(php_self_len + 1);
00661 
00662               if (script_name) {
00663                      memcpy(php_self, script_name, script_name_len + 1);
00664               }
00665               if (path_info) {
00666                      memcpy(php_self + script_name_len, path_info, path_info_len + 1);
00667               }
00668 
00669               /* Build the special-case PHP_SELF variable for the CGI version */
00670               if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
00671                      php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
00672               }
00673               efree(php_self);
00674        } else {
00675               php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
00676               php_self_len = strlen(php_self);
00677               if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
00678                      php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
00679               }
00680        }
00681 }
00682 
00683 static void sapi_cgi_log_message(char *message)
00684 {
00685        TSRMLS_FETCH();
00686 
00687        if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
00688               fcgi_request *request;
00689 
00690               request = (fcgi_request*) SG(server_context);
00691               if (request) {
00692                      int len = strlen(message);
00693                      char *buf = malloc(len+2);
00694 
00695                      memcpy(buf, message, len);
00696                      memcpy(buf + len, "\n", sizeof("\n"));
00697                      fcgi_write(request, FCGI_STDERR, buf, len+1);
00698                      free(buf);
00699               } else {
00700                      fprintf(stderr, "%s\n", message);
00701               }
00702               /* ignore return code */
00703        } else {
00704               fprintf(stderr, "%s\n", message);
00705        }
00706 }
00707 
00708 /* {{{ php_cgi_ini_activate_user_config
00709  */
00710 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)
00711 {
00712        char *ptr;
00713        user_config_cache_entry *new_entry, *entry;
00714        time_t request_time = sapi_get_request_time(TSRMLS_C);
00715 
00716        /* Find cached config entry: If not found, create one */
00717        if (zend_hash_find(&CGIG(user_config_cache), path, path_len + 1, (void **) &entry) == FAILURE) {
00718               new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
00719               new_entry->expires = 0;
00720               new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
00721               zend_hash_init(new_entry->user_config, 0, NULL, (dtor_func_t) config_zval_dtor, 1);
00722               zend_hash_update(&CGIG(user_config_cache), path, path_len + 1, new_entry, sizeof(user_config_cache_entry), (void **) &entry);
00723               free(new_entry);
00724        }
00725 
00726        /* Check whether cache entry has expired and rescan if it is */
00727        if (request_time > entry->expires) {
00728               char *real_path = NULL;
00729               int real_path_len;
00730               char *s1, *s2;
00731               int s_len;
00732 
00733               /* Clear the expired config */
00734               zend_hash_clean(entry->user_config);
00735 
00736               if (!IS_ABSOLUTE_PATH(path, path_len)) {
00737                      real_path = tsrm_realpath(path, NULL TSRMLS_CC);
00738                      /* see #51688, looks like we may get invalid path as doc root using cgi with apache */
00739                      if (real_path == NULL) {
00740                             return;
00741                      }
00742                      real_path_len = strlen(real_path);
00743                      path = real_path;
00744                      path_len = real_path_len;
00745               }
00746 
00747               if (path_len > doc_root_len) {
00748                      s1 = (char *) doc_root;
00749                      s2 = path;
00750                      s_len = doc_root_len;
00751               } else {
00752                      s1 = path;
00753                      s2 = (char *) doc_root;
00754                      s_len = path_len;
00755               }
00756 
00757               /* we have to test if path is part of DOCUMENT_ROOT.
00758                 if it is inside the docroot, we scan the tree up to the docroot 
00759                      to find more user.ini, if not we only scan the current path.
00760                 */
00761 #ifdef PHP_WIN32
00762               if (strnicmp(s1, s2, s_len) == 0) {
00763 #else 
00764               if (strncmp(s1, s2, s_len) == 0) {
00765 #endif
00766                      ptr = s2 + start;  /* start is the point where doc_root ends! */
00767                      while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
00768                             *ptr = 0;
00769                             php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
00770                             *ptr = '/';
00771                             ptr++;
00772                      }
00773               } else {
00774                      php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
00775               }
00776 
00777               if (real_path) {
00778                      free(real_path);
00779               }
00780               entry->expires = request_time + PG(user_ini_cache_ttl);
00781        }
00782 
00783        /* Activate ini entries with values from the user config hash */
00784        php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS TSRMLS_CC);
00785 }
00786 /* }}} */
00787 
00788 static int sapi_cgi_activate(TSRMLS_D)
00789 {
00790        char *path, *doc_root, *server_name;
00791        uint path_len, doc_root_len, server_name_len;
00792 
00793        /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
00794        if (!SG(request_info).path_translated) {
00795               return FAILURE;
00796        }
00797 
00798        if (php_ini_has_per_host_config()) {
00799               /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
00800               server_name = sapi_cgibin_getenv("SERVER_NAME", sizeof("SERVER_NAME") - 1 TSRMLS_CC);
00801               /* SERVER_NAME should also be defined at this stage..but better check it anyway */
00802               if (server_name) {
00803                      server_name_len = strlen(server_name);
00804                      server_name = estrndup(server_name, server_name_len);
00805                      zend_str_tolower(server_name, server_name_len);
00806                      php_ini_activate_per_host_config(server_name, server_name_len + 1 TSRMLS_CC);
00807                      efree(server_name);
00808               }
00809        }
00810 
00811        if (php_ini_has_per_dir_config() ||
00812               (PG(user_ini_filename) && *PG(user_ini_filename))
00813        ) {
00814               /* Prepare search path */
00815               path_len = strlen(SG(request_info).path_translated);
00816 
00817               /* Make sure we have trailing slash! */
00818               if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
00819                      path = emalloc(path_len + 2);
00820                      memcpy(path, SG(request_info).path_translated, path_len + 1);
00821                      path_len = zend_dirname(path, path_len);
00822                      path[path_len++] = DEFAULT_SLASH;
00823               } else {
00824                      path = estrndup(SG(request_info).path_translated, path_len);
00825                      path_len = zend_dirname(path, path_len);
00826               }
00827               path[path_len] = 0;
00828 
00829               /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
00830               php_ini_activate_per_dir_config(path, path_len TSRMLS_CC); /* Note: for global settings sake we check from root to path */
00831 
00832               /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
00833               if (PG(user_ini_filename) && *PG(user_ini_filename)) {
00834                      doc_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT") - 1 TSRMLS_CC);
00835                      /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
00836                      if (doc_root) {
00837                             doc_root_len = strlen(doc_root);
00838                             if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
00839                                    --doc_root_len;
00840                             }
00841 #ifdef PHP_WIN32
00842                             /* paths on windows should be case-insensitive */
00843                             doc_root = estrndup(doc_root, doc_root_len);
00844                             zend_str_tolower(doc_root, doc_root_len);
00845 #endif
00846                             php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len, doc_root_len - 1 TSRMLS_CC);
00847                      }
00848               }
00849 
00850 #ifdef PHP_WIN32
00851               efree(doc_root);
00852 #endif
00853               efree(path);
00854        }
00855 
00856        return SUCCESS;
00857 }
00858 
00859 static int sapi_cgi_deactivate(TSRMLS_D)
00860 {
00861        /* flush only when SAPI was started. The reasons are:
00862               1. SAPI Deactivate is called from two places: module init and request shutdown
00863               2. When the first call occurs and the request is not set up, flush fails on FastCGI.
00864        */
00865        if (SG(sapi_started)) {
00866               if (fcgi_is_fastcgi()) {
00867                      if (
00868 #ifndef PHP_WIN32
00869                             !parent &&
00870 #endif
00871                             !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
00872                             php_handle_aborted_connection();
00873                      }
00874               } else {
00875                      sapi_cgibin_flush(SG(server_context));
00876               }
00877        }
00878        return SUCCESS;
00879 }
00880 
00881 static int php_cgi_startup(sapi_module_struct *sapi_module)
00882 {
00883        if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
00884               return FAILURE;
00885        }
00886        return SUCCESS;
00887 }
00888 
00889 /* {{{ sapi_module_struct cgi_sapi_module
00890  */
00891 static sapi_module_struct cgi_sapi_module = {
00892        "cgi-fcgi",                                      /* name */
00893        "CGI/FastCGI",                                   /* pretty name */
00894 
00895        php_cgi_startup,                          /* startup */
00896        php_module_shutdown_wrapper,       /* shutdown */
00897 
00898        sapi_cgi_activate,                        /* activate */
00899        sapi_cgi_deactivate,               /* deactivate */
00900 
00901        sapi_cgibin_ub_write,                     /* unbuffered write */
00902        sapi_cgibin_flush,                        /* flush */
00903        NULL,                                            /* get uid */
00904        sapi_cgibin_getenv,                       /* getenv */
00905 
00906        php_error,                                       /* error handler */
00907 
00908        NULL,                                            /* header handler */
00909        sapi_cgi_send_headers,                    /* send headers handler */
00910        NULL,                                            /* send header handler */
00911 
00912        sapi_cgi_read_post,                       /* read POST data */
00913        sapi_cgi_read_cookies,                    /* read Cookies */
00914 
00915        sapi_cgi_register_variables,       /* register server variables */
00916        sapi_cgi_log_message,                     /* Log message */
00917        NULL,                                            /* Get request time */
00918        NULL,                                            /* Child terminate */
00919 
00920        STANDARD_SAPI_MODULE_PROPERTIES
00921 };
00922 /* }}} */
00923 
00924 /* {{{ arginfo ext/standard/dl.c */
00925 ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
00926        ZEND_ARG_INFO(0, extension_filename)
00927 ZEND_END_ARG_INFO()
00928 /* }}} */
00929 
00930 static const zend_function_entry additional_functions[] = {
00931        ZEND_FE(dl, arginfo_dl)
00932        {NULL, NULL, NULL}
00933 };
00934 
00935 /* {{{ php_cgi_usage
00936  */
00937 static void php_cgi_usage(char *argv0)
00938 {
00939        char *prog;
00940 
00941        prog = strrchr(argv0, '/');
00942        if (prog) {
00943               prog++;
00944        } else {
00945               prog = "php";
00946        }
00947 
00948        php_printf(   "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
00949                             "       %s <file> [args...]\n"
00950                             "  -a               Run interactively\n"
00951                             "  -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
00952                             "  -C               Do not chdir to the script's directory\n"
00953                             "  -c <path>|<file> Look for php.ini file in this directory\n"
00954                             "  -n               No php.ini file will be used\n"
00955                             "  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
00956                             "  -e               Generate extended information for debugger/profiler\n"
00957                             "  -f <file>        Parse <file>.  Implies `-q'\n"
00958                             "  -h               This help\n"
00959                             "  -i               PHP information\n"
00960                             "  -l               Syntax check only (lint)\n"
00961                             "  -m               Show compiled in modules\n"
00962                             "  -q               Quiet-mode.  Suppress HTTP Header output.\n"
00963                             "  -s               Display colour syntax highlighted source.\n"
00964                             "  -v               Version number\n"
00965                             "  -w               Display source with stripped comments and whitespace.\n"
00966                             "  -z <file>        Load Zend extension <file>.\n"
00967                             "  -T <count>       Measure execution time of script repeated <count> times.\n",
00968                             prog, prog);
00969 }
00970 /* }}} */
00971 
00972 /* {{{ is_valid_path
00973  *
00974  * some server configurations allow '..' to slip through in the
00975  * translated path.   We'll just refuse to handle such a path.
00976  */
00977 static int is_valid_path(const char *path)
00978 {
00979        const char *p;
00980 
00981        if (!path) {
00982               return 0;
00983        }
00984        p = strstr(path, "..");
00985        if (p) {
00986               if ((p == path || IS_SLASH(*(p-1))) &&
00987                      (*(p+2) == 0 || IS_SLASH(*(p+2)))
00988               ) {
00989                      return 0;
00990               }
00991               while (1) {
00992                      p = strstr(p+1, "..");
00993                      if (!p) {
00994                             break;
00995                      }
00996                      if (IS_SLASH(*(p-1)) &&
00997                             (*(p+2) == 0 || IS_SLASH(*(p+2)))
00998                      ) {
00999                                    return 0;
01000                      }
01001               }
01002        }
01003        return 1;
01004 }
01005 /* }}} */
01006 
01007 /* {{{ init_request_info
01008 
01009   initializes request_info structure
01010 
01011   specificly in this section we handle proper translations
01012   for:
01013 
01014   PATH_INFO
01015        derived from the portion of the URI path following
01016        the script name but preceding any query data
01017        may be empty
01018 
01019   PATH_TRANSLATED
01020     derived by taking any path-info component of the
01021        request URI and performing any virtual-to-physical
01022        translation appropriate to map it onto the server's
01023        document repository structure
01024 
01025        empty if PATH_INFO is empty
01026 
01027        The env var PATH_TRANSLATED **IS DIFFERENT** than the
01028        request_info.path_translated variable, the latter should
01029        match SCRIPT_FILENAME instead.
01030 
01031   SCRIPT_NAME
01032     set to a URL path that could identify the CGI script
01033        rather than the interpreter.  PHP_SELF is set to this
01034 
01035   REQUEST_URI
01036     uri section following the domain:port part of a URI
01037 
01038   SCRIPT_FILENAME
01039     The virtual-to-physical translation of SCRIPT_NAME (as per
01040        PATH_TRANSLATED)
01041 
01042   These settings are documented at
01043   http://cgi-spec.golux.com/
01044 
01045 
01046   Based on the following URL request:
01047 
01048   http://localhost/info.php/test?a=b
01049 
01050   should produce, which btw is the same as if
01051   we were running under mod_cgi on apache (ie. not
01052   using ScriptAlias directives):
01053 
01054   PATH_INFO=/test
01055   PATH_TRANSLATED=/docroot/test
01056   SCRIPT_NAME=/info.php
01057   REQUEST_URI=/info.php/test?a=b
01058   SCRIPT_FILENAME=/docroot/info.php
01059   QUERY_STRING=a=b
01060 
01061   but what we get is (cgi/mod_fastcgi under apache):
01062 
01063   PATH_INFO=/info.php/test
01064   PATH_TRANSLATED=/docroot/info.php/test
01065   SCRIPT_NAME=/php/php-cgi  (from the Action setting I suppose)
01066   REQUEST_URI=/info.php/test?a=b
01067   SCRIPT_FILENAME=/path/to/php/bin/php-cgi  (Action setting translated)
01068   QUERY_STRING=a=b
01069 
01070   Comments in the code below refer to using the above URL in a request
01071 
01072  */
01073 static void init_request_info(TSRMLS_D)
01074 {
01075        char *env_script_filename = sapi_cgibin_getenv("SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1 TSRMLS_CC);
01076        char *env_path_translated = sapi_cgibin_getenv("PATH_TRANSLATED", sizeof("PATH_TRANSLATED")-1 TSRMLS_CC);
01077        char *script_path_translated = env_script_filename;
01078 
01079        /* some broken servers do not have script_filename or argv0
01080         * an example, IIS configured in some ways.  then they do more
01081         * broken stuff and set path_translated to the cgi script location */
01082        if (!script_path_translated && env_path_translated) {
01083               script_path_translated = env_path_translated;
01084        }
01085 
01086        /* initialize the defaults */
01087        SG(request_info).path_translated = NULL;
01088        SG(request_info).request_method = NULL;
01089        SG(request_info).proto_num = 1000;
01090        SG(request_info).query_string = NULL;
01091        SG(request_info).request_uri = NULL;
01092        SG(request_info).content_type = NULL;
01093        SG(request_info).content_length = 0;
01094        SG(sapi_headers).http_response_code = 200;
01095 
01096        /* script_path_translated being set is a good indication that
01097         * we are running in a cgi environment, since it is always
01098         * null otherwise.  otherwise, the filename
01099         * of the script will be retreived later via argc/argv */
01100        if (script_path_translated) {
01101               const char *auth;
01102               char *content_length = sapi_cgibin_getenv("CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1 TSRMLS_CC);
01103               char *content_type = sapi_cgibin_getenv("CONTENT_TYPE", sizeof("CONTENT_TYPE")-1 TSRMLS_CC);
01104               char *env_path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
01105               char *env_script_name = sapi_cgibin_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
01106 
01107               /* Hack for buggy IIS that sets incorrect PATH_INFO */
01108               char *env_server_software = sapi_cgibin_getenv("SERVER_SOFTWARE", sizeof("SERVER_SOFTWARE")-1 TSRMLS_CC);
01109               if (env_server_software &&
01110                      env_script_name &&
01111                      env_path_info &&
01112                      strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
01113                      strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
01114               ) {
01115                      env_path_info = _sapi_cgibin_putenv("ORIG_PATH_INFO", env_path_info TSRMLS_CC);
01116                      env_path_info += strlen(env_script_name);
01117                      if (*env_path_info == 0) {
01118                             env_path_info = NULL;
01119                      }
01120                      env_path_info = _sapi_cgibin_putenv("PATH_INFO", env_path_info TSRMLS_CC);
01121               }
01122 
01123               if (CGIG(fix_pathinfo)) {
01124                      struct stat st;
01125                      char *real_path = NULL;
01126                      char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL")-1 TSRMLS_CC);
01127                      char *env_document_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT")-1 TSRMLS_CC);
01128                      char *orig_path_translated = env_path_translated;
01129                      char *orig_path_info = env_path_info;
01130                      char *orig_script_name = env_script_name;
01131                      char *orig_script_filename = env_script_filename;
01132                      int script_path_translated_len;
01133 
01134                      if (!env_document_root && PG(doc_root)) {
01135                             env_document_root = _sapi_cgibin_putenv("DOCUMENT_ROOT", PG(doc_root) TSRMLS_CC);
01136                             /* fix docroot */
01137                             TRANSLATE_SLASHES(env_document_root);
01138                      }
01139 
01140                      if (env_path_translated != NULL && env_redirect_url != NULL &&
01141                          env_path_translated != script_path_translated &&
01142                          strcmp(env_path_translated, script_path_translated) != 0) {
01143                             /*
01144                              * pretty much apache specific.  If we have a redirect_url
01145                              * then our script_filename and script_name point to the
01146                              * php executable
01147                              */
01148                             script_path_translated = env_path_translated;
01149                             /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
01150                             env_script_name = env_redirect_url;
01151                      }
01152 
01153 #ifdef __riscos__
01154                      /* Convert path to unix format*/
01155                      __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
01156                      script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
01157 #endif
01158 
01159                      /*
01160                       * if the file doesn't exist, try to extract PATH_INFO out
01161                       * of it by stat'ing back through the '/'
01162                       * this fixes url's like /info.php/test
01163                       */
01164                      if (script_path_translated &&
01165                             (script_path_translated_len = strlen(script_path_translated)) > 0 &&
01166                             (script_path_translated[script_path_translated_len-1] == '/' ||
01167 #ifdef PHP_WIN32
01168                             script_path_translated[script_path_translated_len-1] == '\\' ||
01169 #endif
01170                             (real_path = tsrm_realpath(script_path_translated, NULL TSRMLS_CC)) == NULL)
01171                      ) {
01172                             char *pt = estrndup(script_path_translated, script_path_translated_len);
01173                             int len = script_path_translated_len;
01174                             char *ptr;
01175 
01176                             while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
01177                                    *ptr = 0;
01178                                    if (stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
01179                                           /*
01180                                            * okay, we found the base script!
01181                                            * work out how many chars we had to strip off;
01182                                            * then we can modify PATH_INFO
01183                                            * accordingly
01184                                            *
01185                                            * we now have the makings of
01186                                            * PATH_INFO=/test
01187                                            * SCRIPT_FILENAME=/docroot/info.php
01188                                            *
01189                                            * we now need to figure out what docroot is.
01190                                            * if DOCUMENT_ROOT is set, this is easy, otherwise,
01191                                            * we have to play the game of hide and seek to figure
01192                                            * out what SCRIPT_NAME should be
01193                                            */
01194                                           int slen = len - strlen(pt);
01195                                           int pilen = env_path_info ? strlen(env_path_info) : 0;
01196                                           char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
01197 
01198                                           if (orig_path_info != path_info) {
01199                                                  if (orig_path_info) {
01200                                                         char old;
01201 
01202                                                         _sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
01203                                                         old = path_info[0];
01204                                                         path_info[0] = 0;
01205                                                         if (!orig_script_name ||
01206                                                                strcmp(orig_script_name, env_path_info) != 0) {
01207                                                                if (orig_script_name) {
01208                                                                       _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
01209                                                                }
01210                                                                SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_path_info TSRMLS_CC);
01211                                                         } else {
01212                                                                SG(request_info).request_uri = orig_script_name;
01213                                                         }
01214                                                         path_info[0] = old;
01215                                                  }
01216                                                  env_path_info = _sapi_cgibin_putenv("PATH_INFO", path_info TSRMLS_CC);
01217                                           }
01218                                           if (!orig_script_filename ||
01219                                                  strcmp(orig_script_filename, pt) != 0) {
01220                                                  if (orig_script_filename) {
01221                                                         _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
01222                                                  }
01223                                                  script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", pt TSRMLS_CC);
01224                                           }
01225                                           TRANSLATE_SLASHES(pt);
01226 
01227                                           /* figure out docroot
01228                                            * SCRIPT_FILENAME minus SCRIPT_NAME
01229                                            */
01230                                           if (env_document_root) {
01231                                                  int l = strlen(env_document_root);
01232                                                  int path_translated_len = 0;
01233                                                  char *path_translated = NULL;
01234 
01235                                                  if (l && env_document_root[l - 1] == '/') {
01236                                                         --l;
01237                                                  }
01238 
01239                                                  /* we have docroot, so we should have:
01240                                                   * DOCUMENT_ROOT=/docroot
01241                                                   * SCRIPT_FILENAME=/docroot/info.php
01242                                                   */
01243 
01244                                                  /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
01245                                                  path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
01246                                                  path_translated = (char *) emalloc(path_translated_len + 1);
01247                                                  memcpy(path_translated, env_document_root, l);
01248                                                  if (env_path_info) {
01249                                                         memcpy(path_translated + l, env_path_info, (path_translated_len - l));
01250                                                  }
01251                                                  path_translated[path_translated_len] = '\0';
01252                                                  if (orig_path_translated) {
01253                                                         _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
01254                                                  }
01255                                                  env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
01256                                                  efree(path_translated);
01257                                           } else if (   env_script_name &&
01258                                                                strstr(pt, env_script_name)
01259                                           ) {
01260                                                  /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
01261                                                  int ptlen = strlen(pt) - strlen(env_script_name);
01262                                                  int path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
01263                                                  char *path_translated = NULL;
01264 
01265                                                  path_translated = (char *) emalloc(path_translated_len + 1);
01266                                                  memcpy(path_translated, pt, ptlen);
01267                                                  if (env_path_info) {
01268                                                         memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
01269                                                  }
01270                                                  path_translated[path_translated_len] = '\0';
01271                                                  if (orig_path_translated) {
01272                                                         _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
01273                                                  }
01274                                                  env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
01275                                                  efree(path_translated);
01276                                           }
01277                                           break;
01278                                    }
01279                             }
01280                             if (!ptr) {
01281                                    /*
01282                                     * if we stripped out all the '/' and still didn't find
01283                                     * a valid path... we will fail, badly. of course we would
01284                                     * have failed anyway... we output 'no input file' now.
01285                                     */
01286                                    if (orig_script_filename) {
01287                                           _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
01288                                    }
01289                                    script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", NULL TSRMLS_CC);
01290                                    SG(sapi_headers).http_response_code = 404;
01291                             }
01292                             if (!SG(request_info).request_uri) {
01293                                    if (!orig_script_name ||
01294                                           strcmp(orig_script_name, env_script_name) != 0) {
01295                                           if (orig_script_name) {
01296                                                  _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
01297                                           }
01298                                           SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
01299                                    } else {
01300                                           SG(request_info).request_uri = orig_script_name;
01301                                    }
01302                             }
01303                             if (pt) {
01304                                    efree(pt);
01305                             }
01306                      } else {
01307                             /* make sure path_info/translated are empty */
01308                             if (!orig_script_filename ||
01309                                    (script_path_translated != orig_script_filename &&
01310                                    strcmp(script_path_translated, orig_script_filename) != 0)) {
01311                                    if (orig_script_filename) {
01312                                           _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
01313                                    }
01314                                    script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", script_path_translated TSRMLS_CC);
01315                             }
01316                             if (env_redirect_url) {
01317                                    if (orig_path_info) {
01318                                           _sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
01319                                           _sapi_cgibin_putenv("PATH_INFO", NULL TSRMLS_CC);
01320                                    }
01321                                    if (orig_path_translated) {
01322                                           _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
01323                                           _sapi_cgibin_putenv("PATH_TRANSLATED", NULL TSRMLS_CC);
01324                                    }
01325                             }
01326                             if (env_script_name != orig_script_name) {
01327                                    if (orig_script_name) {
01328                                           _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
01329                                    }
01330                                    SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
01331                             } else {
01332                                    SG(request_info).request_uri = env_script_name;
01333                             }
01334                             free(real_path);
01335                      }
01336               } else {
01337                      /* pre 4.3 behaviour, shouldn't be used but provides BC */
01338                      if (env_path_info) {
01339                             SG(request_info).request_uri = env_path_info;
01340                      } else {
01341                             SG(request_info).request_uri = env_script_name;
01342                      }
01343                      if (!CGIG(discard_path) && env_path_translated) {
01344                             script_path_translated = env_path_translated;
01345                      }
01346               }
01347 
01348               if (is_valid_path(script_path_translated)) {
01349                      SG(request_info).path_translated = estrdup(script_path_translated);
01350               }
01351 
01352               SG(request_info).request_method = sapi_cgibin_getenv("REQUEST_METHOD", sizeof("REQUEST_METHOD")-1 TSRMLS_CC);
01353               /* FIXME - Work out proto_num here */
01354               SG(request_info).query_string = sapi_cgibin_getenv("QUERY_STRING", sizeof("QUERY_STRING")-1 TSRMLS_CC);
01355               SG(request_info).content_type = (content_type ? content_type : "" );
01356               SG(request_info).content_length = (content_length ? atol(content_length) : 0);
01357 
01358               /* The CGI RFC allows servers to pass on unvalidated Authorization data */
01359               auth = sapi_cgibin_getenv("HTTP_AUTHORIZATION", sizeof("HTTP_AUTHORIZATION")-1 TSRMLS_CC);
01360               php_handle_auth_data(auth TSRMLS_CC);
01361        }
01362 }
01363 /* }}} */
01364 
01365 #ifndef PHP_WIN32
01366 
01369 void fastcgi_cleanup(int signal)
01370 {
01371 #ifdef DEBUG_FASTCGI
01372        fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
01373 #endif
01374 
01375        sigaction(SIGTERM, &old_term, 0);
01376 
01377        /* Kill all the processes in our process group */
01378        kill(-pgroup, SIGTERM);
01379 
01380        if (parent && parent_waiting) {
01381               exit_signal = 1;
01382        } else {
01383               exit(0);
01384        }
01385 }
01386 #endif
01387 
01388 PHP_INI_BEGIN()
01389        STD_PHP_INI_ENTRY("cgi.rfc2616_headers",     "0",  PHP_INI_ALL,    OnUpdateBool,   rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
01390        STD_PHP_INI_ENTRY("cgi.nph",                 "0",  PHP_INI_ALL,    OnUpdateBool,   nph, php_cgi_globals_struct, php_cgi_globals)
01391        STD_PHP_INI_ENTRY("cgi.check_shebang_line",  "1",  PHP_INI_SYSTEM, OnUpdateBool,   check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
01392        STD_PHP_INI_ENTRY("cgi.force_redirect",      "1",  PHP_INI_SYSTEM, OnUpdateBool,   force_redirect, php_cgi_globals_struct, php_cgi_globals)
01393        STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
01394        STD_PHP_INI_ENTRY("cgi.fix_pathinfo",        "1",  PHP_INI_SYSTEM, OnUpdateBool,   fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
01395        STD_PHP_INI_ENTRY("cgi.discard_path",        "0",  PHP_INI_SYSTEM, OnUpdateBool,   discard_path, php_cgi_globals_struct, php_cgi_globals)
01396        STD_PHP_INI_ENTRY("fastcgi.logging",         "1",  PHP_INI_SYSTEM, OnUpdateBool,   fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
01397 #ifdef PHP_WIN32
01398        STD_PHP_INI_ENTRY("fastcgi.impersonate",     "0",  PHP_INI_SYSTEM, OnUpdateBool,   impersonate, php_cgi_globals_struct, php_cgi_globals)
01399 #endif
01400 PHP_INI_END()
01401 
01402 /* {{{ php_cgi_globals_ctor
01403  */
01404 static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals TSRMLS_DC)
01405 {
01406        php_cgi_globals->rfc2616_headers = 0;
01407        php_cgi_globals->nph = 0;
01408        php_cgi_globals->check_shebang_line = 1;
01409        php_cgi_globals->force_redirect = 1;
01410        php_cgi_globals->redirect_status_env = NULL;
01411        php_cgi_globals->fix_pathinfo = 1;
01412        php_cgi_globals->discard_path = 0;
01413        php_cgi_globals->fcgi_logging = 1;
01414 #ifdef PHP_WIN32
01415        php_cgi_globals->impersonate = 0;
01416 #endif
01417        zend_hash_init(&php_cgi_globals->user_config_cache, 0, NULL, (dtor_func_t) user_config_cache_entry_dtor, 1);
01418 }
01419 /* }}} */
01420 
01421 /* {{{ PHP_MINIT_FUNCTION
01422  */
01423 static PHP_MINIT_FUNCTION(cgi)
01424 {
01425 #ifdef ZTS
01426        ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
01427 #else
01428        php_cgi_globals_ctor(&php_cgi_globals TSRMLS_CC);
01429 #endif
01430        REGISTER_INI_ENTRIES();
01431        return SUCCESS;
01432 }
01433 /* }}} */
01434 
01435 /* {{{ PHP_MSHUTDOWN_FUNCTION
01436  */
01437 static PHP_MSHUTDOWN_FUNCTION(cgi)
01438 {
01439        zend_hash_destroy(&CGIG(user_config_cache));
01440 
01441        UNREGISTER_INI_ENTRIES();
01442        return SUCCESS;
01443 }
01444 /* }}} */
01445 
01446 /* {{{ PHP_MINFO_FUNCTION
01447  */
01448 static PHP_MINFO_FUNCTION(cgi)
01449 {
01450        DISPLAY_INI_ENTRIES();
01451 }
01452 /* }}} */
01453 
01454 static zend_module_entry cgi_module_entry = {
01455        STANDARD_MODULE_HEADER,
01456        "cgi-fcgi",
01457        NULL,
01458        PHP_MINIT(cgi),
01459        PHP_MSHUTDOWN(cgi),
01460        NULL,
01461        NULL,
01462        PHP_MINFO(cgi),
01463        NO_VERSION_YET,
01464        STANDARD_MODULE_PROPERTIES
01465 };
01466 
01467 /* {{{ main
01468  */
01469 int main(int argc, char *argv[])
01470 {
01471        int free_query_string = 0;
01472        int exit_status = SUCCESS;
01473        int cgi = 0, c, i, len;
01474        zend_file_handle file_handle;
01475        char *s;
01476 
01477        /* temporary locals */
01478        int behavior = PHP_MODE_STANDARD;
01479        int no_headers = 0;
01480        int orig_optind = php_optind;
01481        char *orig_optarg = php_optarg;
01482        char *script_file = NULL;
01483        int ini_entries_len = 0;
01484        /* end of temporary locals */
01485 
01486 #ifdef ZTS
01487        void ***tsrm_ls;
01488 #endif
01489 
01490        int max_requests = 500;
01491        int requests = 0;
01492        int fastcgi = fcgi_is_fastcgi();
01493        char *bindpath = NULL;
01494        int fcgi_fd = 0;
01495        fcgi_request request;
01496        int repeats = 1;
01497        int benchmark = 0;
01498 #if HAVE_GETTIMEOFDAY
01499        struct timeval start, end;
01500 #else
01501        time_t start, end;
01502 #endif
01503 #ifndef PHP_WIN32
01504        int status = 0;
01505 #endif
01506 
01507 #if 0 && defined(PHP_DEBUG)
01508        /* IIS is always making things more difficult.  This allows
01509         * us to stop PHP and attach a debugger before much gets started */
01510        {
01511               char szMessage [256];
01512               wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]);
01513               MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION);
01514        }
01515 #endif
01516 
01517 #ifdef HAVE_SIGNAL_H
01518 #if defined(SIGPIPE) && defined(SIG_IGN)
01519        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
01520                                                         that sockets created via fsockopen()
01521                                                         don't kill PHP if the remote site
01522                                                         closes it.  in apache|apxs mode apache
01523                                                         does that for us!  thies@thieso.net
01524                                                         20000419 */
01525 #endif
01526 #endif
01527 
01528 #ifdef ZTS
01529        tsrm_startup(1, 1, 0, NULL);
01530        tsrm_ls = ts_resource(0);
01531 #endif
01532 
01533        sapi_startup(&cgi_sapi_module);
01534        cgi_sapi_module.php_ini_path_override = NULL;
01535 
01536 #ifdef PHP_WIN32
01537        _fmode = _O_BINARY; /* sets default for file streams to binary */
01538        setmode(_fileno(stdin),  O_BINARY);       /* make the stdio mode be binary */
01539        setmode(_fileno(stdout), O_BINARY);       /* make the stdio mode be binary */
01540        setmode(_fileno(stderr), O_BINARY);       /* make the stdio mode be binary */
01541 #endif
01542 
01543        if (!fastcgi) {
01544               /* Make sure we detect we are a cgi - a bit redundancy here,
01545                * but the default case is that we have to check only the first one. */
01546               if (getenv("SERVER_SOFTWARE") ||
01547                      getenv("SERVER_NAME") ||
01548                      getenv("GATEWAY_INTERFACE") ||
01549                      getenv("REQUEST_METHOD")
01550               ) {
01551                      cgi = 1;
01552               }
01553        }
01554 
01555        while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
01556               switch (c) {
01557                      case 'c':
01558                             if (cgi_sapi_module.php_ini_path_override) {
01559                                    free(cgi_sapi_module.php_ini_path_override);
01560                             }
01561                             cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
01562                             break;
01563                      case 'n':
01564                             cgi_sapi_module.php_ini_ignore = 1;
01565                             break;
01566                      case 'd': {
01567                             /* define ini entries on command line */
01568                             int len = strlen(php_optarg);
01569                             char *val;
01570 
01571                             if ((val = strchr(php_optarg, '='))) {
01572                                    val++;
01573                                    if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
01574                                           cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
01575                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
01576                                           ini_entries_len += (val - php_optarg);
01577                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
01578                                           ini_entries_len++;
01579                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
01580                                           ini_entries_len += len - (val - php_optarg);
01581                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
01582                                           ini_entries_len += sizeof("\n\0\"") - 2;
01583                                    } else {
01584                                           cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
01585                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
01586                                           memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
01587                                           ini_entries_len += len + sizeof("\n\0") - 2;
01588                                    }
01589                             } else {
01590                                    cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
01591                                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
01592                                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
01593                                    ini_entries_len += len + sizeof("=1\n\0") - 2;
01594                             }
01595                             break;
01596                      }
01597                      /* if we're started on command line, check to see if
01598                       * we are being started as an 'external' fastcgi
01599                       * server by accepting a bindpath parameter. */
01600                      case 'b':
01601                             if (!fastcgi) {
01602                                    bindpath = strdup(php_optarg);
01603                             }
01604                             break;
01605                      case 's': /* generate highlighted HTML from source */
01606                             behavior = PHP_MODE_HIGHLIGHT;
01607                             break;
01608               }
01609        }
01610        php_optind = orig_optind;
01611        php_optarg = orig_optarg;
01612 
01613 #ifdef ZTS
01614        SG(request_info).path_translated = NULL;
01615 #endif
01616 
01617        cgi_sapi_module.executable_location = argv[0];
01618        if (!cgi && !fastcgi && !bindpath) {
01619               cgi_sapi_module.additional_functions = additional_functions;
01620        }
01621 
01622        /* startup after we get the above ini override se we get things right */
01623        if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
01624 #ifdef ZTS
01625               tsrm_shutdown();
01626 #endif
01627               return FAILURE;
01628        }
01629 
01630        /* check force_cgi after startup, so we have proper output */
01631        if (cgi && CGIG(force_redirect)) {
01632               /* Apache will generate REDIRECT_STATUS,
01633                * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
01634                * redirect.so and installation instructions available from
01635                * http://www.koehntopp.de/php.
01636                *   -- kk@netuse.de
01637                */
01638               if (!getenv("REDIRECT_STATUS") &&
01639                      !getenv ("HTTP_REDIRECT_STATUS") &&
01640                      /* this is to allow a different env var to be configured
01641                       * in case some server does something different than above */
01642                      (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
01643               ) {
01644                      zend_try {
01645                             SG(sapi_headers).http_response_code = 400;
01646                             PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
01647 <p>This PHP CGI binary was compiled with force-cgi-redirect enabled.  This\n\
01648 means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
01649 set, e.g. via an Apache Action directive.</p>\n\
01650 <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
01651 manual page for CGI security</a>.</p>\n\
01652 <p>For more information about changing this behaviour or re-enabling this webserver,\n\
01653 consult the installation file that came with this distribution, or visit \n\
01654 <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
01655                      } zend_catch {
01656                      } zend_end_try();
01657 #if defined(ZTS) && !defined(PHP_DEBUG)
01658                      /* XXX we're crashing here in msvc6 debug builds at
01659                       * php_message_handler_for_zend:839 because
01660                       * SG(request_info).path_translated is an invalid pointer.
01661                       * It still happens even though I set it to null, so something
01662                       * weird is going on.
01663                       */
01664                      tsrm_shutdown();
01665 #endif
01666                      return FAILURE;
01667               }
01668        }
01669 
01670        if (bindpath) {
01671               fcgi_fd = fcgi_listen(bindpath, 128);
01672               if (fcgi_fd < 0) {
01673                      fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
01674 #ifdef ZTS
01675                      tsrm_shutdown();
01676 #endif
01677                      return FAILURE;
01678               }
01679               fastcgi = fcgi_is_fastcgi();
01680        }
01681        if (fastcgi) {
01682               /* How many times to run PHP scripts before dying */
01683               if (getenv("PHP_FCGI_MAX_REQUESTS")) {
01684                      max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
01685                      if (max_requests < 0) {
01686                             fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
01687                             return FAILURE;
01688                      }
01689               }
01690 
01691               /* make php call us to get _ENV vars */
01692               php_php_import_environment_variables = php_import_environment_variables;
01693               php_import_environment_variables = cgi_php_import_environment_variables;
01694 
01695               /* library is already initialized, now init our request */
01696               fcgi_init_request(&request, fcgi_fd);
01697 
01698 #ifndef PHP_WIN32
01699        /* Pre-fork, if required */
01700        if (getenv("PHP_FCGI_CHILDREN")) {
01701               char * children_str = getenv("PHP_FCGI_CHILDREN");
01702               children = atoi(children_str);
01703               if (children < 0) {
01704                      fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
01705                      return FAILURE;
01706               }
01707               fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
01708               /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
01709               fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  children_str, strlen(children_str));
01710        } else {
01711               fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
01712               fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  "1", sizeof("1")-1);
01713        }
01714 
01715        if (children) {
01716               int running = 0;
01717               pid_t pid;
01718 
01719               /* Create a process group for ourself & children */
01720               setsid();
01721               pgroup = getpgrp();
01722 #ifdef DEBUG_FASTCGI
01723               fprintf(stderr, "Process group %d\n", pgroup);
01724 #endif
01725 
01726               /* Set up handler to kill children upon exit */
01727               act.sa_flags = 0;
01728               act.sa_handler = fastcgi_cleanup;
01729               if (sigaction(SIGTERM, &act, &old_term) ||
01730                      sigaction(SIGINT,  &act, &old_int)  ||
01731                      sigaction(SIGQUIT, &act, &old_quit)
01732               ) {
01733                      perror("Can't set signals");
01734                      exit(1);
01735               }
01736 
01737               if (fcgi_in_shutdown()) {
01738                      goto parent_out;
01739               }
01740 
01741               while (parent) {
01742                      do {
01743 #ifdef DEBUG_FASTCGI
01744                             fprintf(stderr, "Forking, %d running\n", running);
01745 #endif
01746                             pid = fork();
01747                             switch (pid) {
01748                             case 0:
01749                                    /* One of the children.
01750                                     * Make sure we don't go round the
01751                                     * fork loop any more
01752                                     */
01753                                    parent = 0;
01754 
01755                                    /* don't catch our signals */
01756                                    sigaction(SIGTERM, &old_term, 0);
01757                                    sigaction(SIGQUIT, &old_quit, 0);
01758                                    sigaction(SIGINT,  &old_int,  0);
01759                                    break;
01760                             case -1:
01761                                    perror("php (pre-forking)");
01762                                    exit(1);
01763                                    break;
01764                             default:
01765                                    /* Fine */
01766                                    running++;
01767                                    break;
01768                             }
01769                      } while (parent && (running < children));
01770 
01771                      if (parent) {
01772 #ifdef DEBUG_FASTCGI
01773                             fprintf(stderr, "Wait for kids, pid %d\n", getpid());
01774 #endif
01775                             parent_waiting = 1;
01776                             while (1) {
01777                                    if (wait(&status) >= 0) {
01778                                           running--;
01779                                           break;
01780                                    } else if (exit_signal) {
01781                                           break;
01782                                    }
01783                             }
01784                             if (exit_signal) {
01785 #if 0
01786                                    while (running > 0) {
01787                                           while (wait(&status) < 0) {
01788                                           }
01789                                           running--;
01790                                    }
01791 #endif
01792                                    goto parent_out;
01793                             }
01794                      }
01795               }
01796        } else {
01797               parent = 0;
01798        }
01799 
01800 #endif /* WIN32 */
01801        }
01802 
01803        zend_first_try {
01804               while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
01805                      switch (c) {
01806                             case 'T':
01807                                    benchmark = 1;
01808                                    repeats = atoi(php_optarg);
01809 #ifdef HAVE_GETTIMEOFDAY
01810                                    gettimeofday(&start, NULL);
01811 #else
01812                                    time(&start);
01813 #endif
01814                                    break;
01815                             case 'h':
01816                             case '?':
01817                                    fcgi_shutdown();
01818                                    no_headers = 1;
01819                                    php_output_startup();
01820                                    php_output_activate(TSRMLS_C);
01821                                    SG(headers_sent) = 1;
01822                                    php_cgi_usage(argv[0]);
01823                                    php_end_ob_buffers(1 TSRMLS_CC);
01824                                    exit_status = 0;
01825                                    goto out;
01826                      }
01827               }
01828               php_optind = orig_optind;
01829               php_optarg = orig_optarg;
01830 
01831               /* start of FAST CGI loop */
01832               /* Initialise FastCGI request structure */
01833 #ifdef PHP_WIN32
01834               /* attempt to set security impersonation for fastcgi
01835                * will only happen on NT based OS, others will ignore it. */
01836               if (fastcgi && CGIG(impersonate)) {
01837                      fcgi_impersonate();
01838               }
01839 #endif
01840               while (!fastcgi || fcgi_accept_request(&request) >= 0) {
01841                      SG(server_context) = (void *) &request;
01842                      init_request_info(TSRMLS_C);
01843                      CG(interactive) = 0;
01844 
01845                      if (!cgi && !fastcgi) {
01846                             while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
01847                                    switch (c) {
01848 
01849                                           case 'a':     /* interactive mode */
01850                                                  printf("Interactive mode enabled\n\n");
01851                                                  CG(interactive) = 1;
01852                                                  break;
01853 
01854                                           case 'C': /* don't chdir to the script directory */
01855                                                  SG(options) |= SAPI_OPTION_NO_CHDIR;
01856                                                  break;
01857 
01858                                           case 'e': /* enable extended info output */
01859                                                  CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
01860                                                  break;
01861 
01862                                           case 'f': /* parse file */
01863                                                  if (script_file) {
01864                                                         efree(script_file);
01865                                                  }
01866                                                  script_file = estrdup(php_optarg);
01867                                                  no_headers = 1;
01868                                                  break;
01869 
01870                                           case 'i': /* php info & quit */
01871                                                  if (script_file) {
01872                                                         efree(script_file);
01873                                                  }
01874                                                  if (php_request_startup(TSRMLS_C) == FAILURE) {
01875                                                         SG(server_context) = NULL;
01876                                                         php_module_shutdown(TSRMLS_C);
01877                                                         return FAILURE;
01878                                                  }
01879                                                  if (no_headers) {
01880                                                         SG(headers_sent) = 1;
01881                                                         SG(request_info).no_headers = 1;
01882                                                  }
01883                                                  php_print_info(0xFFFFFFFF TSRMLS_CC);
01884                                                  php_request_shutdown((void *) 0);
01885                                                  fcgi_shutdown();
01886                                                  exit_status = 0;
01887                                                  goto out;
01888 
01889                                           case 'l': /* syntax check mode */
01890                                                  no_headers = 1;
01891                                                  behavior = PHP_MODE_LINT;
01892                                                  break;
01893 
01894                                           case 'm': /* list compiled in modules */
01895                                                  if (script_file) {
01896                                                         efree(script_file);
01897                                                  }
01898                                                  php_output_startup();
01899                                                  php_output_activate(TSRMLS_C);
01900                                                  SG(headers_sent) = 1;
01901                                                  php_printf("[PHP Modules]\n");
01902                                                  print_modules(TSRMLS_C);
01903                                                  php_printf("\n[Zend Modules]\n");
01904                                                  print_extensions(TSRMLS_C);
01905                                                  php_printf("\n");
01906                                                  php_end_ob_buffers(1 TSRMLS_CC);
01907                                                  fcgi_shutdown();
01908                                                  exit_status = 0;
01909                                                  goto out;
01910 
01911 #if 0 /* not yet operational, see also below ... */
01912                                           case '': /* generate indented source mode*/
01913                                                  behavior=PHP_MODE_INDENT;
01914                                                  break;
01915 #endif
01916 
01917                                           case 'q': /* do not generate HTTP headers */
01918                                                  no_headers = 1;
01919                                                  break;
01920 
01921                                           case 'v': /* show php version & quit */
01922                                                  if (script_file) {
01923                                                         efree(script_file);
01924                                                  }
01925                                                  no_headers = 1;
01926                                                  if (php_request_startup(TSRMLS_C) == FAILURE) {
01927                                                         SG(server_context) = NULL;
01928                                                         php_module_shutdown(TSRMLS_C);
01929                                                         return FAILURE;
01930                                                  }
01931                                                  if (no_headers) {
01932                                                         SG(headers_sent) = 1;
01933                                                         SG(request_info).no_headers = 1;
01934                                                  }
01935 #if ZEND_DEBUG
01936                                                  php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2012 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
01937 #else
01938                                                  php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2012 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
01939 #endif
01940                                                  php_request_shutdown((void *) 0);
01941                                                  fcgi_shutdown();
01942                                                  exit_status = 0;
01943                                                  goto out;
01944 
01945                                           case 'w':
01946                                                  behavior = PHP_MODE_STRIP;
01947                                                  break;
01948 
01949                                           case 'z': /* load extension file */
01950                                                  zend_load_extension(php_optarg);
01951                                                  break;
01952 
01953                                           default:
01954                                                  break;
01955                                    }
01956                             }
01957 
01958                             if (script_file) {
01959                                    /* override path_translated if -f on command line */
01960                                    STR_FREE(SG(request_info).path_translated);
01961                                    SG(request_info).path_translated = script_file;
01962                                    /* before registering argv to module exchange the *new* argv[0] */
01963                                    /* we can achieve this without allocating more memory */
01964                                    SG(request_info).argc = argc - (php_optind - 1);
01965                                    SG(request_info).argv = &argv[php_optind - 1];
01966                                    SG(request_info).argv[0] = script_file;
01967                             } else if (argc > php_optind) {
01968                                    /* file is on command line, but not in -f opt */
01969                                    STR_FREE(SG(request_info).path_translated);
01970                                    SG(request_info).path_translated = estrdup(argv[php_optind]);
01971                                    /* arguments after the file are considered script args */
01972                                    SG(request_info).argc = argc - php_optind;
01973                                    SG(request_info).argv = &argv[php_optind];
01974                             }
01975 
01976                             if (no_headers) {
01977                                    SG(headers_sent) = 1;
01978                                    SG(request_info).no_headers = 1;
01979                             }
01980 
01981                             /* all remaining arguments are part of the query string
01982                              * this section of code concatenates all remaining arguments
01983                              * into a single string, seperating args with a &
01984                              * this allows command lines like:
01985                              *
01986                              *  test.php v1=test v2=hello+world!
01987                              *  test.php "v1=test&v2=hello world!"
01988                              *  test.php v1=test "v2=hello world!"
01989                             */
01990                             if (!SG(request_info).query_string && argc > php_optind) {
01991                                    int slen = strlen(PG(arg_separator).input);
01992                                    len = 0;
01993                                    for (i = php_optind; i < argc; i++) {
01994                                           if (i < (argc - 1)) {
01995                                                  len += strlen(argv[i]) + slen;
01996                                           } else {
01997                                                  len += strlen(argv[i]);
01998                                           }
01999                                    }
02000 
02001                                    len += 2;
02002                                    s = malloc(len);
02003                                    *s = '\0';                  /* we are pretending it came from the environment  */
02004                                    for (i = php_optind; i < argc; i++) {
02005                                           strlcat(s, argv[i], len);
02006                                           if (i < (argc - 1)) {
02007                                                  strlcat(s, PG(arg_separator).input, len);
02008                                           }
02009                                    }
02010                                    SG(request_info).query_string = s;
02011                                    free_query_string = 1;
02012                             }
02013                      } /* end !cgi && !fastcgi */
02014 
02015                      /*
02016                             we never take stdin if we're (f)cgi, always
02017                             rely on the web server giving us the info
02018                             we need in the environment.
02019                      */
02020                      if (SG(request_info).path_translated || cgi || fastcgi) {
02021                             file_handle.type = ZEND_HANDLE_FILENAME;
02022                             file_handle.filename = SG(request_info).path_translated;
02023                             file_handle.handle.fp = NULL;
02024                      } else {
02025                             file_handle.filename = "-";
02026                             file_handle.type = ZEND_HANDLE_FP;
02027                             file_handle.handle.fp = stdin;
02028                      }
02029 
02030                      file_handle.opened_path = NULL;
02031                      file_handle.free_filename = 0;
02032 
02033                      /* request startup only after we've done all we can to
02034                       * get path_translated */
02035                      if (php_request_startup(TSRMLS_C) == FAILURE) {
02036                             if (fastcgi) {
02037                                    fcgi_finish_request(&request, 1);
02038                             }
02039                             SG(server_context) = NULL;
02040                             php_module_shutdown(TSRMLS_C);
02041                             return FAILURE;
02042                      }
02043                      if (no_headers) {
02044                             SG(headers_sent) = 1;
02045                             SG(request_info).no_headers = 1;
02046                      }
02047 
02048                      /*
02049                             at this point path_translated will be set if:
02050                             1. we are running from shell and got filename was there
02051                             2. we are running as cgi or fastcgi
02052                      */
02053                      if (cgi || fastcgi || SG(request_info).path_translated) {
02054                             if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
02055                                    zend_try {
02056                                           if (errno == EACCES) {
02057                                                  SG(sapi_headers).http_response_code = 403;
02058                                                  PUTS("Access denied.\n");
02059                                           } else {
02060                                                  SG(sapi_headers).http_response_code = 404;
02061                                                  PUTS("No input file specified.\n");
02062                                           }
02063                                    } zend_catch {
02064                                    } zend_end_try();
02065                                    /* we want to serve more requests if this is fastcgi
02066                                     * so cleanup and continue, request shutdown is
02067                                     * handled later */
02068                                    if (fastcgi) {
02069                                           goto fastcgi_request_done;
02070                                    }
02071 
02072                                    STR_FREE(SG(request_info).path_translated);
02073 
02074                                    if (free_query_string && SG(request_info).query_string) {
02075                                           free(SG(request_info).query_string);
02076                                           SG(request_info).query_string = NULL;
02077                                    }
02078 
02079                                    php_request_shutdown((void *) 0);
02080                                    SG(server_context) = NULL;
02081                                    php_module_shutdown(TSRMLS_C);
02082                                    sapi_shutdown();
02083 #ifdef ZTS
02084                                    tsrm_shutdown();
02085 #endif
02086                                    return FAILURE;
02087                             }
02088                      }
02089 
02090                      if (CGIG(check_shebang_line) && file_handle.handle.fp && (file_handle.handle.fp != stdin)) {
02091                             /* #!php support */
02092                             c = fgetc(file_handle.handle.fp);
02093                             if (c == '#') {
02094                                    while (c != '\n' && c != '\r' && c != EOF) {
02095                                           c = fgetc(file_handle.handle.fp);  /* skip to end of line */
02096                                    }
02097                                    /* handle situations where line is terminated by \r\n */
02098                                    if (c == '\r') {
02099                                           if (fgetc(file_handle.handle.fp) != '\n') {
02100                                                  long pos = ftell(file_handle.handle.fp);
02101                                                  fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
02102                                           }
02103                                    }
02104                                    CG(start_lineno) = 2;
02105                             } else {
02106                                    rewind(file_handle.handle.fp);
02107                             }
02108                      }
02109 
02110                      switch (behavior) {
02111                             case PHP_MODE_STANDARD:
02112                                    php_execute_script(&file_handle TSRMLS_CC);
02113                                    break;
02114                             case PHP_MODE_LINT:
02115                                    PG(during_request_startup) = 0;
02116                                    exit_status = php_lint_script(&file_handle TSRMLS_CC);
02117                                    if (exit_status == SUCCESS) {
02118                                           zend_printf("No syntax errors detected in %s\n", file_handle.filename);
02119                                    } else {
02120                                           zend_printf("Errors parsing %s\n", file_handle.filename);
02121                                    }
02122                                    break;
02123                             case PHP_MODE_STRIP:
02124                                    if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
02125                                           zend_strip(TSRMLS_C);
02126                                           zend_file_handle_dtor(&file_handle TSRMLS_CC);
02127                                           php_end_ob_buffers(1 TSRMLS_CC);
02128                                    }
02129                                    return SUCCESS;
02130                                    break;
02131                             case PHP_MODE_HIGHLIGHT:
02132                                    {
02133                                           zend_syntax_highlighter_ini syntax_highlighter_ini;
02134 
02135                                           if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
02136                                                  php_get_highlight_struct(&syntax_highlighter_ini);
02137                                                  zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
02138                                                  if (fastcgi) {
02139                                                         goto fastcgi_request_done;
02140                                                  }
02141                                                  zend_file_handle_dtor(&file_handle TSRMLS_CC);
02142                                                  php_end_ob_buffers(1 TSRMLS_CC);
02143                                           }
02144                                           return SUCCESS;
02145                                    }
02146                                    break;
02147 #if 0
02148                             /* Zeev might want to do something with this one day */
02149                             case PHP_MODE_INDENT:
02150                                    open_file_for_scanning(&file_handle TSRMLS_CC);
02151                                    zend_indent();
02152                                    zend_file_handle_dtor(&file_handle TSRMLS_CC);
02153                                    return SUCCESS;
02154                                    break;
02155 #endif
02156                      }
02157 
02158 fastcgi_request_done:
02159                      {
02160                             STR_FREE(SG(request_info).path_translated);
02161 
02162                             php_request_shutdown((void *) 0);
02163 
02164                             if (exit_status == 0) {
02165                                    exit_status = EG(exit_status);
02166                             }
02167 
02168                             if (free_query_string && SG(request_info).query_string) {
02169                                    free(SG(request_info).query_string);
02170                                    SG(request_info).query_string = NULL;
02171                             }
02172                      }
02173 
02174                      if (!fastcgi) {
02175                             if (benchmark) {
02176                                    repeats--;
02177                                    if (repeats > 0) {
02178                                           script_file = NULL;
02179                                           php_optind = orig_optind;
02180                                           php_optarg = orig_optarg;
02181                                           continue;
02182                                    }
02183                             }
02184                             break;
02185                      }
02186 
02187                      /* only fastcgi will get here */
02188                      requests++;
02189                      if (max_requests && (requests == max_requests)) {
02190                             fcgi_finish_request(&request, 1);
02191                             if (bindpath) {
02192                                    free(bindpath);
02193                             }
02194                             if (max_requests != 1) {
02195                                    /* no need to return exit_status of the last request */
02196                                    exit_status = 0;
02197                             }
02198                             break;
02199                      }
02200                      /* end of fastcgi loop */
02201               }
02202               fcgi_shutdown();
02203 
02204               if (cgi_sapi_module.php_ini_path_override) {
02205                      free(cgi_sapi_module.php_ini_path_override);
02206               }
02207               if (cgi_sapi_module.ini_entries) {
02208                      free(cgi_sapi_module.ini_entries);
02209               }
02210        } zend_catch {
02211               exit_status = 255;
02212        } zend_end_try();
02213 
02214 out:
02215        if (benchmark) {
02216               int sec;
02217 #ifdef HAVE_GETTIMEOFDAY
02218               int usec;
02219 
02220               gettimeofday(&end, NULL);
02221               sec = (int)(end.tv_sec - start.tv_sec);
02222               if (end.tv_usec >= start.tv_usec) {
02223                      usec = (int)(end.tv_usec - start.tv_usec);
02224               } else {
02225                      sec -= 1;
02226                      usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
02227               }
02228               fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
02229 #else
02230               time(&end);
02231               sec = (int)(end - start);
02232               fprintf(stderr, "\nElapsed time: %d sec\n", sec);
02233 #endif
02234        }
02235 
02236 #ifndef PHP_WIN32
02237 parent_out:
02238 #endif
02239 
02240        SG(server_context) = NULL;
02241        php_module_shutdown(TSRMLS_C);
02242        sapi_shutdown();
02243 
02244 #ifdef ZTS
02245        tsrm_shutdown();
02246 #endif
02247 
02248 #if defined(PHP_WIN32) && ZEND_DEBUG && 0
02249        _CrtDumpMemoryLeaks();
02250 #endif
02251 
02252        return exit_status;
02253 }
02254 /* }}} */
02255 
02256 /*
02257  * Local variables:
02258  * tab-width: 4
02259  * c-basic-offset: 4
02260  * End:
02261  * vim600: sw=4 ts=4 fdm=marker
02262  * vim<600: sw=4 ts=4
02263  */