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