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