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