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 static 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 volatile sig_atomic_t 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 (!parent && request) {
359 sapi_send_headers();
360 if (!fcgi_flush(request, 0)) {
361 php_handle_aborted_connection();
362 }
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 > UINT_MAX) ? UINT_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 static 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 char *decoded_query_string;
1750 int skip_getopt = 0;
1751
1752 #if defined(SIGPIPE) && defined(SIG_IGN)
1753 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1754 that sockets created via fsockopen()
1755 don't kill PHP if the remote site
1756 closes it. in apache|apxs mode apache
1757 does that for us! thies@thieso.net
1758 20000419 */
1759 #endif
1760
1761 #ifdef ZTS
1762 php_tsrm_startup();
1763 # ifdef PHP_WIN32
1764 ZEND_TSRMLS_CACHE_UPDATE();
1765 # endif
1766 #endif
1767
1768 zend_signal_startup();
1769
1770 #ifdef ZTS
1771 ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1772 #else
1773 php_cgi_globals_ctor(&php_cgi_globals);
1774 #endif
1775
1776 sapi_startup(&cgi_sapi_module);
1777 fastcgi = fcgi_is_fastcgi();
1778 cgi_sapi_module.php_ini_path_override = NULL;
1779
1780 #ifdef PHP_WIN32
1781 _fmode = _O_BINARY; /* sets default for file streams to binary */
1782 setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
1783 setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
1784 setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
1785 #endif
1786
1787 if (!fastcgi) {
1788 /* Make sure we detect we are a cgi - a bit redundancy here,
1789 * but the default case is that we have to check only the first one. */
1790 if (getenv("SERVER_SOFTWARE") ||
1791 getenv("SERVER_NAME") ||
1792 getenv("GATEWAY_INTERFACE") ||
1793 getenv("REQUEST_METHOD")
1794 ) {
1795 cgi = 1;
1796 }
1797 }
1798
1799 if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
1800 /* we've got query string that has no = - apache CGI will pass it to command line */
1801 unsigned char *p;
1802 decoded_query_string = strdup(query_string);
1803 php_url_decode(decoded_query_string, strlen(decoded_query_string));
1804 for (p = (unsigned char *)decoded_query_string; *p && *p <= ' '; p++) {
1805 /* skip all leading spaces */
1806 }
1807 if(*p == '-') {
1808 skip_getopt = 1;
1809 }
1810 free(decoded_query_string);
1811 }
1812
1813 php_ini_builder_init(&ini_builder);
1814
1815 while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1816 switch (c) {
1817 case 'c':
1818 if (cgi_sapi_module.php_ini_path_override) {
1819 free(cgi_sapi_module.php_ini_path_override);
1820 }
1821 cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1822 break;
1823 case 'n':
1824 cgi_sapi_module.php_ini_ignore = 1;
1825 break;
1826 case 'd':
1827 /* define ini entries on command line */
1828 php_ini_builder_define(&ini_builder, php_optarg);
1829 break;
1830 /* if we're started on command line, check to see if
1831 * we are being started as an 'external' fastcgi
1832 * server by accepting a bindpath parameter. */
1833 case 'b':
1834 if (!fastcgi) {
1835 bindpath = strdup(php_optarg);
1836 }
1837 break;
1838 case 's': /* generate highlighted HTML from source */
1839 behavior = PHP_MODE_HIGHLIGHT;
1840 break;
1841 }
1842 }
1843 php_optind = orig_optind;
1844 php_optarg = orig_optarg;
1845
1846 cgi_sapi_module.ini_entries = php_ini_builder_finish(&ini_builder);
1847
1848 if (fastcgi || bindpath) {
1849 /* Override SAPI callbacks */
1850 cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
1851 cgi_sapi_module.flush = sapi_fcgi_flush;
1852 cgi_sapi_module.read_post = sapi_fcgi_read_post;
1853 cgi_sapi_module.getenv = sapi_fcgi_getenv;
1854 cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
1855 }
1856
1857 #ifdef ZTS
1858 SG(request_info).path_translated = NULL;
1859 #endif
1860
1861 cgi_sapi_module.executable_location = argv[0];
1862 if (!cgi && !fastcgi && !bindpath) {
1863 cgi_sapi_module.additional_functions = additional_functions;
1864 }
1865
1866 /* startup after we get the above ini override se we get things right */
1867 if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1868 #ifdef ZTS
1869 tsrm_shutdown();
1870 #endif
1871 free(bindpath);
1872 return FAILURE;
1873 }
1874
1875 /* check force_cgi after startup, so we have proper output */
1876 if (cgi && CGIG(force_redirect)) {
1877 /* Apache will generate REDIRECT_STATUS,
1878 * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
1879 * redirect.so and installation instructions available from
1880 * http://www.koehntopp.de/php.
1881 * -- kk@netuse.de
1882 */
1883 if (!getenv("REDIRECT_STATUS") &&
1884 !getenv ("HTTP_REDIRECT_STATUS") &&
1885 /* this is to allow a different env var to be configured
1886 * in case some server does something different than above */
1887 (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
1888 ) {
1889 zend_try {
1890 SG(sapi_headers).http_response_code = 400;
1891 PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1892 <p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
1893 means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1894 set, e.g. via an Apache Action directive.</p>\n\
1895 <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1896 manual page for CGI security</a>.</p>\n\
1897 <p>For more information about changing this behaviour or re-enabling this webserver,\n\
1898 consult the installation file that came with this distribution, or visit \n\
1899 <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1900 } zend_catch {
1901 } zend_end_try();
1902 #if defined(ZTS) && !defined(PHP_DEBUG)
1903 /* XXX we're crashing here in msvc6 debug builds at
1904 * php_message_handler_for_zend:839 because
1905 * SG(request_info).path_translated is an invalid pointer.
1906 * It still happens even though I set it to null, so something
1907 * weird is going on.
1908 */
1909 tsrm_shutdown();
1910 #endif
1911 free(bindpath);
1912 return FAILURE;
1913 }
1914 }
1915
1916 #ifndef HAVE_ATTRIBUTE_WEAK
1917 fcgi_set_logger(fcgi_log);
1918 #endif
1919
1920 if (bindpath) {
1921 int backlog = MIN(SOMAXCONN, 128);
1922 if (getenv("PHP_FCGI_BACKLOG")) {
1923 backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
1924 }
1925 if (backlog < -1 || backlog > SOMAXCONN) {
1926 fprintf(stderr, "Invalid backlog %d, needs to be between -1 and %d\n", backlog, SOMAXCONN);
1927 #ifdef ZTS
1928 tsrm_shutdown();
1929 #endif
1930 return FAILURE;
1931 }
1932 fcgi_fd = fcgi_listen(bindpath, backlog);
1933 if (fcgi_fd < 0) {
1934 fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
1935 #ifdef ZTS
1936 tsrm_shutdown();
1937 #endif
1938 return FAILURE;
1939 }
1940 fastcgi = fcgi_is_fastcgi();
1941 }
1942
1943 /* make php call us to get _ENV vars */
1944 php_php_import_environment_variables = php_import_environment_variables;
1945 php_import_environment_variables = cgi_php_import_environment_variables;
1946
1947 if (fastcgi) {
1948 /* How many times to run PHP scripts before dying */
1949 if (getenv("PHP_FCGI_MAX_REQUESTS")) {
1950 max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
1951 if (max_requests < 0) {
1952 fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
1953 return FAILURE;
1954 }
1955 }
1956
1957 /* library is already initialized, now init our request */
1958 request = fcgi_init_request(fcgi_fd, NULL, NULL, NULL);
1959
1960 /* Pre-fork or spawn, if required */
1961 if (getenv("PHP_FCGI_CHILDREN")) {
1962 char * children_str = getenv("PHP_FCGI_CHILDREN");
1963 children = atoi(children_str);
1964 if (children < 0) {
1965 fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
1966 return FAILURE;
1967 }
1968 fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
1969 /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
1970 fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
1971 } else {
1972 #ifdef PHP_WIN32
1973 /* If this env var is set, the process was invoked as a child. Let
1974 it show the original PHP_FCGI_CHILDREN value, while don't care
1975 otherwise. */
1976 char * children_str = getenv("PHP_FCGI_CHILDREN_FOR_KID");
1977 if (children_str) {
1978 char putenv_buf[sizeof("PHP_FCGI_CHILDREN")+5];
1979
1980 snprintf(putenv_buf, sizeof(putenv_buf), "%s=%s", "PHP_FCGI_CHILDREN", children_str);
1981 putenv(putenv_buf);
1982 putenv("PHP_FCGI_CHILDREN_FOR_KID=");
1983
1984 SetEnvironmentVariable("PHP_FCGI_CHILDREN", children_str);
1985 SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", NULL);
1986 }
1987 #endif
1988 fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
1989 fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
1990 }
1991
1992 #ifndef PHP_WIN32
1993 if (children) {
1994 int running = 0;
1995 pid_t pid;
1996
1997 /* Create a process group for us & children */
1998 setsid();
1999 pgroup = getpgrp();
2000 #ifdef DEBUG_FASTCGI
2001 fprintf(stderr, "Process group %d\n", pgroup);
2002 #endif
2003
2004 /* Set up handler to kill children upon exit */
2005 act.sa_flags = 0;
2006 act.sa_handler = fastcgi_cleanup;
2007 if (sigaction(SIGTERM, &act, &old_term) ||
2008 sigaction(SIGINT, &act, &old_int) ||
2009 sigaction(SIGQUIT, &act, &old_quit)
2010 ) {
2011 perror("Can't set signals");
2012 exit(1);
2013 }
2014
2015 if (fcgi_in_shutdown()) {
2016 goto parent_out;
2017 }
2018
2019 while (parent) {
2020 do {
2021 #ifdef DEBUG_FASTCGI
2022 fprintf(stderr, "Forking, %d running\n", running);
2023 #endif
2024 pid = fork();
2025 switch (pid) {
2026 case 0:
2027 /* One of the children.
2028 * Make sure we don't go round the
2029 * fork loop any more
2030 */
2031 parent = 0;
2032
2033 /* don't catch our signals */
2034 sigaction(SIGTERM, &old_term, 0);
2035 sigaction(SIGQUIT, &old_quit, 0);
2036 sigaction(SIGINT, &old_int, 0);
2037 zend_signal_init();
2038 break;
2039 case -1:
2040 perror("php (pre-forking)");
2041 exit(1);
2042 break;
2043 default:
2044 /* Fine */
2045 running++;
2046 break;
2047 }
2048 } while (parent && (running < children));
2049
2050 if (parent) {
2051 #ifdef DEBUG_FASTCGI
2052 fprintf(stderr, "Wait for kids, pid %d\n", getpid());
2053 #endif
2054 parent_waiting = 1;
2055 while (1) {
2056 if (wait(&status) >= 0) {
2057 running--;
2058 break;
2059 } else if (exit_signal) {
2060 break;
2061 }
2062 }
2063 if (exit_signal) {
2064 #if 0
2065 while (running > 0) {
2066 while (wait(&status) < 0) {
2067 }
2068 running--;
2069 }
2070 #endif
2071 goto parent_out;
2072 }
2073 }
2074 }
2075 } else {
2076 parent = 0;
2077 zend_signal_init();
2078 }
2079
2080 #else
2081 if (children) {
2082 wchar_t *cmd_line_tmp, cmd_line[PHP_WIN32_IOUTIL_MAXPATHLEN];
2083 size_t cmd_line_len;
2084 char kid_buf[16];
2085 int i;
2086
2087 ZeroMemory(&kid_cgi_ps, sizeof(kid_cgi_ps));
2088 kids = children < WIN32_MAX_SPAWN_CHILDREN ? children : WIN32_MAX_SPAWN_CHILDREN;
2089
2090 InitializeCriticalSection(&cleanup_lock);
2091 SetConsoleCtrlHandler(fastcgi_cleanup, TRUE);
2092
2093 /* kids will inherit the env, don't let them spawn */
2094 SetEnvironmentVariable("PHP_FCGI_CHILDREN", NULL);
2095 /* instead, set a temporary env var, so then the child can read and
2096 show the actual setting correctly. */
2097 snprintf(kid_buf, 16, "%d", children);
2098 SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", kid_buf);
2099
2100 /* The current command line is used as is. This should normally be no issue,
2101 even if there were some I/O redirection. If some issues turn out, an
2102 extra parsing might be needed here. */
2103 cmd_line_tmp = GetCommandLineW();
2104 if (!cmd_line_tmp) {
2105 DWORD err = GetLastError();
2106 char *err_text = php_win32_error_to_msg(err);
2107
2108 fprintf(stderr, "unable to get current command line: [0x%08lx]: %s\n", err, err_text);
2109 php_win32_error_msg_free(err_text);
2110
2111 goto parent_out;
2112 }
2113
2114 cmd_line_len = wcslen(cmd_line_tmp);
2115 if (cmd_line_len > sizeof(cmd_line) - 1) {
2116 fprintf(stderr, "command line is too long\n");
2117 goto parent_out;
2118 }
2119 memmove(cmd_line, cmd_line_tmp, (cmd_line_len + 1)*sizeof(wchar_t));
2120
2121 job = CreateJobObject(NULL, NULL);
2122 if (!job) {
2123 DWORD err = GetLastError();
2124 char *err_text = php_win32_error_to_msg(err);
2125
2126 fprintf(stderr, "unable to create job object: [0x%08lx]: %s\n", err, err_text);
2127
2128 php_win32_error_msg_free(err_text);
2129
2130 goto parent_out;
2131 }
2132
2133 job_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
2134 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &job_info, sizeof(job_info))) {
2135 DWORD err = GetLastError();
2136 char *err_text = php_win32_error_to_msg(err);
2137
2138 fprintf(stderr, "unable to configure job object: [0x%08lx]: %s\n", err, err_text);
2139 php_win32_error_msg_free(err_text);
2140 }
2141
2142 while (parent) {
2143 EnterCriticalSection(&cleanup_lock);
2144 if (cleaning_up) {
2145 goto parent_loop_end;
2146 }
2147 LeaveCriticalSection(&cleanup_lock);
2148
2149 i = kids;
2150 while (0 < i--) {
2151 DWORD status;
2152
2153 if (NULL != kid_cgi_ps[i]) {
2154 if(!GetExitCodeProcess(kid_cgi_ps[i], &status) || status != STILL_ACTIVE) {
2155 CloseHandle(kid_cgi_ps[i]);
2156 kid_cgi_ps[i] = NULL;
2157 }
2158 }
2159 }
2160
2161 i = kids;
2162 while (0 < i--) {
2163 PROCESS_INFORMATION pi;
2164 STARTUPINFOW si;
2165
2166 if (NULL != kid_cgi_ps[i]) {
2167 continue;
2168 }
2169
2170 ZeroMemory(&si, sizeof(si));
2171 si.cb = sizeof(si);
2172 ZeroMemory(&pi, sizeof(pi));
2173
2174 si.dwFlags = STARTF_USESTDHANDLES;
2175 si.hStdOutput = INVALID_HANDLE_VALUE;
2176 si.hStdInput = (HANDLE)_get_osfhandle(fcgi_fd);
2177 si.hStdError = INVALID_HANDLE_VALUE;
2178
2179 if (CreateProcessW(NULL, cmd_line, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
2180 kid_cgi_ps[i] = pi.hProcess;
2181 if (!AssignProcessToJobObject(job, pi.hProcess)) {
2182 DWORD err = GetLastError();
2183 char *err_text = php_win32_error_to_msg(err);
2184
2185 fprintf(stderr, "unable to assign child process to job object: [0x%08lx]: %s\n", err, err_text);
2186 php_win32_error_msg_free(err_text);
2187 }
2188 CloseHandle(pi.hThread);
2189 } else {
2190 DWORD err = GetLastError();
2191 char *err_text = php_win32_error_to_msg(err);
2192
2193 kid_cgi_ps[i] = NULL;
2194
2195 fprintf(stderr, "unable to spawn: [0x%08lx]: %s\n", err, err_text);
2196 php_win32_error_msg_free(err_text);
2197 }
2198 }
2199
2200 WaitForMultipleObjects(kids, kid_cgi_ps, FALSE, INFINITE);
2201 }
2202
2203 parent_loop_end:
2204 /* restore my env */
2205 SetEnvironmentVariable("PHP_FCGI_CHILDREN", kid_buf);
2206
2207 DeleteCriticalSection(&cleanup_lock);
2208
2209 goto parent_out;
2210 } else {
2211 parent = 0;
2212 }
2213 #endif /* WIN32 */
2214 }
2215
2216 zend_first_try {
2217 while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
2218 switch (c) {
2219 case 'T':
2220 benchmark = 1;
2221 {
2222 char *comma = strchr(php_optarg, ',');
2223 if (comma) {
2224 warmup_repeats = atoi(php_optarg);
2225 repeats = atoi(comma + 1);
2226 #ifdef HAVE_VALGRIND
2227 if (warmup_repeats > 0) {
2228 CALLGRIND_STOP_INSTRUMENTATION;
2229 /* We're not interested in measuring startup */
2230 CALLGRIND_ZERO_STATS;
2231 }
2232 #endif
2233 } else {
2234 repeats = atoi(php_optarg);
2235 }
2236 }
2237 #ifdef HAVE_GETTIMEOFDAY
2238 gettimeofday(&start, NULL);
2239 #else
2240 time(&start);
2241 #endif
2242 break;
2243 case 'h':
2244 case '?':
2245 case PHP_GETOPT_INVALID_ARG:
2246 if (request) {
2247 fcgi_destroy_request(request);
2248 }
2249 fcgi_shutdown();
2250 no_headers = 1;
2251 SG(headers_sent) = 1;
2252 php_cgi_usage(argv[0]);
2253 php_output_end_all();
2254 exit_status = 0;
2255 if (c == PHP_GETOPT_INVALID_ARG) {
2256 exit_status = 1;
2257 }
2258 goto out;
2259 }
2260 }
2261 php_optind = orig_optind;
2262 php_optarg = orig_optarg;
2263
2264 /* start of FAST CGI loop */
2265 /* Initialise FastCGI request structure */
2266 #ifdef PHP_WIN32
2267 /* attempt to set security impersonation for fastcgi
2268 * will only happen on NT based OS, others will ignore it. */
2269 if (fastcgi && CGIG(impersonate)) {
2270 fcgi_impersonate();
2271 }
2272 #endif
2273 while (!fastcgi || fcgi_accept_request(request) >= 0) {
2274 SG(server_context) = fastcgi ? (void *)request : (void *) 1;
2275 init_request_info(request);
2276
2277 if (!cgi && !fastcgi) {
2278 while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
2279 switch (c) {
2280
2281 case 'a': /* interactive mode */
2282 printf("Interactive mode enabled\n\n");
2283 fflush(stdout);
2284 break;
2285
2286 case 'C': /* don't chdir to the script directory */
2287 SG(options) |= SAPI_OPTION_NO_CHDIR;
2288 break;
2289
2290 case 'e': /* enable extended info output */
2291 CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
2292 break;
2293
2294 case 'f': /* parse file */
2295 if (script_file) {
2296 efree(script_file);
2297 }
2298 script_file = estrdup(php_optarg);
2299 no_headers = 1;
2300 break;
2301
2302 case 'i': /* php info & quit */
2303 if (script_file) {
2304 efree(script_file);
2305 }
2306 if (php_request_startup() == FAILURE) {
2307 SG(server_context) = NULL;
2308 php_module_shutdown();
2309 free(bindpath);
2310 return FAILURE;
2311 }
2312 if (no_headers) {
2313 SG(headers_sent) = 1;
2314 SG(request_info).no_headers = 1;
2315 }
2316 php_print_info(0xFFFFFFFF);
2317 php_request_shutdown((void *) 0);
2318 fcgi_shutdown();
2319 exit_status = 0;
2320 goto out;
2321
2322 case 'l': /* syntax check mode */
2323 no_headers = 1;
2324 behavior = PHP_MODE_LINT;
2325 break;
2326
2327 case 'm': /* list compiled in modules */
2328 if (script_file) {
2329 efree(script_file);
2330 }
2331 SG(headers_sent) = 1;
2332 php_printf("[PHP Modules]\n");
2333 print_modules();
2334 php_printf("\n[Zend Modules]\n");
2335 print_extensions();
2336 php_printf("\n");
2337 php_output_end_all();
2338 fcgi_shutdown();
2339 exit_status = 0;
2340 goto out;
2341
2342 case 'q': /* do not generate HTTP headers */
2343 no_headers = 1;
2344 break;
2345
2346 case 'v': /* show php version & quit */
2347 if (script_file) {
2348 efree(script_file);
2349 }
2350 no_headers = 1;
2351 if (php_request_startup() == FAILURE) {
2352 SG(server_context) = NULL;
2353 php_module_shutdown();
2354 free(bindpath);
2355 return FAILURE;
2356 }
2357 SG(headers_sent) = 1;
2358 SG(request_info).no_headers = 1;
2359 #if ZEND_DEBUG
2360 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());
2361 #else
2362 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());
2363 #endif
2364 php_request_shutdown((void *) 0);
2365 fcgi_shutdown();
2366 exit_status = 0;
2367 goto out;
2368
2369 case 'w':
2370 behavior = PHP_MODE_STRIP;
2371 break;
2372
2373 case 'z': /* load extension file */
2374 zend_load_extension(php_optarg);
2375 break;
2376
2377 default:
2378 break;
2379 }
2380 }
2381
2382 do_repeat:
2383 if (script_file) {
2384 /* override path_translated if -f on command line */
2385 if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2386 SG(request_info).path_translated = script_file;
2387 /* before registering argv to module exchange the *new* argv[0] */
2388 /* we can achieve this without allocating more memory */
2389 SG(request_info).argc = argc - (php_optind - 1);
2390 SG(request_info).argv = &argv[php_optind - 1];
2391 SG(request_info).argv[0] = script_file;
2392 } else if (argc > php_optind) {
2393 /* file is on command line, but not in -f opt */
2394 if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2395 SG(request_info).path_translated = estrdup(argv[php_optind]);
2396 /* arguments after the file are considered script args */
2397 SG(request_info).argc = argc - php_optind;
2398 SG(request_info).argv = &argv[php_optind];
2399 }
2400
2401 if (no_headers) {
2402 SG(headers_sent) = 1;
2403 SG(request_info).no_headers = 1;
2404 }
2405
2406 /* all remaining arguments are part of the query string
2407 * this section of code concatenates all remaining arguments
2408 * into a single string, separating args with a &
2409 * this allows command lines like:
2410 *
2411 * test.php v1=test v2=hello+world!
2412 * test.php "v1=test&v2=hello world!"
2413 * test.php v1=test "v2=hello world!"
2414 */
2415 if (!SG(request_info).query_string && argc > php_optind) {
2416 size_t slen = strlen(PG(arg_separator).input);
2417 len = 0;
2418 for (i = php_optind; i < argc; i++) {
2419 if (i < (argc - 1)) {
2420 len += strlen(argv[i]) + slen;
2421 } else {
2422 len += strlen(argv[i]);
2423 }
2424 }
2425
2426 len += 2;
2427 s = malloc(len);
2428 *s = '\0'; /* we are pretending it came from the environment */
2429 for (i = php_optind; i < argc; i++) {
2430 strlcat(s, argv[i], len);
2431 if (i < (argc - 1)) {
2432 strlcat(s, PG(arg_separator).input, len);
2433 }
2434 }
2435 SG(request_info).query_string = s;
2436 free_query_string = 1;
2437 }
2438 } /* end !cgi && !fastcgi */
2439
2440 #ifdef HAVE_VALGRIND
2441 if (warmup_repeats == 0) {
2442 CALLGRIND_START_INSTRUMENTATION;
2443 }
2444 #endif
2445
2446 /* request startup only after we've done all we can to
2447 * get path_translated */
2448 if (php_request_startup() == FAILURE) {
2449 if (fastcgi) {
2450 fcgi_finish_request(request, 1);
2451 }
2452 SG(server_context) = NULL;
2453 php_module_shutdown();
2454 return FAILURE;
2455 }
2456 if (no_headers) {
2457 SG(headers_sent) = 1;
2458 SG(request_info).no_headers = 1;
2459 }
2460
2461 /*
2462 at this point path_translated will be set if:
2463 1. we are running from shell and got filename was there
2464 2. we are running as cgi or fastcgi
2465 */
2466 if (cgi || fastcgi || SG(request_info).path_translated) {
2467 if (php_fopen_primary_script(&file_handle) == FAILURE) {
2468 zend_try {
2469 if (errno == EACCES) {
2470 SG(sapi_headers).http_response_code = 403;
2471 PUTS("Access denied.\n");
2472 } else {
2473 SG(sapi_headers).http_response_code = 404;
2474 PUTS("No input file specified.\n");
2475 }
2476 } zend_catch {
2477 } zend_end_try();
2478 /* we want to serve more requests if this is fastcgi
2479 * so cleanup and continue, request shutdown is
2480 * handled later */
2481 if (fastcgi) {
2482 goto fastcgi_request_done;
2483 }
2484
2485 if (SG(request_info).path_translated) {
2486 efree(SG(request_info).path_translated);
2487 SG(request_info).path_translated = NULL;
2488 }
2489
2490 if (free_query_string && SG(request_info).query_string) {
2491 free(SG(request_info).query_string);
2492 SG(request_info).query_string = NULL;
2493 }
2494
2495 php_request_shutdown((void *) 0);
2496 SG(server_context) = NULL;
2497 php_module_shutdown();
2498 sapi_shutdown();
2499 #ifdef ZTS
2500 tsrm_shutdown();
2501 #endif
2502 free(bindpath);
2503 return FAILURE;
2504 }
2505 } else {
2506 /* we never take stdin if we're (f)cgi */
2507 zend_stream_init_fp(&file_handle, stdin, "Standard input code");
2508 file_handle.primary_script = 1;
2509 }
2510
2511 if (CGIG(check_shebang_line)) {
2512 CG(skip_shebang) = 1;
2513 }
2514
2515 switch (behavior) {
2516 case PHP_MODE_STANDARD:
2517 php_execute_script(&file_handle);
2518 break;
2519 case PHP_MODE_LINT:
2520 PG(during_request_startup) = 0;
2521 if (php_lint_script(&file_handle) == SUCCESS) {
2522 zend_printf("No syntax errors detected in %s\n", ZSTR_VAL(file_handle.filename));
2523 } else {
2524 zend_printf("Errors parsing %s\n", ZSTR_VAL(file_handle.filename));
2525 exit_status = -1;
2526 }
2527 break;
2528 case PHP_MODE_STRIP:
2529 if (open_file_for_scanning(&file_handle) == SUCCESS) {
2530 zend_strip();
2531 }
2532 break;
2533 case PHP_MODE_HIGHLIGHT:
2534 {
2535 zend_syntax_highlighter_ini syntax_highlighter_ini;
2536
2537 if (open_file_for_scanning(&file_handle) == SUCCESS) {
2538 php_get_highlight_struct(&syntax_highlighter_ini);
2539 zend_highlight(&syntax_highlighter_ini);
2540 }
2541 }
2542 break;
2543 }
2544
2545 fastcgi_request_done:
2546 zend_destroy_file_handle(&file_handle);
2547
2548 if (SG(request_info).path_translated) {
2549 efree(SG(request_info).path_translated);
2550 SG(request_info).path_translated = NULL;
2551 }
2552
2553 php_request_shutdown((void *) 0);
2554
2555 if (exit_status == 0) {
2556 exit_status = EG(exit_status);
2557 }
2558
2559 if (free_query_string && SG(request_info).query_string) {
2560 free(SG(request_info).query_string);
2561 SG(request_info).query_string = NULL;
2562 }
2563
2564 #ifdef HAVE_VALGRIND
2565 /* We're not interested in measuring shutdown */
2566 CALLGRIND_STOP_INSTRUMENTATION;
2567 #endif
2568
2569 if (!fastcgi) {
2570 if (benchmark) {
2571 if (warmup_repeats) {
2572 warmup_repeats--;
2573 if (!warmup_repeats) {
2574 #ifdef HAVE_GETTIMEOFDAY
2575 gettimeofday(&start, NULL);
2576 #else
2577 time(&start);
2578 #endif
2579 }
2580 continue;
2581 } else {
2582 repeats--;
2583 if (repeats > 0) {
2584 script_file = NULL;
2585 php_optind = orig_optind;
2586 php_optarg = orig_optarg;
2587 continue;
2588 }
2589 }
2590 }
2591 if (behavior == PHP_MODE_LINT && argc - 1 > php_optind) {
2592 php_optind++;
2593 script_file = NULL;
2594 goto do_repeat;
2595 }
2596 break;
2597 }
2598
2599 /* only fastcgi will get here */
2600 requests++;
2601 if (max_requests && (requests == max_requests)) {
2602 fcgi_finish_request(request, 1);
2603 free(bindpath);
2604 if (max_requests != 1) {
2605 /* no need to return exit_status of the last request */
2606 exit_status = 0;
2607 }
2608 break;
2609 }
2610 /* end of fastcgi loop */
2611 }
2612
2613 if (request) {
2614 fcgi_destroy_request(request);
2615 }
2616 fcgi_shutdown();
2617
2618 if (cgi_sapi_module.php_ini_path_override) {
2619 free(cgi_sapi_module.php_ini_path_override);
2620 }
2621 php_ini_builder_deinit(&ini_builder);
2622 } zend_catch {
2623 exit_status = 255;
2624 } zend_end_try();
2625
2626 out:
2627 if (benchmark) {
2628 int sec;
2629 #ifdef HAVE_GETTIMEOFDAY
2630 int usec;
2631
2632 gettimeofday(&end, NULL);
2633 sec = (int)(end.tv_sec - start.tv_sec);
2634 if (end.tv_usec >= start.tv_usec) {
2635 usec = (int)(end.tv_usec - start.tv_usec);
2636 } else {
2637 sec -= 1;
2638 usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2639 }
2640 fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2641 #else
2642 time(&end);
2643 sec = (int)(end - start);
2644 fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2645 #endif
2646 }
2647
2648 parent_out:
2649
2650 SG(server_context) = NULL;
2651 php_module_shutdown();
2652 sapi_shutdown();
2653
2654 #ifdef ZTS
2655 tsrm_shutdown();
2656 #endif
2657
2658 #if defined(PHP_WIN32) && ZEND_DEBUG && 0
2659 _CrtDumpMemoryLeaks();
2660 #endif
2661
2662 return exit_status;
2663 }
2664 /* }}} */
2665