PageRenderTime 104ms CodeModel.GetById 15ms RepoModel.GetById 2ms app.codeStats 0ms

/sapi/fpm/fpm/fpm_main.c

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