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