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