1 /*
2 +----------------------------------------------------------------------+
3 | Copyright (c) The PHP Group |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.01 of the PHP license, |
6 | that is bundled with this package in the file LICENSE, and is |
7 | available through the world-wide-web at the following url: |
8 | https://www.php.net/license/3_01.txt |
9 | If you did not receive a copy of the PHP license and are unable to |
10 | obtain it through the world-wide-web, please send a note to |
11 | license@php.net so we can mail you a copy immediately. |
12 +----------------------------------------------------------------------+
13 | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
14 | Stig Bakken <ssb@php.net> |
15 | Zeev Suraski <zeev@php.net> |
16 | FastCGI: Ben Mansell <php@slimyhorror.com> |
17 | Shane Caraveo <shane@caraveo.com> |
18 | Dmitry Stogov <dmitry@php.net> |
19 +----------------------------------------------------------------------+
20 */
21
22 #include "php.h"
23 #include "php_globals.h"
24 #include "php_variables.h"
25 #include "php_ini_builder.h"
26 #include "zend_modules.h"
27
28 #include "SAPI.h"
29
30 #include <stdio.h>
31
32 #ifdef PHP_WIN32
33 # include "win32/time.h"
34 # include "win32/signal.h"
35 # include "win32/winutil.h"
36 # include <process.h>
37 #endif
38
39 #if HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42
43 #if HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
46
47 #include <signal.h>
48
49 #include <locale.h>
50
51 #if HAVE_SYS_TYPES_H
52 # include <sys/types.h>
53 #endif
54
55 #if HAVE_SYS_WAIT_H
56 # include <sys/wait.h>
57 #endif
58
59 #include "zend.h"
60 #include "zend_extensions.h"
61 #include "php_ini.h"
62 #include "php_globals.h"
63 #include "php_main.h"
64 #include "fopen_wrappers.h"
65 #include "http_status_codes.h"
66 #include "ext/standard/php_standard.h"
67 #include "ext/standard/dl_arginfo.h"
68 #include "ext/standard/url.h"
69
70 #ifdef PHP_WIN32
71 # include <io.h>
72 # include <fcntl.h>
73 # include "win32/php_registry.h"
74 #endif
75
76 #ifdef __riscos__
77 # include <unixlib/local.h>
78 int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
79 #endif
80
81 #include "zend_compile.h"
82 #include "zend_execute.h"
83 #include "zend_highlight.h"
84
85 #include "php_getopt.h"
86
87 #include "fastcgi.h"
88 #include "cgi_main_arginfo.h"
89
90 #if defined(PHP_WIN32) && defined(HAVE_OPENSSL)
91 # include "openssl/applink.c"
92 #endif
93
94 #ifdef HAVE_VALGRIND
95 # include "valgrind/callgrind.h"
96 #endif
97
98 #ifndef PHP_WIN32
99 /* XXX this will need to change later when threaded fastcgi is implemented. shane */
100 struct sigaction act, old_term, old_quit, old_int;
101 #endif
102
103 static void (*php_php_import_environment_variables)(zval *array_ptr);
104
105 /* these globals used for forking children on unix systems */
106 /**
107 * Number of child processes that will get created to service requests
108 */
109 static int children = 0;
110
111
112 /**
113 * Set to non-zero if we are the parent process
114 */
115 static int parent = 1;
116
117 #ifndef PHP_WIN32
118 /* Did parent received exit signals SIG_TERM/SIG_INT/SIG_QUIT */
119 static int exit_signal = 0;
120
121 /* Is Parent waiting for children to exit */
122 static int parent_waiting = 0;
123
124 /**
125 * Process group
126 */
127 static pid_t pgroup;
128 #endif
129
130 #define PHP_MODE_STANDARD 1
131 #define PHP_MODE_HIGHLIGHT 2
132 #define PHP_MODE_LINT 4
133 #define PHP_MODE_STRIP 5
134
135 static char *php_optarg = NULL;
136 static int php_optind = 1;
137 static zend_module_entry cgi_module_entry;
138
139 static const opt_struct OPTIONS[] = {
140 {'a', 0, "interactive"},
141 {'b', 1, "bindpath"},
142 {'C', 0, "no-chdir"},
143 {'c', 1, "php-ini"},
144 {'d', 1, "define"},
145 {'e', 0, "profile-info"},
146 {'f', 1, "file"},
147 {'h', 0, "help"},
148 {'i', 0, "info"},
149 {'l', 0, "syntax-check"},
150 {'m', 0, "modules"},
151 {'n', 0, "no-php-ini"},
152 {'q', 0, "no-header"},
153 {'s', 0, "syntax-highlight"},
154 {'s', 0, "syntax-highlighting"},
155 {'w', 0, "strip"},
156 {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
157 {'v', 0, "version"},
158 {'z', 1, "zend-extension"},
159 {'T', 1, "timing"},
160 {'-', 0, NULL} /* end of args */
161 };
162
163 typedef struct _php_cgi_globals_struct {
164 HashTable user_config_cache;
165 char *redirect_status_env;
166 bool rfc2616_headers;
167 bool nph;
168 bool check_shebang_line;
169 bool fix_pathinfo;
170 bool force_redirect;
171 bool discard_path;
172 bool fcgi_logging;
173 #ifdef PHP_WIN32
174 bool impersonate;
175 #endif
176 } php_cgi_globals_struct;
177
178 /* {{{ user_config_cache
179 *
180 * Key for each cache entry is dirname(PATH_TRANSLATED).
181 *
182 * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
183 * the path starting from doc_root through to dirname(PATH_TRANSLATED). There is no point
184 * storing per-file entries as it would not be possible to detect added / deleted entries
185 * between separate files.
186 */
187 typedef struct _user_config_cache_entry {
188 time_t expires;
189 HashTable *user_config;
190 } user_config_cache_entry;
191
user_config_cache_entry_dtor(zval * el)192 static void user_config_cache_entry_dtor(zval *el)
193 {
194 user_config_cache_entry *entry = (user_config_cache_entry *)Z_PTR_P(el);
195 zend_hash_destroy(entry->user_config);
196 free(entry->user_config);
197 free(entry);
198 }
199 /* }}} */
200
201 #ifdef ZTS
202 static int php_cgi_globals_id;
203 #define CGIG(v) ZEND_TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
204 #if defined(PHP_WIN32)
205 ZEND_TSRMLS_CACHE_DEFINE()
206 #endif
207 #else
208 static php_cgi_globals_struct php_cgi_globals;
209 #define CGIG(v) (php_cgi_globals.v)
210 #endif
211
212 #ifdef PHP_WIN32
213 #define TRANSLATE_SLASHES(path) \
214 { \
215 char *tmp = path; \
216 while (*tmp) { \
217 if (*tmp == '\\') *tmp = '/'; \
218 tmp++; \
219 } \
220 }
221 #else
222 #define TRANSLATE_SLASHES(path)
223 #endif
224
225 #ifdef PHP_WIN32
226 #define WIN32_MAX_SPAWN_CHILDREN 64
227 HANDLE kid_cgi_ps[WIN32_MAX_SPAWN_CHILDREN];
228 int kids, cleaning_up = 0;
229 HANDLE job = NULL;
230 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = { 0 };
231 CRITICAL_SECTION cleanup_lock;
232 #endif
233
234 #ifndef HAVE_ATTRIBUTE_WEAK
fcgi_log(int type,const char * format,...)235 static void fcgi_log(int type, const char *format, ...) {
236 va_list ap;
237
238 va_start(ap, format);
239 vfprintf(stderr, format, ap);
240 va_end(ap);
241 }
242 #endif
243
module_name_cmp(Bucket * f,Bucket * s)244 static int module_name_cmp(Bucket *f, Bucket *s)
245 {
246 return strcasecmp( ((zend_module_entry *)Z_PTR(f->val))->name,
247 ((zend_module_entry *)Z_PTR(s->val))->name);
248 }
249
print_modules(void)250 static void print_modules(void)
251 {
252 HashTable sorted_registry;
253 zend_module_entry *module;
254
255 zend_hash_init(&sorted_registry, 64, NULL, NULL, 1);
256 zend_hash_copy(&sorted_registry, &module_registry, NULL);
257 zend_hash_sort(&sorted_registry, module_name_cmp, 0);
258 ZEND_HASH_MAP_FOREACH_PTR(&sorted_registry, module) {
259 php_printf("%s\n", module->name);
260 } ZEND_HASH_FOREACH_END();
261 zend_hash_destroy(&sorted_registry);
262 }
263
print_extension_info(zend_extension * ext)264 static void print_extension_info(zend_extension *ext)
265 {
266 php_printf("%s\n", ext->name);
267 }
268
extension_name_cmp(const zend_llist_element ** f,const zend_llist_element ** s)269 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s)
270 {
271 zend_extension *fe = (zend_extension*)(*f)->data;
272 zend_extension *se = (zend_extension*)(*s)->data;
273 return strcmp(fe->name, se->name);
274 }
275
print_extensions(void)276 static void print_extensions(void)
277 {
278 zend_llist sorted_exts;
279
280 zend_llist_copy(&sorted_exts, &zend_extensions);
281 sorted_exts.dtor = NULL;
282 zend_llist_sort(&sorted_exts, extension_name_cmp);
283 zend_llist_apply(&sorted_exts, (llist_apply_func_t) print_extension_info);
284 zend_llist_destroy(&sorted_exts);
285 }
286
287 #ifndef STDOUT_FILENO
288 #define STDOUT_FILENO 1
289 #endif
290
sapi_cgi_single_write(const char * str,size_t str_length)291 static inline size_t sapi_cgi_single_write(const char *str, size_t str_length)
292 {
293 #ifdef PHP_WRITE_STDOUT
294 int ret;
295
296 ret = write(STDOUT_FILENO, str, str_length);
297 if (ret <= 0) return 0;
298 return ret;
299 #else
300 size_t ret;
301
302 ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
303 return ret;
304 #endif
305 }
306
sapi_cgi_ub_write(const char * str,size_t str_length)307 static size_t sapi_cgi_ub_write(const char *str, size_t str_length)
308 {
309 const char *ptr = str;
310 size_t remaining = str_length;
311 size_t ret;
312
313 while (remaining > 0) {
314 ret = sapi_cgi_single_write(ptr, remaining);
315 if (!ret) {
316 php_handle_aborted_connection();
317 return str_length - remaining;
318 }
319 ptr += ret;
320 remaining -= ret;
321 }
322
323 return str_length;
324 }
325
sapi_fcgi_ub_write(const char * str,size_t str_length)326 static size_t sapi_fcgi_ub_write(const char *str, size_t str_length)
327 {
328 const char *ptr = str;
329 size_t remaining = str_length;
330 fcgi_request *request = (fcgi_request*) SG(server_context);
331
332 while (remaining > 0) {
333 int to_write = remaining > INT_MAX ? INT_MAX : (int)remaining;
334 int ret = fcgi_write(request, FCGI_STDOUT, ptr, to_write);
335
336 if (ret <= 0) {
337 php_handle_aborted_connection();
338 return str_length - remaining;
339 }
340 ptr += ret;
341 remaining -= ret;
342 }
343
344 return str_length;
345 }
346
sapi_cgi_flush(void * server_context)347 static void sapi_cgi_flush(void *server_context)
348 {
349 if (fflush(stdout) == EOF) {
350 php_handle_aborted_connection();
351 }
352 }
353
sapi_fcgi_flush(void * server_context)354 static void sapi_fcgi_flush(void *server_context)
355 {
356 fcgi_request *request = (fcgi_request*) server_context;
357
358 if (
359 !parent &&
360 request && !fcgi_flush(request, 0)) {
361
362 php_handle_aborted_connection();
363 }
364 }
365
366 #define SAPI_CGI_MAX_HEADER_LENGTH 1024
367
sapi_cgi_send_headers(sapi_headers_struct * sapi_headers)368 static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers)
369 {
370 sapi_header_struct *h;
371 zend_llist_position pos;
372 bool ignore_status = 0;
373 int response_status = SG(sapi_headers).http_response_code;
374
375 if (SG(request_info).no_headers == 1) {
376 return SAPI_HEADER_SENT_SUCCESSFULLY;
377 }
378
379 if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
380 {
381 int len;
382 bool has_status = 0;
383 char buf[SAPI_CGI_MAX_HEADER_LENGTH];
384
385 if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
386 char *s;
387 len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s", SG(sapi_headers).http_status_line);
388 if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
389 response_status = atoi((s + 1));
390 }
391
392 if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
393 len = SAPI_CGI_MAX_HEADER_LENGTH;
394 }
395
396 } else {
397 char *s;
398
399 if (SG(sapi_headers).http_status_line &&
400 (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
401 (s - SG(sapi_headers).http_status_line) >= 5 &&
402 strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
403 ) {
404 len = slprintf(buf, sizeof(buf), "Status:%s", s);
405 response_status = atoi((s + 1));
406 } else {
407 h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
408 while (h) {
409 if (h->header_len > sizeof("Status:")-1 &&
410 strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
411 ) {
412 has_status = 1;
413 break;
414 }
415 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
416 }
417 if (!has_status) {
418 http_response_status_code_pair *err = (http_response_status_code_pair*)http_status_map;
419
420 while (err->code != 0) {
421 if (err->code == SG(sapi_headers).http_response_code) {
422 break;
423 }
424 err++;
425 }
426 if (err->str) {
427 len = slprintf(buf, sizeof(buf), "Status: %d %s", SG(sapi_headers).http_response_code, err->str);
428 } else {
429 len = slprintf(buf, sizeof(buf), "Status: %d", SG(sapi_headers).http_response_code);
430 }
431 }
432 }
433 }
434
435 if (!has_status) {
436 PHPWRITE_H(buf, len);
437 PHPWRITE_H("\r\n", 2);
438 ignore_status = 1;
439 }
440 }
441
442 h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
443 while (h) {
444 /* prevent CRLFCRLF */
445 if (h->header_len) {
446 if (h->header_len > sizeof("Status:")-1 &&
447 strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
448 ) {
449 if (!ignore_status) {
450 ignore_status = 1;
451 PHPWRITE_H(h->header, h->header_len);
452 PHPWRITE_H("\r\n", 2);
453 }
454 } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
455 strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
456 ) {
457 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
458 continue;
459 } else {
460 PHPWRITE_H(h->header, h->header_len);
461 PHPWRITE_H("\r\n", 2);
462 }
463 }
464 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
465 }
466 PHPWRITE_H("\r\n", 2);
467
468 return SAPI_HEADER_SENT_SUCCESSFULLY;
469 }
470
471 #ifndef STDIN_FILENO
472 # define STDIN_FILENO 0
473 #endif
474
sapi_cgi_read_post(char * buffer,size_t count_bytes)475 static size_t sapi_cgi_read_post(char *buffer, size_t count_bytes)
476 {
477 size_t read_bytes = 0;
478 int tmp_read_bytes;
479 size_t remaining_bytes;
480
481 assert(SG(request_info).content_length >= SG(read_post_bytes));
482
483 remaining_bytes = (size_t)(SG(request_info).content_length - SG(read_post_bytes));
484
485 count_bytes = MIN(count_bytes, remaining_bytes);
486 while (read_bytes < count_bytes) {
487 #ifdef PHP_WIN32
488 size_t diff = count_bytes - read_bytes;
489 unsigned int to_read = (diff > INT_MAX) ? INT_MAX : (unsigned int)diff;
490
491 tmp_read_bytes = _read(STDIN_FILENO, buffer + read_bytes, to_read);
492 #else
493 tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes);
494 #endif
495 if (tmp_read_bytes <= 0) {
496 break;
497 }
498 read_bytes += tmp_read_bytes;
499 }
500 return read_bytes;
501 }
502
sapi_fcgi_read_post(char * buffer,size_t count_bytes)503 static size_t sapi_fcgi_read_post(char *buffer, size_t count_bytes)
504 {
505 size_t read_bytes = 0;
506 int tmp_read_bytes;
507 fcgi_request *request = (fcgi_request*) SG(server_context);
508 size_t remaining = SG(request_info).content_length - SG(read_post_bytes);
509
510 if (remaining < count_bytes) {
511 count_bytes = remaining;
512 }
513 while (read_bytes < count_bytes) {
514 size_t diff = count_bytes - read_bytes;
515 int to_read = (diff > INT_MAX) ? INT_MAX : (int)diff;
516
517 tmp_read_bytes = fcgi_read(request, buffer + read_bytes, to_read);
518 if (tmp_read_bytes <= 0) {
519 break;
520 }
521 read_bytes += tmp_read_bytes;
522 }
523 return read_bytes;
524 }
525
526 #ifdef PHP_WIN32
527 /* The result needs to be freed! See sapi_getenv(). */
cgi_getenv_win32(const char * name,size_t name_len)528 static char *cgi_getenv_win32(const char *name, size_t name_len)
529 {
530 char *ret = NULL;
531 wchar_t *keyw, *valw;
532 size_t size;
533 int rc;
534
535 keyw = php_win32_cp_conv_any_to_w(name, name_len, PHP_WIN32_CP_IGNORE_LEN_P);
536 if (!keyw) {
537 return NULL;
538 }
539
540 rc = _wgetenv_s(&size, NULL, 0, keyw);
541 if (rc || 0 == size) {
542 free(keyw);
543 return NULL;
544 }
545
546 valw = emalloc((size + 1) * sizeof(wchar_t));
547
548 rc = _wgetenv_s(&size, valw, size, keyw);
549 if (!rc) {
550 ret = php_win32_cp_w_to_any(valw);
551 }
552
553 free(keyw);
554 efree(valw);
555
556 return ret;
557 }
558 #endif
559
sapi_cgi_getenv(const char * name,size_t name_len)560 static char *sapi_cgi_getenv(const char *name, size_t name_len)
561 {
562 #ifndef PHP_WIN32
563 return getenv(name);
564 #else
565 return cgi_getenv_win32(name, name_len);
566 #endif
567 }
568
sapi_fcgi_getenv(const char * name,size_t name_len)569 static char *sapi_fcgi_getenv(const char *name, size_t name_len)
570 {
571 /* when php is started by mod_fastcgi, no regular environment
572 * is provided to PHP. It is always sent to PHP at the start
573 * of a request. So we have to do our own lookup to get env
574 * vars. This could probably be faster somehow. */
575 fcgi_request *request = (fcgi_request*) SG(server_context);
576 char *ret = fcgi_getenv(request, name, (int)name_len);
577
578 #ifndef PHP_WIN32
579 if (ret) return ret;
580 /* if cgi, or fastcgi and not found in fcgi env
581 check the regular environment */
582 return getenv(name);
583 #else
584 if (ret) {
585 /* The functions outside here don't know, where does it come
586 from. They'll need to free the returned memory as it's
587 not necessary from the fcgi env. */
588 return strdup(ret);
589 }
590 /* if cgi, or fastcgi and not found in fcgi env
591 check the regular environment */
592 return cgi_getenv_win32(name, name_len);
593 #endif
594 }
595
_sapi_cgi_putenv(char * name,size_t name_len,char * value)596 static char *_sapi_cgi_putenv(char *name, size_t name_len, char *value)
597 {
598 #if !HAVE_SETENV || !HAVE_UNSETENV
599 size_t len;
600 char *buf;
601 #endif
602
603 #if HAVE_SETENV
604 if (value) {
605 setenv(name, value, 1);
606 }
607 #endif
608 #if HAVE_UNSETENV
609 if (!value) {
610 unsetenv(name);
611 }
612 #endif
613
614 #if !HAVE_SETENV || !HAVE_UNSETENV
615 /* if cgi, or fastcgi and not found in fcgi env
616 check the regular environment
617 this leaks, but it's only cgi anyway, we'll fix
618 it for 5.0
619 */
620 len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
621 buf = (char *) malloc(len);
622 if (buf == NULL) {
623 return getenv(name);
624 }
625 #endif
626 #if !HAVE_SETENV
627 if (value) {
628 len = slprintf(buf, len - 1, "%s=%s", name, value);
629 putenv(buf);
630 }
631 #endif
632 #if !HAVE_UNSETENV
633 if (!value) {
634 len = slprintf(buf, len - 1, "%s=", name);
635 putenv(buf);
636 }
637 #endif
638 return getenv(name);
639 }
640
sapi_cgi_read_cookies(void)641 static char *sapi_cgi_read_cookies(void)
642 {
643 return getenv("HTTP_COOKIE");
644 }
645
sapi_fcgi_read_cookies(void)646 static char *sapi_fcgi_read_cookies(void)
647 {
648 fcgi_request *request = (fcgi_request*) SG(server_context);
649
650 return FCGI_GETENV(request, "HTTP_COOKIE");
651 }
652
cgi_php_load_env_var(const char * var,unsigned int var_len,char * val,unsigned int val_len,void * arg)653 static void cgi_php_load_env_var(const char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg)
654 {
655 zval *array_ptr = (zval *) arg;
656 int filter_arg = (Z_ARR_P(array_ptr) == Z_ARR(PG(http_globals)[TRACK_VARS_ENV])) ? PARSE_ENV : PARSE_SERVER;
657 size_t new_val_len;
658
659 if (sapi_module.input_filter(filter_arg, var, &val, strlen(val), &new_val_len)) {
660 php_register_variable_safe(var, val, new_val_len, array_ptr);
661 }
662 }
663
cgi_php_import_environment_variables(zval * array_ptr)664 static void cgi_php_import_environment_variables(zval *array_ptr)
665 {
666 if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) {
667 if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) != IS_ARRAY) {
668 zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_ENV));
669 }
670
671 if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
672 Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_ENV])) {
673 zend_array_destroy(Z_ARR_P(array_ptr));
674 Z_ARR_P(array_ptr) = zend_array_dup(Z_ARR(PG(http_globals)[TRACK_VARS_ENV]));
675 return;
676 }
677 }
678
679 /* call php's original import as a catch-all */
680 php_php_import_environment_variables(array_ptr);
681
682 if (fcgi_is_fastcgi()) {
683 fcgi_request *request = (fcgi_request*) SG(server_context);
684 fcgi_loadenv(request, cgi_php_load_env_var, array_ptr);
685 }
686 }
687
sapi_cgi_register_variables(zval * track_vars_array)688 static void sapi_cgi_register_variables(zval *track_vars_array)
689 {
690 size_t php_self_len;
691 char *php_self;
692
693 /* In CGI mode, we consider the environment to be a part of the server
694 * variables
695 */
696 php_import_environment_variables(track_vars_array);
697
698 if (CGIG(fix_pathinfo)) {
699 char *script_name = SG(request_info).request_uri;
700 char *path_info;
701 int free_php_self;
702 ALLOCA_FLAG(use_heap)
703
704 if (fcgi_is_fastcgi()) {
705 fcgi_request *request = (fcgi_request*) SG(server_context);
706
707 path_info = FCGI_GETENV(request, "PATH_INFO");
708 } else {
709 path_info = getenv("PATH_INFO");
710 }
711
712 if (path_info) {
713 size_t path_info_len = strlen(path_info);
714
715 if (script_name) {
716 size_t script_name_len = strlen(script_name);
717
718 php_self_len = script_name_len + path_info_len;
719 php_self = do_alloca(php_self_len + 1, use_heap);
720 memcpy(php_self, script_name, script_name_len + 1);
721 memcpy(php_self + script_name_len, path_info, path_info_len + 1);
722 free_php_self = 1;
723 } else {
724 php_self = path_info;
725 php_self_len = path_info_len;
726 free_php_self = 0;
727 }
728 } else if (script_name) {
729 php_self = script_name;
730 php_self_len = strlen(script_name);
731 free_php_self = 0;
732 } else {
733 php_self = "";
734 php_self_len = 0;
735 free_php_self = 0;
736 }
737
738 /* Build the special-case PHP_SELF variable for the CGI version */
739 if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
740 php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
741 }
742 if (free_php_self) {
743 free_alloca(php_self, use_heap);
744 }
745 } else {
746 php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
747 php_self_len = strlen(php_self);
748 if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
749 php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
750 }
751 }
752 }
753
sapi_cgi_log_message(const char * message,int syslog_type_int)754 static void sapi_cgi_log_message(const char *message, int syslog_type_int)
755 {
756 if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
757 fcgi_request *request;
758
759 request = (fcgi_request*) SG(server_context);
760 if (request) {
761 int ret, len = (int)strlen(message);
762 char *buf = malloc(len+2);
763
764 memcpy(buf, message, len);
765 memcpy(buf + len, "\n", sizeof("\n"));
766 ret = fcgi_write(request, FCGI_STDERR, buf, (int)(len + 1));
767 free(buf);
768 if (ret < 0) {
769 php_handle_aborted_connection();
770 }
771 } else {
772 fprintf(stderr, "%s\n", message);
773 }
774 /* ignore return code */
775 } else {
776 fprintf(stderr, "%s\n", message);
777 }
778 }
779
780 /* {{{ php_cgi_ini_activate_user_config */
php_cgi_ini_activate_user_config(char * path,size_t path_len,const char * doc_root,size_t doc_root_len)781 static void php_cgi_ini_activate_user_config(char *path, size_t path_len, const char *doc_root, size_t doc_root_len)
782 {
783 user_config_cache_entry *new_entry, *entry;
784 time_t request_time = (time_t)sapi_get_request_time();
785
786 /* Find cached config entry: If not found, create one */
787 if ((entry = zend_hash_str_find_ptr(&CGIG(user_config_cache), path, path_len)) == NULL) {
788 new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
789 new_entry->expires = 0;
790 new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
791 zend_hash_init(new_entry->user_config, 8, NULL, (dtor_func_t) config_zval_dtor, 1);
792 entry = zend_hash_str_update_ptr(&CGIG(user_config_cache), path, path_len, new_entry);
793 }
794
795 /* Check whether cache entry has expired and rescan if it is */
796 if (request_time > entry->expires) {
797 char *real_path = NULL;
798 char *s1, *s2;
799 size_t s_len;
800
801 /* Clear the expired config */
802 zend_hash_clean(entry->user_config);
803
804 if (!IS_ABSOLUTE_PATH(path, path_len)) {
805 size_t real_path_len;
806 real_path = tsrm_realpath(path, NULL);
807 if (real_path == NULL) {
808 return;
809 }
810 real_path_len = strlen(real_path);
811 path = real_path;
812 path_len = real_path_len;
813 }
814
815 if (path_len > doc_root_len) {
816 s1 = (char *) doc_root;
817 s2 = path;
818 s_len = doc_root_len;
819 } else {
820 s1 = path;
821 s2 = (char *) doc_root;
822 s_len = path_len;
823 }
824
825 /* we have to test if path is part of DOCUMENT_ROOT.
826 if it is inside the docroot, we scan the tree up to the docroot
827 to find more user.ini, if not we only scan the current path.
828 */
829 #ifdef PHP_WIN32
830 if (strnicmp(s1, s2, s_len) == 0) {
831 #else
832 if (strncmp(s1, s2, s_len) == 0) {
833 #endif
834 char *ptr = s2 + doc_root_len;
835 #ifdef PHP_WIN32
836 while ((ptr = strpbrk(ptr, "\\/")) != NULL) {
837 #else
838 while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
839 #endif
840 *ptr = 0;
841 php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
842 *ptr = '/';
843 ptr++;
844 }
845 } else {
846 php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
847 }
848
849 if (real_path) {
850 efree(real_path);
851 }
852 entry->expires = request_time + PG(user_ini_cache_ttl);
853 }
854
855 /* Activate ini entries with values from the user config hash */
856 php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS);
857 }
858 /* }}} */
859
860 static int sapi_cgi_activate(void)
861 {
862 /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
863 if (!SG(request_info).path_translated) {
864 return FAILURE;
865 }
866
867 if (php_ini_has_per_host_config()) {
868 char *server_name;
869
870 /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
871 if (fcgi_is_fastcgi()) {
872 fcgi_request *request = (fcgi_request*) SG(server_context);
873
874 server_name = FCGI_GETENV(request, "SERVER_NAME");
875 } else {
876 server_name = getenv("SERVER_NAME");
877 }
878 /* SERVER_NAME should also be defined at this stage..but better check it anyway */
879 if (server_name) {
880 size_t server_name_len = strlen(server_name);
881 server_name = estrndup(server_name, server_name_len);
882 zend_str_tolower(server_name, server_name_len);
883 php_ini_activate_per_host_config(server_name, server_name_len);
884 efree(server_name);
885 }
886 }
887
888 if (php_ini_has_per_dir_config() ||
889 (PG(user_ini_filename) && *PG(user_ini_filename))
890 ) {
891 char *path;
892 size_t path_len;
893
894 /* Prepare search path */
895 path_len = strlen(SG(request_info).path_translated);
896
897 /* Make sure we have trailing slash! */
898 if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
899 path = emalloc(path_len + 2);
900 memcpy(path, SG(request_info).path_translated, path_len + 1);
901 path_len = zend_dirname(path, path_len);
902 path[path_len++] = DEFAULT_SLASH;
903 } else {
904 path = estrndup(SG(request_info).path_translated, path_len);
905 path_len = zend_dirname(path, path_len);
906 }
907 path[path_len] = 0;
908
909 /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
910 php_ini_activate_per_dir_config(path, path_len); /* Note: for global settings sake we check from root to path */
911
912 /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
913 if (PG(user_ini_filename) && *PG(user_ini_filename)) {
914 char *doc_root;
915
916 if (fcgi_is_fastcgi()) {
917 fcgi_request *request = (fcgi_request*) SG(server_context);
918
919 doc_root = FCGI_GETENV(request, "DOCUMENT_ROOT");
920 } else {
921 doc_root = getenv("DOCUMENT_ROOT");
922 }
923 /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
924 if (doc_root) {
925 size_t doc_root_len = strlen(doc_root);
926 if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
927 --doc_root_len;
928 }
929 #ifdef PHP_WIN32
930 /* paths on windows should be case-insensitive */
931 doc_root = estrndup(doc_root, doc_root_len);
932 zend_str_tolower(doc_root, doc_root_len);
933 #endif
934 php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len);
935
936 #ifdef PHP_WIN32
937 efree(doc_root);
938 #endif
939 }
940 }
941
942 efree(path);
943 }
944
945 return SUCCESS;
946 }
947
948 static int sapi_cgi_deactivate(void)
949 {
950 /* flush only when SAPI was started. The reasons are:
951 1. SAPI Deactivate is called from two places: module init and request shutdown
952 2. When the first call occurs and the request is not set up, flush fails on FastCGI.
953 */
954 if (SG(sapi_started)) {
955 if (fcgi_is_fastcgi()) {
956 if (
957 !parent &&
958 !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
959 php_handle_aborted_connection();
960 }
961 } else {
962 sapi_cgi_flush(SG(server_context));
963 }
964 }
965 return SUCCESS;
966 }
967
968 static int php_cgi_startup(sapi_module_struct *sapi_module)
969 {
970 return php_module_startup(sapi_module, &cgi_module_entry);
971 }
972
973 /* {{{ sapi_module_struct cgi_sapi_module */
974 static sapi_module_struct cgi_sapi_module = {
975 "cgi-fcgi", /* name */
976 "CGI/FastCGI", /* pretty name */
977
978 php_cgi_startup, /* startup */
979 php_module_shutdown_wrapper, /* shutdown */
980
981 sapi_cgi_activate, /* activate */
982 sapi_cgi_deactivate, /* deactivate */
983
984 sapi_cgi_ub_write, /* unbuffered write */
985 sapi_cgi_flush, /* flush */
986 NULL, /* get uid */
987 sapi_cgi_getenv, /* getenv */
988
989 php_error, /* error handler */
990
991 NULL, /* header handler */
992 sapi_cgi_send_headers, /* send headers handler */
993 NULL, /* send header handler */
994
995 sapi_cgi_read_post, /* read POST data */
996 sapi_cgi_read_cookies, /* read Cookies */
997
998 sapi_cgi_register_variables, /* register server variables */
999 sapi_cgi_log_message, /* Log message */
1000 NULL, /* Get request time */
1001 NULL, /* Child terminate */
1002
1003 STANDARD_SAPI_MODULE_PROPERTIES
1004 };
1005 /* }}} */
1006
1007 static const zend_function_entry additional_functions[] = {
1008 ZEND_FE(dl, arginfo_dl)
1009 PHP_FE_END
1010 };
1011
1012 /* {{{ php_cgi_usage */
1013 static void php_cgi_usage(char *argv0)
1014 {
1015 char *prog;
1016
1017 prog = strrchr(argv0, '/');
1018 if (prog) {
1019 prog++;
1020 } else {
1021 prog = "php-cgi";
1022 }
1023
1024 php_printf( "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
1025 " %s <file> [args...]\n"
1026 " -a Run interactively\n"
1027 " -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
1028 " -C Do not chdir to the script's directory\n"
1029 " -c <path>|<file> Look for php.ini file in this directory\n"
1030 " -n No php.ini file will be used\n"
1031 " -d foo[=bar] Define INI entry foo with value 'bar'\n"
1032 " -e Generate extended information for debugger/profiler\n"
1033 " -f <file> Parse <file>. Implies `-q'\n"
1034 " -h This help\n"
1035 " -i PHP information\n"
1036 " -l Syntax check only (lint)\n"
1037 " -m Show compiled in modules\n"
1038 " -q Quiet-mode. Suppress HTTP Header output.\n"
1039 " -s Display colour syntax highlighted source.\n"
1040 " -v Version number\n"
1041 " -w Display source with stripped comments and whitespace.\n"
1042 " -z <file> Load Zend extension <file>.\n"
1043 " -T <count> Measure execution time of script repeated <count> times.\n",
1044 prog, prog);
1045 }
1046 /* }}} */
1047
1048 /* {{{ is_valid_path
1049 *
1050 * some server configurations allow '..' to slip through in the
1051 * translated path. We'll just refuse to handle such a path.
1052 */
1053 static int is_valid_path(const char *path)
1054 {
1055 const char *p = path;
1056
1057 if (UNEXPECTED(!p)) {
1058 return 0;
1059 }
1060 if (UNEXPECTED(*p == '.') && *(p+1) == '.' && (!*(p+2) || IS_SLASH(*(p+2)))) {
1061 return 0;
1062 }
1063 while (*p) {
1064 if (IS_SLASH(*p)) {
1065 p++;
1066 if (UNEXPECTED(*p == '.')) {
1067 p++;
1068 if (UNEXPECTED(*p == '.')) {
1069 p++;
1070 if (UNEXPECTED(!*p) || UNEXPECTED(IS_SLASH(*p))) {
1071 return 0;
1072 }
1073 }
1074 }
1075 }
1076 p++;
1077 }
1078 return 1;
1079 }
1080 /* }}} */
1081
1082 #define CGI_GETENV(name) \
1083 ((has_env) ? \
1084 FCGI_GETENV(request, name) : \
1085 getenv(name))
1086
1087 #define CGI_PUTENV(name, value) \
1088 ((has_env) ? \
1089 FCGI_PUTENV(request, name, value) : \
1090 _sapi_cgi_putenv(name, sizeof(name)-1, value))
1091
1092 /* {{{ init_request_info
1093
1094 initializes request_info structure
1095
1096 specifically in this section we handle proper translations
1097 for:
1098
1099 PATH_INFO
1100 derived from the portion of the URI path following
1101 the script name but preceding any query data
1102 may be empty
1103
1104 PATH_TRANSLATED
1105 derived by taking any path-info component of the
1106 request URI and performing any virtual-to-physical
1107 translation appropriate to map it onto the server's
1108 document repository structure
1109
1110 empty if PATH_INFO is empty
1111
1112 The env var PATH_TRANSLATED **IS DIFFERENT** than the
1113 request_info.path_translated variable, the latter should
1114 match SCRIPT_FILENAME instead.
1115
1116 SCRIPT_NAME
1117 set to a URL path that could identify the CGI script
1118 rather than the interpreter. PHP_SELF is set to this
1119
1120 REQUEST_URI
1121 uri section following the domain:port part of a URI
1122
1123 SCRIPT_FILENAME
1124 The virtual-to-physical translation of SCRIPT_NAME (as per
1125 PATH_TRANSLATED)
1126
1127 These settings are documented at
1128 http://cgi-spec.golux.com/
1129
1130
1131 Based on the following URL request:
1132
1133 http://localhost/info.php/test?a=b
1134
1135 should produce, which btw is the same as if
1136 we were running under mod_cgi on apache (ie. not
1137 using ScriptAlias directives):
1138
1139 PATH_INFO=/test
1140 PATH_TRANSLATED=/docroot/test
1141 SCRIPT_NAME=/info.php
1142 REQUEST_URI=/info.php/test?a=b
1143 SCRIPT_FILENAME=/docroot/info.php
1144 QUERY_STRING=a=b
1145
1146 but what we get is (cgi/mod_fastcgi under apache):
1147
1148 PATH_INFO=/info.php/test
1149 PATH_TRANSLATED=/docroot/info.php/test
1150 SCRIPT_NAME=/php/php-cgi (from the Action setting I suppose)
1151 REQUEST_URI=/info.php/test?a=b
1152 SCRIPT_FILENAME=/path/to/php/bin/php-cgi (Action setting translated)
1153 QUERY_STRING=a=b
1154
1155 Comments in the code below refer to using the above URL in a request
1156
1157 */
1158 static void init_request_info(fcgi_request *request)
1159 {
1160 int has_env = fcgi_has_env(request);
1161 char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
1162 char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
1163 char *script_path_translated = env_script_filename;
1164
1165 /* some broken servers do not have script_filename or argv0
1166 * an example, IIS configured in some ways. then they do more
1167 * broken stuff and set path_translated to the cgi script location */
1168 if (!script_path_translated && env_path_translated) {
1169 script_path_translated = env_path_translated;
1170 }
1171
1172 /* initialize the defaults */
1173 SG(request_info).path_translated = NULL;
1174 SG(request_info).request_method = NULL;
1175 SG(request_info).proto_num = 1000;
1176 SG(request_info).query_string = NULL;
1177 SG(request_info).request_uri = NULL;
1178 SG(request_info).content_type = NULL;
1179 SG(request_info).content_length = 0;
1180 SG(sapi_headers).http_response_code = 200;
1181
1182 /* script_path_translated being set is a good indication that
1183 * we are running in a cgi environment, since it is always
1184 * null otherwise. otherwise, the filename
1185 * of the script will be retrieved later via argc/argv */
1186 if (script_path_translated) {
1187 const char *auth;
1188 char *content_length = CGI_GETENV("CONTENT_LENGTH");
1189 char *content_type = CGI_GETENV("CONTENT_TYPE");
1190 char *env_path_info = CGI_GETENV("PATH_INFO");
1191 char *env_script_name = CGI_GETENV("SCRIPT_NAME");
1192
1193 #ifdef PHP_WIN32
1194 /* Hack for buggy IIS that sets incorrect PATH_INFO */
1195 char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
1196
1197 if (env_server_software &&
1198 env_script_name &&
1199 env_path_info &&
1200 strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
1201 strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
1202 ) {
1203 env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
1204 env_path_info += strlen(env_script_name);
1205 if (*env_path_info == 0) {
1206 env_path_info = NULL;
1207 }
1208 env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
1209 }
1210 #endif
1211
1212 if (CGIG(fix_pathinfo)) {
1213 zend_stat_t st = {0};
1214 char *real_path = NULL;
1215 char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
1216 char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
1217 char *orig_path_translated = env_path_translated;
1218 char *orig_path_info = env_path_info;
1219 char *orig_script_name = env_script_name;
1220 char *orig_script_filename = env_script_filename;
1221 size_t script_path_translated_len;
1222
1223 if (!env_document_root && PG(doc_root)) {
1224 env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
1225 /* fix docroot */
1226 TRANSLATE_SLASHES(env_document_root);
1227 }
1228
1229 if (env_path_translated != NULL && env_redirect_url != NULL &&
1230 env_path_translated != script_path_translated &&
1231 strcmp(env_path_translated, script_path_translated) != 0) {
1232 /*
1233 * pretty much apache specific. If we have a redirect_url
1234 * then our script_filename and script_name point to the
1235 * php executable
1236 */
1237 script_path_translated = env_path_translated;
1238 /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
1239 env_script_name = env_redirect_url;
1240 }
1241
1242 #ifdef __riscos__
1243 /* Convert path to unix format*/
1244 __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
1245 script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
1246 #endif
1247
1248 /*
1249 * if the file doesn't exist, try to extract PATH_INFO out
1250 * of it by stat'ing back through the '/'
1251 * this fixes url's like /info.php/test
1252 */
1253 if (script_path_translated &&
1254 (script_path_translated_len = strlen(script_path_translated)) > 0 &&
1255 (script_path_translated[script_path_translated_len-1] == '/' ||
1256 #ifdef PHP_WIN32
1257 script_path_translated[script_path_translated_len-1] == '\\' ||
1258 #endif
1259 (real_path = tsrm_realpath(script_path_translated, NULL)) == NULL)
1260 ) {
1261 char *pt = estrndup(script_path_translated, script_path_translated_len);
1262 size_t len = script_path_translated_len;
1263 char *ptr;
1264
1265 while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
1266 *ptr = 0;
1267 if (zend_stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
1268 /*
1269 * okay, we found the base script!
1270 * work out how many chars we had to strip off;
1271 * then we can modify PATH_INFO
1272 * accordingly
1273 *
1274 * we now have the makings of
1275 * PATH_INFO=/test
1276 * SCRIPT_FILENAME=/docroot/info.php
1277 *
1278 * we now need to figure out what docroot is.
1279 * if DOCUMENT_ROOT is set, this is easy, otherwise,
1280 * we have to play the game of hide and seek to figure
1281 * out what SCRIPT_NAME should be
1282 */
1283 size_t slen = len - strlen(pt);
1284 size_t pilen = env_path_info ? strlen(env_path_info) : 0;
1285 char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
1286
1287 if (orig_path_info != path_info) {
1288 if (orig_path_info) {
1289 char old;
1290
1291 CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1292 old = path_info[0];
1293 path_info[0] = 0;
1294 if (!orig_script_name ||
1295 strcmp(orig_script_name, env_path_info) != 0) {
1296 if (orig_script_name) {
1297 CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1298 }
1299 SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
1300 } else {
1301 SG(request_info).request_uri = orig_script_name;
1302 }
1303 path_info[0] = old;
1304 }
1305 env_path_info = CGI_PUTENV("PATH_INFO", path_info);
1306 }
1307 if (!orig_script_filename ||
1308 strcmp(orig_script_filename, pt) != 0) {
1309 if (orig_script_filename) {
1310 CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1311 }
1312 script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
1313 }
1314 TRANSLATE_SLASHES(pt);
1315
1316 /* figure out docroot
1317 * SCRIPT_FILENAME minus SCRIPT_NAME
1318 */
1319 if (env_document_root) {
1320 size_t l = strlen(env_document_root);
1321 size_t path_translated_len = 0;
1322 char *path_translated = NULL;
1323
1324 if (l && env_document_root[l - 1] == '/') {
1325 --l;
1326 }
1327
1328 /* we have docroot, so we should have:
1329 * DOCUMENT_ROOT=/docroot
1330 * SCRIPT_FILENAME=/docroot/info.php
1331 */
1332
1333 /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
1334 path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
1335 path_translated = (char *) emalloc(path_translated_len + 1);
1336 memcpy(path_translated, env_document_root, l);
1337 if (env_path_info) {
1338 memcpy(path_translated + l, env_path_info, (path_translated_len - l));
1339 }
1340 path_translated[path_translated_len] = '\0';
1341 if (orig_path_translated) {
1342 CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1343 }
1344 env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1345 efree(path_translated);
1346 } else if ( env_script_name &&
1347 strstr(pt, env_script_name)
1348 ) {
1349 /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
1350 size_t ptlen = strlen(pt) - strlen(env_script_name);
1351 size_t path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
1352
1353 char *path_translated = (char *) emalloc(path_translated_len + 1);
1354 memcpy(path_translated, pt, ptlen);
1355 if (env_path_info) {
1356 memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
1357 }
1358 path_translated[path_translated_len] = '\0';
1359 if (orig_path_translated) {
1360 CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1361 }
1362 env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1363 efree(path_translated);
1364 }
1365 break;
1366 }
1367 }
1368 if (!ptr) {
1369 /*
1370 * if we stripped out all the '/' and still didn't find
1371 * a valid path... we will fail, badly. of course we would
1372 * have failed anyway... we output 'no input file' now.
1373 */
1374 if (orig_script_filename) {
1375 CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1376 }
1377 script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
1378 SG(sapi_headers).http_response_code = 404;
1379 }
1380 if (!SG(request_info).request_uri) {
1381 if (!orig_script_name ||
1382 strcmp(orig_script_name, env_script_name) != 0) {
1383 if (orig_script_name) {
1384 CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1385 }
1386 SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1387 } else {
1388 SG(request_info).request_uri = orig_script_name;
1389 }
1390 }
1391 if (pt) {
1392 efree(pt);
1393 }
1394 } else {
1395 /* make sure path_info/translated are empty */
1396 if (!orig_script_filename ||
1397 (script_path_translated != orig_script_filename &&
1398 strcmp(script_path_translated, orig_script_filename) != 0)) {
1399 if (orig_script_filename) {
1400 CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1401 }
1402 script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
1403 }
1404 if (env_redirect_url) {
1405 if (orig_path_info) {
1406 CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1407 CGI_PUTENV("PATH_INFO", NULL);
1408 }
1409 if (orig_path_translated) {
1410 CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1411 CGI_PUTENV("PATH_TRANSLATED", NULL);
1412 }
1413 }
1414 if (env_script_name != orig_script_name) {
1415 if (orig_script_name) {
1416 CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1417 }
1418 SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1419 } else {
1420 SG(request_info).request_uri = env_script_name;
1421 }
1422 efree(real_path);
1423 }
1424 } else {
1425 /* pre 4.3 behaviour, shouldn't be used but provides BC */
1426 if (env_path_info) {
1427 SG(request_info).request_uri = env_path_info;
1428 } else {
1429 SG(request_info).request_uri = env_script_name;
1430 }
1431 if (!CGIG(discard_path) && env_path_translated) {
1432 script_path_translated = env_path_translated;
1433 }
1434 }
1435
1436 if (is_valid_path(script_path_translated)) {
1437 SG(request_info).path_translated = estrdup(script_path_translated);
1438 }
1439
1440 SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
1441 /* FIXME - Work out proto_num here */
1442 SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
1443 SG(request_info).content_type = (content_type ? content_type : "" );
1444 SG(request_info).content_length = (content_length ? atol(content_length) : 0);
1445
1446 /* The CGI RFC allows servers to pass on unvalidated Authorization data */
1447 auth = CGI_GETENV("HTTP_AUTHORIZATION");
1448 php_handle_auth_data(auth);
1449 }
1450 }
1451 /* }}} */
1452
1453 #ifndef PHP_WIN32
1454 /**
1455 * Clean up child processes upon exit
1456 */
1457 void fastcgi_cleanup(int signal)
1458 {
1459 #ifdef DEBUG_FASTCGI
1460 fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
1461 #endif
1462
1463 sigaction(SIGTERM, &old_term, 0);
1464
1465 /* Kill all the processes in our process group */
1466 kill(-pgroup, SIGTERM);
1467
1468 if (parent && parent_waiting) {
1469 exit_signal = 1;
1470 } else {
1471 exit(0);
1472 }
1473 }
1474 #else
1475 BOOL WINAPI fastcgi_cleanup(DWORD sig)
1476 {
1477 int i = kids;
1478
1479 EnterCriticalSection(&cleanup_lock);
1480 cleaning_up = 1;
1481 LeaveCriticalSection(&cleanup_lock);
1482
1483 while (0 < i--) {
1484 if (NULL == kid_cgi_ps[i]) {
1485 continue;
1486 }
1487
1488 TerminateProcess(kid_cgi_ps[i], 0);
1489 CloseHandle(kid_cgi_ps[i]);
1490 kid_cgi_ps[i] = NULL;
1491 }
1492
1493 if (job) {
1494 CloseHandle(job);
1495 }
1496
1497 parent = 0;
1498
1499 return TRUE;
1500 }
1501 #endif
1502
1503 PHP_INI_BEGIN()
1504 STD_PHP_INI_BOOLEAN("cgi.rfc2616_headers", "0", PHP_INI_ALL, OnUpdateBool, rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
1505 STD_PHP_INI_BOOLEAN("cgi.nph", "0", PHP_INI_ALL, OnUpdateBool, nph, php_cgi_globals_struct, php_cgi_globals)
1506 STD_PHP_INI_BOOLEAN("cgi.check_shebang_line", "1", PHP_INI_SYSTEM, OnUpdateBool, check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
1507 STD_PHP_INI_BOOLEAN("cgi.force_redirect", "1", PHP_INI_SYSTEM, OnUpdateBool, force_redirect, php_cgi_globals_struct, php_cgi_globals)
1508 STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
1509 STD_PHP_INI_BOOLEAN("cgi.fix_pathinfo", "1", PHP_INI_SYSTEM, OnUpdateBool, fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
1510 STD_PHP_INI_BOOLEAN("cgi.discard_path", "0", PHP_INI_SYSTEM, OnUpdateBool, discard_path, php_cgi_globals_struct, php_cgi_globals)
1511 STD_PHP_INI_BOOLEAN("fastcgi.logging", "1", PHP_INI_SYSTEM, OnUpdateBool, fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
1512 #ifdef PHP_WIN32
1513 STD_PHP_INI_BOOLEAN("fastcgi.impersonate", "0", PHP_INI_SYSTEM, OnUpdateBool, impersonate, php_cgi_globals_struct, php_cgi_globals)
1514 #endif
1515 PHP_INI_END()
1516
1517 /* {{{ php_cgi_globals_ctor */
1518 static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals)
1519 {
1520 #if defined(ZTS) && defined(PHP_WIN32)
1521 ZEND_TSRMLS_CACHE_UPDATE();
1522 #endif
1523 php_cgi_globals->rfc2616_headers = 0;
1524 php_cgi_globals->nph = 0;
1525 php_cgi_globals->check_shebang_line = 1;
1526 php_cgi_globals->force_redirect = 1;
1527 php_cgi_globals->redirect_status_env = NULL;
1528 php_cgi_globals->fix_pathinfo = 1;
1529 php_cgi_globals->discard_path = 0;
1530 php_cgi_globals->fcgi_logging = 1;
1531 #ifdef PHP_WIN32
1532 php_cgi_globals->impersonate = 0;
1533 #endif
1534 zend_hash_init(&php_cgi_globals->user_config_cache, 8, NULL, user_config_cache_entry_dtor, 1);
1535 }
1536 /* }}} */
1537
1538 /* {{{ PHP_MINIT_FUNCTION */
1539 static PHP_MINIT_FUNCTION(cgi)
1540 {
1541 REGISTER_INI_ENTRIES();
1542 return SUCCESS;
1543 }
1544 /* }}} */
1545
1546 /* {{{ PHP_MSHUTDOWN_FUNCTION */
1547 static PHP_MSHUTDOWN_FUNCTION(cgi)
1548 {
1549 zend_hash_destroy(&CGIG(user_config_cache));
1550
1551 UNREGISTER_INI_ENTRIES();
1552 return SUCCESS;
1553 }
1554 /* }}} */
1555
1556 /* {{{ PHP_MINFO_FUNCTION */
1557 static PHP_MINFO_FUNCTION(cgi)
1558 {
1559 DISPLAY_INI_ENTRIES();
1560 }
1561 /* }}} */
1562
1563 PHP_FUNCTION(apache_child_terminate) /* {{{ */
1564 {
1565 if (zend_parse_parameters_none()) {
1566 RETURN_THROWS();
1567 }
1568 if (fcgi_is_fastcgi()) {
1569 fcgi_terminate();
1570 }
1571 }
1572 /* }}} */
1573
1574
1575 PHP_FUNCTION(apache_request_headers) /* {{{ */
1576 {
1577 if (zend_parse_parameters_none()) {
1578 RETURN_THROWS();
1579 }
1580 array_init(return_value);
1581 if (fcgi_is_fastcgi()) {
1582 fcgi_request *request = (fcgi_request*) SG(server_context);
1583
1584 fcgi_loadenv(request, sapi_add_request_header, return_value);
1585 } else {
1586 char buf[128];
1587 char **env, *p, *q, *var, *val, *t = buf;
1588 size_t alloc_size = sizeof(buf);
1589 zend_ulong var_len;
1590
1591 for (env = environ; env != NULL && *env != NULL; env++) {
1592 val = strchr(*env, '=');
1593 if (!val) { /* malformed entry? */
1594 continue;
1595 }
1596 var_len = val - *env;
1597 if (var_len >= alloc_size) {
1598 alloc_size = var_len + 64;
1599 t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1600 }
1601 var = *env;
1602 if (var_len > 5 &&
1603 var[0] == 'H' &&
1604 var[1] == 'T' &&
1605 var[2] == 'T' &&
1606 var[3] == 'P' &&
1607 var[4] == '_') {
1608
1609 var_len -= 5;
1610
1611 if (var_len >= alloc_size) {
1612 alloc_size = var_len + 64;
1613 t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1614 }
1615 p = var + 5;
1616
1617 var = q = t;
1618 /* First char keep uppercase */
1619 *q++ = *p++;
1620 while (*p) {
1621 if (*p == '=') {
1622 /* End of name */
1623 break;
1624 } else if (*p == '_') {
1625 *q++ = '-';
1626 p++;
1627 /* First char after - keep uppercase */
1628 if (*p && *p!='=') {
1629 *q++ = *p++;
1630 }
1631 } else if (*p >= 'A' && *p <= 'Z') {
1632 /* lowercase */
1633 *q++ = (*p++ - 'A' + 'a');
1634 } else {
1635 *q++ = *p++;
1636 }
1637 }
1638 *q = 0;
1639 } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1640 memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1641 var = "Content-Type";
1642 } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1643 memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1644 var = "Content-Length";
1645 } else {
1646 continue;
1647 }
1648 val++;
1649 add_assoc_string_ex(return_value, var, var_len, val);
1650 }
1651 if (t != buf && t != NULL) {
1652 efree(t);
1653 }
1654 }
1655 }
1656 /* }}} */
1657
1658 static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
1659 {
1660 if (h->header_len > 0) {
1661 char *s;
1662 size_t len = 0;
1663 ALLOCA_FLAG(use_heap)
1664
1665 char *p = strchr(h->header, ':');
1666 if (NULL != p) {
1667 len = p - h->header;
1668 }
1669 if (len > 0) {
1670 while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
1671 len--;
1672 }
1673 if (len) {
1674 s = do_alloca(len + 1, use_heap);
1675 memcpy(s, h->header, len);
1676 s[len] = 0;
1677 do {
1678 p++;
1679 } while (*p == ' ' || *p == '\t');
1680 add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
1681 free_alloca(s, use_heap);
1682 }
1683 }
1684 }
1685 }
1686 /* }}} */
1687
1688 PHP_FUNCTION(apache_response_headers) /* {{{ */
1689 {
1690 if (zend_parse_parameters_none() == FAILURE) {
1691 RETURN_THROWS();
1692 }
1693
1694 array_init(return_value);
1695 zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
1696 }
1697 /* }}} */
1698
1699 static zend_module_entry cgi_module_entry = {
1700 STANDARD_MODULE_HEADER,
1701 "cgi-fcgi",
1702 ext_functions,
1703 PHP_MINIT(cgi),
1704 PHP_MSHUTDOWN(cgi),
1705 NULL,
1706 NULL,
1707 PHP_MINFO(cgi),
1708 PHP_VERSION,
1709 STANDARD_MODULE_PROPERTIES
1710 };
1711
1712 /* {{{ main */
1713 int main(int argc, char *argv[])
1714 {
1715 int free_query_string = 0;
1716 int exit_status = SUCCESS;
1717 int cgi = 0, c, i;
1718 size_t len;
1719 zend_file_handle file_handle;
1720 char *s;
1721
1722 /* temporary locals */
1723 int behavior = PHP_MODE_STANDARD;
1724 int no_headers = 0;
1725 int orig_optind = php_optind;
1726 char *orig_optarg = php_optarg;
1727 char *script_file = NULL;
1728 struct php_ini_builder ini_builder;
1729 /* end of temporary locals */
1730
1731 int max_requests = 500;
1732 int requests = 0;
1733 int fastcgi;
1734 char *bindpath = NULL;
1735 int fcgi_fd = 0;
1736 fcgi_request *request = NULL;
1737 int warmup_repeats = 0;
1738 int repeats = 1;
1739 int benchmark = 0;
1740 #if HAVE_GETTIMEOFDAY
1741 struct timeval start, end;
1742 #else
1743 time_t start, end;
1744 #endif
1745 #ifndef PHP_WIN32
1746 int status = 0;
1747 #endif
1748 char *query_string;
1749 int skip_getopt = 0;
1750
1751 #if defined(SIGPIPE) && defined(SIG_IGN)
1752 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1753 that sockets created via fsockopen()
1754 don't kill PHP if the remote site
1755 closes it. in apache|apxs mode apache
1756 does that for us! thies@thieso.net
1757 20000419 */
1758 #endif
1759
1760 #ifdef ZTS
1761 php_tsrm_startup();
1762 # ifdef PHP_WIN32
1763 ZEND_TSRMLS_CACHE_UPDATE();
1764 # endif
1765 #endif
1766
1767 zend_signal_startup();
1768
1769 #ifdef ZTS
1770 ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1771 #else
1772 php_cgi_globals_ctor(&php_cgi_globals);
1773 #endif
1774
1775 sapi_startup(&cgi_sapi_module);
1776 fastcgi = fcgi_is_fastcgi();
1777 cgi_sapi_module.php_ini_path_override = NULL;
1778
1779 #ifdef PHP_WIN32
1780 _fmode = _O_BINARY; /* sets default for file streams to binary */
1781 setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
1782 setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
1783 setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
1784 #endif
1785
1786 if (!fastcgi) {
1787 /* Make sure we detect we are a cgi - a bit redundancy here,
1788 * but the default case is that we have to check only the first one. */
1789 if (getenv("SERVER_SOFTWARE") ||
1790 getenv("SERVER_NAME") ||
1791 getenv("GATEWAY_INTERFACE") ||
1792 getenv("REQUEST_METHOD")
1793 ) {
1794 cgi = 1;
1795 }
1796 }
1797
1798 /* Apache CGI will pass the query string to the command line if it doesn't contain a '='.
1799 * This can create an issue where a malicious request can pass command line arguments to
1800 * the executable. Ideally we skip argument parsing when we're in cgi or fastcgi mode,
1801 * but that breaks PHP scripts on Linux with a hashbang: `#!/php-cgi -d option=value`.
1802 * Therefore, this code only prevents passing arguments if the query string starts with a '-'.
1803 * Similarly, scripts spawned in subprocesses on Windows may have the same issue.
1804 * However, Windows has lots of conversion rules and command line parsing rules that
1805 * are too difficult and dangerous to reliably emulate. */
1806 if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
1807 #ifdef PHP_WIN32
1808 skip_getopt = cgi || fastcgi;
1809 #else
1810 unsigned char *p;
1811 char *decoded_query_string = strdup(query_string);
1812 php_url_decode(decoded_query_string, strlen(decoded_query_string));
1813 for (p = (unsigned char *)decoded_query_string; *p && *p <= ' '; p++) {
1814 /* skip all leading spaces */
1815 }
1816 if(*p == '-') {
1817 skip_getopt = 1;
1818 }
1819
1820 free(decoded_query_string);
1821 #endif
1822 }
1823
1824 php_ini_builder_init(&ini_builder);
1825
1826 while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1827 switch (c) {
1828 case 'c':
1829 if (cgi_sapi_module.php_ini_path_override) {
1830 free(cgi_sapi_module.php_ini_path_override);
1831 }
1832 cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1833 break;
1834 case 'n':
1835 cgi_sapi_module.php_ini_ignore = 1;
1836 break;
1837 case 'd':
1838 /* define ini entries on command line */
1839 php_ini_builder_define(&ini_builder, php_optarg);
1840 break;
1841 /* if we're started on command line, check to see if
1842 * we are being started as an 'external' fastcgi
1843 * server by accepting a bindpath parameter. */
1844 case 'b':
1845 if (!fastcgi) {
1846 bindpath = strdup(php_optarg);
1847 }
1848 break;
1849 case 's': /* generate highlighted HTML from source */
1850 behavior = PHP_MODE_HIGHLIGHT;
1851 break;
1852 }
1853 }
1854 php_optind = orig_optind;
1855 php_optarg = orig_optarg;
1856
1857 cgi_sapi_module.ini_entries = php_ini_builder_finish(&ini_builder);
1858
1859 if (fastcgi || bindpath) {
1860 /* Override SAPI callbacks */
1861 cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
1862 cgi_sapi_module.flush = sapi_fcgi_flush;
1863 cgi_sapi_module.read_post = sapi_fcgi_read_post;
1864 cgi_sapi_module.getenv = sapi_fcgi_getenv;
1865 cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
1866 }
1867
1868 #ifdef ZTS
1869 SG(request_info).path_translated = NULL;
1870 #endif
1871
1872 cgi_sapi_module.executable_location = argv[0];
1873 if (!cgi && !fastcgi && !bindpath) {
1874 cgi_sapi_module.additional_functions = additional_functions;
1875 }
1876
1877 /* startup after we get the above ini override se we get things right */
1878 if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1879 #ifdef ZTS
1880 tsrm_shutdown();
1881 #endif
1882 free(bindpath);
1883 return FAILURE;
1884 }
1885
1886 /* check force_cgi after startup, so we have proper output */
1887 if (cgi && CGIG(force_redirect)) {
1888 /* This is to allow a different environment variable to be configured
1889 * in case the we cannot auto-detect which environment variable to use.
1890 * Checking this first to allow user overrides in case the environment
1891 * variable can be set by an untrusted party. */
1892 const char *redirect_status_env = CGIG(redirect_status_env);
1893 if (!redirect_status_env) {
1894 /* Apache will generate REDIRECT_STATUS. */
1895 redirect_status_env = "REDIRECT_STATUS";
1896 }
1897
1898 if (!getenv(redirect_status_env)) {
1899 zend_try {
1900 SG(sapi_headers).http_response_code = 400;
1901 PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1902 <p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
1903 means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1904 set, e.g. via an Apache Action directive.</p>\n\
1905 <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1906 manual page for CGI security</a>.</p>\n\
1907 <p>For more information about changing this behaviour or re-enabling this webserver,\n\
1908 consult the installation file that came with this distribution, or visit \n\
1909 <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1910 } zend_catch {
1911 } zend_end_try();
1912 #if defined(ZTS) && !defined(PHP_DEBUG)
1913 /* XXX we're crashing here in msvc6 debug builds at
1914 * php_message_handler_for_zend:839 because
1915 * SG(request_info).path_translated is an invalid pointer.
1916 * It still happens even though I set it to null, so something
1917 * weird is going on.
1918 */
1919 tsrm_shutdown();
1920 #endif
1921 free(bindpath);
1922 return FAILURE;
1923 }
1924 }
1925
1926 #ifndef HAVE_ATTRIBUTE_WEAK
1927 fcgi_set_logger(fcgi_log);
1928 #endif
1929
1930 if (bindpath) {
1931 int backlog = 128;
1932 if (getenv("PHP_FCGI_BACKLOG")) {
1933 backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
1934 }
1935 fcgi_fd = fcgi_listen(bindpath, backlog);
1936 if (fcgi_fd < 0) {
1937 fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
1938 #ifdef ZTS
1939 tsrm_shutdown();
1940 #endif
1941 return FAILURE;
1942 }
1943 fastcgi = fcgi_is_fastcgi();
1944 }
1945
1946 /* make php call us to get _ENV vars */
1947 php_php_import_environment_variables = php_import_environment_variables;
1948 php_import_environment_variables = cgi_php_import_environment_variables;
1949
1950 if (fastcgi) {
1951 /* How many times to run PHP scripts before dying */
1952 if (getenv("PHP_FCGI_MAX_REQUESTS")) {
1953 max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
1954 if (max_requests < 0) {
1955 fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
1956 return FAILURE;
1957 }
1958 }
1959
1960 /* library is already initialized, now init our request */
1961 request = fcgi_init_request(fcgi_fd, NULL, NULL, NULL);
1962
1963 /* Pre-fork or spawn, if required */
1964 if (getenv("PHP_FCGI_CHILDREN")) {
1965 char * children_str = getenv("PHP_FCGI_CHILDREN");
1966 children = atoi(children_str);
1967 if (children < 0) {
1968 fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
1969 return FAILURE;
1970 }
1971 fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
1972 /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
1973 fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
1974 } else {
1975 #ifdef PHP_WIN32
1976 /* If this env var is set, the process was invoked as a child. Let
1977 it show the original PHP_FCGI_CHILDREN value, while don't care
1978 otherwise. */
1979 char * children_str = getenv("PHP_FCGI_CHILDREN_FOR_KID");
1980 if (children_str) {
1981 char putenv_buf[sizeof("PHP_FCGI_CHILDREN")+5];
1982
1983 snprintf(putenv_buf, sizeof(putenv_buf), "%s=%s", "PHP_FCGI_CHILDREN", children_str);
1984 putenv(putenv_buf);
1985 putenv("PHP_FCGI_CHILDREN_FOR_KID=");
1986
1987 SetEnvironmentVariable("PHP_FCGI_CHILDREN", children_str);
1988 SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", NULL);
1989 }
1990 #endif
1991 fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
1992 fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
1993 }
1994
1995 #ifndef PHP_WIN32
1996 if (children) {
1997 int running = 0;
1998 pid_t pid;
1999
2000 /* Create a process group for us & children */
2001 setsid();
2002 pgroup = getpgrp();
2003 #ifdef DEBUG_FASTCGI
2004 fprintf(stderr, "Process group %d\n", pgroup);
2005 #endif
2006
2007 /* Set up handler to kill children upon exit */
2008 act.sa_flags = 0;
2009 act.sa_handler = fastcgi_cleanup;
2010 if (sigaction(SIGTERM, &act, &old_term) ||
2011 sigaction(SIGINT, &act, &old_int) ||
2012 sigaction(SIGQUIT, &act, &old_quit)
2013 ) {
2014 perror("Can't set signals");
2015 exit(1);
2016 }
2017
2018 if (fcgi_in_shutdown()) {
2019 goto parent_out;
2020 }
2021
2022 while (parent) {
2023 do {
2024 #ifdef DEBUG_FASTCGI
2025 fprintf(stderr, "Forking, %d running\n", running);
2026 #endif
2027 pid = fork();
2028 switch (pid) {
2029 case 0:
2030 /* One of the children.
2031 * Make sure we don't go round the
2032 * fork loop any more
2033 */
2034 parent = 0;
2035
2036 /* don't catch our signals */
2037 sigaction(SIGTERM, &old_term, 0);
2038 sigaction(SIGQUIT, &old_quit, 0);
2039 sigaction(SIGINT, &old_int, 0);
2040 zend_signal_init();
2041 break;
2042 case -1:
2043 perror("php (pre-forking)");
2044 exit(1);
2045 break;
2046 default:
2047 /* Fine */
2048 running++;
2049 break;
2050 }
2051 } while (parent && (running < children));
2052
2053 if (parent) {
2054 #ifdef DEBUG_FASTCGI
2055 fprintf(stderr, "Wait for kids, pid %d\n", getpid());
2056 #endif
2057 parent_waiting = 1;
2058 while (1) {
2059 if (wait(&status) >= 0) {
2060 running--;
2061 break;
2062 } else if (exit_signal) {
2063 break;
2064 }
2065 }
2066 if (exit_signal) {
2067 #if 0
2068 while (running > 0) {
2069 while (wait(&status) < 0) {
2070 }
2071 running--;
2072 }
2073 #endif
2074 goto parent_out;
2075 }
2076 }
2077 }
2078 } else {
2079 parent = 0;
2080 zend_signal_init();
2081 }
2082
2083 #else
2084 if (children) {
2085 wchar_t *cmd_line_tmp, cmd_line[PHP_WIN32_IOUTIL_MAXPATHLEN];
2086 size_t cmd_line_len;
2087 char kid_buf[16];
2088 int i;
2089
2090 ZeroMemory(&kid_cgi_ps, sizeof(kid_cgi_ps));
2091 kids = children < WIN32_MAX_SPAWN_CHILDREN ? children : WIN32_MAX_SPAWN_CHILDREN;
2092
2093 InitializeCriticalSection(&cleanup_lock);
2094 SetConsoleCtrlHandler(fastcgi_cleanup, TRUE);
2095
2096 /* kids will inherit the env, don't let them spawn */
2097 SetEnvironmentVariable("PHP_FCGI_CHILDREN", NULL);
2098 /* instead, set a temporary env var, so then the child can read and
2099 show the actual setting correctly. */
2100 snprintf(kid_buf, 16, "%d", children);
2101 SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", kid_buf);
2102
2103 /* The current command line is used as is. This should normally be no issue,
2104 even if there were some I/O redirection. If some issues turn out, an
2105 extra parsing might be needed here. */
2106 cmd_line_tmp = GetCommandLineW();
2107 if (!cmd_line_tmp) {
2108 DWORD err = GetLastError();
2109 char *err_text = php_win32_error_to_msg(err);
2110
2111 fprintf(stderr, "unable to get current command line: [0x%08lx]: %s\n", err, err_text);
2112 php_win32_error_msg_free(err_text);
2113
2114 goto parent_out;
2115 }
2116
2117 cmd_line_len = wcslen(cmd_line_tmp);
2118 if (cmd_line_len > sizeof(cmd_line) - 1) {
2119 fprintf(stderr, "command line is too long\n");
2120 goto parent_out;
2121 }
2122 memmove(cmd_line, cmd_line_tmp, (cmd_line_len + 1)*sizeof(wchar_t));
2123
2124 job = CreateJobObject(NULL, NULL);
2125 if (!job) {
2126 DWORD err = GetLastError();
2127 char *err_text = php_win32_error_to_msg(err);
2128
2129 fprintf(stderr, "unable to create job object: [0x%08lx]: %s\n", err, err_text);
2130
2131 php_win32_error_msg_free(err_text);
2132
2133 goto parent_out;
2134 }
2135
2136 job_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
2137 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &job_info, sizeof(job_info))) {
2138 DWORD err = GetLastError();
2139 char *err_text = php_win32_error_to_msg(err);
2140
2141 fprintf(stderr, "unable to configure job object: [0x%08lx]: %s\n", err, err_text);
2142 php_win32_error_msg_free(err_text);
2143 }
2144
2145 while (parent) {
2146 EnterCriticalSection(&cleanup_lock);
2147 if (cleaning_up) {
2148 goto parent_loop_end;
2149 }
2150 LeaveCriticalSection(&cleanup_lock);
2151
2152 i = kids;
2153 while (0 < i--) {
2154 DWORD status;
2155
2156 if (NULL != kid_cgi_ps[i]) {
2157 if(!GetExitCodeProcess(kid_cgi_ps[i], &status) || status != STILL_ACTIVE) {
2158 CloseHandle(kid_cgi_ps[i]);
2159 kid_cgi_ps[i] = NULL;
2160 }
2161 }
2162 }
2163
2164 i = kids;
2165 while (0 < i--) {
2166 PROCESS_INFORMATION pi;
2167 STARTUPINFOW si;
2168
2169 if (NULL != kid_cgi_ps[i]) {
2170 continue;
2171 }
2172
2173 ZeroMemory(&si, sizeof(si));
2174 si.cb = sizeof(si);
2175 ZeroMemory(&pi, sizeof(pi));
2176
2177 si.dwFlags = STARTF_USESTDHANDLES;
2178 si.hStdOutput = INVALID_HANDLE_VALUE;
2179 si.hStdInput = (HANDLE)_get_osfhandle(fcgi_fd);
2180 si.hStdError = INVALID_HANDLE_VALUE;
2181
2182 if (CreateProcessW(NULL, cmd_line, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
2183 kid_cgi_ps[i] = pi.hProcess;
2184 if (!AssignProcessToJobObject(job, pi.hProcess)) {
2185 DWORD err = GetLastError();
2186 char *err_text = php_win32_error_to_msg(err);
2187
2188 fprintf(stderr, "unable to assign child process to job object: [0x%08lx]: %s\n", err, err_text);
2189 php_win32_error_msg_free(err_text);
2190 }
2191 CloseHandle(pi.hThread);
2192 } else {
2193 DWORD err = GetLastError();
2194 char *err_text = php_win32_error_to_msg(err);
2195
2196 kid_cgi_ps[i] = NULL;
2197
2198 fprintf(stderr, "unable to spawn: [0x%08lx]: %s\n", err, err_text);
2199 php_win32_error_msg_free(err_text);
2200 }
2201 }
2202
2203 WaitForMultipleObjects(kids, kid_cgi_ps, FALSE, INFINITE);
2204 }
2205
2206 parent_loop_end:
2207 /* restore my env */
2208 SetEnvironmentVariable("PHP_FCGI_CHILDREN", kid_buf);
2209
2210 DeleteCriticalSection(&cleanup_lock);
2211
2212 goto parent_out;
2213 } else {
2214 parent = 0;
2215 }
2216 #endif /* WIN32 */
2217 }
2218
2219 zend_first_try {
2220 while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
2221 switch (c) {
2222 case 'T':
2223 benchmark = 1;
2224 {
2225 char *comma = strchr(php_optarg, ',');
2226 if (comma) {
2227 warmup_repeats = atoi(php_optarg);
2228 repeats = atoi(comma + 1);
2229 #ifdef HAVE_VALGRIND
2230 if (warmup_repeats > 0) {
2231 CALLGRIND_STOP_INSTRUMENTATION;
2232 /* We're not interested in measuring startup */
2233 CALLGRIND_ZERO_STATS;
2234 }
2235 #endif
2236 } else {
2237 repeats = atoi(php_optarg);
2238 }
2239 }
2240 #ifdef HAVE_GETTIMEOFDAY
2241 gettimeofday(&start, NULL);
2242 #else
2243 time(&start);
2244 #endif
2245 break;
2246 case 'h':
2247 case '?':
2248 case PHP_GETOPT_INVALID_ARG:
2249 if (request) {
2250 fcgi_destroy_request(request);
2251 }
2252 fcgi_shutdown();
2253 no_headers = 1;
2254 SG(headers_sent) = 1;
2255 php_cgi_usage(argv[0]);
2256 php_output_end_all();
2257 exit_status = 0;
2258 if (c == PHP_GETOPT_INVALID_ARG) {
2259 exit_status = 1;
2260 }
2261 goto out;
2262 }
2263 }
2264 php_optind = orig_optind;
2265 php_optarg = orig_optarg;
2266
2267 /* start of FAST CGI loop */
2268 /* Initialise FastCGI request structure */
2269 #ifdef PHP_WIN32
2270 /* attempt to set security impersonation for fastcgi
2271 * will only happen on NT based OS, others will ignore it. */
2272 if (fastcgi && CGIG(impersonate)) {
2273 fcgi_impersonate();
2274 }
2275 #endif
2276 while (!fastcgi || fcgi_accept_request(request) >= 0) {
2277 SG(server_context) = fastcgi ? (void *)request : (void *) 1;
2278 init_request_info(request);
2279
2280 if (!cgi && !fastcgi) {
2281 while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
2282 switch (c) {
2283
2284 case 'a': /* interactive mode */
2285 printf("Interactive mode enabled\n\n");
2286 fflush(stdout);
2287 break;
2288
2289 case 'C': /* don't chdir to the script directory */
2290 SG(options) |= SAPI_OPTION_NO_CHDIR;
2291 break;
2292
2293 case 'e': /* enable extended info output */
2294 CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
2295 break;
2296
2297 case 'f': /* parse file */
2298 if (script_file) {
2299 efree(script_file);
2300 }
2301 script_file = estrdup(php_optarg);
2302 no_headers = 1;
2303 break;
2304
2305 case 'i': /* php info & quit */
2306 if (script_file) {
2307 efree(script_file);
2308 }
2309 if (php_request_startup() == FAILURE) {
2310 SG(server_context) = NULL;
2311 php_module_shutdown();
2312 free(bindpath);
2313 return FAILURE;
2314 }
2315 if (no_headers) {
2316 SG(headers_sent) = 1;
2317 SG(request_info).no_headers = 1;
2318 }
2319 php_print_info(0xFFFFFFFF);
2320 php_request_shutdown((void *) 0);
2321 fcgi_shutdown();
2322 exit_status = 0;
2323 goto out;
2324
2325 case 'l': /* syntax check mode */
2326 no_headers = 1;
2327 behavior = PHP_MODE_LINT;
2328 break;
2329
2330 case 'm': /* list compiled in modules */
2331 if (script_file) {
2332 efree(script_file);
2333 }
2334 SG(headers_sent) = 1;
2335 php_printf("[PHP Modules]\n");
2336 print_modules();
2337 php_printf("\n[Zend Modules]\n");
2338 print_extensions();
2339 php_printf("\n");
2340 php_output_end_all();
2341 fcgi_shutdown();
2342 exit_status = 0;
2343 goto out;
2344
2345 case 'q': /* do not generate HTTP headers */
2346 no_headers = 1;
2347 break;
2348
2349 case 'v': /* show php version & quit */
2350 if (script_file) {
2351 efree(script_file);
2352 }
2353 no_headers = 1;
2354 if (php_request_startup() == FAILURE) {
2355 SG(server_context) = NULL;
2356 php_module_shutdown();
2357 free(bindpath);
2358 return FAILURE;
2359 }
2360 SG(headers_sent) = 1;
2361 SG(request_info).no_headers = 1;
2362 #if ZEND_DEBUG
2363 php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
2364 #else
2365 php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
2366 #endif
2367 php_request_shutdown((void *) 0);
2368 fcgi_shutdown();
2369 exit_status = 0;
2370 goto out;
2371
2372 case 'w':
2373 behavior = PHP_MODE_STRIP;
2374 break;
2375
2376 case 'z': /* load extension file */
2377 zend_load_extension(php_optarg);
2378 break;
2379
2380 default:
2381 break;
2382 }
2383 }
2384
2385 do_repeat:
2386 if (script_file) {
2387 /* override path_translated if -f on command line */
2388 if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2389 SG(request_info).path_translated = script_file;
2390 /* before registering argv to module exchange the *new* argv[0] */
2391 /* we can achieve this without allocating more memory */
2392 SG(request_info).argc = argc - (php_optind - 1);
2393 SG(request_info).argv = &argv[php_optind - 1];
2394 SG(request_info).argv[0] = script_file;
2395 } else if (argc > php_optind) {
2396 /* file is on command line, but not in -f opt */
2397 if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2398 SG(request_info).path_translated = estrdup(argv[php_optind]);
2399 /* arguments after the file are considered script args */
2400 SG(request_info).argc = argc - php_optind;
2401 SG(request_info).argv = &argv[php_optind];
2402 }
2403
2404 if (no_headers) {
2405 SG(headers_sent) = 1;
2406 SG(request_info).no_headers = 1;
2407 }
2408
2409 /* all remaining arguments are part of the query string
2410 * this section of code concatenates all remaining arguments
2411 * into a single string, separating args with a &
2412 * this allows command lines like:
2413 *
2414 * test.php v1=test v2=hello+world!
2415 * test.php "v1=test&v2=hello world!"
2416 * test.php v1=test "v2=hello world!"
2417 */
2418 if (!SG(request_info).query_string && argc > php_optind) {
2419 size_t slen = strlen(PG(arg_separator).input);
2420 len = 0;
2421 for (i = php_optind; i < argc; i++) {
2422 if (i < (argc - 1)) {
2423 len += strlen(argv[i]) + slen;
2424 } else {
2425 len += strlen(argv[i]);
2426 }
2427 }
2428
2429 len += 2;
2430 s = malloc(len);
2431 *s = '\0'; /* we are pretending it came from the environment */
2432 for (i = php_optind; i < argc; i++) {
2433 strlcat(s, argv[i], len);
2434 if (i < (argc - 1)) {
2435 strlcat(s, PG(arg_separator).input, len);
2436 }
2437 }
2438 SG(request_info).query_string = s;
2439 free_query_string = 1;
2440 }
2441 } /* end !cgi && !fastcgi */
2442
2443 #ifdef HAVE_VALGRIND
2444 if (warmup_repeats == 0) {
2445 CALLGRIND_START_INSTRUMENTATION;
2446 }
2447 #endif
2448
2449 /* request startup only after we've done all we can to
2450 * get path_translated */
2451 if (php_request_startup() == FAILURE) {
2452 if (fastcgi) {
2453 fcgi_finish_request(request, 1);
2454 }
2455 SG(server_context) = NULL;
2456 php_module_shutdown();
2457 return FAILURE;
2458 }
2459 if (no_headers) {
2460 SG(headers_sent) = 1;
2461 SG(request_info).no_headers = 1;
2462 }
2463
2464 /*
2465 at this point path_translated will be set if:
2466 1. we are running from shell and got filename was there
2467 2. we are running as cgi or fastcgi
2468 */
2469 if (cgi || fastcgi || SG(request_info).path_translated) {
2470 if (php_fopen_primary_script(&file_handle) == FAILURE) {
2471 zend_try {
2472 if (errno == EACCES) {
2473 SG(sapi_headers).http_response_code = 403;
2474 PUTS("Access denied.\n");
2475 } else {
2476 SG(sapi_headers).http_response_code = 404;
2477 PUTS("No input file specified.\n");
2478 }
2479 } zend_catch {
2480 } zend_end_try();
2481 /* we want to serve more requests if this is fastcgi
2482 * so cleanup and continue, request shutdown is
2483 * handled later */
2484 if (fastcgi) {
2485 goto fastcgi_request_done;
2486 }
2487
2488 if (SG(request_info).path_translated) {
2489 efree(SG(request_info).path_translated);
2490 SG(request_info).path_translated = NULL;
2491 }
2492
2493 if (free_query_string && SG(request_info).query_string) {
2494 free(SG(request_info).query_string);
2495 SG(request_info).query_string = NULL;
2496 }
2497
2498 php_request_shutdown((void *) 0);
2499 SG(server_context) = NULL;
2500 php_module_shutdown();
2501 sapi_shutdown();
2502 #ifdef ZTS
2503 tsrm_shutdown();
2504 #endif
2505 free(bindpath);
2506 return FAILURE;
2507 }
2508 } else {
2509 /* we never take stdin if we're (f)cgi */
2510 zend_stream_init_fp(&file_handle, stdin, "Standard input code");
2511 file_handle.primary_script = 1;
2512 }
2513
2514 if (CGIG(check_shebang_line)) {
2515 CG(skip_shebang) = 1;
2516 }
2517
2518 switch (behavior) {
2519 case PHP_MODE_STANDARD:
2520 php_execute_script(&file_handle);
2521 break;
2522 case PHP_MODE_LINT:
2523 PG(during_request_startup) = 0;
2524 if (php_lint_script(&file_handle) == SUCCESS) {
2525 zend_printf("No syntax errors detected in %s\n", ZSTR_VAL(file_handle.filename));
2526 } else {
2527 zend_printf("Errors parsing %s\n", ZSTR_VAL(file_handle.filename));
2528 exit_status = -1;
2529 }
2530 break;
2531 case PHP_MODE_STRIP:
2532 if (open_file_for_scanning(&file_handle) == SUCCESS) {
2533 zend_strip();
2534 }
2535 break;
2536 case PHP_MODE_HIGHLIGHT:
2537 {
2538 zend_syntax_highlighter_ini syntax_highlighter_ini;
2539
2540 if (open_file_for_scanning(&file_handle) == SUCCESS) {
2541 php_get_highlight_struct(&syntax_highlighter_ini);
2542 zend_highlight(&syntax_highlighter_ini);
2543 }
2544 }
2545 break;
2546 }
2547
2548 fastcgi_request_done:
2549 zend_destroy_file_handle(&file_handle);
2550
2551 if (SG(request_info).path_translated) {
2552 efree(SG(request_info).path_translated);
2553 SG(request_info).path_translated = NULL;
2554 }
2555
2556 php_request_shutdown((void *) 0);
2557
2558 if (exit_status == 0) {
2559 exit_status = EG(exit_status);
2560 }
2561
2562 if (free_query_string && SG(request_info).query_string) {
2563 free(SG(request_info).query_string);
2564 SG(request_info).query_string = NULL;
2565 }
2566
2567 #ifdef HAVE_VALGRIND
2568 /* We're not interested in measuring shutdown */
2569 CALLGRIND_STOP_INSTRUMENTATION;
2570 #endif
2571
2572 if (!fastcgi) {
2573 if (benchmark) {
2574 if (warmup_repeats) {
2575 warmup_repeats--;
2576 if (!warmup_repeats) {
2577 #ifdef HAVE_GETTIMEOFDAY
2578 gettimeofday(&start, NULL);
2579 #else
2580 time(&start);
2581 #endif
2582 }
2583 continue;
2584 } else {
2585 repeats--;
2586 if (repeats > 0) {
2587 script_file = NULL;
2588 php_optind = orig_optind;
2589 php_optarg = orig_optarg;
2590 continue;
2591 }
2592 }
2593 }
2594 if (behavior == PHP_MODE_LINT && argc - 1 > php_optind) {
2595 php_optind++;
2596 script_file = NULL;
2597 goto do_repeat;
2598 }
2599 break;
2600 }
2601
2602 /* only fastcgi will get here */
2603 requests++;
2604 if (max_requests && (requests == max_requests)) {
2605 fcgi_finish_request(request, 1);
2606 free(bindpath);
2607 if (max_requests != 1) {
2608 /* no need to return exit_status of the last request */
2609 exit_status = 0;
2610 }
2611 break;
2612 }
2613 /* end of fastcgi loop */
2614 }
2615
2616 if (request) {
2617 fcgi_destroy_request(request);
2618 }
2619 fcgi_shutdown();
2620
2621 if (cgi_sapi_module.php_ini_path_override) {
2622 free(cgi_sapi_module.php_ini_path_override);
2623 }
2624 php_ini_builder_deinit(&ini_builder);
2625 } zend_catch {
2626 exit_status = 255;
2627 } zend_end_try();
2628
2629 out:
2630 if (benchmark) {
2631 int sec;
2632 #ifdef HAVE_GETTIMEOFDAY
2633 int usec;
2634
2635 gettimeofday(&end, NULL);
2636 sec = (int)(end.tv_sec - start.tv_sec);
2637 if (end.tv_usec >= start.tv_usec) {
2638 usec = (int)(end.tv_usec - start.tv_usec);
2639 } else {
2640 sec -= 1;
2641 usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2642 }
2643 fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2644 #else
2645 time(&end);
2646 sec = (int)(end - start);
2647 fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2648 #endif
2649 }
2650
2651 parent_out:
2652
2653 SG(server_context) = NULL;
2654 php_module_shutdown();
2655 sapi_shutdown();
2656
2657 #ifdef ZTS
2658 tsrm_shutdown();
2659 #endif
2660
2661 #if defined(PHP_WIN32) && ZEND_DEBUG && 0
2662 _CrtDumpMemoryLeaks();
2663 #endif
2664
2665 return exit_status;
2666 }
2667 /* }}} */
2668