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