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