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