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