xref: /PHP-5.5/sapi/fpm/fpm/fpm_main.c (revision 76a290d0)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 5                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2015 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: cgi_main.c 291497 2009-11-30 14:43:22Z dmitry $ */
25 
26 #include "php.h"
27 #include "php_globals.h"
28 #include "php_variables.h"
29 #include "zend_modules.h"
30 #include "php.h"
31 #include "zend_ini_scanner.h"
32 #include "zend_globals.h"
33 #include "zend_stream.h"
34 
35 #include "SAPI.h"
36 
37 #include <stdio.h>
38 #include "php.h"
39 
40 #ifdef PHP_WIN32
41 # include "win32/time.h"
42 # include "win32/signal.h"
43 # include <process.h>
44 #endif
45 
46 #if HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
49 
50 #if HAVE_UNISTD_H
51 # include <unistd.h>
52 #endif
53 
54 #if HAVE_SIGNAL_H
55 # include <signal.h>
56 #endif
57 
58 #if HAVE_SETLOCALE
59 # include <locale.h>
60 #endif
61 
62 #if HAVE_SYS_TYPES_H
63 # include <sys/types.h>
64 #endif
65 
66 #if HAVE_SYS_WAIT_H
67 # include <sys/wait.h>
68 #endif
69 
70 #if HAVE_FCNTL_H
71 # include <fcntl.h>
72 #endif
73 
74 #include "zend.h"
75 #include "zend_extensions.h"
76 #include "php_ini.h"
77 #include "php_globals.h"
78 #include "php_main.h"
79 #include "fopen_wrappers.h"
80 #include "ext/standard/php_standard.h"
81 
82 #ifdef PHP_WIN32
83 # include <io.h>
84 # include <fcntl.h>
85 # include "win32/php_registry.h"
86 #endif
87 
88 #ifdef __riscos__
89 # include <unixlib/local.h>
90 int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
91 #endif
92 
93 #include "zend_compile.h"
94 #include "zend_execute.h"
95 #include "zend_highlight.h"
96 #include "zend_indent.h"
97 
98 #include "php_getopt.h"
99 
100 #include "fastcgi.h"
101 
102 #include <php_config.h>
103 #include "fpm.h"
104 #include "fpm_request.h"
105 #include "fpm_status.h"
106 #include "fpm_conf.h"
107 #include "fpm_php.h"
108 #include "fpm_log.h"
109 #include "zlog.h"
110 
111 #ifndef PHP_WIN32
112 /* XXX this will need to change later when threaded fastcgi is implemented.  shane */
113 struct sigaction act, old_term, old_quit, old_int;
114 #endif
115 
116 static void (*php_php_import_environment_variables)(zval *array_ptr TSRMLS_DC);
117 
118 #ifndef PHP_WIN32
119 /* these globals used for forking children on unix systems */
120 
121 /**
122  * Set to non-zero if we are the parent process
123  */
124 static int parent = 1;
125 #endif
126 
127 static int request_body_fd;
128 static int fpm_is_running = 0;
129 
130 static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC);
131 static void fastcgi_ini_parser(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg TSRMLS_DC);
132 
133 #define PHP_MODE_STANDARD	1
134 #define PHP_MODE_HIGHLIGHT	2
135 #define PHP_MODE_INDENT		3
136 #define PHP_MODE_LINT		4
137 #define PHP_MODE_STRIP		5
138 
139 static char *php_optarg = NULL;
140 static int php_optind = 1;
141 static zend_module_entry cgi_module_entry;
142 
143 static const opt_struct OPTIONS[] = {
144 	{'c', 1, "php-ini"},
145 	{'d', 1, "define"},
146 	{'e', 0, "profile-info"},
147 	{'h', 0, "help"},
148 	{'i', 0, "info"},
149 	{'m', 0, "modules"},
150 	{'n', 0, "no-php-ini"},
151 	{'?', 0, "usage"},/* help alias (both '?' and 'usage') */
152 	{'v', 0, "version"},
153 	{'y', 1, "fpm-config"},
154 	{'t', 0, "test"},
155 	{'p', 1, "prefix"},
156 	{'g', 1, "pid"},
157 	{'R', 0, "allow-to-run-as-root"},
158 	{'D', 0, "daemonize"},
159 	{'F', 0, "nodaemonize"},
160 	{'-', 0, NULL} /* end of args */
161 };
162 
163 typedef struct _php_cgi_globals_struct {
164 	zend_bool rfc2616_headers;
165 	zend_bool nph;
166 	zend_bool fix_pathinfo;
167 	zend_bool force_redirect;
168 	zend_bool discard_path;
169 	zend_bool fcgi_logging;
170 	char *redirect_status_env;
171 	HashTable user_config_cache;
172 	char *error_header;
173 	char *fpm_config;
174 } php_cgi_globals_struct;
175 
176 /* {{{ user_config_cache
177  *
178  * Key for each cache entry is dirname(PATH_TRANSLATED).
179  *
180  * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
181  *       the path starting from doc_root throught to dirname(PATH_TRANSLATED).  There is no point
182  *       storing per-file entries as it would not be possible to detect added / deleted entries
183  *       between separate files.
184  */
185 typedef struct _user_config_cache_entry {
186 	time_t expires;
187 	HashTable *user_config;
188 } user_config_cache_entry;
189 
user_config_cache_entry_dtor(user_config_cache_entry * entry)190 static void user_config_cache_entry_dtor(user_config_cache_entry *entry)
191 {
192 	zend_hash_destroy(entry->user_config);
193 	free(entry->user_config);
194 }
195 /* }}} */
196 
197 #ifdef ZTS
198 static int php_cgi_globals_id;
199 #define CGIG(v) TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
200 #else
201 static php_cgi_globals_struct php_cgi_globals;
202 #define CGIG(v) (php_cgi_globals.v)
203 #endif
204 
205 #ifdef PHP_WIN32
206 #define TRANSLATE_SLASHES(path) \
207 	{ \
208 		char *tmp = path; \
209 		while (*tmp) { \
210 			if (*tmp == '\\') *tmp = '/'; \
211 			tmp++; \
212 		} \
213 	}
214 #else
215 #define TRANSLATE_SLASHES(path)
216 #endif
217 
print_module_info(zend_module_entry * module,void * arg TSRMLS_DC)218 static int print_module_info(zend_module_entry *module, void *arg TSRMLS_DC)
219 {
220 	php_printf("%s\n", module->name);
221 	return 0;
222 }
223 
module_name_cmp(const void * a,const void * b TSRMLS_DC)224 static int module_name_cmp(const void *a, const void *b TSRMLS_DC)
225 {
226 	Bucket *f = *((Bucket **) a);
227 	Bucket *s = *((Bucket **) b);
228 
229 	return strcasecmp(	((zend_module_entry *)f->pData)->name,
230 						((zend_module_entry *)s->pData)->name);
231 }
232 
print_modules(TSRMLS_D)233 static void print_modules(TSRMLS_D)
234 {
235 	HashTable sorted_registry;
236 	zend_module_entry tmp;
237 
238 	zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
239 	zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
240 	zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
241 	zend_hash_apply_with_argument(&sorted_registry, (apply_func_arg_t) print_module_info, NULL TSRMLS_CC);
242 	zend_hash_destroy(&sorted_registry);
243 }
244 
print_extension_info(zend_extension * ext,void * arg TSRMLS_DC)245 static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC)
246 {
247 	php_printf("%s\n", ext->name);
248 	return 0;
249 }
250 
extension_name_cmp(const zend_llist_element ** f,const zend_llist_element ** s TSRMLS_DC)251 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s TSRMLS_DC)
252 {
253 	return strcmp(	((zend_extension *)(*f)->data)->name,
254 					((zend_extension *)(*s)->data)->name);
255 }
256 
print_extensions(TSRMLS_D)257 static void print_extensions(TSRMLS_D)
258 {
259 	zend_llist sorted_exts;
260 
261 	zend_llist_copy(&sorted_exts, &zend_extensions);
262 	sorted_exts.dtor = NULL;
263 	zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
264 	zend_llist_apply_with_argument(&sorted_exts, (llist_apply_with_arg_func_t) print_extension_info, NULL TSRMLS_CC);
265 	zend_llist_destroy(&sorted_exts);
266 }
267 
268 #ifndef STDOUT_FILENO
269 #define STDOUT_FILENO 1
270 #endif
271 
sapi_cgibin_single_write(const char * str,uint str_length TSRMLS_DC)272 static inline size_t sapi_cgibin_single_write(const char *str, uint str_length TSRMLS_DC)
273 {
274 	ssize_t ret;
275 
276 	/* sapi has started which means everyhting must be send through fcgi */
277 	if (fpm_is_running) {
278 		fcgi_request *request = (fcgi_request*) SG(server_context);
279 		ret = fcgi_write(request, FCGI_STDOUT, str, str_length);
280 		if (ret <= 0) {
281 			return 0;
282 		}
283 		return (size_t)ret;
284 	}
285 
286 	/* sapi has not started, output to stdout instead of fcgi */
287 #ifdef PHP_WRITE_STDOUT
288 	ret = write(STDOUT_FILENO, str, str_length);
289 	if (ret <= 0) {
290 		return 0;
291 	}
292 	return (size_t)ret;
293 #else
294 	return fwrite(str, 1, MIN(str_length, 16384), stdout);
295 #endif
296 }
297 
sapi_cgibin_ub_write(const char * str,uint str_length TSRMLS_DC)298 static int sapi_cgibin_ub_write(const char *str, uint str_length TSRMLS_DC)
299 {
300 	const char *ptr = str;
301 	uint remaining = str_length;
302 	size_t ret;
303 
304 	while (remaining > 0) {
305 		ret = sapi_cgibin_single_write(ptr, remaining TSRMLS_CC);
306 		if (!ret) {
307 			php_handle_aborted_connection();
308 			return str_length - remaining;
309 		}
310 		ptr += ret;
311 		remaining -= ret;
312 	}
313 
314 	return str_length;
315 }
316 
317 
sapi_cgibin_flush(void * server_context)318 static void sapi_cgibin_flush(void *server_context)
319 {
320 	/* fpm has started, let use fcgi instead of stdout */
321 	if (fpm_is_running) {
322 		fcgi_request *request = (fcgi_request*) server_context;
323 		if (
324 #ifndef PHP_WIN32
325 	      !parent &&
326 #endif
327 	      request && !fcgi_flush(request, 0)) {
328 			php_handle_aborted_connection();
329 		}
330 		return;
331 	}
332 
333 	/* fpm has not started yet, let use stdout instead of fcgi */
334 	if (fflush(stdout) == EOF) {
335 		php_handle_aborted_connection();
336 	}
337 }
338 
339 #define SAPI_CGI_MAX_HEADER_LENGTH 1024
340 
341 typedef struct _http_error {
342 	int code;
343 	const char* msg;
344 } http_error;
345 
346 static const http_error http_error_codes[] = {
347 	{100, "Continue"},
348 	{101, "Switching Protocols"},
349 	{200, "OK"},
350 	{201, "Created"},
351 	{202, "Accepted"},
352 	{203, "Non-Authoritative Information"},
353 	{204, "No Content"},
354 	{205, "Reset Content"},
355 	{206, "Partial Content"},
356 	{300, "Multiple Choices"},
357 	{301, "Moved Permanently"},
358 	{302, "Moved Temporarily"},
359 	{303, "See Other"},
360 	{304, "Not Modified"},
361 	{305, "Use Proxy"},
362 	{400, "Bad Request"},
363 	{401, "Unauthorized"},
364 	{402, "Payment Required"},
365 	{403, "Forbidden"},
366 	{404, "Not Found"},
367 	{405, "Method Not Allowed"},
368 	{406, "Not Acceptable"},
369 	{407, "Proxy Authentication Required"},
370 	{408, "Request Time-out"},
371 	{409, "Conflict"},
372 	{410, "Gone"},
373 	{411, "Length Required"},
374 	{412, "Precondition Failed"},
375 	{413, "Request Entity Too Large"},
376 	{414, "Request-URI Too Large"},
377 	{415, "Unsupported Media Type"},
378 	{428, "Precondition Required"},
379 	{429, "Too Many Requests"},
380 	{431, "Request Header Fields Too Large"},
381 	{500, "Internal Server Error"},
382 	{501, "Not Implemented"},
383 	{502, "Bad Gateway"},
384 	{503, "Service Unavailable"},
385 	{504, "Gateway Time-out"},
386 	{505, "HTTP Version not supported"},
387 	{511, "Network Authentication Required"},
388 	{0,   NULL}
389 };
390 
sapi_cgi_send_headers(sapi_headers_struct * sapi_headers TSRMLS_DC)391 static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
392 {
393 	char buf[SAPI_CGI_MAX_HEADER_LENGTH];
394 	sapi_header_struct *h;
395 	zend_llist_position pos;
396 	zend_bool ignore_status = 0;
397 	int response_status = SG(sapi_headers).http_response_code;
398 
399 	if (SG(request_info).no_headers == 1) {
400 		return  SAPI_HEADER_SENT_SUCCESSFULLY;
401 	}
402 
403 	if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
404 	{
405 		int len;
406 		zend_bool has_status = 0;
407 
408 		if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
409 			char *s;
410 			len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
411 			if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
412 				response_status = atoi((s + 1));
413 			}
414 
415 			if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
416 				len = SAPI_CGI_MAX_HEADER_LENGTH;
417 			}
418 
419 		} else {
420 			char *s;
421 
422 			if (SG(sapi_headers).http_status_line &&
423 				(s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
424 				(s - SG(sapi_headers).http_status_line) >= 5 &&
425 				strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
426 			) {
427 				len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
428 				response_status = atoi((s + 1));
429 			} else {
430 				h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
431 				while (h) {
432 					if (h->header_len > sizeof("Status:") - 1 &&
433 						strncasecmp(h->header, "Status:", sizeof("Status:") - 1) == 0
434 					) {
435 						has_status = 1;
436 						break;
437 					}
438 					h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
439 				}
440 				if (!has_status) {
441 					http_error *err = (http_error*)http_error_codes;
442 
443 					while (err->code != 0) {
444 						if (err->code == SG(sapi_headers).http_response_code) {
445 							break;
446 						}
447 						err++;
448 					}
449 					if (err->msg) {
450 						len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->msg);
451 					} else {
452 						len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
453 					}
454 				}
455 			}
456 		}
457 
458 		if (!has_status) {
459 			PHPWRITE_H(buf, len);
460 			ignore_status = 1;
461 		}
462 	}
463 
464 	h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
465 	while (h) {
466 		/* prevent CRLFCRLF */
467 		if (h->header_len) {
468 			if (h->header_len > sizeof("Status:") - 1 &&
469 				strncasecmp(h->header, "Status:", sizeof("Status:") - 1) == 0
470 			) {
471 				if (!ignore_status) {
472 					ignore_status = 1;
473 					PHPWRITE_H(h->header, h->header_len);
474 					PHPWRITE_H("\r\n", 2);
475 				}
476 			} else if (response_status == 304 && h->header_len > sizeof("Content-Type:") - 1 &&
477 				strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:") - 1) == 0
478 			) {
479 				h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
480 				continue;
481 			} else {
482 				PHPWRITE_H(h->header, h->header_len);
483 				PHPWRITE_H("\r\n", 2);
484 			}
485 		}
486 		h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
487 	}
488 	PHPWRITE_H("\r\n", 2);
489 
490 	return SAPI_HEADER_SENT_SUCCESSFULLY;
491 }
492 
493 #ifndef STDIN_FILENO
494 # define STDIN_FILENO 0
495 #endif
496 
sapi_cgi_read_post(char * buffer,uint count_bytes TSRMLS_DC)497 static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
498 {
499 	uint read_bytes = 0;
500 	int tmp_read_bytes;
501 
502 	count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
503 	while (read_bytes < count_bytes) {
504 		fcgi_request *request = (fcgi_request*) SG(server_context);
505 		if (request_body_fd == -1) {
506 			char *request_body_filename = sapi_cgibin_getenv((char *) "REQUEST_BODY_FILE",
507 					sizeof("REQUEST_BODY_FILE") - 1 TSRMLS_CC);
508 
509 			if (request_body_filename && *request_body_filename) {
510 				request_body_fd = open(request_body_filename, O_RDONLY);
511 
512 				if (0 > request_body_fd) {
513 					php_error(E_WARNING, "REQUEST_BODY_FILE: open('%s') failed: %s (%d)",
514 							request_body_filename, strerror(errno), errno);
515 					return 0;
516 				}
517 			}
518 		}
519 
520 		/* If REQUEST_BODY_FILE variable not available - read post body from fastcgi stream */
521 		if (request_body_fd < 0) {
522 			tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes);
523 		} else {
524 			tmp_read_bytes = read(request_body_fd, buffer + read_bytes, count_bytes - read_bytes);
525 		}
526 		if (tmp_read_bytes <= 0) {
527 			break;
528 		}
529 		read_bytes += tmp_read_bytes;
530 	}
531 	return read_bytes;
532 }
533 
sapi_cgibin_getenv(char * name,size_t name_len TSRMLS_DC)534 static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC)
535 {
536 	/* if fpm has started, use fcgi env */
537 	if (fpm_is_running) {
538 		fcgi_request *request = (fcgi_request*) SG(server_context);
539 		return fcgi_getenv(request, name, name_len);
540 	}
541 
542 	/* if fpm has not started yet, use std env */
543 	return getenv(name);
544 }
545 
_sapi_cgibin_putenv(char * name,char * value TSRMLS_DC)546 static char *_sapi_cgibin_putenv(char *name, char *value TSRMLS_DC)
547 {
548 	int name_len;
549 
550 	if (!name) {
551 		return NULL;
552 	}
553 	name_len = strlen(name);
554 
555 	fcgi_request *request = (fcgi_request*) SG(server_context);
556 	return fcgi_putenv(request, name, name_len, value);
557 }
558 
sapi_cgi_read_cookies(TSRMLS_D)559 static char *sapi_cgi_read_cookies(TSRMLS_D)
560 {
561 	return sapi_cgibin_getenv((char *) "HTTP_COOKIE", sizeof("HTTP_COOKIE") - 1 TSRMLS_CC);
562 }
563 
cgi_php_import_environment_variables(zval * array_ptr TSRMLS_DC)564 void cgi_php_import_environment_variables(zval *array_ptr TSRMLS_DC)
565 {
566 	fcgi_request *request;
567 	HashPosition pos;
568 	char *var, **val;
569 	uint var_len;
570 	ulong idx;
571 	int filter_arg;
572 
573 
574 	if (PG(http_globals)[TRACK_VARS_ENV] &&
575 		array_ptr != PG(http_globals)[TRACK_VARS_ENV] &&
576 		Z_TYPE_P(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
577 		zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_ENV])) > 0
578 	) {
579 		zval_dtor(array_ptr);
580 		*array_ptr = *PG(http_globals)[TRACK_VARS_ENV];
581 		INIT_PZVAL(array_ptr);
582 		zval_copy_ctor(array_ptr);
583 		return;
584 	} else if (PG(http_globals)[TRACK_VARS_SERVER] &&
585 		array_ptr != PG(http_globals)[TRACK_VARS_SERVER] &&
586 		Z_TYPE_P(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
587 		zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER])) > 0
588 	) {
589 		zval_dtor(array_ptr);
590 		*array_ptr = *PG(http_globals)[TRACK_VARS_SERVER];
591 		INIT_PZVAL(array_ptr);
592 		zval_copy_ctor(array_ptr);
593 		return;
594 	}
595 
596 	/* call php's original import as a catch-all */
597 	php_php_import_environment_variables(array_ptr TSRMLS_CC);
598 
599 	request = (fcgi_request*) SG(server_context);
600 	filter_arg = (array_ptr == PG(http_globals)[TRACK_VARS_ENV])?PARSE_ENV:PARSE_SERVER;
601 
602 	for (zend_hash_internal_pointer_reset_ex(request->env, &pos);
603 	     zend_hash_get_current_key_ex(request->env, &var, &var_len, &idx, 0, &pos) == HASH_KEY_IS_STRING &&
604 	     zend_hash_get_current_data_ex(request->env, (void **) &val, &pos) == SUCCESS;
605 	     zend_hash_move_forward_ex(request->env, &pos)
606 	) {
607 		unsigned int new_val_len;
608 
609 		if (sapi_module.input_filter(filter_arg, var, val, strlen(*val), &new_val_len TSRMLS_CC)) {
610 			php_register_variable_safe(var, *val, new_val_len, array_ptr TSRMLS_CC);
611 		}
612 	}
613 }
614 
sapi_cgi_register_variables(zval * track_vars_array TSRMLS_DC)615 static void sapi_cgi_register_variables(zval *track_vars_array TSRMLS_DC)
616 {
617 	unsigned int php_self_len;
618 	char *php_self;
619 
620 	/* In CGI mode, we consider the environment to be a part of the server
621 	 * variables
622 	 */
623 	php_import_environment_variables(track_vars_array TSRMLS_CC);
624 
625 	if (CGIG(fix_pathinfo)) {
626 		char *script_name = SG(request_info).request_uri;
627 		unsigned int script_name_len = script_name ? strlen(script_name) : 0;
628 		char *path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO") - 1 TSRMLS_CC);
629 		unsigned int path_info_len = path_info ? strlen(path_info) : 0;
630 
631 		php_self_len = script_name_len + path_info_len;
632 		php_self = emalloc(php_self_len + 1);
633 
634 		/* Concat script_name and path_info into php_self */
635 		if (script_name) {
636 			memcpy(php_self, script_name, script_name_len + 1);
637 		}
638 		if (path_info) {
639 			memcpy(php_self + script_name_len, path_info, path_info_len + 1);
640 		}
641 
642 		/* Build the special-case PHP_SELF variable for the CGI version */
643 		if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
644 			php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
645 		}
646 		efree(php_self);
647 	} else {
648 		php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
649 		php_self_len = strlen(php_self);
650 		if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
651 			php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
652 		}
653 	}
654 }
655 
656 /* {{{ sapi_cgi_log_fastcgi
657  *
658  * Ignore level, we want to send all messages through fastcgi
659  */
sapi_cgi_log_fastcgi(int level,char * message,size_t len)660 void sapi_cgi_log_fastcgi(int level, char *message, size_t len)
661 {
662 	TSRMLS_FETCH();
663 
664 	fcgi_request *request = (fcgi_request*) SG(server_context);
665 
666 	/* ensure we want:
667 	 * - to log (fastcgi.logging in php.ini)
668 	 * - we are currently dealing with a request
669 	 * - the message is not empty
670 	 */
671 	if (CGIG(fcgi_logging) && request && message && len > 0) {
672 		ssize_t ret;
673 		char *buf = malloc(len + 2);
674 		memcpy(buf, message, len);
675 		memcpy(buf + len, "\n", sizeof("\n"));
676 		ret = fcgi_write(request, FCGI_STDERR, buf, len + 1);
677 		free(buf);
678 		if (ret < 0) {
679 			php_handle_aborted_connection();
680 		}
681 	}
682 }
683 /* }}} */
684 
685 /* {{{ sapi_cgi_log_message
686  */
sapi_cgi_log_message(char * message)687 static void sapi_cgi_log_message(char *message)
688 {
689 	zlog(ZLOG_NOTICE, "PHP message: %s", message);
690 }
691 /* }}} */
692 
693 /* {{{ php_cgi_ini_activate_user_config
694  */
php_cgi_ini_activate_user_config(char * path,int path_len,const char * doc_root,int doc_root_len,int start TSRMLS_DC)695 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)
696 {
697 	char *ptr;
698 	user_config_cache_entry *new_entry, *entry;
699 	time_t request_time = sapi_get_request_time(TSRMLS_C);
700 
701 	/* Find cached config entry: If not found, create one */
702 	if (zend_hash_find(&CGIG(user_config_cache), path, path_len + 1, (void **) &entry) == FAILURE) {
703 		new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
704 		new_entry->expires = 0;
705 		new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
706 		zend_hash_init(new_entry->user_config, 0, NULL, (dtor_func_t) config_zval_dtor, 1);
707 		zend_hash_update(&CGIG(user_config_cache), path, path_len + 1, new_entry, sizeof(user_config_cache_entry), (void **) &entry);
708 		free(new_entry);
709 	}
710 
711 	/* Check whether cache entry has expired and rescan if it is */
712 	if (request_time > entry->expires) {
713 		char * real_path;
714 		int real_path_len;
715 		char *s1, *s2;
716 		int s_len;
717 
718 		/* Clear the expired config */
719 		zend_hash_clean(entry->user_config);
720 
721 		if (!IS_ABSOLUTE_PATH(path, path_len)) {
722 			real_path = tsrm_realpath(path, NULL TSRMLS_CC);
723 			if (real_path == NULL) {
724 				return;
725 			}
726 			real_path_len = strlen(real_path);
727 			path = real_path;
728 			path_len = real_path_len;
729 		}
730 
731 		if (path_len > doc_root_len) {
732 			s1 = (char *) doc_root;
733 			s2 = path;
734 			s_len = doc_root_len;
735 		} else {
736 			s1 = path;
737 			s2 = (char *) doc_root;
738 			s_len = path_len;
739 		}
740 
741 		/* we have to test if path is part of DOCUMENT_ROOT.
742 		  if it is inside the docroot, we scan the tree up to the docroot
743 			to find more user.ini, if not we only scan the current path.
744 		  */
745 #ifdef PHP_WIN32
746 		if (strnicmp(s1, s2, s_len) == 0) {
747 #else
748 		if (strncmp(s1, s2, s_len) == 0) {
749 #endif
750 			ptr = s2 + start;  /* start is the point where doc_root ends! */
751 			while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
752 				*ptr = 0;
753 				php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
754 				*ptr = '/';
755 				ptr++;
756 			}
757 		} else {
758 			php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
759 		}
760 
761 		entry->expires = request_time + PG(user_ini_cache_ttl);
762 	}
763 
764 	/* Activate ini entries with values from the user config hash */
765 	php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS TSRMLS_CC);
766 }
767 /* }}} */
768 
769 static int sapi_cgi_activate(TSRMLS_D)
770 {
771 	char *path, *doc_root, *server_name;
772 	uint path_len, doc_root_len, server_name_len;
773 
774 	/* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
775 	if (!SG(request_info).path_translated) {
776 		return FAILURE;
777 	}
778 
779 	if (php_ini_has_per_host_config()) {
780 		/* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
781 		server_name = sapi_cgibin_getenv("SERVER_NAME", sizeof("SERVER_NAME") - 1 TSRMLS_CC);
782 		/* SERVER_NAME should also be defined at this stage..but better check it anyway */
783 		if (server_name) {
784 			server_name_len = strlen(server_name);
785 			server_name = estrndup(server_name, server_name_len);
786 			zend_str_tolower(server_name, server_name_len);
787 			php_ini_activate_per_host_config(server_name, server_name_len + 1 TSRMLS_CC);
788 			efree(server_name);
789 		}
790 	}
791 
792 	if (php_ini_has_per_dir_config() ||
793 		(PG(user_ini_filename) && *PG(user_ini_filename))
794 	) {
795 		/* Prepare search path */
796 		path_len = strlen(SG(request_info).path_translated);
797 
798 		/* Make sure we have trailing slash! */
799 		if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
800 			path = emalloc(path_len + 2);
801 			memcpy(path, SG(request_info).path_translated, path_len + 1);
802 			path_len = zend_dirname(path, path_len);
803 			path[path_len++] = DEFAULT_SLASH;
804 		} else {
805 			path = estrndup(SG(request_info).path_translated, path_len);
806 			path_len = zend_dirname(path, path_len);
807 		}
808 		path[path_len] = 0;
809 
810 		/* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
811 		php_ini_activate_per_dir_config(path, path_len TSRMLS_CC); /* Note: for global settings sake we check from root to path */
812 
813 		/* Load and activate user ini files in path starting from DOCUMENT_ROOT */
814 		if (PG(user_ini_filename) && *PG(user_ini_filename)) {
815 			doc_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT") - 1 TSRMLS_CC);
816 			/* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
817 			if (doc_root) {
818 				doc_root_len = strlen(doc_root);
819 				if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
820 					--doc_root_len;
821 				}
822 #ifdef PHP_WIN32
823 				/* paths on windows should be case-insensitive */
824 				doc_root = estrndup(doc_root, doc_root_len);
825 				zend_str_tolower(doc_root, doc_root_len);
826 #endif
827 				php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len, doc_root_len - 1 TSRMLS_CC);
828 			}
829 		}
830 
831 #ifdef PHP_WIN32
832 		efree(doc_root);
833 #endif
834 		efree(path);
835 	}
836 
837 	return SUCCESS;
838 }
839 
840 static int sapi_cgi_deactivate(TSRMLS_D)
841 {
842 	/* flush only when SAPI was started. The reasons are:
843 		1. SAPI Deactivate is called from two places: module init and request shutdown
844 		2. When the first call occurs and the request is not set up, flush fails on FastCGI.
845 	*/
846 	if (SG(sapi_started)) {
847 		if (
848 #ifndef PHP_WIN32
849 		    !parent &&
850 #endif
851 		    !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
852 			php_handle_aborted_connection();
853 		}
854 	}
855 	return SUCCESS;
856 }
857 
858 static int php_cgi_startup(sapi_module_struct *sapi_module)
859 {
860 	if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
861 		return FAILURE;
862 	}
863 	return SUCCESS;
864 }
865 
866 /* {{{ sapi_module_struct cgi_sapi_module
867  */
868 static sapi_module_struct cgi_sapi_module = {
869 	"fpm-fcgi",						/* name */
870 	"FPM/FastCGI",					/* pretty name */
871 
872 	php_cgi_startup,				/* startup */
873 	php_module_shutdown_wrapper,	/* shutdown */
874 
875 	sapi_cgi_activate,				/* activate */
876 	sapi_cgi_deactivate,			/* deactivate */
877 
878 	sapi_cgibin_ub_write,			/* unbuffered write */
879 	sapi_cgibin_flush,				/* flush */
880 	NULL,							/* get uid */
881 	sapi_cgibin_getenv,				/* getenv */
882 
883 	php_error,						/* error handler */
884 
885 	NULL,							/* header handler */
886 	sapi_cgi_send_headers,			/* send headers handler */
887 	NULL,							/* send header handler */
888 
889 	sapi_cgi_read_post,				/* read POST data */
890 	sapi_cgi_read_cookies,			/* read Cookies */
891 
892 	sapi_cgi_register_variables,	/* register server variables */
893 	sapi_cgi_log_message,			/* Log message */
894 	NULL,							/* Get request time */
895 	NULL,							/* Child terminate */
896 
897 	STANDARD_SAPI_MODULE_PROPERTIES
898 };
899 /* }}} */
900 
901 /* {{{ arginfo ext/standard/dl.c */
902 ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
903 	ZEND_ARG_INFO(0, extension_filename)
904 ZEND_END_ARG_INFO()
905 /* }}} */
906 
907 static const zend_function_entry additional_functions[] = {
908 	ZEND_FE(dl, arginfo_dl)
909 	{NULL, NULL, NULL}
910 };
911 
912 /* {{{ php_cgi_usage
913  */
914 static void php_cgi_usage(char *argv0)
915 {
916 	char *prog;
917 
918 	prog = strrchr(argv0, '/');
919 	if (prog) {
920 		prog++;
921 	} else {
922 		prog = "php";
923 	}
924 
925 	php_printf(	"Usage: %s [-n] [-e] [-h] [-i] [-m] [-v] [-t] [-p <prefix>] [-g <pid>] [-c <file>] [-d foo[=bar]] [-y <file>] [-D] [-F]\n"
926 				"  -c <path>|<file> Look for php.ini file in this directory\n"
927 				"  -n               No php.ini file will be used\n"
928 				"  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
929 				"  -e               Generate extended information for debugger/profiler\n"
930 				"  -h               This help\n"
931 				"  -i               PHP information\n"
932 				"  -m               Show compiled in modules\n"
933 				"  -v               Version number\n"
934 				"  -p, --prefix <dir>\n"
935 				"                   Specify alternative prefix path to FastCGI process manager (default: %s).\n"
936 				"  -g, --pid <file>\n"
937 				"                   Specify the PID file location.\n"
938 				"  -y, --fpm-config <file>\n"
939 				"                   Specify alternative path to FastCGI process manager config file.\n"
940 				"  -t, --test       Test FPM configuration and exit\n"
941 				"  -D, --daemonize  force to run in background, and ignore daemonize option from config file\n"
942 				"  -F, --nodaemonize\n"
943 				"                   force to stay in foreground, and ignore daemonize option from config file\n"
944 				"  -R, --allow-to-run-as-root\n"
945 				"                   Allow pool to run as root (disabled by default)\n",
946 				prog, PHP_PREFIX);
947 }
948 /* }}} */
949 
950 /* {{{ is_valid_path
951  *
952  * some server configurations allow '..' to slip through in the
953  * translated path.   We'll just refuse to handle such a path.
954  */
955 static int is_valid_path(const char *path)
956 {
957 	const char *p;
958 
959 	if (!path) {
960 		return 0;
961 	}
962 	p = strstr(path, "..");
963 	if (p) {
964 		if ((p == path || IS_SLASH(*(p-1))) &&
965 			(*(p+2) == 0 || IS_SLASH(*(p+2)))
966 		) {
967 			return 0;
968 		}
969 		while (1) {
970 			p = strstr(p+1, "..");
971 			if (!p) {
972 				break;
973 			}
974 			if (IS_SLASH(*(p-1)) &&
975 				(*(p+2) == 0 || IS_SLASH(*(p+2)))
976 			) {
977 					return 0;
978 			}
979 		}
980 	}
981 	return 1;
982 }
983 /* }}} */
984 
985 /* {{{ init_request_info
986 
987   initializes request_info structure
988 
989   specificly in this section we handle proper translations
990   for:
991 
992   PATH_INFO
993 	derived from the portion of the URI path following
994 	the script name but preceding any query data
995 	may be empty
996 
997   PATH_TRANSLATED
998     derived by taking any path-info component of the
999 	request URI and performing any virtual-to-physical
1000 	translation appropriate to map it onto the server's
1001 	document repository structure
1002 
1003 	empty if PATH_INFO is empty
1004 
1005 	The env var PATH_TRANSLATED **IS DIFFERENT** than the
1006 	request_info.path_translated variable, the latter should
1007 	match SCRIPT_FILENAME instead.
1008 
1009   SCRIPT_NAME
1010     set to a URL path that could identify the CGI script
1011 	rather than the interpreter.  PHP_SELF is set to this
1012 
1013   REQUEST_URI
1014     uri section following the domain:port part of a URI
1015 
1016   SCRIPT_FILENAME
1017     The virtual-to-physical translation of SCRIPT_NAME (as per
1018 	PATH_TRANSLATED)
1019 
1020   These settings are documented at
1021   http://cgi-spec.golux.com/
1022 
1023 
1024   Based on the following URL request:
1025 
1026   http://localhost/info.php/test?a=b
1027 
1028   should produce, which btw is the same as if
1029   we were running under mod_cgi on apache (ie. not
1030   using ScriptAlias directives):
1031 
1032   PATH_INFO=/test
1033   PATH_TRANSLATED=/docroot/test
1034   SCRIPT_NAME=/info.php
1035   REQUEST_URI=/info.php/test?a=b
1036   SCRIPT_FILENAME=/docroot/info.php
1037   QUERY_STRING=a=b
1038 
1039   but what we get is (cgi/mod_fastcgi under apache):
1040 
1041   PATH_INFO=/info.php/test
1042   PATH_TRANSLATED=/docroot/info.php/test
1043   SCRIPT_NAME=/php/php-cgi  (from the Action setting I suppose)
1044   REQUEST_URI=/info.php/test?a=b
1045   SCRIPT_FILENAME=/path/to/php/bin/php-cgi  (Action setting translated)
1046   QUERY_STRING=a=b
1047 
1048   Comments in the code below refer to using the above URL in a request
1049 
1050  */
1051 static void init_request_info(TSRMLS_D)
1052 {
1053 	char *env_script_filename = sapi_cgibin_getenv("SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME") - 1 TSRMLS_CC);
1054 	char *env_path_translated = sapi_cgibin_getenv("PATH_TRANSLATED", sizeof("PATH_TRANSLATED") - 1 TSRMLS_CC);
1055 	char *script_path_translated = env_script_filename;
1056 	char *ini;
1057 	int apache_was_here = 0;
1058 
1059 	/* some broken servers do not have script_filename or argv0
1060 	 * an example, IIS configured in some ways.  then they do more
1061 	 * broken stuff and set path_translated to the cgi script location */
1062 	if (!script_path_translated && env_path_translated) {
1063 		script_path_translated = env_path_translated;
1064 	}
1065 
1066 	/* initialize the defaults */
1067 	SG(request_info).path_translated = NULL;
1068 	SG(request_info).request_method = NULL;
1069 	SG(request_info).proto_num = 1000;
1070 	SG(request_info).query_string = NULL;
1071 	SG(request_info).request_uri = NULL;
1072 	SG(request_info).content_type = NULL;
1073 	SG(request_info).content_length = 0;
1074 	SG(sapi_headers).http_response_code = 200;
1075 
1076 	/* script_path_translated being set is a good indication that
1077 	 * we are running in a cgi environment, since it is always
1078 	 * null otherwise.  otherwise, the filename
1079 	 * of the script will be retreived later via argc/argv */
1080 	if (script_path_translated) {
1081 		const char *auth;
1082 		char *content_length = sapi_cgibin_getenv("CONTENT_LENGTH", sizeof("CONTENT_LENGTH") - 1 TSRMLS_CC);
1083 		char *content_type = sapi_cgibin_getenv("CONTENT_TYPE", sizeof("CONTENT_TYPE") - 1 TSRMLS_CC);
1084 		char *env_path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO") - 1 TSRMLS_CC);
1085 		char *env_script_name = sapi_cgibin_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME") - 1 TSRMLS_CC);
1086 
1087 		/* Hack for buggy IIS that sets incorrect PATH_INFO */
1088 		char *env_server_software = sapi_cgibin_getenv("SERVER_SOFTWARE", sizeof("SERVER_SOFTWARE") - 1 TSRMLS_CC);
1089 		if (env_server_software &&
1090 			env_script_name &&
1091 			env_path_info &&
1092 			strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS") - 1) == 0 &&
1093 			strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
1094 		) {
1095 			env_path_info = _sapi_cgibin_putenv("ORIG_PATH_INFO", env_path_info TSRMLS_CC);
1096 			env_path_info += strlen(env_script_name);
1097 			if (*env_path_info == 0) {
1098 				env_path_info = NULL;
1099 			}
1100 			env_path_info = _sapi_cgibin_putenv("PATH_INFO", env_path_info TSRMLS_CC);
1101 		}
1102 
1103 #define APACHE_PROXY_FCGI_PREFIX "proxy:fcgi://"
1104 		/* Fix proxy URLs in SCRIPT_FILENAME generated by Apache mod_proxy_fcgi:
1105 		 *     proxy:fcgi://localhost:9000/some-dir/info.php/test?foo=bar
1106 		 * should be changed to:
1107 		 *     /some-dir/info.php/test
1108 		 * See: http://bugs.php.net/bug.php?id=54152
1109 		 *      https://issues.apache.org/bugzilla/show_bug.cgi?id=50851
1110 		 */
1111 		if (env_script_filename &&
1112 			strncasecmp(env_script_filename, APACHE_PROXY_FCGI_PREFIX, sizeof(APACHE_PROXY_FCGI_PREFIX) - 1) == 0) {
1113 			/* advance to first character of hostname */
1114 			char *p = env_script_filename + (sizeof(APACHE_PROXY_FCGI_PREFIX) - 1);
1115 			while (*p != '\0' && *p != '/') {
1116 				p++;	/* move past hostname and port */
1117 			}
1118 			if (*p != '\0') {
1119 				/* Copy path portion in place to avoid memory leak.  Note
1120 				 * that this also affects what script_path_translated points
1121 				 * to. */
1122 				memmove(env_script_filename, p, strlen(p) + 1);
1123 				apache_was_here = 1;
1124 			}
1125 			/* ignore query string if sent by Apache (RewriteRule) */
1126 			p = strchr(env_script_filename, '?');
1127 			if (p) {
1128 				*p =0;
1129 			}
1130 		}
1131 
1132 		if (CGIG(fix_pathinfo)) {
1133 			struct stat st;
1134 			char *real_path = NULL;
1135 			char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL") - 1 TSRMLS_CC);
1136 			char *env_document_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT") - 1 TSRMLS_CC);
1137 			char *orig_path_translated = env_path_translated;
1138 			char *orig_path_info = env_path_info;
1139 			char *orig_script_name = env_script_name;
1140 			char *orig_script_filename = env_script_filename;
1141 			int script_path_translated_len;
1142 
1143 			if (!env_document_root && PG(doc_root)) {
1144 				env_document_root = _sapi_cgibin_putenv("DOCUMENT_ROOT", PG(doc_root) TSRMLS_CC);
1145 				/* fix docroot */
1146 				TRANSLATE_SLASHES(env_document_root);
1147 			}
1148 
1149 			if (!apache_was_here && env_path_translated != NULL && env_redirect_url != NULL &&
1150 			    env_path_translated != script_path_translated &&
1151 			    strcmp(env_path_translated, script_path_translated) != 0) {
1152 				/*
1153 				 * pretty much apache specific.  If we have a redirect_url
1154 				 * then our script_filename and script_name point to the
1155 				 * php executable
1156 				 * we don't want to do this for the new mod_proxy_fcgi approach,
1157 				 * where redirect_url may also exist but the below will break
1158 				 * with rewrites to PATH_INFO, hence the !apache_was_here check
1159 				 */
1160 				script_path_translated = env_path_translated;
1161 				/* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
1162 				env_script_name = env_redirect_url;
1163 			}
1164 
1165 #ifdef __riscos__
1166 			/* Convert path to unix format*/
1167 			__riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
1168 			script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
1169 #endif
1170 
1171 			/*
1172 			 * if the file doesn't exist, try to extract PATH_INFO out
1173 			 * of it by stat'ing back through the '/'
1174 			 * this fixes url's like /info.php/test
1175 			 */
1176 			if (script_path_translated &&
1177 				(script_path_translated_len = strlen(script_path_translated)) > 0 &&
1178 				(script_path_translated[script_path_translated_len-1] == '/' ||
1179 #ifdef PHP_WIN32
1180 				script_path_translated[script_path_translated_len-1] == '\\' ||
1181 #endif
1182 				(real_path = tsrm_realpath(script_path_translated, NULL TSRMLS_CC)) == NULL)
1183 			) {
1184 				char *pt = estrndup(script_path_translated, script_path_translated_len);
1185 				int len = script_path_translated_len;
1186 				char *ptr;
1187 
1188 				if (pt) {
1189 					while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
1190 						*ptr = 0;
1191 						if (stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
1192 							/*
1193 							 * okay, we found the base script!
1194 							 * work out how many chars we had to strip off;
1195 							 * then we can modify PATH_INFO
1196 							 * accordingly
1197 							 *
1198 							 * we now have the makings of
1199 							 * PATH_INFO=/test
1200 							 * SCRIPT_FILENAME=/docroot/info.php
1201 							 *
1202 							 * we now need to figure out what docroot is.
1203 							 * if DOCUMENT_ROOT is set, this is easy, otherwise,
1204 							 * we have to play the game of hide and seek to figure
1205 							 * out what SCRIPT_NAME should be
1206 							 */
1207 							int ptlen = strlen(pt);
1208 							int slen = len - ptlen;
1209 							int pilen = env_path_info ? strlen(env_path_info) : 0;
1210 							int tflag = 0;
1211 							char *path_info;
1212 							if (apache_was_here) {
1213 								/* recall that PATH_INFO won't exist */
1214 								path_info = script_path_translated + ptlen;
1215 								tflag = (slen != 0 && (!orig_path_info || strcmp(orig_path_info, path_info) != 0));
1216 							} else {
1217 								path_info = env_path_info ? env_path_info + pilen - slen : NULL;
1218 								tflag = (orig_path_info != path_info);
1219 							}
1220 
1221 							if (tflag) {
1222 								if (orig_path_info) {
1223 									char old;
1224 
1225 									_sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
1226 									old = path_info[0];
1227 									path_info[0] = 0;
1228 									if (!orig_script_name ||
1229 										strcmp(orig_script_name, env_path_info) != 0) {
1230 										if (orig_script_name) {
1231 											_sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
1232 										}
1233 										SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_path_info TSRMLS_CC);
1234 									} else {
1235 										SG(request_info).request_uri = orig_script_name;
1236 									}
1237 									path_info[0] = old;
1238 								} else if (apache_was_here && env_script_name) {
1239 									/* Using mod_proxy_fcgi and ProxyPass, apache cannot set PATH_INFO
1240 									 * As we can extract PATH_INFO from PATH_TRANSLATED
1241 									 * it is probably also in SCRIPT_NAME and need to be removed
1242 									 */
1243 									int snlen = strlen(env_script_name);
1244 									if (snlen>slen && !strcmp(env_script_name+snlen-slen, path_info)) {
1245 										_sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
1246 										env_script_name[snlen-slen] = 0;
1247 										SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
1248 									}
1249 								}
1250 								env_path_info = _sapi_cgibin_putenv("PATH_INFO", path_info TSRMLS_CC);
1251 							}
1252 							if (!orig_script_filename ||
1253 								strcmp(orig_script_filename, pt) != 0) {
1254 								if (orig_script_filename) {
1255 									_sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
1256 								}
1257 								script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", pt TSRMLS_CC);
1258 							}
1259 							TRANSLATE_SLASHES(pt);
1260 
1261 							/* figure out docroot
1262 							 * SCRIPT_FILENAME minus SCRIPT_NAME
1263 							 */
1264 							if (env_document_root) {
1265 								int l = strlen(env_document_root);
1266 								int path_translated_len = 0;
1267 								char *path_translated = NULL;
1268 
1269 								if (l && env_document_root[l - 1] == '/') {
1270 									--l;
1271 								}
1272 
1273 								/* we have docroot, so we should have:
1274 								 * DOCUMENT_ROOT=/docroot
1275 								 * SCRIPT_FILENAME=/docroot/info.php
1276 								 */
1277 
1278 								/* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
1279 								path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
1280 								path_translated = (char *) emalloc(path_translated_len + 1);
1281 								memcpy(path_translated, env_document_root, l);
1282 								if (env_path_info) {
1283 									memcpy(path_translated + l, env_path_info, (path_translated_len - l));
1284 								}
1285 								path_translated[path_translated_len] = '\0';
1286 								if (orig_path_translated) {
1287 									_sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
1288 								}
1289 								env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
1290 								efree(path_translated);
1291 							} else if (	env_script_name &&
1292 										strstr(pt, env_script_name)
1293 							) {
1294 								/* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
1295 								int ptlen = strlen(pt) - strlen(env_script_name);
1296 								int path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
1297 								char *path_translated = NULL;
1298 
1299 								path_translated = (char *) emalloc(path_translated_len + 1);
1300 								memcpy(path_translated, pt, ptlen);
1301 								if (env_path_info) {
1302 									memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
1303 								}
1304 								path_translated[path_translated_len] = '\0';
1305 								if (orig_path_translated) {
1306 									_sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
1307 								}
1308 								env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
1309 								efree(path_translated);
1310 							}
1311 							break;
1312 						}
1313 					}
1314 				} else {
1315 					ptr = NULL;
1316 				}
1317 				if (!ptr) {
1318 					/*
1319 					 * if we stripped out all the '/' and still didn't find
1320 					 * a valid path... we will fail, badly. of course we would
1321 					 * have failed anyway... we output 'no input file' now.
1322 					 */
1323 					if (orig_script_filename) {
1324 						_sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
1325 					}
1326 					script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", NULL TSRMLS_CC);
1327 					SG(sapi_headers).http_response_code = 404;
1328 				}
1329 				if (!SG(request_info).request_uri) {
1330 					if (!orig_script_name ||
1331 						strcmp(orig_script_name, env_script_name) != 0) {
1332 						if (orig_script_name) {
1333 							_sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
1334 						}
1335 						SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
1336 					} else {
1337 						SG(request_info).request_uri = orig_script_name;
1338 					}
1339 				}
1340 				if (pt) {
1341 					efree(pt);
1342 				}
1343 			} else {
1344 				/* make sure original values are remembered in ORIG_ copies if we've changed them */
1345 				if (!orig_script_filename ||
1346 					(script_path_translated != orig_script_filename &&
1347 					strcmp(script_path_translated, orig_script_filename) != 0)) {
1348 					if (orig_script_filename) {
1349 						_sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
1350 					}
1351 					script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", script_path_translated TSRMLS_CC);
1352 				}
1353 				if (!apache_was_here && env_redirect_url) {
1354 					/* if we used PATH_TRANSLATED to work around Apache mod_fastcgi (but not mod_proxy_fcgi,
1355 					 * hence !apache_was_here) weirdness, strip info accordingly */
1356 					if (orig_path_info) {
1357 						_sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
1358 						_sapi_cgibin_putenv("PATH_INFO", NULL TSRMLS_CC);
1359 					}
1360 					if (orig_path_translated) {
1361 						_sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
1362 						_sapi_cgibin_putenv("PATH_TRANSLATED", NULL TSRMLS_CC);
1363 					}
1364 				}
1365 				if (env_script_name != orig_script_name) {
1366 					if (orig_script_name) {
1367 						_sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
1368 					}
1369 					SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
1370 				} else {
1371 					SG(request_info).request_uri = env_script_name;
1372 				}
1373 				free(real_path);
1374 			}
1375 		} else {
1376 			/* pre 4.3 behaviour, shouldn't be used but provides BC */
1377 			if (env_path_info) {
1378 				SG(request_info).request_uri = env_path_info;
1379 			} else {
1380 				SG(request_info).request_uri = env_script_name;
1381 			}
1382 			if (!CGIG(discard_path) && env_path_translated) {
1383 				script_path_translated = env_path_translated;
1384 			}
1385 		}
1386 
1387 		if (is_valid_path(script_path_translated)) {
1388 			SG(request_info).path_translated = estrdup(script_path_translated);
1389 		}
1390 
1391 		SG(request_info).request_method = sapi_cgibin_getenv("REQUEST_METHOD", sizeof("REQUEST_METHOD") - 1 TSRMLS_CC);
1392 		/* FIXME - Work out proto_num here */
1393 		SG(request_info).query_string = sapi_cgibin_getenv("QUERY_STRING", sizeof("QUERY_STRING") - 1 TSRMLS_CC);
1394 		SG(request_info).content_type = (content_type ? content_type : "" );
1395 		SG(request_info).content_length = (content_length ? atol(content_length) : 0);
1396 
1397 		/* The CGI RFC allows servers to pass on unvalidated Authorization data */
1398 		auth = sapi_cgibin_getenv("HTTP_AUTHORIZATION", sizeof("HTTP_AUTHORIZATION") - 1 TSRMLS_CC);
1399 		php_handle_auth_data(auth TSRMLS_CC);
1400 	}
1401 
1402 	/* INI stuff */
1403 	ini = sapi_cgibin_getenv("PHP_VALUE", sizeof("PHP_VALUE") - 1 TSRMLS_CC);
1404 	if (ini) {
1405 		int mode = ZEND_INI_USER;
1406 		char *tmp;
1407 		spprintf(&tmp, 0, "%s\n", ini);
1408 		zend_parse_ini_string(tmp, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t)fastcgi_ini_parser, &mode TSRMLS_CC);
1409 		efree(tmp);
1410 	}
1411 
1412 	ini = sapi_cgibin_getenv("PHP_ADMIN_VALUE", sizeof("PHP_ADMIN_VALUE") - 1 TSRMLS_CC);
1413 	if (ini) {
1414 		int mode = ZEND_INI_SYSTEM;
1415 		char *tmp;
1416 		spprintf(&tmp, 0, "%s\n", ini);
1417 		zend_parse_ini_string(tmp, 1, ZEND_INI_SCANNER_NORMAL, (zend_ini_parser_cb_t)fastcgi_ini_parser, &mode TSRMLS_CC);
1418 		efree(tmp);
1419 	}
1420 }
1421 /* }}} */
1422 
1423 static void fastcgi_ini_parser(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg TSRMLS_DC) /* {{{ */
1424 {
1425 	int *mode = (int *)arg;
1426 	char *key;
1427 	char *value = NULL;
1428 	struct key_value_s kv;
1429 
1430 	if (!mode || !arg1) return;
1431 
1432 	if (callback_type != ZEND_INI_PARSER_ENTRY) {
1433 		zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: only classic entries are allowed");
1434 		return;
1435 	}
1436 
1437 	key = Z_STRVAL_P(arg1);
1438 
1439 	if (!key || strlen(key) < 1) {
1440 		zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: empty key");
1441 		return;
1442 	}
1443 
1444 	if (arg2) {
1445 		value = Z_STRVAL_P(arg2);
1446 	}
1447 
1448 	if (!value) {
1449 		zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: empty value for key '%s'", key);
1450 		return;
1451 	}
1452 
1453 	kv.key = key;
1454 	kv.value = value;
1455 	kv.next = NULL;
1456 	if (fpm_php_apply_defines_ex(&kv, *mode) == -1) {
1457 		zlog(ZLOG_ERROR, "Passing INI directive through FastCGI: unable to set '%s'", key);
1458 	}
1459 }
1460 /* }}} */
1461 
1462 PHP_INI_BEGIN()
1463 	STD_PHP_INI_ENTRY("cgi.rfc2616_headers",     "0",  PHP_INI_ALL,    OnUpdateBool,   rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
1464 	STD_PHP_INI_ENTRY("cgi.nph",                 "0",  PHP_INI_ALL,    OnUpdateBool,   nph, php_cgi_globals_struct, php_cgi_globals)
1465 	STD_PHP_INI_ENTRY("cgi.force_redirect",      "1",  PHP_INI_SYSTEM, OnUpdateBool,   force_redirect, php_cgi_globals_struct, php_cgi_globals)
1466 	STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
1467 	STD_PHP_INI_ENTRY("cgi.fix_pathinfo",        "1",  PHP_INI_SYSTEM, OnUpdateBool,   fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
1468 	STD_PHP_INI_ENTRY("cgi.discard_path",        "0",  PHP_INI_SYSTEM, OnUpdateBool,   discard_path, php_cgi_globals_struct, php_cgi_globals)
1469 	STD_PHP_INI_ENTRY("fastcgi.logging",         "1",  PHP_INI_SYSTEM, OnUpdateBool,   fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
1470 	STD_PHP_INI_ENTRY("fastcgi.error_header",    NULL, PHP_INI_SYSTEM, OnUpdateString, error_header, php_cgi_globals_struct, php_cgi_globals)
1471 	STD_PHP_INI_ENTRY("fpm.config",    NULL, PHP_INI_SYSTEM, OnUpdateString, fpm_config, php_cgi_globals_struct, php_cgi_globals)
1472 PHP_INI_END()
1473 
1474 /* {{{ php_cgi_globals_ctor
1475  */
1476 static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals TSRMLS_DC)
1477 {
1478 	php_cgi_globals->rfc2616_headers = 0;
1479 	php_cgi_globals->nph = 0;
1480 	php_cgi_globals->force_redirect = 1;
1481 	php_cgi_globals->redirect_status_env = NULL;
1482 	php_cgi_globals->fix_pathinfo = 1;
1483 	php_cgi_globals->discard_path = 0;
1484 	php_cgi_globals->fcgi_logging = 1;
1485 	zend_hash_init(&php_cgi_globals->user_config_cache, 0, NULL, (dtor_func_t) user_config_cache_entry_dtor, 1);
1486 	php_cgi_globals->error_header = NULL;
1487 	php_cgi_globals->fpm_config = NULL;
1488 }
1489 /* }}} */
1490 
1491 /* {{{ PHP_MINIT_FUNCTION
1492  */
1493 static PHP_MINIT_FUNCTION(cgi)
1494 {
1495 #ifdef ZTS
1496 	ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1497 #else
1498 	php_cgi_globals_ctor(&php_cgi_globals TSRMLS_CC);
1499 #endif
1500 	REGISTER_INI_ENTRIES();
1501 	return SUCCESS;
1502 }
1503 /* }}} */
1504 
1505 /* {{{ PHP_MSHUTDOWN_FUNCTION
1506  */
1507 static PHP_MSHUTDOWN_FUNCTION(cgi)
1508 {
1509 	zend_hash_destroy(&CGIG(user_config_cache));
1510 
1511 	UNREGISTER_INI_ENTRIES();
1512 	return SUCCESS;
1513 }
1514 /* }}} */
1515 
1516 /* {{{ PHP_MINFO_FUNCTION
1517  */
1518 static PHP_MINFO_FUNCTION(cgi)
1519 {
1520 	php_info_print_table_start();
1521 	php_info_print_table_row(2, "php-fpm", "active");
1522 	php_info_print_table_end();
1523 
1524 	DISPLAY_INI_ENTRIES();
1525 }
1526 /* }}} */
1527 
1528 PHP_FUNCTION(fastcgi_finish_request) /* {{{ */
1529 {
1530 	fcgi_request *request = (fcgi_request*) SG(server_context);
1531 
1532 	if (request->fd >= 0) {
1533 
1534 		php_output_end_all(TSRMLS_C);
1535 		php_header(TSRMLS_C);
1536 
1537 		fcgi_flush(request, 1);
1538 		fcgi_close(request, 0, 0);
1539 		RETURN_TRUE;
1540 	}
1541 
1542 	RETURN_FALSE;
1543 
1544 }
1545 /* }}} */
1546 
1547 static const zend_function_entry cgi_fcgi_sapi_functions[] = {
1548 	PHP_FE(fastcgi_finish_request,              NULL)
1549 	{NULL, NULL, NULL}
1550 };
1551 
1552 static zend_module_entry cgi_module_entry = {
1553 	STANDARD_MODULE_HEADER,
1554 	"cgi-fcgi",
1555 	cgi_fcgi_sapi_functions,
1556 	PHP_MINIT(cgi),
1557 	PHP_MSHUTDOWN(cgi),
1558 	NULL,
1559 	NULL,
1560 	PHP_MINFO(cgi),
1561 	NO_VERSION_YET,
1562 	STANDARD_MODULE_PROPERTIES
1563 };
1564 
1565 /* {{{ main
1566  */
1567 int main(int argc, char *argv[])
1568 {
1569 	int exit_status = FPM_EXIT_OK;
1570 	int cgi = 0, c, use_extended_info = 0;
1571 	zend_file_handle file_handle;
1572 
1573 	/* temporary locals */
1574 	int orig_optind = php_optind;
1575 	char *orig_optarg = php_optarg;
1576 	int ini_entries_len = 0;
1577 	/* end of temporary locals */
1578 
1579 #ifdef ZTS
1580 	void ***tsrm_ls;
1581 #endif
1582 
1583 	int max_requests = 500;
1584 	int requests = 0;
1585 	int fcgi_fd = 0;
1586 	fcgi_request request;
1587 	char *fpm_config = NULL;
1588 	char *fpm_prefix = NULL;
1589 	char *fpm_pid = NULL;
1590 	int test_conf = 0;
1591 	int force_daemon = -1;
1592 	int php_information = 0;
1593 	int php_allow_to_run_as_root = 0;
1594 
1595 #ifdef HAVE_SIGNAL_H
1596 #if defined(SIGPIPE) && defined(SIG_IGN)
1597 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1598 								that sockets created via fsockopen()
1599 								don't kill PHP if the remote site
1600 								closes it.  in apache|apxs mode apache
1601 								does that for us!  thies@thieso.net
1602 								20000419 */
1603 #endif
1604 #endif
1605 
1606 #ifdef ZTS
1607 	tsrm_startup(1, 1, 0, NULL);
1608 	tsrm_ls = ts_resource(0);
1609 #endif
1610 
1611 	sapi_startup(&cgi_sapi_module);
1612 	cgi_sapi_module.php_ini_path_override = NULL;
1613 	cgi_sapi_module.php_ini_ignore_cwd = 1;
1614 
1615 	fcgi_init();
1616 
1617 #ifdef PHP_WIN32
1618 	_fmode = _O_BINARY; /* sets default for file streams to binary */
1619 	setmode(_fileno(stdin),  O_BINARY);	/* make the stdio mode be binary */
1620 	setmode(_fileno(stdout), O_BINARY);	/* make the stdio mode be binary */
1621 	setmode(_fileno(stderr), O_BINARY);	/* make the stdio mode be binary */
1622 #endif
1623 
1624 	while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1625 		switch (c) {
1626 			case 'c':
1627 				if (cgi_sapi_module.php_ini_path_override) {
1628 					free(cgi_sapi_module.php_ini_path_override);
1629 				}
1630 				cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1631 				break;
1632 
1633 			case 'n':
1634 				cgi_sapi_module.php_ini_ignore = 1;
1635 				break;
1636 
1637 			case 'd': {
1638 				/* define ini entries on command line */
1639 				int len = strlen(php_optarg);
1640 				char *val;
1641 
1642 				if ((val = strchr(php_optarg, '='))) {
1643 					val++;
1644 					if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
1645 						cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
1646 						memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
1647 						ini_entries_len += (val - php_optarg);
1648 						memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
1649 						ini_entries_len++;
1650 						memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
1651 						ini_entries_len += len - (val - php_optarg);
1652 						memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
1653 						ini_entries_len += sizeof("\n\0\"") - 2;
1654 					} else {
1655 						cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
1656 						memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1657 						memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
1658 						ini_entries_len += len + sizeof("\n\0") - 2;
1659 					}
1660 				} else {
1661 					cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
1662 					memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1663 					memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
1664 					ini_entries_len += len + sizeof("=1\n\0") - 2;
1665 				}
1666 				break;
1667 			}
1668 
1669 			case 'y':
1670 				fpm_config = php_optarg;
1671 				break;
1672 
1673 			case 'p':
1674 				fpm_prefix = php_optarg;
1675 				break;
1676 
1677 			case 'g':
1678 				fpm_pid = php_optarg;
1679 				break;
1680 
1681 			case 'e': /* enable extended info output */
1682 				use_extended_info = 1;
1683 				break;
1684 
1685 			case 't':
1686 				test_conf++;
1687 				break;
1688 
1689 			case 'm': /* list compiled in modules */
1690 				cgi_sapi_module.startup(&cgi_sapi_module);
1691 				php_output_activate(TSRMLS_C);
1692 				SG(headers_sent) = 1;
1693 				php_printf("[PHP Modules]\n");
1694 				print_modules(TSRMLS_C);
1695 				php_printf("\n[Zend Modules]\n");
1696 				print_extensions(TSRMLS_C);
1697 				php_printf("\n");
1698 				php_output_end_all(TSRMLS_C);
1699 				php_output_deactivate(TSRMLS_C);
1700 				fcgi_shutdown();
1701 				exit_status = FPM_EXIT_OK;
1702 				goto out;
1703 
1704 			case 'i': /* php info & quit */
1705 				php_information = 1;
1706 				break;
1707 
1708 			case 'R': /* allow to run as root */
1709 				php_allow_to_run_as_root = 1;
1710 				break;
1711 
1712 			case 'D': /* daemonize */
1713 				force_daemon = 1;
1714 				break;
1715 
1716 			case 'F': /* nodaemonize */
1717 				force_daemon = 0;
1718 				break;
1719 
1720 			default:
1721 			case 'h':
1722 			case '?':
1723 				cgi_sapi_module.startup(&cgi_sapi_module);
1724 				php_output_activate(TSRMLS_C);
1725 				SG(headers_sent) = 1;
1726 				php_cgi_usage(argv[0]);
1727 				php_output_end_all(TSRMLS_C);
1728 				php_output_deactivate(TSRMLS_C);
1729 				fcgi_shutdown();
1730 				exit_status = (c == 'h') ? FPM_EXIT_OK : FPM_EXIT_USAGE;
1731 				goto out;
1732 
1733 			case 'v': /* show php version & quit */
1734 				cgi_sapi_module.startup(&cgi_sapi_module);
1735 				if (php_request_startup(TSRMLS_C) == FAILURE) {
1736 					SG(server_context) = NULL;
1737 					php_module_shutdown(TSRMLS_C);
1738 					return FPM_EXIT_SOFTWARE;
1739 				}
1740 				SG(headers_sent) = 1;
1741 				SG(request_info).no_headers = 1;
1742 
1743 #if ZEND_DEBUG
1744 				php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2015 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__,        __TIME__, get_zend_version());
1745 #else
1746 				php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2015 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__,      get_zend_version());
1747 #endif
1748 				php_request_shutdown((void *) 0);
1749 				fcgi_shutdown();
1750 				exit_status = FPM_EXIT_OK;
1751 				goto out;
1752 		}
1753 	}
1754 
1755 	if (php_information) {
1756 		cgi_sapi_module.phpinfo_as_text = 1;
1757 		cgi_sapi_module.startup(&cgi_sapi_module);
1758 		if (php_request_startup(TSRMLS_C) == FAILURE) {
1759 			SG(server_context) = NULL;
1760 			php_module_shutdown(TSRMLS_C);
1761 			return FPM_EXIT_SOFTWARE;
1762 		}
1763 		SG(headers_sent) = 1;
1764 		SG(request_info).no_headers = 1;
1765 		php_print_info(0xFFFFFFFF TSRMLS_CC);
1766 		php_request_shutdown((void *) 0);
1767 		fcgi_shutdown();
1768 		exit_status = FPM_EXIT_OK;
1769 		goto out;
1770 	}
1771 
1772 	/* No other args are permitted here as there is no interactive mode */
1773 	if (argc != php_optind) {
1774 		cgi_sapi_module.startup(&cgi_sapi_module);
1775 		php_output_activate(TSRMLS_C);
1776 		SG(headers_sent) = 1;
1777 		php_cgi_usage(argv[0]);
1778 		php_output_end_all(TSRMLS_C);
1779 		php_output_deactivate(TSRMLS_C);
1780 		fcgi_shutdown();
1781 		exit_status = FPM_EXIT_USAGE;
1782 		goto out;
1783 	}
1784 
1785 	php_optind = orig_optind;
1786 	php_optarg = orig_optarg;
1787 
1788 #ifdef ZTS
1789 	SG(request_info).path_translated = NULL;
1790 #endif
1791 
1792 	cgi_sapi_module.additional_functions = additional_functions;
1793 	cgi_sapi_module.executable_location = argv[0];
1794 
1795 	/* startup after we get the above ini override se we get things right */
1796 	if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1797 #ifdef ZTS
1798 		tsrm_shutdown();
1799 #endif
1800 		return FPM_EXIT_SOFTWARE;
1801 	}
1802 
1803 	if (use_extended_info) {
1804 		CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
1805 	}
1806 
1807 	/* check force_cgi after startup, so we have proper output */
1808 	if (cgi && CGIG(force_redirect)) {
1809 		/* Apache will generate REDIRECT_STATUS,
1810 		 * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
1811 		 * redirect.so and installation instructions available from
1812 		 * http://www.koehntopp.de/php.
1813 		 *   -- kk@netuse.de
1814 		 */
1815 		if (!getenv("REDIRECT_STATUS") &&
1816 			!getenv ("HTTP_REDIRECT_STATUS") &&
1817 			/* this is to allow a different env var to be configured
1818 			 * in case some server does something different than above */
1819 			(!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
1820 		) {
1821 			zend_try {
1822 				SG(sapi_headers).http_response_code = 400;
1823 				PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1824 <p>This PHP CGI binary was compiled with force-cgi-redirect enabled.  This\n\
1825 means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1826 set, e.g. via an Apache Action directive.</p>\n\
1827 <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1828 manual page for CGI security</a>.</p>\n\
1829 <p>For more information about changing this behaviour or re-enabling this webserver,\n\
1830 consult the installation file that came with this distribution, or visit \n\
1831 <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1832 			} zend_catch {
1833 			} zend_end_try();
1834 #if defined(ZTS) && !defined(PHP_DEBUG)
1835 			/* XXX we're crashing here in msvc6 debug builds at
1836 			 * php_message_handler_for_zend:839 because
1837 			 * SG(request_info).path_translated is an invalid pointer.
1838 			 * It still happens even though I set it to null, so something
1839 			 * weird is going on.
1840 			 */
1841 			tsrm_shutdown();
1842 #endif
1843 			return FPM_EXIT_SOFTWARE;
1844 		}
1845 	}
1846 
1847 	if (0 > fpm_init(argc, argv, fpm_config ? fpm_config : CGIG(fpm_config), fpm_prefix, fpm_pid, test_conf, php_allow_to_run_as_root, force_daemon)) {
1848 
1849 		if (fpm_globals.send_config_pipe[1]) {
1850 			int writeval = 0;
1851 			zlog(ZLOG_DEBUG, "Sending \"0\" (error) to parent via fd=%d", fpm_globals.send_config_pipe[1]);
1852 			write(fpm_globals.send_config_pipe[1], &writeval, sizeof(writeval));
1853 			close(fpm_globals.send_config_pipe[1]);
1854 		}
1855 		return FPM_EXIT_CONFIG;
1856 	}
1857 
1858 	if (fpm_globals.send_config_pipe[1]) {
1859 		int writeval = 1;
1860 		zlog(ZLOG_DEBUG, "Sending \"1\" (OK) to parent via fd=%d", fpm_globals.send_config_pipe[1]);
1861 		write(fpm_globals.send_config_pipe[1], &writeval, sizeof(writeval));
1862 		close(fpm_globals.send_config_pipe[1]);
1863 	}
1864 	fpm_is_running = 1;
1865 
1866 	fcgi_fd = fpm_run(&max_requests);
1867 	parent = 0;
1868 
1869 	/* onced forked tell zlog to also send messages through sapi_cgi_log_fastcgi() */
1870 	zlog_set_external_logger(sapi_cgi_log_fastcgi);
1871 
1872 	/* make php call us to get _ENV vars */
1873 	php_php_import_environment_variables = php_import_environment_variables;
1874 	php_import_environment_variables = cgi_php_import_environment_variables;
1875 
1876 	/* library is already initialized, now init our request */
1877 	fcgi_init_request(&request, fcgi_fd);
1878 
1879 	zend_first_try {
1880 		while (fcgi_accept_request(&request) >= 0) {
1881 			char *primary_script = NULL;
1882 			request_body_fd = -1;
1883 			SG(server_context) = (void *) &request;
1884 			init_request_info(TSRMLS_C);
1885 			CG(interactive) = 0;
1886 
1887 			fpm_request_info();
1888 
1889 			/* request startup only after we've done all we can to
1890 			 *            get path_translated */
1891 			if (php_request_startup(TSRMLS_C) == FAILURE) {
1892 				fcgi_finish_request(&request, 1);
1893 				SG(server_context) = NULL;
1894 				php_module_shutdown(TSRMLS_C);
1895 				return FPM_EXIT_SOFTWARE;
1896 			}
1897 
1898 			/* check if request_method has been sent.
1899 			 * if not, it's certainly not an HTTP over fcgi request */
1900 			if (!SG(request_info).request_method) {
1901 				goto fastcgi_request_done;
1902 			}
1903 
1904 			if (fpm_status_handle_request(TSRMLS_C)) {
1905 				goto fastcgi_request_done;
1906 			}
1907 
1908 			/* If path_translated is NULL, terminate here with a 404 */
1909 			if (!SG(request_info).path_translated) {
1910 				zend_try {
1911 					zlog(ZLOG_DEBUG, "Primary script unknown");
1912 					SG(sapi_headers).http_response_code = 404;
1913 					PUTS("File not found.\n");
1914 				} zend_catch {
1915 				} zend_end_try();
1916 				goto fastcgi_request_done;
1917 			}
1918 
1919 			if (fpm_php_limit_extensions(SG(request_info).path_translated)) {
1920 				SG(sapi_headers).http_response_code = 403;
1921 				PUTS("Access denied.\n");
1922 				goto fastcgi_request_done;
1923 			}
1924 
1925 			/*
1926 			 * have to duplicate SG(request_info).path_translated to be able to log errrors
1927 			 * php_fopen_primary_script seems to delete SG(request_info).path_translated on failure
1928 			 */
1929 			primary_script = estrdup(SG(request_info).path_translated);
1930 
1931 			/* path_translated exists, we can continue ! */
1932 			if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
1933 				zend_try {
1934 					zlog(ZLOG_ERROR, "Unable to open primary script: %s (%s)", primary_script, strerror(errno));
1935 					if (errno == EACCES) {
1936 						SG(sapi_headers).http_response_code = 403;
1937 						PUTS("Access denied.\n");
1938 					} else {
1939 						SG(sapi_headers).http_response_code = 404;
1940 						PUTS("No input file specified.\n");
1941 					}
1942 				} zend_catch {
1943 				} zend_end_try();
1944 				/* we want to serve more requests if this is fastcgi
1945 				 * so cleanup and continue, request shutdown is
1946 				 * handled later */
1947 
1948 				goto fastcgi_request_done;
1949 			}
1950 
1951 			fpm_request_executing();
1952 
1953 			php_execute_script(&file_handle TSRMLS_CC);
1954 
1955 fastcgi_request_done:
1956 			if (primary_script) {
1957 				efree(primary_script);
1958 			}
1959 
1960 			if (request_body_fd != -1) {
1961 				close(request_body_fd);
1962 			}
1963 			request_body_fd = -2;
1964 
1965 			if (EG(exit_status) == 255) {
1966 				if (CGIG(error_header) && *CGIG(error_header)) {
1967 					sapi_header_line ctr = {0};
1968 
1969 					ctr.line = CGIG(error_header);
1970 					ctr.line_len = strlen(CGIG(error_header));
1971 					sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
1972 				}
1973 			}
1974 
1975 			fpm_request_end(TSRMLS_C);
1976 			fpm_log_write(NULL TSRMLS_CC);
1977 
1978 			STR_FREE(SG(request_info).path_translated);
1979 			SG(request_info).path_translated = NULL;
1980 
1981 			php_request_shutdown((void *) 0);
1982 
1983 			requests++;
1984 			if (max_requests && (requests == max_requests)) {
1985 				fcgi_finish_request(&request, 1);
1986 				break;
1987 			}
1988 			/* end of fastcgi loop */
1989 		}
1990 		fcgi_shutdown();
1991 
1992 		if (cgi_sapi_module.php_ini_path_override) {
1993 			free(cgi_sapi_module.php_ini_path_override);
1994 		}
1995 		if (cgi_sapi_module.ini_entries) {
1996 			free(cgi_sapi_module.ini_entries);
1997 		}
1998 	} zend_catch {
1999 		exit_status = FPM_EXIT_SOFTWARE;
2000 	} zend_end_try();
2001 
2002 out:
2003 
2004 	SG(server_context) = NULL;
2005 	if (parent) {
2006 		php_module_shutdown(TSRMLS_C);
2007 		sapi_shutdown();
2008 	}
2009 
2010 #ifdef ZTS
2011 	tsrm_shutdown();
2012 #endif
2013 
2014 #if defined(PHP_WIN32) && ZEND_DEBUG && 0
2015 	_CrtDumpMemoryLeaks();
2016 #endif
2017 
2018 	return exit_status;
2019 }
2020 /* }}} */
2021 
2022 /*
2023  * Local variables:
2024  * tab-width: 4
2025  * c-basic-offset: 4
2026  * End:
2027  * vim600: sw=4 ts=4 fdm=marker
2028  * vim<600: sw=4 ts=4
2029  */
2030