1 /*
2 +----------------------------------------------------------------------+
3 | PHP Version 7 |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 1997-2018 The PHP Group |
6 +----------------------------------------------------------------------+
7 | This source file is subject to version 3.01 of the PHP license, |
8 | that is bundled with this package in the file LICENSE, and is |
9 | available through the world-wide-web at the following url: |
10 | http://www.php.net/license/3_01.txt |
11 | If you did not receive a copy of the PHP license and are unable to |
12 | obtain it through the world-wide-web, please send a note to |
13 | license@php.net so we can mail you a copy immediately. |
14 +----------------------------------------------------------------------+
15 | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
16 | Stig Bakken <ssb@php.net> |
17 | Zeev Suraski <zeev@php.net> |
18 | FastCGI: Ben Mansell <php@slimyhorror.com> |
19 | Shane Caraveo <shane@caraveo.com> |
20 | Dmitry Stogov <dmitry@php.net> |
21 +----------------------------------------------------------------------+
22 */
23
24 #include "php.h"
25 #include "php_globals.h"
26 #include "php_variables.h"
27 #include "zend_modules.h"
28
29 #include "SAPI.h"
30
31 #include <stdio.h>
32
33 #ifdef PHP_WIN32
34 # include "win32/time.h"
35 # include "win32/signal.h"
36 # include "win32/winutil.h"
37 # include <process.h>
38 #endif
39
40 #if HAVE_SYS_TIME_H
41 # include <sys/time.h>
42 #endif
43
44 #if HAVE_UNISTD_H
45 # include <unistd.h>
46 #endif
47
48 #if HAVE_SIGNAL_H
49 # include <signal.h>
50 #endif
51
52 #if HAVE_SETLOCALE
53 # include <locale.h>
54 #endif
55
56 #if HAVE_SYS_TYPES_H
57 # include <sys/types.h>
58 #endif
59
60 #if HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63
64 #include "zend.h"
65 #include "zend_extensions.h"
66 #include "php_ini.h"
67 #include "php_globals.h"
68 #include "php_main.h"
69 #include "fopen_wrappers.h"
70 #include "http_status_codes.h"
71 #include "ext/standard/php_standard.h"
72 #include "ext/standard/url.h"
73
74 #ifdef PHP_WIN32
75 # include <io.h>
76 # include <fcntl.h>
77 # include "win32/php_registry.h"
78 #endif
79
80 #ifdef __riscos__
81 # include <unixlib/local.h>
82 int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
83 #endif
84
85 #include "zend_compile.h"
86 #include "zend_execute.h"
87 #include "zend_highlight.h"
88
89 #include "php_getopt.h"
90
91 #include "fastcgi.h"
92
93 #if defined(PHP_WIN32) && defined(HAVE_OPENSSL)
94 # include "openssl/applink.c"
95 #endif
96
97 #ifdef HAVE_VALGRIND
98 # include "valgrind/callgrind.h"
99 #endif
100
101 #ifndef PHP_WIN32
102 /* XXX this will need to change later when threaded fastcgi is implemented. shane */
103 struct sigaction act, old_term, old_quit, old_int;
104 #endif
105
106 static void (*php_php_import_environment_variables)(zval *array_ptr);
107
108 /* these globals used for forking children on unix systems */
109 /**
110 * Number of child processes that will get created to service requests
111 */
112 static int children = 0;
113
114
115 /**
116 * Set to non-zero if we are the parent process
117 */
118 static int parent = 1;
119
120 #ifndef PHP_WIN32
121 /* Did parent received exit signals SIG_TERM/SIG_INT/SIG_QUIT */
122 static int exit_signal = 0;
123
124 /* Is Parent waiting for children to exit */
125 static int parent_waiting = 0;
126
127 /**
128 * Process group
129 */
130 static pid_t pgroup;
131 #endif
132
133 #define PHP_MODE_STANDARD 1
134 #define PHP_MODE_HIGHLIGHT 2
135 #define PHP_MODE_LINT 4
136 #define PHP_MODE_STRIP 5
137
138 static char *php_optarg = NULL;
139 static int php_optind = 1;
140 static zend_module_entry cgi_module_entry;
141
142 static const opt_struct OPTIONS[] = {
143 {'a', 0, "interactive"},
144 {'b', 1, "bindpath"},
145 {'C', 0, "no-chdir"},
146 {'c', 1, "php-ini"},
147 {'d', 1, "define"},
148 {'e', 0, "profile-info"},
149 {'f', 1, "file"},
150 {'h', 0, "help"},
151 {'i', 0, "info"},
152 {'l', 0, "syntax-check"},
153 {'m', 0, "modules"},
154 {'n', 0, "no-php-ini"},
155 {'q', 0, "no-header"},
156 {'s', 0, "syntax-highlight"},
157 {'s', 0, "syntax-highlighting"},
158 {'w', 0, "strip"},
159 {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
160 {'v', 0, "version"},
161 {'z', 1, "zend-extension"},
162 {'T', 1, "timing"},
163 {'-', 0, NULL} /* end of args */
164 };
165
166 typedef struct _php_cgi_globals_struct {
167 HashTable user_config_cache;
168 char *redirect_status_env;
169 zend_bool rfc2616_headers;
170 zend_bool nph;
171 zend_bool check_shebang_line;
172 zend_bool fix_pathinfo;
173 zend_bool force_redirect;
174 zend_bool discard_path;
175 zend_bool fcgi_logging;
176 #ifdef PHP_WIN32
177 zend_bool impersonate;
178 #endif
179 } php_cgi_globals_struct;
180
181 /* {{{ user_config_cache
182 *
183 * Key for each cache entry is dirname(PATH_TRANSLATED).
184 *
185 * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
186 * the path starting from doc_root throught to dirname(PATH_TRANSLATED). There is no point
187 * storing per-file entries as it would not be possible to detect added / deleted entries
188 * between separate files.
189 */
190 typedef struct _user_config_cache_entry {
191 time_t expires;
192 HashTable *user_config;
193 } user_config_cache_entry;
194
user_config_cache_entry_dtor(zval * el)195 static void user_config_cache_entry_dtor(zval *el)
196 {
197 user_config_cache_entry *entry = (user_config_cache_entry *)Z_PTR_P(el);
198 zend_hash_destroy(entry->user_config);
199 free(entry->user_config);
200 free(entry);
201 }
202 /* }}} */
203
204 #ifdef ZTS
205 static int php_cgi_globals_id;
206 #define CGIG(v) ZEND_TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
207 #if defined(PHP_WIN32)
208 ZEND_TSRMLS_CACHE_DEFINE()
209 #endif
210 #else
211 static php_cgi_globals_struct php_cgi_globals;
212 #define CGIG(v) (php_cgi_globals.v)
213 #endif
214
215 #ifdef PHP_WIN32
216 #define TRANSLATE_SLASHES(path) \
217 { \
218 char *tmp = path; \
219 while (*tmp) { \
220 if (*tmp == '\\') *tmp = '/'; \
221 tmp++; \
222 } \
223 }
224 #else
225 #define TRANSLATE_SLASHES(path)
226 #endif
227
228 #ifdef PHP_WIN32
229 #define WIN32_MAX_SPAWN_CHILDREN 64
230 HANDLE kid_cgi_ps[WIN32_MAX_SPAWN_CHILDREN];
231 int kids, cleaning_up = 0;
232 HANDLE job = NULL;
233 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = { 0 };
234 CRITICAL_SECTION cleanup_lock;
235 #endif
236
237 #ifndef HAVE_ATTRIBUTE_WEAK
fcgi_log(int type,const char * format,...)238 static void fcgi_log(int type, const char *format, ...) {
239 va_list ap;
240
241 va_start(ap, format);
242 vfprintf(stderr, format, ap);
243 va_end(ap);
244 }
245 #endif
246
print_module_info(zval * element)247 static int print_module_info(zval *element)
248 {
249 zend_module_entry *module = Z_PTR_P(element);
250 php_printf("%s\n", module->name);
251 return ZEND_HASH_APPLY_KEEP;
252 }
253
module_name_cmp(const void * a,const void * b)254 static int module_name_cmp(const void *a, const void *b)
255 {
256 Bucket *f = (Bucket *) a;
257 Bucket *s = (Bucket *) b;
258
259 return strcasecmp( ((zend_module_entry *)Z_PTR(f->val))->name,
260 ((zend_module_entry *)Z_PTR(s->val))->name);
261 }
262
print_modules(void)263 static void print_modules(void)
264 {
265 HashTable sorted_registry;
266
267 zend_hash_init(&sorted_registry, 64, NULL, NULL, 1);
268 zend_hash_copy(&sorted_registry, &module_registry, NULL);
269 zend_hash_sort(&sorted_registry, module_name_cmp, 0);
270 zend_hash_apply(&sorted_registry, print_module_info);
271 zend_hash_destroy(&sorted_registry);
272 }
273
print_extension_info(zend_extension * ext,void * arg)274 static int print_extension_info(zend_extension *ext, void *arg)
275 {
276 php_printf("%s\n", ext->name);
277 return 0;
278 }
279
extension_name_cmp(const zend_llist_element ** f,const zend_llist_element ** s)280 static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s)
281 {
282 zend_extension *fe = (zend_extension*)(*f)->data;
283 zend_extension *se = (zend_extension*)(*s)->data;
284 return strcmp(fe->name, se->name);
285 }
286
print_extensions(void)287 static void print_extensions(void)
288 {
289 zend_llist sorted_exts;
290
291 zend_llist_copy(&sorted_exts, &zend_extensions);
292 sorted_exts.dtor = NULL;
293 zend_llist_sort(&sorted_exts, extension_name_cmp);
294 zend_llist_apply_with_argument(&sorted_exts, (llist_apply_with_arg_func_t) print_extension_info, NULL);
295 zend_llist_destroy(&sorted_exts);
296 }
297
298 #ifndef STDOUT_FILENO
299 #define STDOUT_FILENO 1
300 #endif
301
sapi_cgi_single_write(const char * str,size_t str_length)302 static inline size_t sapi_cgi_single_write(const char *str, size_t str_length)
303 {
304 #ifdef PHP_WRITE_STDOUT
305 int ret;
306
307 ret = write(STDOUT_FILENO, str, str_length);
308 if (ret <= 0) return 0;
309 return ret;
310 #else
311 size_t ret;
312
313 ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
314 return ret;
315 #endif
316 }
317
sapi_cgi_ub_write(const char * str,size_t str_length)318 static size_t sapi_cgi_ub_write(const char *str, size_t str_length)
319 {
320 const char *ptr = str;
321 size_t remaining = str_length;
322 size_t ret;
323
324 while (remaining > 0) {
325 ret = sapi_cgi_single_write(ptr, remaining);
326 if (!ret) {
327 php_handle_aborted_connection();
328 return str_length - remaining;
329 }
330 ptr += ret;
331 remaining -= ret;
332 }
333
334 return str_length;
335 }
336
sapi_fcgi_ub_write(const char * str,size_t str_length)337 static size_t sapi_fcgi_ub_write(const char *str, size_t str_length)
338 {
339 const char *ptr = str;
340 size_t remaining = str_length;
341 fcgi_request *request = (fcgi_request*) SG(server_context);
342
343 while (remaining > 0) {
344 int to_write = remaining > INT_MAX ? INT_MAX : (int)remaining;
345 int ret = fcgi_write(request, FCGI_STDOUT, ptr, to_write);
346
347 if (ret <= 0) {
348 php_handle_aborted_connection();
349 return str_length - remaining;
350 }
351 ptr += ret;
352 remaining -= ret;
353 }
354
355 return str_length;
356 }
357
sapi_cgi_flush(void * server_context)358 static void sapi_cgi_flush(void *server_context)
359 {
360 if (fflush(stdout) == EOF) {
361 php_handle_aborted_connection();
362 }
363 }
364
sapi_fcgi_flush(void * server_context)365 static void sapi_fcgi_flush(void *server_context)
366 {
367 fcgi_request *request = (fcgi_request*) server_context;
368
369 if (
370 !parent &&
371 request && !fcgi_flush(request, 0)) {
372
373 php_handle_aborted_connection();
374 }
375 }
376
377 #define SAPI_CGI_MAX_HEADER_LENGTH 1024
378
sapi_cgi_send_headers(sapi_headers_struct * sapi_headers)379 static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers)
380 {
381 sapi_header_struct *h;
382 zend_llist_position pos;
383 zend_bool ignore_status = 0;
384 int response_status = SG(sapi_headers).http_response_code;
385
386 if (SG(request_info).no_headers == 1) {
387 return SAPI_HEADER_SENT_SUCCESSFULLY;
388 }
389
390 if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
391 {
392 int len;
393 zend_bool has_status = 0;
394 char buf[SAPI_CGI_MAX_HEADER_LENGTH];
395
396 if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
397 char *s;
398 len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
399 if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
400 response_status = atoi((s + 1));
401 }
402
403 if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
404 len = SAPI_CGI_MAX_HEADER_LENGTH;
405 }
406
407 } else {
408 char *s;
409
410 if (SG(sapi_headers).http_status_line &&
411 (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
412 (s - SG(sapi_headers).http_status_line) >= 5 &&
413 strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
414 ) {
415 len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
416 response_status = atoi((s + 1));
417 } else {
418 h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
419 while (h) {
420 if (h->header_len > sizeof("Status:")-1 &&
421 strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
422 ) {
423 has_status = 1;
424 break;
425 }
426 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
427 }
428 if (!has_status) {
429 http_response_status_code_pair *err = (http_response_status_code_pair*)http_status_map;
430
431 while (err->code != 0) {
432 if (err->code == SG(sapi_headers).http_response_code) {
433 break;
434 }
435 err++;
436 }
437 if (err->str) {
438 len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->str);
439 } else {
440 len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
441 }
442 }
443 }
444 }
445
446 if (!has_status) {
447 PHPWRITE_H(buf, len);
448 ignore_status = 1;
449 }
450 }
451
452 h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
453 while (h) {
454 /* prevent CRLFCRLF */
455 if (h->header_len) {
456 if (h->header_len > sizeof("Status:")-1 &&
457 strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
458 ) {
459 if (!ignore_status) {
460 ignore_status = 1;
461 PHPWRITE_H(h->header, h->header_len);
462 PHPWRITE_H("\r\n", 2);
463 }
464 } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
465 strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
466 ) {
467 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
468 continue;
469 } else {
470 PHPWRITE_H(h->header, h->header_len);
471 PHPWRITE_H("\r\n", 2);
472 }
473 }
474 h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
475 }
476 PHPWRITE_H("\r\n", 2);
477
478 return SAPI_HEADER_SENT_SUCCESSFULLY;
479 }
480
481 #ifndef STDIN_FILENO
482 # define STDIN_FILENO 0
483 #endif
484
sapi_cgi_read_post(char * buffer,size_t count_bytes)485 static size_t sapi_cgi_read_post(char *buffer, size_t count_bytes)
486 {
487 size_t read_bytes = 0;
488 int tmp_read_bytes;
489 size_t remaining_bytes;
490
491 assert(SG(request_info).content_length >= SG(read_post_bytes));
492
493 remaining_bytes = (size_t)(SG(request_info).content_length - SG(read_post_bytes));
494
495 count_bytes = MIN(count_bytes, remaining_bytes);
496 while (read_bytes < count_bytes) {
497 #ifdef PHP_WIN32
498 size_t diff = count_bytes - read_bytes;
499 unsigned int to_read = (diff > UINT_MAX) ? UINT_MAX : (unsigned int)diff;
500
501 tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, to_read);
502 #else
503 tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes);
504 #endif
505 if (tmp_read_bytes <= 0) {
506 break;
507 }
508 read_bytes += tmp_read_bytes;
509 }
510 return read_bytes;
511 }
512
sapi_fcgi_read_post(char * buffer,size_t count_bytes)513 static size_t sapi_fcgi_read_post(char *buffer, size_t count_bytes)
514 {
515 size_t read_bytes = 0;
516 int tmp_read_bytes;
517 fcgi_request *request = (fcgi_request*) SG(server_context);
518 size_t remaining = SG(request_info).content_length - SG(read_post_bytes);
519
520 if (remaining < count_bytes) {
521 count_bytes = remaining;
522 }
523 while (read_bytes < count_bytes) {
524 size_t diff = count_bytes - read_bytes;
525 int to_read = (diff > INT_MAX) ? INT_MAX : (int)diff;
526
527 tmp_read_bytes = fcgi_read(request, buffer + read_bytes, to_read);
528 if (tmp_read_bytes <= 0) {
529 break;
530 }
531 read_bytes += tmp_read_bytes;
532 }
533 return read_bytes;
534 }
535
536 #ifdef PHP_WIN32
537 /* The result needs to be freed! See sapi_getenv(). */
cgi_getenv_win32(const char * name,size_t name_len)538 static char *cgi_getenv_win32(const char *name, size_t name_len)
539 {
540 char *ret = NULL;
541 wchar_t *keyw, *valw;
542 size_t size;
543 int rc;
544
545 keyw = php_win32_cp_conv_any_to_w(name, name_len, PHP_WIN32_CP_IGNORE_LEN_P);
546 if (!keyw) {
547 return NULL;
548 }
549
550 rc = _wgetenv_s(&size, NULL, 0, keyw);
551 if (rc || 0 == size) {
552 free(keyw);
553 return NULL;
554 }
555
556 valw = emalloc((size + 1) * sizeof(wchar_t));
557
558 rc = _wgetenv_s(&size, valw, size, keyw);
559 if (!rc) {
560 ret = php_win32_cp_w_to_any(valw);
561 }
562
563 free(keyw);
564 efree(valw);
565
566 return ret;
567 }
568 #endif
569
sapi_cgi_getenv(char * name,size_t name_len)570 static char *sapi_cgi_getenv(char *name, size_t name_len)
571 {
572 #ifndef PHP_WIN32
573 return getenv(name);
574 #else
575 return cgi_getenv_win32(name, name_len);
576 #endif
577 }
578
sapi_fcgi_getenv(char * name,size_t name_len)579 static char *sapi_fcgi_getenv(char *name, size_t name_len)
580 {
581 /* when php is started by mod_fastcgi, no regular environment
582 * is provided to PHP. It is always sent to PHP at the start
583 * of a request. So we have to do our own lookup to get env
584 * vars. This could probably be faster somehow. */
585 fcgi_request *request = (fcgi_request*) SG(server_context);
586 char *ret = fcgi_getenv(request, name, (int)name_len);
587
588 #ifndef PHP_WIN32
589 if (ret) return ret;
590 /* if cgi, or fastcgi and not found in fcgi env
591 check the regular environment */
592 return getenv(name);
593 #else
594 if (ret) {
595 /* The functions outside here don't know, where does it come
596 from. They'll need to free the returned memory as it's
597 not necessary from the fcgi env. */
598 return strdup(ret);
599 }
600 /* if cgi, or fastcgi and not found in fcgi env
601 check the regular environment */
602 return cgi_getenv_win32(name, name_len);
603 #endif
604 }
605
_sapi_cgi_putenv(char * name,size_t name_len,char * value)606 static char *_sapi_cgi_putenv(char *name, size_t name_len, char *value)
607 {
608 #if !HAVE_SETENV || !HAVE_UNSETENV
609 size_t len;
610 char *buf;
611 #endif
612
613 #if HAVE_SETENV
614 if (value) {
615 setenv(name, value, 1);
616 }
617 #endif
618 #if HAVE_UNSETENV
619 if (!value) {
620 unsetenv(name);
621 }
622 #endif
623
624 #if !HAVE_SETENV || !HAVE_UNSETENV
625 /* if cgi, or fastcgi and not found in fcgi env
626 check the regular environment
627 this leaks, but it's only cgi anyway, we'll fix
628 it for 5.0
629 */
630 len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
631 buf = (char *) malloc(len);
632 if (buf == NULL) {
633 return getenv(name);
634 }
635 #endif
636 #if !HAVE_SETENV
637 if (value) {
638 len = slprintf(buf, len - 1, "%s=%s", name, value);
639 putenv(buf);
640 }
641 #endif
642 #if !HAVE_UNSETENV
643 if (!value) {
644 len = slprintf(buf, len - 1, "%s=", name);
645 putenv(buf);
646 }
647 #endif
648 return getenv(name);
649 }
650
sapi_cgi_read_cookies(void)651 static char *sapi_cgi_read_cookies(void)
652 {
653 return getenv("HTTP_COOKIE");
654 }
655
sapi_fcgi_read_cookies(void)656 static char *sapi_fcgi_read_cookies(void)
657 {
658 fcgi_request *request = (fcgi_request*) SG(server_context);
659
660 return FCGI_GETENV(request, "HTTP_COOKIE");
661 }
662
cgi_php_load_env_var(char * var,unsigned int var_len,char * val,unsigned int val_len,void * arg)663 static void cgi_php_load_env_var(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg)
664 {
665 zval *array_ptr = (zval*)arg;
666 int filter_arg = (Z_ARR_P(array_ptr) == Z_ARR(PG(http_globals)[TRACK_VARS_ENV]))?PARSE_ENV:PARSE_SERVER;
667 size_t new_val_len;
668
669 if (sapi_module.input_filter(filter_arg, var, &val, strlen(val), &new_val_len)) {
670 php_register_variable_safe(var, val, new_val_len, array_ptr);
671 }
672 }
673
cgi_php_import_environment_variables(zval * array_ptr)674 static void cgi_php_import_environment_variables(zval *array_ptr)
675 {
676 if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) {
677 if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) != IS_ARRAY) {
678 zend_is_auto_global_str("_ENV", sizeof("_ENV")-1);
679 }
680
681 if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
682 Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_ENV])) {
683 zend_array_destroy(Z_ARR_P(array_ptr));
684 Z_ARR_P(array_ptr) = zend_array_dup(Z_ARR(PG(http_globals)[TRACK_VARS_ENV]));
685 return;
686 }
687 }
688
689 /* call php's original import as a catch-all */
690 php_php_import_environment_variables(array_ptr);
691
692 if (fcgi_is_fastcgi()) {
693 fcgi_request *request = (fcgi_request*) SG(server_context);
694 fcgi_loadenv(request, cgi_php_load_env_var, array_ptr);
695 }
696 }
697
sapi_cgi_register_variables(zval * track_vars_array)698 static void sapi_cgi_register_variables(zval *track_vars_array)
699 {
700 size_t php_self_len;
701 char *php_self;
702
703 /* In CGI mode, we consider the environment to be a part of the server
704 * variables
705 */
706 php_import_environment_variables(track_vars_array);
707
708 if (CGIG(fix_pathinfo)) {
709 char *script_name = SG(request_info).request_uri;
710 char *path_info;
711 int free_php_self;
712 ALLOCA_FLAG(use_heap)
713
714 if (fcgi_is_fastcgi()) {
715 fcgi_request *request = (fcgi_request*) SG(server_context);
716
717 path_info = FCGI_GETENV(request, "PATH_INFO");
718 } else {
719 path_info = getenv("PATH_INFO");
720 }
721
722 if (path_info) {
723 size_t path_info_len = strlen(path_info);
724
725 if (script_name) {
726 size_t script_name_len = strlen(script_name);
727
728 php_self_len = script_name_len + path_info_len;
729 php_self = do_alloca(php_self_len + 1, use_heap);
730 memcpy(php_self, script_name, script_name_len + 1);
731 memcpy(php_self + script_name_len, path_info, path_info_len + 1);
732 free_php_self = 1;
733 } else {
734 php_self = path_info;
735 php_self_len = path_info_len;
736 free_php_self = 0;
737 }
738 } else if (script_name) {
739 php_self = script_name;
740 php_self_len = strlen(script_name);
741 free_php_self = 0;
742 } else {
743 php_self = "";
744 php_self_len = 0;
745 free_php_self = 0;
746 }
747
748 /* Build the special-case PHP_SELF variable for the CGI version */
749 if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
750 php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
751 }
752 if (free_php_self) {
753 free_alloca(php_self, use_heap);
754 }
755 } else {
756 php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
757 php_self_len = strlen(php_self);
758 if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
759 php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
760 }
761 }
762 }
763
sapi_cgi_log_message(char * message,int syslog_type_int)764 static void sapi_cgi_log_message(char *message, int syslog_type_int)
765 {
766 if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
767 fcgi_request *request;
768
769 request = (fcgi_request*) SG(server_context);
770 if (request) {
771 int ret, len = (int)strlen(message);
772 char *buf = malloc(len+2);
773
774 memcpy(buf, message, len);
775 memcpy(buf + len, "\n", sizeof("\n"));
776 ret = fcgi_write(request, FCGI_STDERR, buf, (int)(len + 1));
777 free(buf);
778 if (ret < 0) {
779 php_handle_aborted_connection();
780 }
781 } else {
782 fprintf(stderr, "%s\n", message);
783 }
784 /* ignore return code */
785 } else {
786 fprintf(stderr, "%s\n", message);
787 }
788 }
789
790 /* {{{ php_cgi_ini_activate_user_config
791 */
php_cgi_ini_activate_user_config(char * path,size_t path_len,const char * doc_root,size_t doc_root_len)792 static void php_cgi_ini_activate_user_config(char *path, size_t path_len, const char *doc_root, size_t doc_root_len)
793 {
794 user_config_cache_entry *new_entry, *entry;
795 time_t request_time = (time_t)sapi_get_request_time();
796
797 /* Find cached config entry: If not found, create one */
798 if ((entry = zend_hash_str_find_ptr(&CGIG(user_config_cache), path, path_len)) == NULL) {
799 new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
800 new_entry->expires = 0;
801 new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
802 zend_hash_init(new_entry->user_config, 8, NULL, (dtor_func_t) config_zval_dtor, 1);
803 entry = zend_hash_str_update_ptr(&CGIG(user_config_cache), path, path_len, new_entry);
804 }
805
806 /* Check whether cache entry has expired and rescan if it is */
807 if (request_time > entry->expires) {
808 char *real_path = NULL;
809 char *s1, *s2;
810 size_t s_len;
811
812 /* Clear the expired config */
813 zend_hash_clean(entry->user_config);
814
815 if (!IS_ABSOLUTE_PATH(path, path_len)) {
816 size_t real_path_len;
817 real_path = tsrm_realpath(path, NULL);
818 if (real_path == NULL) {
819 return;
820 }
821 real_path_len = strlen(real_path);
822 path = real_path;
823 path_len = real_path_len;
824 }
825
826 if (path_len > doc_root_len) {
827 s1 = (char *) doc_root;
828 s2 = path;
829 s_len = doc_root_len;
830 } else {
831 s1 = path;
832 s2 = (char *) doc_root;
833 s_len = path_len;
834 }
835
836 /* we have to test if path is part of DOCUMENT_ROOT.
837 if it is inside the docroot, we scan the tree up to the docroot
838 to find more user.ini, if not we only scan the current path.
839 */
840 #ifdef PHP_WIN32
841 if (strnicmp(s1, s2, s_len) == 0) {
842 #else
843 if (strncmp(s1, s2, s_len) == 0) {
844 #endif
845 char *ptr = s2 + doc_root_len;
846 #ifdef PHP_WIN32
847 while ((ptr = strpbrk(ptr, "\\/")) != NULL) {
848 #else
849 while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
850 #endif
851 *ptr = 0;
852 php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
853 *ptr = '/';
854 ptr++;
855 }
856 } else {
857 php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
858 }
859
860 if (real_path) {
861 efree(real_path);
862 }
863 entry->expires = request_time + PG(user_ini_cache_ttl);
864 }
865
866 /* Activate ini entries with values from the user config hash */
867 php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS);
868 }
869 /* }}} */
870
871 static int sapi_cgi_activate(void)
872 {
873 /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
874 if (!SG(request_info).path_translated) {
875 return FAILURE;
876 }
877
878 if (php_ini_has_per_host_config()) {
879 char *server_name;
880
881 /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
882 if (fcgi_is_fastcgi()) {
883 fcgi_request *request = (fcgi_request*) SG(server_context);
884
885 server_name = FCGI_GETENV(request, "SERVER_NAME");
886 } else {
887 server_name = getenv("SERVER_NAME");
888 }
889 /* SERVER_NAME should also be defined at this stage..but better check it anyway */
890 if (server_name) {
891 size_t server_name_len = strlen(server_name);
892 server_name = estrndup(server_name, server_name_len);
893 zend_str_tolower(server_name, server_name_len);
894 php_ini_activate_per_host_config(server_name, server_name_len);
895 efree(server_name);
896 }
897 }
898
899 if (php_ini_has_per_dir_config() ||
900 (PG(user_ini_filename) && *PG(user_ini_filename))
901 ) {
902 char *path;
903 size_t path_len;
904
905 /* Prepare search path */
906 path_len = strlen(SG(request_info).path_translated);
907
908 /* Make sure we have trailing slash! */
909 if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
910 path = emalloc(path_len + 2);
911 memcpy(path, SG(request_info).path_translated, path_len + 1);
912 path_len = zend_dirname(path, path_len);
913 path[path_len++] = DEFAULT_SLASH;
914 } else {
915 path = estrndup(SG(request_info).path_translated, path_len);
916 path_len = zend_dirname(path, path_len);
917 }
918 path[path_len] = 0;
919
920 /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
921 php_ini_activate_per_dir_config(path, path_len); /* Note: for global settings sake we check from root to path */
922
923 /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
924 if (PG(user_ini_filename) && *PG(user_ini_filename)) {
925 char *doc_root;
926
927 if (fcgi_is_fastcgi()) {
928 fcgi_request *request = (fcgi_request*) SG(server_context);
929
930 doc_root = FCGI_GETENV(request, "DOCUMENT_ROOT");
931 } else {
932 doc_root = getenv("DOCUMENT_ROOT");
933 }
934 /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
935 if (doc_root) {
936 size_t doc_root_len = strlen(doc_root);
937 if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
938 --doc_root_len;
939 }
940 #ifdef PHP_WIN32
941 /* paths on windows should be case-insensitive */
942 doc_root = estrndup(doc_root, doc_root_len);
943 zend_str_tolower(doc_root, doc_root_len);
944 #endif
945 php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len);
946
947 #ifdef PHP_WIN32
948 efree(doc_root);
949 #endif
950 }
951 }
952
953 efree(path);
954 }
955
956 return SUCCESS;
957 }
958
959 static int sapi_cgi_deactivate(void)
960 {
961 /* flush only when SAPI was started. The reasons are:
962 1. SAPI Deactivate is called from two places: module init and request shutdown
963 2. When the first call occurs and the request is not set up, flush fails on FastCGI.
964 */
965 if (SG(sapi_started)) {
966 if (fcgi_is_fastcgi()) {
967 if (
968 !parent &&
969 !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
970 php_handle_aborted_connection();
971 }
972 } else {
973 sapi_cgi_flush(SG(server_context));
974 }
975 }
976 return SUCCESS;
977 }
978
979 static int php_cgi_startup(sapi_module_struct *sapi_module)
980 {
981 if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
982 return FAILURE;
983 }
984 return SUCCESS;
985 }
986
987 /* {{{ sapi_module_struct cgi_sapi_module
988 */
989 static sapi_module_struct cgi_sapi_module = {
990 "cgi-fcgi", /* name */
991 "CGI/FastCGI", /* pretty name */
992
993 php_cgi_startup, /* startup */
994 php_module_shutdown_wrapper, /* shutdown */
995
996 sapi_cgi_activate, /* activate */
997 sapi_cgi_deactivate, /* deactivate */
998
999 sapi_cgi_ub_write, /* unbuffered write */
1000 sapi_cgi_flush, /* flush */
1001 NULL, /* get uid */
1002 sapi_cgi_getenv, /* getenv */
1003
1004 php_error, /* error handler */
1005
1006 NULL, /* header handler */
1007 sapi_cgi_send_headers, /* send headers handler */
1008 NULL, /* send header handler */
1009
1010 sapi_cgi_read_post, /* read POST data */
1011 sapi_cgi_read_cookies, /* read Cookies */
1012
1013 sapi_cgi_register_variables, /* register server variables */
1014 sapi_cgi_log_message, /* Log message */
1015 NULL, /* Get request time */
1016 NULL, /* Child terminate */
1017
1018 STANDARD_SAPI_MODULE_PROPERTIES
1019 };
1020 /* }}} */
1021
1022 /* {{{ arginfo ext/standard/dl.c */
1023 ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
1024 ZEND_ARG_INFO(0, extension_filename)
1025 ZEND_END_ARG_INFO()
1026 /* }}} */
1027
1028 static const zend_function_entry additional_functions[] = {
1029 ZEND_FE(dl, arginfo_dl)
1030 PHP_FE_END
1031 };
1032
1033 /* {{{ php_cgi_usage
1034 */
1035 static void php_cgi_usage(char *argv0)
1036 {
1037 char *prog;
1038
1039 prog = strrchr(argv0, '/');
1040 if (prog) {
1041 prog++;
1042 } else {
1043 prog = "php";
1044 }
1045
1046 php_printf( "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
1047 " %s <file> [args...]\n"
1048 " -a Run interactively\n"
1049 " -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
1050 " -C Do not chdir to the script's directory\n"
1051 " -c <path>|<file> Look for php.ini file in this directory\n"
1052 " -n No php.ini file will be used\n"
1053 " -d foo[=bar] Define INI entry foo with value 'bar'\n"
1054 " -e Generate extended information for debugger/profiler\n"
1055 " -f <file> Parse <file>. Implies `-q'\n"
1056 " -h This help\n"
1057 " -i PHP information\n"
1058 " -l Syntax check only (lint)\n"
1059 " -m Show compiled in modules\n"
1060 " -q Quiet-mode. Suppress HTTP Header output.\n"
1061 " -s Display colour syntax highlighted source.\n"
1062 " -v Version number\n"
1063 " -w Display source with stripped comments and whitespace.\n"
1064 " -z <file> Load Zend extension <file>.\n"
1065 " -T <count> Measure execution time of script repeated <count> times.\n",
1066 prog, prog);
1067 }
1068 /* }}} */
1069
1070 /* {{{ is_valid_path
1071 *
1072 * some server configurations allow '..' to slip through in the
1073 * translated path. We'll just refuse to handle such a path.
1074 */
1075 static int is_valid_path(const char *path)
1076 {
1077 const char *p = path;
1078
1079 if (UNEXPECTED(!p)) {
1080 return 0;
1081 }
1082 if (UNEXPECTED(*p == '.') && *(p+1) == '.' && (!*(p+2) || IS_SLASH(*(p+2)))) {
1083 return 0;
1084 }
1085 while (*p) {
1086 if (IS_SLASH(*p)) {
1087 p++;
1088 if (UNEXPECTED(*p == '.')) {
1089 p++;
1090 if (UNEXPECTED(*p == '.')) {
1091 p++;
1092 if (UNEXPECTED(!*p) || UNEXPECTED(IS_SLASH(*p))) {
1093 return 0;
1094 }
1095 }
1096 }
1097 }
1098 p++;
1099 }
1100 return 1;
1101 }
1102 /* }}} */
1103
1104 #define CGI_GETENV(name) \
1105 ((has_env) ? \
1106 FCGI_GETENV(request, name) : \
1107 getenv(name))
1108
1109 #define CGI_PUTENV(name, value) \
1110 ((has_env) ? \
1111 FCGI_PUTENV(request, name, value) : \
1112 _sapi_cgi_putenv(name, sizeof(name)-1, value))
1113
1114 /* {{{ init_request_info
1115
1116 initializes request_info structure
1117
1118 specificly in this section we handle proper translations
1119 for:
1120
1121 PATH_INFO
1122 derived from the portion of the URI path following
1123 the script name but preceding any query data
1124 may be empty
1125
1126 PATH_TRANSLATED
1127 derived by taking any path-info component of the
1128 request URI and performing any virtual-to-physical
1129 translation appropriate to map it onto the server's
1130 document repository structure
1131
1132 empty if PATH_INFO is empty
1133
1134 The env var PATH_TRANSLATED **IS DIFFERENT** than the
1135 request_info.path_translated variable, the latter should
1136 match SCRIPT_FILENAME instead.
1137
1138 SCRIPT_NAME
1139 set to a URL path that could identify the CGI script
1140 rather than the interpreter. PHP_SELF is set to this
1141
1142 REQUEST_URI
1143 uri section following the domain:port part of a URI
1144
1145 SCRIPT_FILENAME
1146 The virtual-to-physical translation of SCRIPT_NAME (as per
1147 PATH_TRANSLATED)
1148
1149 These settings are documented at
1150 http://cgi-spec.golux.com/
1151
1152
1153 Based on the following URL request:
1154
1155 http://localhost/info.php/test?a=b
1156
1157 should produce, which btw is the same as if
1158 we were running under mod_cgi on apache (ie. not
1159 using ScriptAlias directives):
1160
1161 PATH_INFO=/test
1162 PATH_TRANSLATED=/docroot/test
1163 SCRIPT_NAME=/info.php
1164 REQUEST_URI=/info.php/test?a=b
1165 SCRIPT_FILENAME=/docroot/info.php
1166 QUERY_STRING=a=b
1167
1168 but what we get is (cgi/mod_fastcgi under apache):
1169
1170 PATH_INFO=/info.php/test
1171 PATH_TRANSLATED=/docroot/info.php/test
1172 SCRIPT_NAME=/php/php-cgi (from the Action setting I suppose)
1173 REQUEST_URI=/info.php/test?a=b
1174 SCRIPT_FILENAME=/path/to/php/bin/php-cgi (Action setting translated)
1175 QUERY_STRING=a=b
1176
1177 Comments in the code below refer to using the above URL in a request
1178
1179 */
1180 static void init_request_info(fcgi_request *request)
1181 {
1182 int has_env = fcgi_has_env(request);
1183 char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
1184 char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
1185 char *script_path_translated = env_script_filename;
1186
1187 /* some broken servers do not have script_filename or argv0
1188 * an example, IIS configured in some ways. then they do more
1189 * broken stuff and set path_translated to the cgi script location */
1190 if (!script_path_translated && env_path_translated) {
1191 script_path_translated = env_path_translated;
1192 }
1193
1194 /* initialize the defaults */
1195 SG(request_info).path_translated = NULL;
1196 SG(request_info).request_method = NULL;
1197 SG(request_info).proto_num = 1000;
1198 SG(request_info).query_string = NULL;
1199 SG(request_info).request_uri = NULL;
1200 SG(request_info).content_type = NULL;
1201 SG(request_info).content_length = 0;
1202 SG(sapi_headers).http_response_code = 200;
1203
1204 /* script_path_translated being set is a good indication that
1205 * we are running in a cgi environment, since it is always
1206 * null otherwise. otherwise, the filename
1207 * of the script will be retrieved later via argc/argv */
1208 if (script_path_translated) {
1209 const char *auth;
1210 char *content_length = CGI_GETENV("CONTENT_LENGTH");
1211 char *content_type = CGI_GETENV("CONTENT_TYPE");
1212 char *env_path_info = CGI_GETENV("PATH_INFO");
1213 char *env_script_name = CGI_GETENV("SCRIPT_NAME");
1214
1215 #ifdef PHP_WIN32
1216 /* Hack for buggy IIS that sets incorrect PATH_INFO */
1217 char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
1218
1219 if (env_server_software &&
1220 env_script_name &&
1221 env_path_info &&
1222 strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
1223 strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
1224 ) {
1225 env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
1226 env_path_info += strlen(env_script_name);
1227 if (*env_path_info == 0) {
1228 env_path_info = NULL;
1229 }
1230 env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
1231 }
1232 #endif
1233
1234 if (CGIG(fix_pathinfo)) {
1235 zend_stat_t st;
1236 char *real_path = NULL;
1237 char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
1238 char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
1239 char *orig_path_translated = env_path_translated;
1240 char *orig_path_info = env_path_info;
1241 char *orig_script_name = env_script_name;
1242 char *orig_script_filename = env_script_filename;
1243 size_t script_path_translated_len;
1244
1245 if (!env_document_root && PG(doc_root)) {
1246 env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
1247 /* fix docroot */
1248 TRANSLATE_SLASHES(env_document_root);
1249 }
1250
1251 if (env_path_translated != NULL && env_redirect_url != NULL &&
1252 env_path_translated != script_path_translated &&
1253 strcmp(env_path_translated, script_path_translated) != 0) {
1254 /*
1255 * pretty much apache specific. If we have a redirect_url
1256 * then our script_filename and script_name point to the
1257 * php executable
1258 */
1259 script_path_translated = env_path_translated;
1260 /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
1261 env_script_name = env_redirect_url;
1262 }
1263
1264 #ifdef __riscos__
1265 /* Convert path to unix format*/
1266 __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
1267 script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
1268 #endif
1269
1270 /*
1271 * if the file doesn't exist, try to extract PATH_INFO out
1272 * of it by stat'ing back through the '/'
1273 * this fixes url's like /info.php/test
1274 */
1275 if (script_path_translated &&
1276 (script_path_translated_len = strlen(script_path_translated)) > 0 &&
1277 (script_path_translated[script_path_translated_len-1] == '/' ||
1278 #ifdef PHP_WIN32
1279 script_path_translated[script_path_translated_len-1] == '\\' ||
1280 #endif
1281 (real_path = tsrm_realpath(script_path_translated, NULL)) == NULL)
1282 ) {
1283 char *pt = estrndup(script_path_translated, script_path_translated_len);
1284 size_t len = script_path_translated_len;
1285 char *ptr;
1286
1287 while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
1288 *ptr = 0;
1289 if (zend_stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
1290 /*
1291 * okay, we found the base script!
1292 * work out how many chars we had to strip off;
1293 * then we can modify PATH_INFO
1294 * accordingly
1295 *
1296 * we now have the makings of
1297 * PATH_INFO=/test
1298 * SCRIPT_FILENAME=/docroot/info.php
1299 *
1300 * we now need to figure out what docroot is.
1301 * if DOCUMENT_ROOT is set, this is easy, otherwise,
1302 * we have to play the game of hide and seek to figure
1303 * out what SCRIPT_NAME should be
1304 */
1305 size_t slen = len - strlen(pt);
1306 size_t pilen = env_path_info ? strlen(env_path_info) : 0;
1307 char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
1308
1309 if (orig_path_info != path_info) {
1310 if (orig_path_info) {
1311 char old;
1312
1313 CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1314 old = path_info[0];
1315 path_info[0] = 0;
1316 if (!orig_script_name ||
1317 strcmp(orig_script_name, env_path_info) != 0) {
1318 if (orig_script_name) {
1319 CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1320 }
1321 SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
1322 } else {
1323 SG(request_info).request_uri = orig_script_name;
1324 }
1325 path_info[0] = old;
1326 }
1327 env_path_info = CGI_PUTENV("PATH_INFO", path_info);
1328 }
1329 if (!orig_script_filename ||
1330 strcmp(orig_script_filename, pt) != 0) {
1331 if (orig_script_filename) {
1332 CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1333 }
1334 script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
1335 }
1336 TRANSLATE_SLASHES(pt);
1337
1338 /* figure out docroot
1339 * SCRIPT_FILENAME minus SCRIPT_NAME
1340 */
1341 if (env_document_root) {
1342 size_t l = strlen(env_document_root);
1343 size_t path_translated_len = 0;
1344 char *path_translated = NULL;
1345
1346 if (l && env_document_root[l - 1] == '/') {
1347 --l;
1348 }
1349
1350 /* we have docroot, so we should have:
1351 * DOCUMENT_ROOT=/docroot
1352 * SCRIPT_FILENAME=/docroot/info.php
1353 */
1354
1355 /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
1356 path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
1357 path_translated = (char *) emalloc(path_translated_len + 1);
1358 memcpy(path_translated, env_document_root, l);
1359 if (env_path_info) {
1360 memcpy(path_translated + l, env_path_info, (path_translated_len - l));
1361 }
1362 path_translated[path_translated_len] = '\0';
1363 if (orig_path_translated) {
1364 CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1365 }
1366 env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1367 efree(path_translated);
1368 } else if ( env_script_name &&
1369 strstr(pt, env_script_name)
1370 ) {
1371 /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
1372 size_t ptlen = strlen(pt) - strlen(env_script_name);
1373 size_t path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
1374
1375 char *path_translated = (char *) emalloc(path_translated_len + 1);
1376 memcpy(path_translated, pt, ptlen);
1377 if (env_path_info) {
1378 memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
1379 }
1380 path_translated[path_translated_len] = '\0';
1381 if (orig_path_translated) {
1382 CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1383 }
1384 env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1385 efree(path_translated);
1386 }
1387 break;
1388 }
1389 }
1390 if (!ptr) {
1391 /*
1392 * if we stripped out all the '/' and still didn't find
1393 * a valid path... we will fail, badly. of course we would
1394 * have failed anyway... we output 'no input file' now.
1395 */
1396 if (orig_script_filename) {
1397 CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1398 }
1399 script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
1400 SG(sapi_headers).http_response_code = 404;
1401 }
1402 if (!SG(request_info).request_uri) {
1403 if (!orig_script_name ||
1404 strcmp(orig_script_name, env_script_name) != 0) {
1405 if (orig_script_name) {
1406 CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1407 }
1408 SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1409 } else {
1410 SG(request_info).request_uri = orig_script_name;
1411 }
1412 }
1413 if (pt) {
1414 efree(pt);
1415 }
1416 } else {
1417 /* make sure path_info/translated are empty */
1418 if (!orig_script_filename ||
1419 (script_path_translated != orig_script_filename &&
1420 strcmp(script_path_translated, orig_script_filename) != 0)) {
1421 if (orig_script_filename) {
1422 CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1423 }
1424 script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
1425 }
1426 if (env_redirect_url) {
1427 if (orig_path_info) {
1428 CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1429 CGI_PUTENV("PATH_INFO", NULL);
1430 }
1431 if (orig_path_translated) {
1432 CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1433 CGI_PUTENV("PATH_TRANSLATED", NULL);
1434 }
1435 }
1436 if (env_script_name != orig_script_name) {
1437 if (orig_script_name) {
1438 CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1439 }
1440 SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1441 } else {
1442 SG(request_info).request_uri = env_script_name;
1443 }
1444 efree(real_path);
1445 }
1446 } else {
1447 /* pre 4.3 behaviour, shouldn't be used but provides BC */
1448 if (env_path_info) {
1449 SG(request_info).request_uri = env_path_info;
1450 } else {
1451 SG(request_info).request_uri = env_script_name;
1452 }
1453 if (!CGIG(discard_path) && env_path_translated) {
1454 script_path_translated = env_path_translated;
1455 }
1456 }
1457
1458 if (is_valid_path(script_path_translated)) {
1459 SG(request_info).path_translated = estrdup(script_path_translated);
1460 }
1461
1462 SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
1463 /* FIXME - Work out proto_num here */
1464 SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
1465 SG(request_info).content_type = (content_type ? content_type : "" );
1466 SG(request_info).content_length = (content_length ? atol(content_length) : 0);
1467
1468 /* The CGI RFC allows servers to pass on unvalidated Authorization data */
1469 auth = CGI_GETENV("HTTP_AUTHORIZATION");
1470 php_handle_auth_data(auth);
1471 }
1472 }
1473 /* }}} */
1474
1475 #ifndef PHP_WIN32
1476 /**
1477 * Clean up child processes upon exit
1478 */
1479 void fastcgi_cleanup(int signal)
1480 {
1481 #ifdef DEBUG_FASTCGI
1482 fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
1483 #endif
1484
1485 sigaction(SIGTERM, &old_term, 0);
1486
1487 /* Kill all the processes in our process group */
1488 kill(-pgroup, SIGTERM);
1489
1490 if (parent && parent_waiting) {
1491 exit_signal = 1;
1492 } else {
1493 exit(0);
1494 }
1495 }
1496 #else
1497 BOOL WINAPI fastcgi_cleanup(DWORD sig)
1498 {
1499 int i = kids;
1500
1501 EnterCriticalSection(&cleanup_lock);
1502 cleaning_up = 1;
1503 LeaveCriticalSection(&cleanup_lock);
1504
1505 while (0 < i--) {
1506 if (NULL == kid_cgi_ps[i]) {
1507 continue;
1508 }
1509
1510 TerminateProcess(kid_cgi_ps[i], 0);
1511 CloseHandle(kid_cgi_ps[i]);
1512 kid_cgi_ps[i] = NULL;
1513 }
1514
1515 if (job) {
1516 CloseHandle(job);
1517 }
1518
1519 parent = 0;
1520
1521 return TRUE;
1522 }
1523 #endif
1524
1525 PHP_INI_BEGIN()
1526 STD_PHP_INI_ENTRY("cgi.rfc2616_headers", "0", PHP_INI_ALL, OnUpdateBool, rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
1527 STD_PHP_INI_ENTRY("cgi.nph", "0", PHP_INI_ALL, OnUpdateBool, nph, php_cgi_globals_struct, php_cgi_globals)
1528 STD_PHP_INI_ENTRY("cgi.check_shebang_line", "1", PHP_INI_SYSTEM, OnUpdateBool, check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
1529 STD_PHP_INI_ENTRY("cgi.force_redirect", "1", PHP_INI_SYSTEM, OnUpdateBool, force_redirect, php_cgi_globals_struct, php_cgi_globals)
1530 STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
1531 STD_PHP_INI_ENTRY("cgi.fix_pathinfo", "1", PHP_INI_SYSTEM, OnUpdateBool, fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
1532 STD_PHP_INI_ENTRY("cgi.discard_path", "0", PHP_INI_SYSTEM, OnUpdateBool, discard_path, php_cgi_globals_struct, php_cgi_globals)
1533 STD_PHP_INI_ENTRY("fastcgi.logging", "1", PHP_INI_SYSTEM, OnUpdateBool, fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
1534 #ifdef PHP_WIN32
1535 STD_PHP_INI_ENTRY("fastcgi.impersonate", "0", PHP_INI_SYSTEM, OnUpdateBool, impersonate, php_cgi_globals_struct, php_cgi_globals)
1536 #endif
1537 PHP_INI_END()
1538
1539 /* {{{ php_cgi_globals_ctor
1540 */
1541 static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals)
1542 {
1543 #ifdef ZTS
1544 ZEND_TSRMLS_CACHE_UPDATE();
1545 #endif
1546 php_cgi_globals->rfc2616_headers = 0;
1547 php_cgi_globals->nph = 0;
1548 php_cgi_globals->check_shebang_line = 1;
1549 php_cgi_globals->force_redirect = 1;
1550 php_cgi_globals->redirect_status_env = NULL;
1551 php_cgi_globals->fix_pathinfo = 1;
1552 php_cgi_globals->discard_path = 0;
1553 php_cgi_globals->fcgi_logging = 1;
1554 #ifdef PHP_WIN32
1555 php_cgi_globals->impersonate = 0;
1556 #endif
1557 zend_hash_init(&php_cgi_globals->user_config_cache, 8, NULL, user_config_cache_entry_dtor, 1);
1558 }
1559 /* }}} */
1560
1561 /* {{{ PHP_MINIT_FUNCTION
1562 */
1563 static PHP_MINIT_FUNCTION(cgi)
1564 {
1565 REGISTER_INI_ENTRIES();
1566 return SUCCESS;
1567 }
1568 /* }}} */
1569
1570 /* {{{ PHP_MSHUTDOWN_FUNCTION
1571 */
1572 static PHP_MSHUTDOWN_FUNCTION(cgi)
1573 {
1574 zend_hash_destroy(&CGIG(user_config_cache));
1575
1576 UNREGISTER_INI_ENTRIES();
1577 return SUCCESS;
1578 }
1579 /* }}} */
1580
1581 /* {{{ PHP_MINFO_FUNCTION
1582 */
1583 static PHP_MINFO_FUNCTION(cgi)
1584 {
1585 DISPLAY_INI_ENTRIES();
1586 }
1587 /* }}} */
1588
1589 PHP_FUNCTION(apache_child_terminate) /* {{{ */
1590 {
1591 if (zend_parse_parameters_none()) {
1592 return;
1593 }
1594 if (fcgi_is_fastcgi()) {
1595 fcgi_terminate();
1596 }
1597 }
1598 /* }}} */
1599
1600
1601 PHP_FUNCTION(apache_request_headers) /* {{{ */
1602 {
1603 if (zend_parse_parameters_none()) {
1604 return;
1605 }
1606 array_init(return_value);
1607 if (fcgi_is_fastcgi()) {
1608 fcgi_request *request = (fcgi_request*) SG(server_context);
1609
1610 fcgi_loadenv(request, sapi_add_request_header, return_value);
1611 } else {
1612 char buf[128];
1613 char **env, *p, *q, *var, *val, *t = buf;
1614 size_t alloc_size = sizeof(buf);
1615 zend_ulong var_len;
1616
1617 for (env = environ; env != NULL && *env != NULL; env++) {
1618 val = strchr(*env, '=');
1619 if (!val) { /* malformed entry? */
1620 continue;
1621 }
1622 var_len = val - *env;
1623 if (var_len >= alloc_size) {
1624 alloc_size = var_len + 64;
1625 t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1626 }
1627 var = *env;
1628 if (var_len > 5 &&
1629 var[0] == 'H' &&
1630 var[1] == 'T' &&
1631 var[2] == 'T' &&
1632 var[3] == 'P' &&
1633 var[4] == '_') {
1634
1635 var_len -= 5;
1636
1637 if (var_len >= alloc_size) {
1638 alloc_size = var_len + 64;
1639 t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1640 }
1641 p = var + 5;
1642
1643 var = q = t;
1644 /* First char keep uppercase */
1645 *q++ = *p++;
1646 while (*p) {
1647 if (*p == '=') {
1648 /* End of name */
1649 break;
1650 } else if (*p == '_') {
1651 *q++ = '-';
1652 p++;
1653 /* First char after - keep uppercase */
1654 if (*p && *p!='=') {
1655 *q++ = *p++;
1656 }
1657 } else if (*p >= 'A' && *p <= 'Z') {
1658 /* lowercase */
1659 *q++ = (*p++ - 'A' + 'a');
1660 } else {
1661 *q++ = *p++;
1662 }
1663 }
1664 *q = 0;
1665 } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1666 memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1667 var = "Content-Type";
1668 } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1669 memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1670 var = "Content-Length";
1671 } else {
1672 continue;
1673 }
1674 val++;
1675 add_assoc_string_ex(return_value, var, var_len, val);
1676 }
1677 if (t != buf && t != NULL) {
1678 efree(t);
1679 }
1680 }
1681 }
1682 /* }}} */
1683
1684 static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
1685 {
1686 if (h->header_len > 0) {
1687 char *s;
1688 size_t len = 0;
1689 ALLOCA_FLAG(use_heap)
1690
1691 char *p = strchr(h->header, ':');
1692 if (NULL != p) {
1693 len = p - h->header;
1694 }
1695 if (len > 0) {
1696 while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
1697 len--;
1698 }
1699 if (len) {
1700 s = do_alloca(len + 1, use_heap);
1701 memcpy(s, h->header, len);
1702 s[len] = 0;
1703 do {
1704 p++;
1705 } while (*p == ' ' || *p == '\t');
1706 add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
1707 free_alloca(s, use_heap);
1708 }
1709 }
1710 }
1711 }
1712 /* }}} */
1713
1714 PHP_FUNCTION(apache_response_headers) /* {{{ */
1715 {
1716 if (zend_parse_parameters_none() == FAILURE) {
1717 return;
1718 }
1719
1720 array_init(return_value);
1721 zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
1722 }
1723 /* }}} */
1724
1725 ZEND_BEGIN_ARG_INFO(arginfo_no_args, 0)
1726 ZEND_END_ARG_INFO()
1727
1728 static const zend_function_entry cgi_functions[] = {
1729 PHP_FE(apache_child_terminate, arginfo_no_args)
1730 PHP_FE(apache_request_headers, arginfo_no_args)
1731 PHP_FE(apache_response_headers, arginfo_no_args)
1732 PHP_FALIAS(getallheaders, apache_request_headers, arginfo_no_args)
1733 PHP_FE_END
1734 };
1735
1736 static zend_module_entry cgi_module_entry = {
1737 STANDARD_MODULE_HEADER,
1738 "cgi-fcgi",
1739 cgi_functions,
1740 PHP_MINIT(cgi),
1741 PHP_MSHUTDOWN(cgi),
1742 NULL,
1743 NULL,
1744 PHP_MINFO(cgi),
1745 NO_VERSION_YET,
1746 STANDARD_MODULE_PROPERTIES
1747 };
1748
1749 /* {{{ main
1750 */
1751 int main(int argc, char *argv[])
1752 {
1753 int free_query_string = 0;
1754 int exit_status = SUCCESS;
1755 int cgi = 0, c, i;
1756 size_t len;
1757 zend_file_handle file_handle;
1758 char *s;
1759
1760 /* temporary locals */
1761 int behavior = PHP_MODE_STANDARD;
1762 int no_headers = 0;
1763 int orig_optind = php_optind;
1764 char *orig_optarg = php_optarg;
1765 char *script_file = NULL;
1766 size_t ini_entries_len = 0;
1767 /* end of temporary locals */
1768
1769 int max_requests = 500;
1770 int requests = 0;
1771 int fastcgi;
1772 char *bindpath = NULL;
1773 int fcgi_fd = 0;
1774 fcgi_request *request = NULL;
1775 int warmup_repeats = 0;
1776 int repeats = 1;
1777 int benchmark = 0;
1778 #if HAVE_GETTIMEOFDAY
1779 struct timeval start, end;
1780 #else
1781 time_t start, end;
1782 #endif
1783 #ifndef PHP_WIN32
1784 int status = 0;
1785 #endif
1786 char *query_string;
1787 char *decoded_query_string;
1788 int skip_getopt = 0;
1789
1790 #ifdef HAVE_SIGNAL_H
1791 #if defined(SIGPIPE) && defined(SIG_IGN)
1792 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1793 that sockets created via fsockopen()
1794 don't kill PHP if the remote site
1795 closes it. in apache|apxs mode apache
1796 does that for us! thies@thieso.net
1797 20000419 */
1798 #endif
1799 #endif
1800
1801 #ifdef ZTS
1802 tsrm_startup(1, 1, 0, NULL);
1803 (void)ts_resource(0);
1804 ZEND_TSRMLS_CACHE_UPDATE();
1805 #endif
1806
1807 zend_signal_startup();
1808
1809 #ifdef ZTS
1810 ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1811 #else
1812 php_cgi_globals_ctor(&php_cgi_globals);
1813 #endif
1814
1815 sapi_startup(&cgi_sapi_module);
1816 fastcgi = fcgi_is_fastcgi();
1817 cgi_sapi_module.php_ini_path_override = NULL;
1818
1819 #ifdef PHP_WIN32
1820 _fmode = _O_BINARY; /* sets default for file streams to binary */
1821 setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
1822 setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
1823 setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
1824 #endif
1825
1826 if (!fastcgi) {
1827 /* Make sure we detect we are a cgi - a bit redundancy here,
1828 * but the default case is that we have to check only the first one. */
1829 if (getenv("SERVER_SOFTWARE") ||
1830 getenv("SERVER_NAME") ||
1831 getenv("GATEWAY_INTERFACE") ||
1832 getenv("REQUEST_METHOD")
1833 ) {
1834 cgi = 1;
1835 }
1836 }
1837
1838 if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
1839 /* we've got query string that has no = - apache CGI will pass it to command line */
1840 unsigned char *p;
1841 decoded_query_string = strdup(query_string);
1842 php_url_decode(decoded_query_string, strlen(decoded_query_string));
1843 for (p = (unsigned char *)decoded_query_string; *p && *p <= ' '; p++) {
1844 /* skip all leading spaces */
1845 }
1846 if(*p == '-') {
1847 skip_getopt = 1;
1848 }
1849 free(decoded_query_string);
1850 }
1851
1852 while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1853 switch (c) {
1854 case 'c':
1855 if (cgi_sapi_module.php_ini_path_override) {
1856 free(cgi_sapi_module.php_ini_path_override);
1857 }
1858 cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1859 break;
1860 case 'n':
1861 cgi_sapi_module.php_ini_ignore = 1;
1862 break;
1863 case 'd': {
1864 /* define ini entries on command line */
1865 size_t len = strlen(php_optarg);
1866 char *val;
1867
1868 if ((val = strchr(php_optarg, '='))) {
1869 val++;
1870 if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
1871 cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
1872 memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
1873 ini_entries_len += (val - php_optarg);
1874 memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
1875 ini_entries_len++;
1876 memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
1877 ini_entries_len += len - (val - php_optarg);
1878 memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
1879 ini_entries_len += sizeof("\n\0\"") - 2;
1880 } else {
1881 cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
1882 memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1883 memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
1884 ini_entries_len += len + sizeof("\n\0") - 2;
1885 }
1886 } else {
1887 cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
1888 memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1889 memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
1890 ini_entries_len += len + sizeof("=1\n\0") - 2;
1891 }
1892 break;
1893 }
1894 /* if we're started on command line, check to see if
1895 * we are being started as an 'external' fastcgi
1896 * server by accepting a bindpath parameter. */
1897 case 'b':
1898 if (!fastcgi) {
1899 bindpath = strdup(php_optarg);
1900 }
1901 break;
1902 case 's': /* generate highlighted HTML from source */
1903 behavior = PHP_MODE_HIGHLIGHT;
1904 break;
1905 }
1906 }
1907 php_optind = orig_optind;
1908 php_optarg = orig_optarg;
1909
1910 if (fastcgi || bindpath) {
1911 /* Override SAPI callbacks */
1912 cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
1913 cgi_sapi_module.flush = sapi_fcgi_flush;
1914 cgi_sapi_module.read_post = sapi_fcgi_read_post;
1915 cgi_sapi_module.getenv = sapi_fcgi_getenv;
1916 cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
1917 }
1918
1919 #ifdef ZTS
1920 SG(request_info).path_translated = NULL;
1921 #endif
1922
1923 cgi_sapi_module.executable_location = argv[0];
1924 if (!cgi && !fastcgi && !bindpath) {
1925 cgi_sapi_module.additional_functions = additional_functions;
1926 }
1927
1928 /* startup after we get the above ini override se we get things right */
1929 if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1930 #ifdef ZTS
1931 tsrm_shutdown();
1932 #endif
1933 return FAILURE;
1934 }
1935
1936 /* check force_cgi after startup, so we have proper output */
1937 if (cgi && CGIG(force_redirect)) {
1938 /* Apache will generate REDIRECT_STATUS,
1939 * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
1940 * redirect.so and installation instructions available from
1941 * http://www.koehntopp.de/php.
1942 * -- kk@netuse.de
1943 */
1944 if (!getenv("REDIRECT_STATUS") &&
1945 !getenv ("HTTP_REDIRECT_STATUS") &&
1946 /* this is to allow a different env var to be configured
1947 * in case some server does something different than above */
1948 (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
1949 ) {
1950 zend_try {
1951 SG(sapi_headers).http_response_code = 400;
1952 PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1953 <p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
1954 means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1955 set, e.g. via an Apache Action directive.</p>\n\
1956 <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1957 manual page for CGI security</a>.</p>\n\
1958 <p>For more information about changing this behaviour or re-enabling this webserver,\n\
1959 consult the installation file that came with this distribution, or visit \n\
1960 <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1961 } zend_catch {
1962 } zend_end_try();
1963 #if defined(ZTS) && !defined(PHP_DEBUG)
1964 /* XXX we're crashing here in msvc6 debug builds at
1965 * php_message_handler_for_zend:839 because
1966 * SG(request_info).path_translated is an invalid pointer.
1967 * It still happens even though I set it to null, so something
1968 * weird is going on.
1969 */
1970 tsrm_shutdown();
1971 #endif
1972 return FAILURE;
1973 }
1974 }
1975
1976 #ifndef HAVE_ATTRIBUTE_WEAK
1977 fcgi_set_logger(fcgi_log);
1978 #endif
1979
1980 if (bindpath) {
1981 int backlog = 128;
1982 if (getenv("PHP_FCGI_BACKLOG")) {
1983 backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
1984 }
1985 fcgi_fd = fcgi_listen(bindpath, backlog);
1986 if (fcgi_fd < 0) {
1987 fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
1988 #ifdef ZTS
1989 tsrm_shutdown();
1990 #endif
1991 return FAILURE;
1992 }
1993 fastcgi = fcgi_is_fastcgi();
1994 }
1995
1996 /* make php call us to get _ENV vars */
1997 php_php_import_environment_variables = php_import_environment_variables;
1998 php_import_environment_variables = cgi_php_import_environment_variables;
1999
2000 if (fastcgi) {
2001 /* How many times to run PHP scripts before dying */
2002 if (getenv("PHP_FCGI_MAX_REQUESTS")) {
2003 max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
2004 if (max_requests < 0) {
2005 fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
2006 return FAILURE;
2007 }
2008 }
2009
2010 /* library is already initialized, now init our request */
2011 request = fcgi_init_request(fcgi_fd, NULL, NULL, NULL);
2012
2013 /* Pre-fork or spawn, if required */
2014 if (getenv("PHP_FCGI_CHILDREN")) {
2015 char * children_str = getenv("PHP_FCGI_CHILDREN");
2016 children = atoi(children_str);
2017 if (children < 0) {
2018 fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
2019 return FAILURE;
2020 }
2021 fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
2022 /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
2023 fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
2024 } else {
2025 #ifdef PHP_WIN32
2026 /* If this env var is set, the process was invoked as a child. Let
2027 it show the original PHP_FCGI_CHILDREN value, while don't care
2028 otherwise. */
2029 char * children_str = getenv("PHP_FCGI_CHILDREN_FOR_KID");
2030 if (children_str) {
2031 char putenv_buf[sizeof("PHP_FCGI_CHILDREN")+5];
2032
2033 snprintf(putenv_buf, sizeof(putenv_buf), "%s=%s", "PHP_FCGI_CHILDREN", children_str);
2034 putenv(putenv_buf);
2035 putenv("PHP_FCGI_CHILDREN_FOR_KID=");
2036
2037 SetEnvironmentVariable("PHP_FCGI_CHILDREN", children_str);
2038 SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", NULL);
2039 }
2040 #endif
2041 fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
2042 fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
2043 }
2044
2045 #ifndef PHP_WIN32
2046 if (children) {
2047 int running = 0;
2048 pid_t pid;
2049
2050 /* Create a process group for ourself & children */
2051 setsid();
2052 pgroup = getpgrp();
2053 #ifdef DEBUG_FASTCGI
2054 fprintf(stderr, "Process group %d\n", pgroup);
2055 #endif
2056
2057 /* Set up handler to kill children upon exit */
2058 act.sa_flags = 0;
2059 act.sa_handler = fastcgi_cleanup;
2060 if (sigaction(SIGTERM, &act, &old_term) ||
2061 sigaction(SIGINT, &act, &old_int) ||
2062 sigaction(SIGQUIT, &act, &old_quit)
2063 ) {
2064 perror("Can't set signals");
2065 exit(1);
2066 }
2067
2068 if (fcgi_in_shutdown()) {
2069 goto parent_out;
2070 }
2071
2072 while (parent) {
2073 do {
2074 #ifdef DEBUG_FASTCGI
2075 fprintf(stderr, "Forking, %d running\n", running);
2076 #endif
2077 pid = fork();
2078 switch (pid) {
2079 case 0:
2080 /* One of the children.
2081 * Make sure we don't go round the
2082 * fork loop any more
2083 */
2084 parent = 0;
2085
2086 /* don't catch our signals */
2087 sigaction(SIGTERM, &old_term, 0);
2088 sigaction(SIGQUIT, &old_quit, 0);
2089 sigaction(SIGINT, &old_int, 0);
2090 zend_signal_init();
2091 break;
2092 case -1:
2093 perror("php (pre-forking)");
2094 exit(1);
2095 break;
2096 default:
2097 /* Fine */
2098 running++;
2099 break;
2100 }
2101 } while (parent && (running < children));
2102
2103 if (parent) {
2104 #ifdef DEBUG_FASTCGI
2105 fprintf(stderr, "Wait for kids, pid %d\n", getpid());
2106 #endif
2107 parent_waiting = 1;
2108 while (1) {
2109 if (wait(&status) >= 0) {
2110 running--;
2111 break;
2112 } else if (exit_signal) {
2113 break;
2114 }
2115 }
2116 if (exit_signal) {
2117 #if 0
2118 while (running > 0) {
2119 while (wait(&status) < 0) {
2120 }
2121 running--;
2122 }
2123 #endif
2124 goto parent_out;
2125 }
2126 }
2127 }
2128 } else {
2129 parent = 0;
2130 zend_signal_init();
2131 }
2132
2133 #else
2134 if (children) {
2135 wchar_t *cmd_line_tmp, cmd_line[PHP_WIN32_IOUTIL_MAXPATHLEN];
2136 size_t cmd_line_len;
2137 char kid_buf[16];
2138 int i;
2139
2140 ZeroMemory(&kid_cgi_ps, sizeof(kid_cgi_ps));
2141 kids = children < WIN32_MAX_SPAWN_CHILDREN ? children : WIN32_MAX_SPAWN_CHILDREN;
2142
2143 InitializeCriticalSection(&cleanup_lock);
2144 SetConsoleCtrlHandler(fastcgi_cleanup, TRUE);
2145
2146 /* kids will inherit the env, don't let them spawn */
2147 SetEnvironmentVariable("PHP_FCGI_CHILDREN", NULL);
2148 /* instead, set a temporary env var, so then the child can read and
2149 show the actual setting correctly. */
2150 snprintf(kid_buf, 16, "%d", children);
2151 SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", kid_buf);
2152
2153 /* The current command line is used as is. This should normally be no issue,
2154 even if there were some I/O redirection. If some issues turn out, an
2155 extra parsing might be needed here. */
2156 cmd_line_tmp = GetCommandLineW();
2157 if (!cmd_line_tmp) {
2158 DWORD err = GetLastError();
2159 char *err_text = php_win32_error_to_msg(err);
2160
2161 fprintf(stderr, "unable to get current command line: [0x%08lx]: %s\n", err, err_text);
2162
2163 goto parent_out;
2164 }
2165
2166 cmd_line_len = wcslen(cmd_line_tmp);
2167 if (cmd_line_len > sizeof(cmd_line) - 1) {
2168 fprintf(stderr, "command line is too long\n");
2169 goto parent_out;
2170 }
2171 memmove(cmd_line, cmd_line_tmp, (cmd_line_len + 1)*sizeof(wchar_t));
2172
2173 job = CreateJobObject(NULL, NULL);
2174 if (!job) {
2175 DWORD err = GetLastError();
2176 char *err_text = php_win32_error_to_msg(err);
2177
2178 fprintf(stderr, "unable to create job object: [0x%08lx]: %s\n", err, err_text);
2179
2180 goto parent_out;
2181 }
2182
2183 job_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
2184 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &job_info, sizeof(job_info))) {
2185 DWORD err = GetLastError();
2186 char *err_text = php_win32_error_to_msg(err);
2187
2188 fprintf(stderr, "unable to configure job object: [0x%08lx]: %s\n", err, err_text);
2189 }
2190
2191 while (parent) {
2192 EnterCriticalSection(&cleanup_lock);
2193 if (cleaning_up) {
2194 goto parent_loop_end;
2195 }
2196 LeaveCriticalSection(&cleanup_lock);
2197
2198 i = kids;
2199 while (0 < i--) {
2200 DWORD status;
2201
2202 if (NULL != kid_cgi_ps[i]) {
2203 if(!GetExitCodeProcess(kid_cgi_ps[i], &status) || status != STILL_ACTIVE) {
2204 CloseHandle(kid_cgi_ps[i]);
2205 kid_cgi_ps[i] = NULL;
2206 }
2207 }
2208 }
2209
2210 i = kids;
2211 while (0 < i--) {
2212 PROCESS_INFORMATION pi;
2213 STARTUPINFOW si;
2214
2215 if (NULL != kid_cgi_ps[i]) {
2216 continue;
2217 }
2218
2219 ZeroMemory(&si, sizeof(si));
2220 si.cb = sizeof(si);
2221 ZeroMemory(&pi, sizeof(pi));
2222
2223 si.dwFlags = STARTF_USESTDHANDLES;
2224 si.hStdOutput = INVALID_HANDLE_VALUE;
2225 si.hStdInput = (HANDLE)_get_osfhandle(fcgi_fd);
2226 si.hStdError = INVALID_HANDLE_VALUE;
2227
2228 if (CreateProcessW(NULL, cmd_line, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
2229 kid_cgi_ps[i] = pi.hProcess;
2230 if (!AssignProcessToJobObject(job, pi.hProcess)) {
2231 DWORD err = GetLastError();
2232 char *err_text = php_win32_error_to_msg(err);
2233
2234 fprintf(stderr, "unable to assign child process to job object: [0x%08lx]: %s\n", err, err_text);
2235 }
2236 CloseHandle(pi.hThread);
2237 } else {
2238 DWORD err = GetLastError();
2239 char *err_text = php_win32_error_to_msg(err);
2240
2241 kid_cgi_ps[i] = NULL;
2242
2243 fprintf(stderr, "unable to spawn: [0x%08lx]: %s\n", err, err_text);
2244 }
2245 }
2246
2247 WaitForMultipleObjects(kids, kid_cgi_ps, FALSE, INFINITE);
2248 }
2249
2250 parent_loop_end:
2251 /* restore my env */
2252 SetEnvironmentVariable("PHP_FCGI_CHILDREN", kid_buf);
2253
2254 DeleteCriticalSection(&cleanup_lock);
2255
2256 goto parent_out;
2257 } else {
2258 parent = 0;
2259 }
2260 #endif /* WIN32 */
2261 }
2262
2263 zend_first_try {
2264 while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
2265 switch (c) {
2266 case 'T':
2267 benchmark = 1;
2268 {
2269 char *comma = strchr(php_optarg, ',');
2270 if (comma) {
2271 warmup_repeats = atoi(php_optarg);
2272 repeats = atoi(comma + 1);
2273 #ifdef HAVE_VALGRIND
2274 if (warmup_repeats > 0) {
2275 CALLGRIND_STOP_INSTRUMENTATION;
2276 }
2277 #endif
2278 } else {
2279 repeats = atoi(php_optarg);
2280 }
2281 }
2282 #ifdef HAVE_GETTIMEOFDAY
2283 gettimeofday(&start, NULL);
2284 #else
2285 time(&start);
2286 #endif
2287 break;
2288 case 'h':
2289 case '?':
2290 case PHP_GETOPT_INVALID_ARG:
2291 if (request) {
2292 fcgi_destroy_request(request);
2293 }
2294 fcgi_shutdown();
2295 no_headers = 1;
2296 SG(headers_sent) = 1;
2297 php_cgi_usage(argv[0]);
2298 php_output_end_all();
2299 exit_status = 0;
2300 if (c == PHP_GETOPT_INVALID_ARG) {
2301 exit_status = 1;
2302 }
2303 goto out;
2304 }
2305 }
2306 php_optind = orig_optind;
2307 php_optarg = orig_optarg;
2308
2309 /* start of FAST CGI loop */
2310 /* Initialise FastCGI request structure */
2311 #ifdef PHP_WIN32
2312 /* attempt to set security impersonation for fastcgi
2313 * will only happen on NT based OS, others will ignore it. */
2314 if (fastcgi && CGIG(impersonate)) {
2315 fcgi_impersonate();
2316 }
2317 #endif
2318 while (!fastcgi || fcgi_accept_request(request) >= 0) {
2319 SG(server_context) = fastcgi ? (void *)request : (void *) 1;
2320 init_request_info(request);
2321
2322 if (!cgi && !fastcgi) {
2323 while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
2324 switch (c) {
2325
2326 case 'a': /* interactive mode */
2327 printf("Interactive mode enabled\n\n");
2328 break;
2329
2330 case 'C': /* don't chdir to the script directory */
2331 SG(options) |= SAPI_OPTION_NO_CHDIR;
2332 break;
2333
2334 case 'e': /* enable extended info output */
2335 CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
2336 break;
2337
2338 case 'f': /* parse file */
2339 if (script_file) {
2340 efree(script_file);
2341 }
2342 script_file = estrdup(php_optarg);
2343 no_headers = 1;
2344 break;
2345
2346 case 'i': /* php info & quit */
2347 if (script_file) {
2348 efree(script_file);
2349 }
2350 if (php_request_startup() == FAILURE) {
2351 SG(server_context) = NULL;
2352 php_module_shutdown();
2353 return FAILURE;
2354 }
2355 if (no_headers) {
2356 SG(headers_sent) = 1;
2357 SG(request_info).no_headers = 1;
2358 }
2359 php_print_info(0xFFFFFFFF);
2360 php_request_shutdown((void *) 0);
2361 fcgi_shutdown();
2362 exit_status = 0;
2363 goto out;
2364
2365 case 'l': /* syntax check mode */
2366 no_headers = 1;
2367 behavior = PHP_MODE_LINT;
2368 break;
2369
2370 case 'm': /* list compiled in modules */
2371 if (script_file) {
2372 efree(script_file);
2373 }
2374 SG(headers_sent) = 1;
2375 php_printf("[PHP Modules]\n");
2376 print_modules();
2377 php_printf("\n[Zend Modules]\n");
2378 print_extensions();
2379 php_printf("\n");
2380 php_output_end_all();
2381 fcgi_shutdown();
2382 exit_status = 0;
2383 goto out;
2384
2385 case 'q': /* do not generate HTTP headers */
2386 no_headers = 1;
2387 break;
2388
2389 case 'v': /* show php version & quit */
2390 if (script_file) {
2391 efree(script_file);
2392 }
2393 no_headers = 1;
2394 if (php_request_startup() == FAILURE) {
2395 SG(server_context) = NULL;
2396 php_module_shutdown();
2397 return FAILURE;
2398 }
2399 SG(headers_sent) = 1;
2400 SG(request_info).no_headers = 1;
2401 #if ZEND_DEBUG
2402 php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2018 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
2403 #else
2404 php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2018 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
2405 #endif
2406 php_request_shutdown((void *) 0);
2407 fcgi_shutdown();
2408 exit_status = 0;
2409 goto out;
2410
2411 case 'w':
2412 behavior = PHP_MODE_STRIP;
2413 break;
2414
2415 case 'z': /* load extension file */
2416 zend_load_extension(php_optarg);
2417 break;
2418
2419 default:
2420 break;
2421 }
2422 }
2423
2424 if (script_file) {
2425 /* override path_translated if -f on command line */
2426 if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2427 SG(request_info).path_translated = script_file;
2428 /* before registering argv to module exchange the *new* argv[0] */
2429 /* we can achieve this without allocating more memory */
2430 SG(request_info).argc = argc - (php_optind - 1);
2431 SG(request_info).argv = &argv[php_optind - 1];
2432 SG(request_info).argv[0] = script_file;
2433 } else if (argc > php_optind) {
2434 /* file is on command line, but not in -f opt */
2435 if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2436 SG(request_info).path_translated = estrdup(argv[php_optind]);
2437 /* arguments after the file are considered script args */
2438 SG(request_info).argc = argc - php_optind;
2439 SG(request_info).argv = &argv[php_optind];
2440 }
2441
2442 if (no_headers) {
2443 SG(headers_sent) = 1;
2444 SG(request_info).no_headers = 1;
2445 }
2446
2447 /* all remaining arguments are part of the query string
2448 * this section of code concatenates all remaining arguments
2449 * into a single string, separating args with a &
2450 * this allows command lines like:
2451 *
2452 * test.php v1=test v2=hello+world!
2453 * test.php "v1=test&v2=hello world!"
2454 * test.php v1=test "v2=hello world!"
2455 */
2456 if (!SG(request_info).query_string && argc > php_optind) {
2457 size_t slen = strlen(PG(arg_separator).input);
2458 len = 0;
2459 for (i = php_optind; i < argc; i++) {
2460 if (i < (argc - 1)) {
2461 len += strlen(argv[i]) + slen;
2462 } else {
2463 len += strlen(argv[i]);
2464 }
2465 }
2466
2467 len += 2;
2468 s = malloc(len);
2469 *s = '\0'; /* we are pretending it came from the environment */
2470 for (i = php_optind; i < argc; i++) {
2471 strlcat(s, argv[i], len);
2472 if (i < (argc - 1)) {
2473 strlcat(s, PG(arg_separator).input, len);
2474 }
2475 }
2476 SG(request_info).query_string = s;
2477 free_query_string = 1;
2478 }
2479 } /* end !cgi && !fastcgi */
2480
2481 /*
2482 we never take stdin if we're (f)cgi, always
2483 rely on the web server giving us the info
2484 we need in the environment.
2485 */
2486 if (SG(request_info).path_translated || cgi || fastcgi) {
2487 file_handle.type = ZEND_HANDLE_FILENAME;
2488 file_handle.filename = SG(request_info).path_translated;
2489 file_handle.handle.fp = NULL;
2490 } else {
2491 file_handle.filename = "Standard input code";
2492 file_handle.type = ZEND_HANDLE_FP;
2493 file_handle.handle.fp = stdin;
2494 }
2495
2496 file_handle.opened_path = NULL;
2497 file_handle.free_filename = 0;
2498
2499 /* request startup only after we've done all we can to
2500 * get path_translated */
2501 if (php_request_startup() == FAILURE) {
2502 if (fastcgi) {
2503 fcgi_finish_request(request, 1);
2504 }
2505 SG(server_context) = NULL;
2506 php_module_shutdown();
2507 return FAILURE;
2508 }
2509 if (no_headers) {
2510 SG(headers_sent) = 1;
2511 SG(request_info).no_headers = 1;
2512 }
2513
2514 /*
2515 at this point path_translated will be set if:
2516 1. we are running from shell and got filename was there
2517 2. we are running as cgi or fastcgi
2518 */
2519 if (cgi || fastcgi || SG(request_info).path_translated) {
2520 if (php_fopen_primary_script(&file_handle) == FAILURE) {
2521 zend_try {
2522 if (errno == EACCES) {
2523 SG(sapi_headers).http_response_code = 403;
2524 PUTS("Access denied.\n");
2525 } else {
2526 SG(sapi_headers).http_response_code = 404;
2527 PUTS("No input file specified.\n");
2528 }
2529 } zend_catch {
2530 } zend_end_try();
2531 /* we want to serve more requests if this is fastcgi
2532 * so cleanup and continue, request shutdown is
2533 * handled later */
2534 if (fastcgi) {
2535 goto fastcgi_request_done;
2536 }
2537
2538 if (SG(request_info).path_translated) {
2539 efree(SG(request_info).path_translated);
2540 SG(request_info).path_translated = NULL;
2541 }
2542
2543 if (free_query_string && SG(request_info).query_string) {
2544 free(SG(request_info).query_string);
2545 SG(request_info).query_string = NULL;
2546 }
2547
2548 php_request_shutdown((void *) 0);
2549 SG(server_context) = NULL;
2550 php_module_shutdown();
2551 sapi_shutdown();
2552 #ifdef ZTS
2553 tsrm_shutdown();
2554 #endif
2555 return FAILURE;
2556 }
2557 }
2558
2559 if (CGIG(check_shebang_line)) {
2560 /* #!php support */
2561 switch (file_handle.type) {
2562 case ZEND_HANDLE_FD:
2563 if (file_handle.handle.fd < 0) {
2564 break;
2565 }
2566 file_handle.type = ZEND_HANDLE_FP;
2567 file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
2568 /* break missing intentionally */
2569 case ZEND_HANDLE_FP:
2570 if (!file_handle.handle.fp ||
2571 (file_handle.handle.fp == stdin)) {
2572 break;
2573 }
2574 c = fgetc(file_handle.handle.fp);
2575 if (c == '#') {
2576 while (c != '\n' && c != '\r' && c != EOF) {
2577 c = fgetc(file_handle.handle.fp); /* skip to end of line */
2578 }
2579 /* handle situations where line is terminated by \r\n */
2580 if (c == '\r') {
2581 if (fgetc(file_handle.handle.fp) != '\n') {
2582 zend_long pos = zend_ftell(file_handle.handle.fp);
2583 zend_fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
2584 }
2585 }
2586 CG(start_lineno) = 2;
2587 } else {
2588 rewind(file_handle.handle.fp);
2589 }
2590 break;
2591 case ZEND_HANDLE_STREAM:
2592 c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
2593 if (c == '#') {
2594 while (c != '\n' && c != '\r' && c != EOF) {
2595 c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
2596 }
2597 /* handle situations where line is terminated by \r\n */
2598 if (c == '\r') {
2599 if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
2600 zend_off_t pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
2601 php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
2602 }
2603 }
2604 CG(start_lineno) = 2;
2605 } else {
2606 php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
2607 }
2608 break;
2609 case ZEND_HANDLE_MAPPED:
2610 if (file_handle.handle.stream.mmap.buf[0] == '#') {
2611 size_t i = 1;
2612
2613 c = file_handle.handle.stream.mmap.buf[i++];
2614 while (c != '\n' && c != '\r' && i < file_handle.handle.stream.mmap.len) {
2615 c = file_handle.handle.stream.mmap.buf[i++];
2616 }
2617 if (c == '\r') {
2618 if (i < file_handle.handle.stream.mmap.len && file_handle.handle.stream.mmap.buf[i] == '\n') {
2619 i++;
2620 }
2621 }
2622 if(i > file_handle.handle.stream.mmap.len) {
2623 i = file_handle.handle.stream.mmap.len;
2624 }
2625 file_handle.handle.stream.mmap.buf += i;
2626 file_handle.handle.stream.mmap.len -= i;
2627 }
2628 break;
2629 default:
2630 break;
2631 }
2632 }
2633
2634 switch (behavior) {
2635 case PHP_MODE_STANDARD:
2636 php_execute_script(&file_handle);
2637 break;
2638 case PHP_MODE_LINT:
2639 PG(during_request_startup) = 0;
2640 exit_status = php_lint_script(&file_handle);
2641 if (exit_status == SUCCESS) {
2642 zend_printf("No syntax errors detected in %s\n", file_handle.filename);
2643 } else {
2644 zend_printf("Errors parsing %s\n", file_handle.filename);
2645 }
2646 break;
2647 case PHP_MODE_STRIP:
2648 if (open_file_for_scanning(&file_handle) == SUCCESS) {
2649 zend_strip();
2650 zend_file_handle_dtor(&file_handle);
2651 php_output_teardown();
2652 }
2653 return SUCCESS;
2654 break;
2655 case PHP_MODE_HIGHLIGHT:
2656 {
2657 zend_syntax_highlighter_ini syntax_highlighter_ini;
2658
2659 if (open_file_for_scanning(&file_handle) == SUCCESS) {
2660 php_get_highlight_struct(&syntax_highlighter_ini);
2661 zend_highlight(&syntax_highlighter_ini);
2662 if (fastcgi) {
2663 goto fastcgi_request_done;
2664 }
2665 zend_file_handle_dtor(&file_handle);
2666 php_output_teardown();
2667 }
2668 return SUCCESS;
2669 }
2670 break;
2671 }
2672
2673 fastcgi_request_done:
2674 {
2675 if (SG(request_info).path_translated) {
2676 efree(SG(request_info).path_translated);
2677 SG(request_info).path_translated = NULL;
2678 }
2679
2680 php_request_shutdown((void *) 0);
2681
2682 if (exit_status == 0) {
2683 exit_status = EG(exit_status);
2684 }
2685
2686 if (free_query_string && SG(request_info).query_string) {
2687 free(SG(request_info).query_string);
2688 SG(request_info).query_string = NULL;
2689 }
2690 }
2691
2692 if (!fastcgi) {
2693 if (benchmark) {
2694 if (warmup_repeats) {
2695 warmup_repeats--;
2696 if (!warmup_repeats) {
2697 #ifdef HAVE_GETTIMEOFDAY
2698 gettimeofday(&start, NULL);
2699 #else
2700 time(&start);
2701 #endif
2702 #ifdef HAVE_VALGRIND
2703 CALLGRIND_START_INSTRUMENTATION;
2704 #endif
2705 }
2706 continue;
2707 } else {
2708 repeats--;
2709 if (repeats > 0) {
2710 script_file = NULL;
2711 php_optind = orig_optind;
2712 php_optarg = orig_optarg;
2713 continue;
2714 }
2715 }
2716 }
2717 break;
2718 }
2719
2720 /* only fastcgi will get here */
2721 requests++;
2722 if (max_requests && (requests == max_requests)) {
2723 fcgi_finish_request(request, 1);
2724 if (bindpath) {
2725 free(bindpath);
2726 }
2727 if (max_requests != 1) {
2728 /* no need to return exit_status of the last request */
2729 exit_status = 0;
2730 }
2731 break;
2732 }
2733 /* end of fastcgi loop */
2734 }
2735
2736 if (request) {
2737 fcgi_destroy_request(request);
2738 }
2739 fcgi_shutdown();
2740
2741 if (cgi_sapi_module.php_ini_path_override) {
2742 free(cgi_sapi_module.php_ini_path_override);
2743 }
2744 if (cgi_sapi_module.ini_entries) {
2745 free(cgi_sapi_module.ini_entries);
2746 }
2747 } zend_catch {
2748 exit_status = 255;
2749 } zend_end_try();
2750
2751 out:
2752 if (benchmark) {
2753 int sec;
2754 #ifdef HAVE_GETTIMEOFDAY
2755 int usec;
2756
2757 gettimeofday(&end, NULL);
2758 sec = (int)(end.tv_sec - start.tv_sec);
2759 if (end.tv_usec >= start.tv_usec) {
2760 usec = (int)(end.tv_usec - start.tv_usec);
2761 } else {
2762 sec -= 1;
2763 usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2764 }
2765 fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2766 #else
2767 time(&end);
2768 sec = (int)(end - start);
2769 fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2770 #endif
2771 }
2772
2773 parent_out:
2774
2775 SG(server_context) = NULL;
2776 php_module_shutdown();
2777 sapi_shutdown();
2778
2779 #ifdef ZTS
2780 tsrm_shutdown();
2781 #endif
2782
2783 #if defined(PHP_WIN32) && ZEND_DEBUG && 0
2784 _CrtDumpMemoryLeaks();
2785 #endif
2786
2787 return exit_status;
2788 }
2789 /* }}} */
2790
2791 /*
2792 * Local variables:
2793 * tab-width: 4
2794 * c-basic-offset: 4
2795 * End:
2796 * vim600: sw=4 ts=4 fdm=marker
2797 * vim<600: sw=4 ts=4
2798 */
2799