PageRenderTime 63ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/sapi/cgi/cgi_main.c

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