PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/cgi/cgi_main.c

http://github.com/dreamcat4/php-fpm
C | 1660 lines | 1308 code | 144 blank | 208 comment | 195 complexity | b07d06ea3e953b50c8b60e6e881200bc MD5 | raw file
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2008 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,v 1.267.2.15.2.66 2008/11/28 11:56:50 dmitry Exp $ */
  24. #include <php.h>
  25. #include <php_globals.h>
  26. #include <php_variables.h>
  27. #include <zend_modules.h>
  28. #include <SAPI.h>
  29. #include <stdio.h>
  30. #ifdef PHP_WIN32
  31. #include "win32/time.h"
  32. #include "win32/signal.h"
  33. #include <process.h>
  34. #endif
  35. #if HAVE_SYS_TIME_H
  36. #include <sys/time.h>
  37. #endif
  38. #if HAVE_UNISTD_H
  39. #include <unistd.h>
  40. #endif
  41. #if HAVE_SIGNAL_H
  42. #include <signal.h>
  43. #endif
  44. #if HAVE_SETLOCALE
  45. #include <locale.h>
  46. #endif
  47. #if HAVE_SYS_TYPES_H
  48. #include <sys/types.h>
  49. #endif
  50. #if HAVE_SYS_WAIT_H
  51. #include <sys/wait.h>
  52. #endif
  53. #if HAVE_FCNTL_H
  54. #include <fcntl.h>
  55. #endif
  56. #include <zend.h>
  57. #include <zend_extensions.h>
  58. #include <php_ini.h>
  59. #include <php_main.h>
  60. #include <fopen_wrappers.h>
  61. #include <ext/standard/php_standard.h>
  62. #ifdef PHP_WIN32
  63. #include <io.h>
  64. #include <fcntl.h>
  65. #include "win32/php_registry.h"
  66. #endif
  67. #ifdef __riscos__
  68. #include <unixlib/local.h>
  69. int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
  70. #endif
  71. #include "zend_compile.h"
  72. #include "zend_execute.h"
  73. #include "zend_highlight.h"
  74. #include "zend_indent.h"
  75. #include "php_getopt.h"
  76. #include "fastcgi.h"
  77. #ifdef FPM_AUTOCONFIG_H
  78. #include <fpm_autoconfig.h>
  79. #else
  80. #include <php_config.h>
  81. #endif
  82. #include <fpm/fpm.h>
  83. #include <fpm/fpm_request.h>
  84. static void (*php_php_import_environment_variables)(zval *array_ptr TSRMLS_DC);
  85. static int parent = 1;
  86. static int request_body_fd;
  87. static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC);
  88. static char *php_optarg = NULL;
  89. static int php_optind = 1;
  90. static zend_module_entry cgi_module_entry;
  91. static const opt_struct OPTIONS[] = {
  92. {'a', 0, "interactive"},
  93. {'b', 1, "bindpath"},
  94. {'C', 0, "no-chdir"},
  95. {'c', 1, "php-ini"},
  96. {'d', 1, "define"},
  97. {'e', 0, "profile-info"},
  98. {'f', 1, "file"},
  99. {'h', 0, "help"},
  100. {'i', 0, "info"},
  101. {'l', 0, "syntax-check"},
  102. {'m', 0, "modules"},
  103. {'n', 0, "no-php-ini"},
  104. {'q', 0, "no-header"},
  105. {'s', 0, "syntax-highlight"},
  106. {'s', 0, "syntax-highlighting"},
  107. {'w', 0, "strip"},
  108. {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
  109. {'v', 0, "version"},
  110. {'x', 0, "fpm"},
  111. {'y', 1, "fpm-config"},
  112. {'z', 1, "zend-extension"},
  113. {'-', 0, NULL} /* end of args */
  114. };
  115. typedef struct _php_cgi_globals_struct {
  116. zend_bool rfc2616_headers;
  117. zend_bool nph;
  118. zend_bool check_shebang_line;
  119. #if ENABLE_PATHINFO_CHECK
  120. zend_bool fix_pathinfo;
  121. #endif
  122. zend_bool fcgi_logging;
  123. # ifdef PHP_WIN32
  124. zend_bool impersonate;
  125. # endif
  126. char *error_header;
  127. } php_cgi_globals_struct;
  128. #ifdef ZTS
  129. static int php_cgi_globals_id;
  130. #define CGIG(v) TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
  131. #else
  132. static php_cgi_globals_struct php_cgi_globals;
  133. #define CGIG(v) (php_cgi_globals.v)
  134. #endif
  135. #ifdef PHP_WIN32
  136. #define TRANSLATE_SLASHES(path) \
  137. { \
  138. char *tmp = path; \
  139. while (*tmp) { \
  140. if (*tmp == '\\') *tmp = '/'; \
  141. tmp++; \
  142. } \
  143. }
  144. #else
  145. #define TRANSLATE_SLASHES(path)
  146. #endif
  147. static int print_module_info(zend_module_entry *module, void *arg TSRMLS_DC)
  148. {
  149. php_printf("%s\n", module->name);
  150. return 0;
  151. }
  152. static int module_name_cmp(const void *a, const void *b TSRMLS_DC)
  153. {
  154. Bucket *f = *((Bucket **) a);
  155. Bucket *s = *((Bucket **) b);
  156. return strcasecmp(((zend_module_entry *)f->pData)->name,
  157. ((zend_module_entry *)s->pData)->name);
  158. }
  159. static void print_modules(TSRMLS_D)
  160. {
  161. HashTable sorted_registry;
  162. zend_module_entry tmp;
  163. zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
  164. zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
  165. zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
  166. zend_hash_apply_with_argument(&sorted_registry, (apply_func_arg_t) print_module_info, NULL TSRMLS_CC);
  167. zend_hash_destroy(&sorted_registry);
  168. }
  169. static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC)
  170. {
  171. php_printf("%s\n", ext->name);
  172. return 0;
  173. }
  174. static int extension_name_cmp(const zend_llist_element **f,
  175. const zend_llist_element **s TSRMLS_DC)
  176. {
  177. return strcmp(((zend_extension *)(*f)->data)->name,
  178. ((zend_extension *)(*s)->data)->name);
  179. }
  180. static void print_extensions(TSRMLS_D)
  181. {
  182. zend_llist sorted_exts;
  183. zend_llist_copy(&sorted_exts, &zend_extensions);
  184. sorted_exts.dtor = NULL;
  185. zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
  186. zend_llist_apply_with_argument(&sorted_exts, (llist_apply_with_arg_func_t) print_extension_info, NULL TSRMLS_CC);
  187. zend_llist_destroy(&sorted_exts);
  188. }
  189. #ifndef STDOUT_FILENO
  190. #define STDOUT_FILENO 1
  191. #endif
  192. static inline size_t sapi_cgibin_single_write(const char *str, uint str_length TSRMLS_DC)
  193. {
  194. long ret;
  195. if (fcgi_is_fastcgi()) {
  196. fcgi_request *request = (fcgi_request*) SG(server_context);
  197. long ret = fcgi_write(request, FCGI_STDOUT, str, str_length);
  198. if (ret <= 0) {
  199. return 0;
  200. }
  201. return ret;
  202. }
  203. ret = write(STDOUT_FILENO, str, str_length);
  204. if (ret <= 0) return 0;
  205. return ret;
  206. }
  207. static int sapi_cgibin_ub_write(const char *str, uint str_length TSRMLS_DC)
  208. {
  209. const char *ptr = str;
  210. uint remaining = str_length;
  211. size_t ret;
  212. while (remaining > 0) {
  213. ret = sapi_cgibin_single_write(ptr, remaining TSRMLS_CC);
  214. if (!ret) {
  215. php_handle_aborted_connection();
  216. return str_length - remaining;
  217. }
  218. ptr += ret;
  219. remaining -= ret;
  220. }
  221. return str_length;
  222. }
  223. static void sapi_cgibin_flush(void *server_context)
  224. {
  225. if (fcgi_is_fastcgi()) {
  226. fcgi_request *request = (fcgi_request*) server_context;
  227. if (
  228. #ifndef PHP_WIN32
  229. !parent &&
  230. #endif
  231. request && !fcgi_flush(request, 0)) {
  232. php_handle_aborted_connection();
  233. }
  234. return;
  235. }
  236. if (fflush(stdout) == EOF) {
  237. php_handle_aborted_connection();
  238. }
  239. }
  240. #define SAPI_CGI_MAX_HEADER_LENGTH 1024
  241. typedef struct _http_error {
  242. int code;
  243. const char* msg;
  244. } http_error;
  245. static const http_error http_error_codes[] = {
  246. {100, "Continue"},
  247. {101, "Switching Protocols"},
  248. {200, "OK"},
  249. {201, "Created"},
  250. {202, "Accepted"},
  251. {203, "Non-Authoritative Information"},
  252. {204, "No Content"},
  253. {205, "Reset Content"},
  254. {206, "Partial Content"},
  255. {300, "Multiple Choices"},
  256. {301, "Moved Permanently"},
  257. {302, "Moved Temporarily"},
  258. {303, "See Other"},
  259. {304, "Not Modified"},
  260. {305, "Use Proxy"},
  261. {400, "Bad Request"},
  262. {401, "Unauthorized"},
  263. {402, "Payment Required"},
  264. {403, "Forbidden"},
  265. {404, "Not Found"},
  266. {405, "Method Not Allowed"},
  267. {406, "Not Acceptable"},
  268. {407, "Proxy Authentication Required"},
  269. {408, "Request Time-out"},
  270. {409, "Conflict"},
  271. {410, "Gone"},
  272. {411, "Length Required"},
  273. {412, "Precondition Failed"},
  274. {413, "Request Entity Too Large"},
  275. {414, "Request-URI Too Large"},
  276. {415, "Unsupported Media Type"},
  277. {500, "Internal Server Error"},
  278. {501, "Not Implemented"},
  279. {502, "Bad Gateway"},
  280. {503, "Service Unavailable"},
  281. {504, "Gateway Time-out"},
  282. {505, "HTTP Version not supported"},
  283. {0, NULL}
  284. };
  285. static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
  286. {
  287. char buf[SAPI_CGI_MAX_HEADER_LENGTH];
  288. sapi_header_struct *h;
  289. zend_llist_position pos;
  290. zend_bool ignore_status = 0;
  291. int response_status = SG(sapi_headers).http_response_code;
  292. if (SG(request_info).no_headers == 1) {
  293. return SAPI_HEADER_SENT_SUCCESSFULLY;
  294. }
  295. if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
  296. {
  297. int len;
  298. zend_bool has_status = 0;
  299. if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
  300. char *s;
  301. len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
  302. if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
  303. response_status = atoi((s + 1));
  304. }
  305. if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
  306. len = SAPI_CGI_MAX_HEADER_LENGTH;
  307. }
  308. } else {
  309. char *s;
  310. if (SG(sapi_headers).http_status_line &&
  311. (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
  312. (s - SG(sapi_headers).http_status_line) >= 5 &&
  313. strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0) {
  314. len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
  315. response_status = atoi((s + 1));
  316. } else {
  317. h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
  318. while (h) {
  319. if (h->header_len > sizeof("Status:")-1 &&
  320. strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0) {
  321. has_status = 1;
  322. break;
  323. }
  324. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  325. }
  326. if (!has_status) {
  327. http_error *err = (http_error*)http_error_codes;
  328. while (err->code != 0) {
  329. if (err->code == SG(sapi_headers).http_response_code) {
  330. break;
  331. }
  332. err++;
  333. }
  334. if (err->msg) {
  335. len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->msg);
  336. } else {
  337. len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
  338. }
  339. }
  340. }
  341. }
  342. if (!has_status) {
  343. PHPWRITE_H(buf, len);
  344. ignore_status = 1;
  345. }
  346. }
  347. h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
  348. while (h) {
  349. /* prevent CRLFCRLF */
  350. if (h->header_len) {
  351. if (h->header_len > sizeof("Status:")-1 &&
  352. strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0) {
  353. if (!ignore_status) {
  354. ignore_status = 1;
  355. PHPWRITE_H(h->header, h->header_len);
  356. PHPWRITE_H("\r\n", 2);
  357. }
  358. } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
  359. strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0) {
  360. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  361. continue;
  362. } else {
  363. PHPWRITE_H(h->header, h->header_len);
  364. PHPWRITE_H("\r\n", 2);
  365. }
  366. }
  367. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  368. }
  369. PHPWRITE_H("\r\n", 2);
  370. return SAPI_HEADER_SENT_SUCCESSFULLY;
  371. }
  372. static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
  373. {
  374. int read_bytes=0, tmp_read_bytes;
  375. count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
  376. while (read_bytes < count_bytes) {
  377. if (fcgi_is_fastcgi()) {
  378. fcgi_request *request = (fcgi_request*) SG(server_context);
  379. if (request_body_fd == -1) {
  380. char *request_body_filename = sapi_cgibin_getenv((char *) "REQUEST_BODY_FILE",
  381. sizeof("REQUEST_BODY_FILE")-1 TSRMLS_CC);
  382. if (request_body_filename && *request_body_filename) {
  383. request_body_fd = open(request_body_filename, O_RDONLY);
  384. if (0 > request_body_fd) {
  385. php_error(E_WARNING, "REQUEST_BODY_FILE: open('%s') failed: %s (%d)",
  386. request_body_filename, strerror(errno), errno);
  387. return 0;
  388. }
  389. }
  390. }
  391. /* If REQUEST_BODY_FILE variable not available - read post body from fastcgi stream */
  392. if (request_body_fd < 0) {
  393. tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes);
  394. } else {
  395. tmp_read_bytes = read(request_body_fd, buffer + read_bytes, count_bytes - read_bytes);
  396. }
  397. } else {
  398. tmp_read_bytes = read(0, buffer + read_bytes, count_bytes - read_bytes);
  399. }
  400. if (tmp_read_bytes <= 0) {
  401. break;
  402. }
  403. read_bytes += tmp_read_bytes;
  404. }
  405. return read_bytes;
  406. }
  407. static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC)
  408. {
  409. /* when php is started by mod_fastcgi, no regular environment
  410. is provided to PHP. It is always sent to PHP at the start
  411. of a request. So we have to do our own lookup to get env
  412. vars. This could probably be faster somehow. */
  413. if (fcgi_is_fastcgi()) {
  414. fcgi_request *request = (fcgi_request*) SG(server_context);
  415. return fcgi_getenv(request, name, name_len);
  416. }
  417. /* if cgi, or fastcgi and not found in fcgi env
  418. check the regular environment */
  419. return getenv(name);
  420. }
  421. static char *_sapi_cgibin_putenv(char *name, char *value TSRMLS_DC)
  422. {
  423. int name_len;
  424. #if !HAVE_SETENV || !HAVE_UNSETENV
  425. int len;
  426. char *buf;
  427. #endif
  428. if (!name) {
  429. return NULL;
  430. }
  431. name_len = strlen(name);
  432. /* when php is started by mod_fastcgi, no regular environment
  433. is provided to PHP. It is always sent to PHP at the start
  434. of a request. So we have to do our own lookup to get env
  435. vars. This could probably be faster somehow. */
  436. if (fcgi_is_fastcgi()) {
  437. fcgi_request *request = (fcgi_request*) SG(server_context);
  438. return fcgi_putenv(request, name, name_len, value);
  439. }
  440. #if HAVE_SETENV
  441. if (value) {
  442. setenv(name, value, 1);
  443. }
  444. #endif
  445. #if HAVE_UNSETENV
  446. if (!value) {
  447. unsetenv(name);
  448. }
  449. #endif
  450. #if !HAVE_SETENV || !HAVE_UNSETENV
  451. /* if cgi, or fastcgi and not found in fcgi env
  452. check the regular environment
  453. this leaks, but it's only cgi anyway, we'll fix
  454. it for 5.0
  455. */
  456. len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
  457. buf = (char *) malloc(len);
  458. if (buf == NULL) {
  459. return getenv(name);
  460. }
  461. #endif
  462. #if !HAVE_SETENV
  463. if (value) {
  464. len = slprintf(buf, len - 1, "%s=%s", name, value);
  465. putenv(buf);
  466. }
  467. #endif
  468. #if !HAVE_UNSETENV
  469. if (!value) {
  470. len = slprintf(buf, len - 1, "%s=", name);
  471. putenv(buf);
  472. }
  473. #endif
  474. return getenv(name);
  475. }
  476. static char *sapi_cgi_read_cookies(TSRMLS_D)
  477. {
  478. return sapi_cgibin_getenv((char *) "HTTP_COOKIE", sizeof("HTTP_COOKIE")-1 TSRMLS_CC);
  479. }
  480. void cgi_php_import_environment_variables(zval *array_ptr TSRMLS_DC)
  481. {
  482. if (PG(http_globals)[TRACK_VARS_ENV] &&
  483. array_ptr != PG(http_globals)[TRACK_VARS_ENV] &&
  484. Z_TYPE_P(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
  485. zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_ENV])) > 0) {
  486. zval_dtor(array_ptr);
  487. *array_ptr = *PG(http_globals)[TRACK_VARS_ENV];
  488. INIT_PZVAL(array_ptr);
  489. zval_copy_ctor(array_ptr);
  490. return;
  491. } else if (PG(http_globals)[TRACK_VARS_SERVER] &&
  492. array_ptr != PG(http_globals)[TRACK_VARS_SERVER] &&
  493. Z_TYPE_P(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
  494. zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER])) > 0) {
  495. zval_dtor(array_ptr);
  496. *array_ptr = *PG(http_globals)[TRACK_VARS_SERVER];
  497. INIT_PZVAL(array_ptr);
  498. zval_copy_ctor(array_ptr);
  499. return;
  500. }
  501. /* call php's original import as a catch-all */
  502. php_php_import_environment_variables(array_ptr TSRMLS_CC);
  503. if (fcgi_is_fastcgi()) {
  504. fcgi_request *request = (fcgi_request*) SG(server_context);
  505. HashPosition pos;
  506. int magic_quotes_gpc = PG(magic_quotes_gpc);
  507. char *var, **val;
  508. uint var_len;
  509. ulong idx;
  510. int filter_arg = (array_ptr == PG(http_globals)[TRACK_VARS_ENV])?PARSE_ENV:PARSE_SERVER;
  511. /* turn off magic_quotes while importing environment variables */
  512. PG(magic_quotes_gpc) = 0;
  513. for (zend_hash_internal_pointer_reset_ex(&request->env, &pos);
  514. zend_hash_get_current_key_ex(&request->env, &var, &var_len, &idx, 0, &pos) == HASH_KEY_IS_STRING &&
  515. zend_hash_get_current_data_ex(&request->env, (void **) &val, &pos) == SUCCESS;
  516. zend_hash_move_forward_ex(&request->env, &pos)) {
  517. unsigned int new_val_len;
  518. if (sapi_module.input_filter(filter_arg, var, val, strlen(*val), &new_val_len TSRMLS_CC)) {
  519. php_register_variable_safe(var, *val, new_val_len, array_ptr TSRMLS_CC);
  520. }
  521. }
  522. PG(magic_quotes_gpc) = magic_quotes_gpc;
  523. }
  524. }
  525. static void sapi_cgi_register_variables(zval *track_vars_array TSRMLS_DC)
  526. {
  527. unsigned int php_self_len;
  528. char *php_self;
  529. /* In CGI mode, we consider the environment to be a part of the server
  530. * variables
  531. */
  532. php_import_environment_variables(track_vars_array TSRMLS_CC);
  533. #if ENABLE_PATHINFO_CHECK
  534. if (CGIG(fix_pathinfo)) {
  535. char *script_name = SG(request_info).request_uri;
  536. unsigned int script_name_len = script_name ? strlen(script_name) : 0;
  537. char *path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
  538. unsigned int path_info_len = path_info ? strlen(path_info) : 0;
  539. php_self_len = script_name_len + path_info_len;
  540. php_self = emalloc(php_self_len + 1);
  541. if (script_name) {
  542. memcpy(php_self, script_name, script_name_len + 1);
  543. }
  544. if (path_info) {
  545. memcpy(php_self + script_name_len, path_info, path_info_len + 1);
  546. }
  547. /* Build the special-case PHP_SELF variable for the CGI version */
  548. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
  549. php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
  550. }
  551. efree(php_self);
  552. return;
  553. }
  554. #endif
  555. php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
  556. php_self_len = strlen(php_self);
  557. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
  558. php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
  559. }
  560. }
  561. static void sapi_cgi_log_message(char *message)
  562. {
  563. TSRMLS_FETCH();
  564. if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
  565. fcgi_request *request;
  566. request = (fcgi_request*) SG(server_context);
  567. if (request) {
  568. int len = strlen(message);
  569. char *buf = malloc(len+2);
  570. memcpy(buf, message, len);
  571. memcpy(buf + len, "\n", sizeof("\n"));
  572. fcgi_write(request, FCGI_STDERR, buf, len+1);
  573. free(buf);
  574. } else {
  575. fprintf(stderr, "%s\n", message);
  576. }
  577. /* ignore return code */
  578. } else
  579. fprintf(stderr, "%s\n", message);
  580. }
  581. static int sapi_cgi_deactivate(TSRMLS_D)
  582. {
  583. /* flush only when SAPI was started. The reasons are:
  584. 1. SAPI Deactivate is called from two places: module init and request shutdown
  585. 2. When the first call occurs and the request is not set up, flush fails on
  586. FastCGI.
  587. */
  588. if (SG(sapi_started)) {
  589. sapi_cgibin_flush(SG(server_context));
  590. }
  591. return SUCCESS;
  592. }
  593. static int php_cgi_startup(sapi_module_struct *sapi_module)
  594. {
  595. if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
  596. return FAILURE;
  597. }
  598. return SUCCESS;
  599. }
  600. /* {{{ sapi_module_struct cgi_sapi_module
  601. */
  602. static sapi_module_struct cgi_sapi_module = {
  603. "cgi-fcgi", /* name */
  604. "CGI/FastCGI", /* pretty name */
  605. php_cgi_startup, /* startup */
  606. php_module_shutdown_wrapper, /* shutdown */
  607. NULL, /* activate */
  608. sapi_cgi_deactivate, /* deactivate */
  609. sapi_cgibin_ub_write, /* unbuffered write */
  610. sapi_cgibin_flush, /* flush */
  611. NULL, /* get uid */
  612. sapi_cgibin_getenv, /* getenv */
  613. php_error, /* error handler */
  614. NULL, /* header handler */
  615. sapi_cgi_send_headers, /* send headers handler */
  616. NULL, /* send header handler */
  617. sapi_cgi_read_post, /* read POST data */
  618. sapi_cgi_read_cookies, /* read Cookies */
  619. sapi_cgi_register_variables, /* register server variables */
  620. sapi_cgi_log_message, /* Log message */
  621. NULL, /* Get request time */
  622. STANDARD_SAPI_MODULE_PROPERTIES
  623. };
  624. /* }}} */
  625. /* {{{ php_cgi_usage
  626. */
  627. static void php_cgi_usage(char *argv0)
  628. {
  629. char *prog;
  630. prog = strrchr(argv0, '/');
  631. if (prog) {
  632. prog++;
  633. } else {
  634. prog = "php";
  635. }
  636. php_printf("Usage: %s [options]\n"
  637. "\n"
  638. " -C Do not chdir to the script's directory\n"
  639. " -c <path>|<file> Look for php.ini file in this directory\n"
  640. " -n No php.ini file will be used\n"
  641. " -d foo[=bar] Define INI entry foo with value 'bar'\n"
  642. " -e Generate extended information for debugger/profiler\n"
  643. " -h This help\n"
  644. " -i PHP information\n"
  645. " -m Show compiled in modules\n"
  646. " -v Version number\n"
  647. " -y, --fpm-config <file>\n"
  648. " Specify alternative path to FastCGI process manager config file.\n"
  649. " -z <file> Load Zend extension <file>.\n"
  650. ,
  651. prog);
  652. }
  653. /* }}} */
  654. /* {{{ is_valid_path
  655. *
  656. * some server configurations allow '..' to slip through in the
  657. * translated path. We'll just refuse to handle such a path.
  658. */
  659. static int is_valid_path(const char *path)
  660. {
  661. const char *p;
  662. if (!path) {
  663. return 0;
  664. }
  665. p = strstr(path, "..");
  666. if (p) {
  667. if ((p == path || IS_SLASH(*(p-1))) &&
  668. (*(p+2) == 0 || IS_SLASH(*(p+2)))) {
  669. return 0;
  670. }
  671. while (1) {
  672. p = strstr(p+1, "..");
  673. if (!p) {
  674. break;
  675. }
  676. if (IS_SLASH(*(p-1)) &&
  677. (*(p+2) == 0 || IS_SLASH(*(p+2)))) {
  678. return 0;
  679. }
  680. }
  681. }
  682. return 1;
  683. }
  684. /* }}} */
  685. /* {{{ init_request_info
  686. initializes request_info structure
  687. specificly in this section we handle proper translations
  688. for:
  689. PATH_INFO
  690. derived from the portion of the URI path following
  691. the script name but preceding any query data
  692. may be empty
  693. PATH_TRANSLATED
  694. derived by taking any path-info component of the
  695. request URI and performing any virtual-to-physical
  696. translation appropriate to map it onto the server's
  697. document repository structure
  698. empty if PATH_INFO is empty
  699. The env var PATH_TRANSLATED **IS DIFFERENT** than the
  700. request_info.path_translated variable, the latter should
  701. match SCRIPT_FILENAME instead.
  702. SCRIPT_NAME
  703. set to a URL path that could identify the CGI script
  704. rather than the interpreter. PHP_SELF is set to this.
  705. REQUEST_URI
  706. uri section following the domain:port part of a URI
  707. SCRIPT_FILENAME
  708. The virtual-to-physical translation of SCRIPT_NAME (as per
  709. PATH_TRANSLATED)
  710. These settings are documented at
  711. http://cgi-spec.golux.com/
  712. Based on the following URL request:
  713. http://localhost/info.php/test?a=b
  714. should produce, which btw is the same as if
  715. we were running under mod_cgi on apache (ie. not
  716. using ScriptAlias directives):
  717. PATH_INFO=/test
  718. PATH_TRANSLATED=/docroot/test
  719. SCRIPT_NAME=/info.php
  720. REQUEST_URI=/info.php/test?a=b
  721. SCRIPT_FILENAME=/docroot/info.php
  722. QUERY_STRING=a=b
  723. but what we get is (cgi/mod_fastcgi under apache):
  724. PATH_INFO=/info.php/test
  725. PATH_TRANSLATED=/docroot/info.php/test
  726. SCRIPT_NAME=/php/php-cgi (from the Action setting I suppose)
  727. REQUEST_URI=/info.php/test?a=b
  728. SCRIPT_FILENAME=/path/to/php/bin/php-cgi (Action setting translated)
  729. QUERY_STRING=a=b
  730. Comments in the code below refer to using the above URL in a request
  731. */
  732. static void init_request_info(TSRMLS_D)
  733. {
  734. char *env_script_filename = sapi_cgibin_getenv("SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1 TSRMLS_CC);
  735. char *env_path_translated = sapi_cgibin_getenv("PATH_TRANSLATED", sizeof("PATH_TRANSLATED")-1 TSRMLS_CC);
  736. char *script_path_translated = env_script_filename;
  737. #if !DISCARD_PATH
  738. /* some broken servers do not have script_filename or argv0
  739. an example, IIS configured in some ways. then they do more
  740. broken stuff and set path_translated to the cgi script location */
  741. if (!script_path_translated && env_path_translated) {
  742. script_path_translated = env_path_translated;
  743. }
  744. #endif
  745. /* initialize the defaults */
  746. SG(request_info).path_translated = NULL;
  747. SG(request_info).request_method = NULL;
  748. SG(request_info).proto_num = 1000;
  749. SG(request_info).query_string = NULL;
  750. SG(request_info).request_uri = NULL;
  751. SG(request_info).content_type = NULL;
  752. SG(request_info).content_length = 0;
  753. SG(sapi_headers).http_response_code = 200;
  754. /* script_path_translated being set is a good indication that
  755. we are running in a cgi environment, since it is always
  756. null otherwise. otherwise, the filename
  757. of the script will be retreived later via argc/argv */
  758. if (script_path_translated) {
  759. const char *auth;
  760. char *content_length = sapi_cgibin_getenv("CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1 TSRMLS_CC);
  761. char *content_type = sapi_cgibin_getenv("CONTENT_TYPE", sizeof("CONTENT_TYPE")-1 TSRMLS_CC);
  762. char *env_path_info = sapi_cgibin_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
  763. char *env_script_name = sapi_cgibin_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
  764. #if ENABLE_PATHINFO_CHECK
  765. struct stat st;
  766. char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL")-1 TSRMLS_CC);
  767. char *env_document_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT")-1 TSRMLS_CC);
  768. int script_path_translated_len;
  769. /* Hack for buggy IIS that sets incorrect PATH_INFO */
  770. char *env_server_software = sapi_cgibin_getenv("SERVER_SOFTWARE", sizeof("SERVER_SOFTWARE")-1 TSRMLS_CC);
  771. if (env_server_software &&
  772. env_script_name &&
  773. env_path_info &&
  774. strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
  775. strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0) {
  776. env_path_info = _sapi_cgibin_putenv("ORIG_PATH_INFO", env_path_info TSRMLS_CC);
  777. env_path_info += strlen(env_script_name);
  778. if (*env_path_info == 0) {
  779. env_path_info = NULL;
  780. }
  781. env_path_info = _sapi_cgibin_putenv("PATH_INFO", env_path_info TSRMLS_CC);
  782. }
  783. if (CGIG(fix_pathinfo)) {
  784. char *real_path = NULL;
  785. char *orig_path_translated = env_path_translated;
  786. char *orig_path_info = env_path_info;
  787. char *orig_script_name = env_script_name;
  788. char *orig_script_filename = env_script_filename;
  789. if (!env_document_root && PG(doc_root)) {
  790. env_document_root = _sapi_cgibin_putenv("DOCUMENT_ROOT", PG(doc_root) TSRMLS_CC);
  791. /* fix docroot */
  792. TRANSLATE_SLASHES(env_document_root);
  793. }
  794. if (env_path_translated != NULL && env_redirect_url != NULL) {
  795. /*
  796. pretty much apache specific. If we have a redirect_url
  797. then our script_filename and script_name point to the
  798. php executable
  799. */
  800. script_path_translated = env_path_translated;
  801. /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
  802. env_script_name = env_redirect_url;
  803. }
  804. #ifdef __riscos__
  805. /* Convert path to unix format*/
  806. __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
  807. script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
  808. #endif
  809. /*
  810. * if the file doesn't exist, try to extract PATH_INFO out
  811. * of it by stat'ing back through the '/'
  812. * this fixes url's like /info.php/test
  813. */
  814. if (script_path_translated &&
  815. (script_path_translated_len = strlen(script_path_translated)) > 0 &&
  816. (script_path_translated[script_path_translated_len-1] == '/' ||
  817. #ifdef PHP_WIN32
  818. script_path_translated[script_path_translated_len-1] == '\\' ||
  819. #endif
  820. (real_path = tsrm_realpath(script_path_translated, NULL TSRMLS_CC)) == NULL)) {
  821. char *pt = estrndup(script_path_translated, script_path_translated_len);
  822. int len = script_path_translated_len;
  823. char *ptr;
  824. while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
  825. *ptr = 0;
  826. if (stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
  827. /*
  828. * okay, we found the base script!
  829. * work out how many chars we had to strip off;
  830. * then we can modify PATH_INFO
  831. * accordingly
  832. *
  833. * we now have the makings of
  834. * PATH_INFO=/test
  835. * SCRIPT_FILENAME=/docroot/info.php
  836. *
  837. * we now need to figure out what docroot is.
  838. * if DOCUMENT_ROOT is set, this is easy, otherwise,
  839. * we have to play the game of hide and seek to figure
  840. * out what SCRIPT_NAME should be
  841. */
  842. int slen = len - strlen(pt);
  843. int pilen = env_path_info ? strlen(env_path_info) : 0;
  844. char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
  845. if (orig_path_info != path_info) {
  846. if (orig_path_info) {
  847. char old;
  848. _sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
  849. old = path_info[0];
  850. path_info[0] = 0;
  851. if (!orig_script_name ||
  852. strcmp(orig_script_name, env_path_info) != 0) {
  853. if (orig_script_name) {
  854. _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
  855. }
  856. SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_path_info TSRMLS_CC);
  857. } else {
  858. SG(request_info).request_uri = orig_script_name;
  859. }
  860. path_info[0] = old;
  861. }
  862. env_path_info = _sapi_cgibin_putenv("PATH_INFO", path_info TSRMLS_CC);
  863. }
  864. if (!orig_script_filename ||
  865. strcmp(orig_script_filename, pt) != 0) {
  866. if (orig_script_filename) {
  867. _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
  868. }
  869. script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", pt TSRMLS_CC);
  870. }
  871. TRANSLATE_SLASHES(pt);
  872. /* figure out docroot
  873. SCRIPT_FILENAME minus SCRIPT_NAME
  874. */
  875. if (env_document_root) {
  876. int l = strlen(env_document_root);
  877. int path_translated_len = 0;
  878. char *path_translated = NULL;
  879. if (l && env_document_root[l - 1] == '/') {
  880. --l;
  881. }
  882. /* we have docroot, so we should have:
  883. * DOCUMENT_ROOT=/docroot
  884. * SCRIPT_FILENAME=/docroot/info.php
  885. */
  886. /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
  887. path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
  888. path_translated = (char *) emalloc(path_translated_len + 1);
  889. memcpy(path_translated, env_document_root, l);
  890. if (env_path_info) {
  891. memcpy(path_translated + l, env_path_info, (path_translated_len - l));
  892. }
  893. path_translated[path_translated_len] = '\0';
  894. if (orig_path_translated) {
  895. _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
  896. }
  897. env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
  898. efree(path_translated);
  899. } else if (env_script_name &&
  900. strstr(pt, env_script_name)
  901. ) {
  902. /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
  903. int ptlen = strlen(pt) - strlen(env_script_name);
  904. int path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
  905. char *path_translated = NULL;
  906. path_translated = (char *) emalloc(path_translated_len + 1);
  907. memcpy(path_translated, pt, ptlen);
  908. if (env_path_info) {
  909. memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
  910. }
  911. path_translated[path_translated_len] = '\0';
  912. if (orig_path_translated) {
  913. _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
  914. }
  915. env_path_translated = _sapi_cgibin_putenv("PATH_TRANSLATED", path_translated TSRMLS_CC);
  916. efree(path_translated);
  917. }
  918. break;
  919. }
  920. }
  921. if (!ptr) {
  922. /*
  923. * if we stripped out all the '/' and still didn't find
  924. * a valid path... we will fail, badly. of course we would
  925. * have failed anyway... we output 'no input file' now.
  926. */
  927. if (orig_script_filename) {
  928. _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
  929. }
  930. script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", NULL TSRMLS_CC);
  931. SG(sapi_headers).http_response_code = 404;
  932. }
  933. if (!SG(request_info).request_uri) {
  934. if (!orig_script_name ||
  935. strcmp(orig_script_name, env_script_name) != 0) {
  936. if (orig_script_name) {
  937. _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
  938. }
  939. SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
  940. } else {
  941. SG(request_info).request_uri = orig_script_name;
  942. }
  943. }
  944. if (pt) {
  945. efree(pt);
  946. }
  947. if (is_valid_path(script_path_translated)) {
  948. SG(request_info).path_translated = estrdup(script_path_translated);
  949. }
  950. } else {
  951. /* make sure path_info/translated are empty */
  952. if (!orig_script_filename ||
  953. (script_path_translated != orig_script_filename &&
  954. strcmp(script_path_translated, orig_script_filename) != 0)) {
  955. if (orig_script_filename) {
  956. _sapi_cgibin_putenv("ORIG_SCRIPT_FILENAME", orig_script_filename TSRMLS_CC);
  957. }
  958. script_path_translated = _sapi_cgibin_putenv("SCRIPT_FILENAME", script_path_translated TSRMLS_CC);
  959. }
  960. if (env_redirect_url) {
  961. if (orig_path_info) {
  962. _sapi_cgibin_putenv("ORIG_PATH_INFO", orig_path_info TSRMLS_CC);
  963. _sapi_cgibin_putenv("PATH_INFO", NULL TSRMLS_CC);
  964. }
  965. if (orig_path_translated) {
  966. _sapi_cgibin_putenv("ORIG_PATH_TRANSLATED", orig_path_translated TSRMLS_CC);
  967. _sapi_cgibin_putenv("PATH_TRANSLATED", NULL TSRMLS_CC);
  968. }
  969. }
  970. if (env_script_name != orig_script_name) {
  971. if (orig_script_name) {
  972. _sapi_cgibin_putenv("ORIG_SCRIPT_NAME", orig_script_name TSRMLS_CC);
  973. }
  974. SG(request_info).request_uri = _sapi_cgibin_putenv("SCRIPT_NAME", env_script_name TSRMLS_CC);
  975. } else {
  976. SG(request_info).request_uri = env_script_name;
  977. }
  978. if (is_valid_path(script_path_translated)) {
  979. SG(request_info).path_translated = estrdup(script_path_translated);
  980. }
  981. free(real_path);
  982. }
  983. } else {
  984. #endif
  985. /* pre 4.3 behaviour, shouldn't be used but provides BC */
  986. if (env_path_info) {
  987. SG(request_info).request_uri = env_path_info;
  988. } else {
  989. SG(request_info).request_uri = env_script_name;
  990. }
  991. #if !DISCARD_PATH
  992. if (env_path_translated) {
  993. script_path_translated = env_path_translated;
  994. }
  995. #endif
  996. if (is_valid_path(script_path_translated)) {
  997. SG(request_info).path_translated = estrdup(script_path_translated);
  998. }
  999. #if ENABLE_PATHINFO_CHECK
  1000. }
  1001. #endif
  1002. SG(request_info).request_method = sapi_cgibin_getenv("REQUEST_METHOD", sizeof("REQUEST_METHOD")-1 TSRMLS_CC);
  1003. /* FIXME - Work out proto_num here */
  1004. SG(request_info).query_string = sapi_cgibin_getenv("QUERY_STRING", sizeof("QUERY_STRING")-1 TSRMLS_CC);
  1005. SG(request_info).content_type = (content_type ? content_type : "" );
  1006. SG(request_info).content_length = (content_length ? atoi(content_length) : 0);
  1007. /* The CGI RFC allows servers to pass on unvalidated Authorization data */
  1008. auth = sapi_cgibin_getenv("HTTP_AUTHORIZATION", sizeof("HTTP_AUTHORIZATION")-1 TSRMLS_CC);
  1009. php_handle_auth_data(auth TSRMLS_CC);
  1010. }
  1011. }
  1012. /* }}} */
  1013. PHP_INI_BEGIN()
  1014. STD_PHP_INI_ENTRY("cgi.rfc2616_headers", "0", PHP_INI_ALL, OnUpdateBool, rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
  1015. STD_PHP_INI_ENTRY("cgi.nph", "0", PHP_INI_ALL, OnUpdateBool, nph, php_cgi_globals_struct, php_cgi_globals)
  1016. STD_PHP_INI_ENTRY("cgi.check_shebang_line", "1", PHP_INI_SYSTEM, OnUpdateBool, check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
  1017. #if ENABLE_PATHINFO_CHECK
  1018. STD_PHP_INI_ENTRY("cgi.fix_pathinfo", "1", PHP_INI_SYSTEM, OnUpdateBool, fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
  1019. #endif
  1020. STD_PHP_INI_ENTRY("fastcgi.logging", "1", PHP_INI_SYSTEM, OnUpdateBool, fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
  1021. # ifdef PHP_WIN32
  1022. STD_PHP_INI_ENTRY("fastcgi.impersonate", "0", PHP_INI_SYSTEM, OnUpdateBool, impersonate, php_cgi_globals_struct, php_cgi_globals)
  1023. # endif
  1024. STD_PHP_INI_ENTRY("fastcgi.error_header", NULL, PHP_INI_SYSTEM, OnUpdateString, error_header, php_cgi_globals_struct, php_cgi_globals)
  1025. PHP_INI_END()
  1026. /* {{{ php_cgi_globals_ctor
  1027. */
  1028. static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals TSRMLS_DC)
  1029. {
  1030. php_cgi_globals->rfc2616_headers = 0;
  1031. php_cgi_globals->nph = 0;
  1032. php_cgi_globals->check_shebang_line = 1;
  1033. #if ENABLE_PATHINFO_CHECK
  1034. php_cgi_globals->fix_pathinfo = 1;
  1035. #endif
  1036. php_cgi_globals->fcgi_logging = 1;
  1037. # ifdef PHP_WIN32
  1038. php_cgi_globals->impersonate = 0;
  1039. # endif
  1040. php_cgi_globals->error_header = NULL;
  1041. }
  1042. /* }}} */
  1043. /* {{{ PHP_MINIT_FUNCTION
  1044. */
  1045. static PHP_MINIT_FUNCTION(cgi)
  1046. {
  1047. #ifdef ZTS
  1048. ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
  1049. #else
  1050. php_cgi_globals_ctor(&php_cgi_globals TSRMLS_CC);
  1051. #endif
  1052. REGISTER_INI_ENTRIES();
  1053. return SUCCESS;
  1054. }
  1055. /* }}} */
  1056. /* {{{ PHP_MSHUTDOWN_FUNCTION
  1057. */
  1058. static PHP_MSHUTDOWN_FUNCTION(cgi)
  1059. {
  1060. UNREGISTER_INI_ENTRIES();
  1061. return SUCCESS;
  1062. }
  1063. /* }}} */
  1064. /* {{{ PHP_MINFO_FUNCTION
  1065. */
  1066. static PHP_MINFO_FUNCTION(cgi)
  1067. {
  1068. DISPLAY_INI_ENTRIES();
  1069. php_info_print_table_start();
  1070. php_info_print_table_row(2, "php-fpm", "active");
  1071. php_info_print_table_row(2, "php-fpm version", PHP_FPM_VERSION);
  1072. php_info_print_table_end();
  1073. }
  1074. /* }}} */
  1075. PHP_FUNCTION(fastcgi_finish_request)
  1076. {
  1077. fcgi_request *request = (fcgi_request*) SG(server_context);
  1078. if (fcgi_is_fastcgi() && request->fd >= 0) {
  1079. php_end_ob_buffers(1 TSRMLS_CC);
  1080. php_header(TSRMLS_C);
  1081. fcgi_flush(request, 1);
  1082. fcgi_close(request, 0, 0);
  1083. RETURN_TRUE;
  1084. }
  1085. RETURN_FALSE;
  1086. }
  1087. function_entry cgi_fcgi_sapi_functions[] = {
  1088. PHP_FE(fastcgi_finish_request, NULL)
  1089. {NULL, NULL, NULL}
  1090. };
  1091. static zend_module_entry cgi_module_entry = {
  1092. STANDARD_MODULE_HEADER,
  1093. "cgi-fcgi",
  1094. cgi_fcgi_sapi_functions,
  1095. PHP_MINIT(cgi),
  1096. PHP_MSHUTDOWN(cgi),
  1097. NULL,
  1098. NULL,
  1099. PHP_MINFO(cgi),
  1100. NO_VERSION_YET,
  1101. STANDARD_MODULE_PROPERTIES
  1102. };
  1103. /* {{{ main
  1104. */
  1105. int main(int argc, char *argv[])
  1106. {
  1107. int free_query_string = 0;
  1108. int exit_status = SUCCESS;
  1109. int c;
  1110. zend_file_handle file_handle = {};
  1111. int retval;
  1112. /* temporary locals */
  1113. int orig_optind = php_optind;
  1114. char *orig_optarg = php_optarg;
  1115. int ini_entries_len = 0;
  1116. /* end of temporary locals */
  1117. #ifdef ZTS
  1118. void ***tsrm_ls;
  1119. #endif
  1120. int max_requests = 500;
  1121. int requests = 0;
  1122. int fcgi_fd = 0;
  1123. fcgi_request request;
  1124. char *fpm_config = NULL;
  1125. #ifdef HAVE_SIGNAL_H
  1126. #if defined(SIGPIPE) && defined(SIG_IGN)
  1127. signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
  1128. that sockets created via fsockopen()
  1129. don't kill PHP if the remote site
  1130. closes it. in apache|apxs mode apache
  1131. does that for us! thies@thieso.net
  1132. 20000419 */
  1133. #endif
  1134. #endif
  1135. #ifdef ZTS
  1136. tsrm_startup(1, 1, 0, NULL);
  1137. tsrm_ls = ts_resource(0);
  1138. #endif
  1139. sapi_startup(&cgi_sapi_module);
  1140. cgi_sapi_module.php_ini_path_override = NULL;
  1141. #ifdef PHP_WIN32
  1142. _fmode = _O_BINARY; /* sets default for file streams to binary */
  1143. setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
  1144. setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
  1145. setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
  1146. #endif
  1147. while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0)) != -1) {
  1148. switch (c) {
  1149. case 'c':
  1150. if (cgi_sapi_module.php_ini_path_override) {
  1151. free(cgi_sapi_module.php_ini_path_override);
  1152. }
  1153. cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
  1154. break;
  1155. case 'n':
  1156. cgi_sapi_module.php_ini_ignore = 1;
  1157. break;
  1158. case 'C': /* don't chdir to the script directory */
  1159. SG(options) |= SAPI_OPTION_NO_CHDIR;
  1160. break;
  1161. case 'd': {
  1162. /* define ini entries on command line */
  1163. int len = strlen(php_optarg);
  1164. char *val;
  1165. if ((val = strchr(php_optarg, '='))) {
  1166. val++;
  1167. if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
  1168. cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
  1169. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
  1170. ini_entries_len += (val - php_optarg);
  1171. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
  1172. ini_entries_len++;
  1173. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
  1174. ini_entries_len += len - (val - php_optarg);
  1175. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
  1176. ini_entries_len += sizeof("\n\0\"") - 2;
  1177. } else {
  1178. cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
  1179. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
  1180. memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
  1181. ini_entries_len += len + sizeof("\n\0") - 2;
  1182. }
  1183. } else {
  1184. cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
  1185. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
  1186. memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
  1187. ini_entries_len += len + sizeof("=1\n\0") - 2;
  1188. }
  1189. break;
  1190. }
  1191. case 'y':
  1192. fpm_config = php_optarg;
  1193. break;
  1194. case 'e': /* enable extended info output */
  1195. /* CG(extended_info) = 1; */ /* 5_2 */
  1196. CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO; /* 5_3 */
  1197. break;
  1198. case 'm': /* list compiled in modules */
  1199. cgi_sapi_module.startup(&cgi_sapi_module);
  1200. php_output_startup();
  1201. php_output_activate(TSRMLS_C);
  1202. SG(headers_sent) = 1;
  1203. php_printf("[PHP Modules]\n");
  1204. print_modules(TSRMLS_C);
  1205. php_printf("\n[Zend Modules]\n");
  1206. print_extensions(TSRMLS_C);
  1207. php_printf("\n");
  1208. php_end_ob_buffers(1 TSRMLS_CC);
  1209. exit_status = 0;
  1210. goto out;
  1211. case 'i': /* php info & quit */
  1212. cgi_sapi_module.startup(&cgi_sapi_module);
  1213. if (php_request_startup(TSRMLS_C) == FAILURE) {
  1214. SG(server_context) = NULL;
  1215. php_module_shutdown(TSRMLS_C);
  1216. return FAILURE;
  1217. }
  1218. SG(headers_sent) = 1;
  1219. SG(request_info).no_headers = 1;
  1220. php_print_info(0xFFFFFFFF TSRMLS_CC);
  1221. php_request_shutdown((void *) 0);
  1222. exit_status = 0;
  1223. goto out;
  1224. case 'h':
  1225. case '?':
  1226. cgi_sapi_module.startup(&cgi_sapi_module);
  1227. php_output_startup();
  1228. php_output_activate(TSRMLS_C);
  1229. SG(headers_sent) = 1;
  1230. php_cgi_usage(argv[0]);
  1231. php_end_ob_buffers(1 TSRMLS_CC);
  1232. exit_status = 0;
  1233. goto out;
  1234. case 'v': /* show php version & quit */
  1235. cgi_sapi_module.startup(&cgi_sapi_module);
  1236. if (php_request_startup(TSRMLS_C) == FAILURE) {
  1237. SG(server_context) = NULL;
  1238. php_module_shutdown(TSRMLS_C);
  1239. return FAILURE;
  1240. }
  1241. SG(headers_sent) = 1;
  1242. SG(request_info).no_headers = 1;
  1243. #if SUHOSIN_PATCH
  1244. #if ZEND_DEBUG
  1245. php_printf("PHP %s with Suhosin-Patch %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2009 The PHP Group\n%s", PHP_VERSION, SUHOSIN_PATCH_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
  1246. #else
  1247. php_printf("PHP %s with Suhosin-Patch %s (%s) (built: %s %s)\nCopyright (c) 1997-2009 The PHP Group\n%s", PHP_VERSION, SUHOSIN_PATCH_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
  1248. #endif
  1249. #else
  1250. #if ZEND_DEBUG
  1251. 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());
  1252. #else
  1253. 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());
  1254. #endif
  1255. #endif
  1256. php_request_shutdown((void *) 0);
  1257. exit_status = 0;
  1258. goto out;
  1259. }
  1260. }
  1261. php_optind = orig_optind;
  1262. php_optarg = orig_optarg;
  1263. #ifdef ZTS
  1264. SG(request_info).path_translated = NULL;
  1265. #endif
  1266. cgi_sapi_module.executable_location = argv[0];
  1267. /* startup after we get the above ini override se we get things right */
  1268. if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
  1269. #ifdef ZTS
  1270. tsrm_shutdown();
  1271. #endif
  1272. return FAILURE;
  1273. }
  1274. if (0 > fpm_init(argc, argv, fpm_config)) {
  1275. return FAILURE;
  1276. }
  1277. fcgi_fd = fpm_run(&max_requests);
  1278. parent = 0;
  1279. fcgi_set_is_fastcgi(1);
  1280. /* make php call us to get _ENV vars */
  1281. php_php_import_environment_variables = php_import_environment_variables;
  1282. php_import_environment_variables = cgi_php_import_environment_variables;
  1283. /* library is already initialized, now init our request */
  1284. fcgi_init_request(&request, fcgi_fd);
  1285. zend_first_try {
  1286. /* start of FAST CGI loop */
  1287. /* Initialise FastCGI request structure */
  1288. #ifdef PHP_WIN32
  1289. /* attempt to set security impersonation for fastcgi
  1290. will only happen on NT based OS, others will ignore it. */
  1291. if (fastcgi && CGIG(impersonate)) {
  1292. fcgi_impersonate();
  1293. }
  1294. #endif
  1295. while (fcgi_accept_request(&request) >= 0) {
  1296. request_body_fd = -1;
  1297. SG(server_context) = (void *) &request;
  1298. init_request_info(TSRMLS_C);
  1299. CG(interactive) = 0;
  1300. fpm_request_info();
  1301. /*
  1302. we never take stdin if we're (f)cgi, always
  1303. rely on the web server giving us the info
  1304. we need in the environment.
  1305. */
  1306. if (SG(request_info).path_translated) {
  1307. file_handle.type = ZEND_HANDLE_FILENAME;
  1308. file_handle.filename = SG(request_info).path_translated;
  1309. file_handle.handle.fp = NULL;
  1310. }
  1311. file_handle.opened_path = NULL;
  1312. file_handle.free_filename = 0;
  1313. /* request startup only after we've done all we can to
  1314. get path_translated */
  1315. if (php_request_startup(TSRMLS_C) == FAILURE) {
  1316. fcgi_finish_request(&request);
  1317. SG(server_context) = NULL;
  1318. php_module_shutdown(TSRMLS_C);
  1319. return FAILURE;
  1320. }
  1321. /*
  1322. at this point path_translated will be set if:
  1323. 1. we are running from shell and got filename was there
  1324. 2. we are running as cgi or fastcgi
  1325. */
  1326. retval = FAILURE;
  1327. if (SG(request_info).path_translated) {
  1328. if (!php_check_open_basedir(SG(request_info).path_translated TSRMLS_CC)) {
  1329. retval = php_fopen_primary_script(&file_handle TSRMLS_CC);
  1330. }
  1331. }
  1332. /*
  1333. if we are unable to open path_translated and we are not
  1334. running from shell (so fp == NULL), then fail.
  1335. */
  1336. if (retval == FAILURE && file_handle.handle.fp == NULL) {
  1337. if (errno == EACCES) {
  1338. SG(sapi_headers).http_response_code = 403;
  1339. PUTS("Access denied.\n");
  1340. } else {
  1341. SG(sapi_headers).http_response_code = 404;
  1342. PUTS("No input file specified.\n");
  1343. }
  1344. /* we want to serve more requests if this is fastcgi
  1345. so cleanup and continue, request shutdown is
  1346. handled later */
  1347. goto fastcgi_request_done;
  1348. STR_FREE(SG(request_info).path_translated);
  1349. if (free_query_string && SG(request_info).query_string) {
  1350. free(SG(request_info).query_string);
  1351. SG(request_info).query_string = NULL;
  1352. }
  1353. php_request_shutdown((void *) 0);
  1354. SG(server_context) = NULL;
  1355. php_module_shutdown(TSRMLS_C);
  1356. sapi_shutdown();
  1357. #ifdef ZTS
  1358. tsrm_shutdown();
  1359. #endif
  1360. return FAILURE;
  1361. }
  1362. fpm_request_executing();
  1363. php_execute_script(&file_handle TSRMLS_CC);
  1364. fastcgi_request_done:
  1365. if (request_body_fd != -1) close(request_body_fd);
  1366. request_body_fd = -2;
  1367. {
  1368. char *path_translated;
  1369. /* Go through this trouble so that the memory manager doesn't warn
  1370. * about SG(request_info).path_translated leaking
  1371. */
  1372. if (SG(request_info).path_translated) {
  1373. path_translated = strdup(SG(request_info).path_translated);
  1374. STR_FREE(SG(request_info).path_translated);
  1375. SG(request_info).path_translated = path_translated;
  1376. }
  1377. if (EG(exit_status) == 255) {
  1378. if (CGIG(error_header) && *CGIG(error_header)) {
  1379. sapi_header_line ctr = {0};
  1380. ctr.line = CGIG(error_header);
  1381. ctr.line_len = strlen(CGIG(error_header));
  1382. sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
  1383. }
  1384. }
  1385. php_request_shutdown((void *) 0);
  1386. if (exit_status == 0) {
  1387. exit_status = EG(exit_status);
  1388. }
  1389. if (SG(request_info).path_translated) {
  1390. free(SG(request_info).path_translated);
  1391. SG(request_info).path_translated = NULL;
  1392. }
  1393. if (free_query_string && SG(request_info).query_string) {
  1394. free(SG(request_info).query_string);
  1395. SG(request_info).query_string = NULL;
  1396. }
  1397. }
  1398. requests++;
  1399. if (max_requests && (requests == max_requests)) {
  1400. fcgi_finish_request(&request);
  1401. break;
  1402. }
  1403. /* end of fastcgi loop */
  1404. }
  1405. fcgi_shutdown();
  1406. if (fcgi_in_shutdown() || /* graceful shutdown by a signal */
  1407. (max_requests && (requests == max_requests)) /* we were told to process max_requests and we are done */
  1408. ) {
  1409. exit_status = 0;
  1410. }
  1411. else {
  1412. exit_status = 255;
  1413. }
  1414. if (cgi_sapi_module.php_ini_path_override) {
  1415. free(cgi_sapi_module.php_ini_path_override);
  1416. }
  1417. if (cgi_sapi_module.ini_entries) {
  1418. free(cgi_sapi_module.ini_entries);
  1419. }
  1420. } zend_catch {
  1421. exit_status = 255;
  1422. } zend_end_try();
  1423. out:
  1424. SG(server_context) = NULL;
  1425. php_module_shutdown(TSRMLS_C);
  1426. sapi_shutdown();
  1427. #ifdef ZTS
  1428. /*tsrm_shutdown();*/
  1429. #endif
  1430. #if defined(PHP_WIN32) && ZEND_DEBUG && 0
  1431. _CrtDumpMemoryLeaks();
  1432. #endif
  1433. return exit_status;
  1434. }
  1435. /* }}} */
  1436. /*
  1437. * Local variables:
  1438. * tab-width: 4
  1439. * c-basic-offset: 4
  1440. * End:
  1441. * vim600: sw=4 ts=4 fdm=marker
  1442. * vim<600: sw=4 ts=4
  1443. */