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