PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/sapi/cgi/cgi_main.c

http://github.com/php/php-src
C | 2704 lines | 2062 code | 310 blank | 332 comment | 460 complexity | 8bc125cbc75d72c5e8f17ffa8068c917 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | http://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
  14. | Stig Bakken <ssb@php.net> |
  15. | Zeev Suraski <zeev@php.net> |
  16. | FastCGI: Ben Mansell <php@slimyhorror.com> |
  17. | Shane Caraveo <shane@caraveo.com> |
  18. | Dmitry Stogov <dmitry@php.net> |
  19. +----------------------------------------------------------------------+
  20. */
  21. #include "php.h"
  22. #include "php_globals.h"
  23. #include "php_variables.h"
  24. #include "zend_modules.h"
  25. #include "SAPI.h"
  26. #include <stdio.h>
  27. #ifdef PHP_WIN32
  28. # include "win32/time.h"
  29. # include "win32/signal.h"
  30. # include "win32/winutil.h"
  31. # include <process.h>
  32. #endif
  33. #if HAVE_SYS_TIME_H
  34. # include <sys/time.h>
  35. #endif
  36. #if HAVE_UNISTD_H
  37. # include <unistd.h>
  38. #endif
  39. #include <signal.h>
  40. #include <locale.h>
  41. #if HAVE_SYS_TYPES_H
  42. # include <sys/types.h>
  43. #endif
  44. #if HAVE_SYS_WAIT_H
  45. # include <sys/wait.h>
  46. #endif
  47. #include "zend.h"
  48. #include "zend_extensions.h"
  49. #include "php_ini.h"
  50. #include "php_globals.h"
  51. #include "php_main.h"
  52. #include "fopen_wrappers.h"
  53. #include "http_status_codes.h"
  54. #include "ext/standard/php_standard.h"
  55. #include "ext/standard/url.h"
  56. #ifdef PHP_WIN32
  57. # include <io.h>
  58. # include <fcntl.h>
  59. # include "win32/php_registry.h"
  60. #endif
  61. #ifdef __riscos__
  62. # include <unixlib/local.h>
  63. int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
  64. #endif
  65. #include "zend_compile.h"
  66. #include "zend_execute.h"
  67. #include "zend_highlight.h"
  68. #include "php_getopt.h"
  69. #include "fastcgi.h"
  70. #if defined(PHP_WIN32) && defined(HAVE_OPENSSL)
  71. # include "openssl/applink.c"
  72. #endif
  73. #ifdef HAVE_VALGRIND
  74. # include "valgrind/callgrind.h"
  75. #endif
  76. #ifndef PHP_WIN32
  77. /* XXX this will need to change later when threaded fastcgi is implemented. shane */
  78. struct sigaction act, old_term, old_quit, old_int;
  79. #endif
  80. static void (*php_php_import_environment_variables)(zval *array_ptr);
  81. /* these globals used for forking children on unix systems */
  82. /**
  83. * Number of child processes that will get created to service requests
  84. */
  85. static int children = 0;
  86. /**
  87. * Set to non-zero if we are the parent process
  88. */
  89. static int parent = 1;
  90. #ifndef PHP_WIN32
  91. /* Did parent received exit signals SIG_TERM/SIG_INT/SIG_QUIT */
  92. static int exit_signal = 0;
  93. /* Is Parent waiting for children to exit */
  94. static int parent_waiting = 0;
  95. /**
  96. * Process group
  97. */
  98. static pid_t pgroup;
  99. #endif
  100. #define PHP_MODE_STANDARD 1
  101. #define PHP_MODE_HIGHLIGHT 2
  102. #define PHP_MODE_LINT 4
  103. #define PHP_MODE_STRIP 5
  104. static char *php_optarg = NULL;
  105. static int php_optind = 1;
  106. static zend_module_entry cgi_module_entry;
  107. static const opt_struct OPTIONS[] = {
  108. {'a', 0, "interactive"},
  109. {'b', 1, "bindpath"},
  110. {'C', 0, "no-chdir"},
  111. {'c', 1, "php-ini"},
  112. {'d', 1, "define"},
  113. {'e', 0, "profile-info"},
  114. {'f', 1, "file"},
  115. {'h', 0, "help"},
  116. {'i', 0, "info"},
  117. {'l', 0, "syntax-check"},
  118. {'m', 0, "modules"},
  119. {'n', 0, "no-php-ini"},
  120. {'q', 0, "no-header"},
  121. {'s', 0, "syntax-highlight"},
  122. {'s', 0, "syntax-highlighting"},
  123. {'w', 0, "strip"},
  124. {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
  125. {'v', 0, "version"},
  126. {'z', 1, "zend-extension"},
  127. {'T', 1, "timing"},
  128. {'-', 0, NULL} /* end of args */
  129. };
  130. typedef struct _php_cgi_globals_struct {
  131. HashTable user_config_cache;
  132. char *redirect_status_env;
  133. zend_bool rfc2616_headers;
  134. zend_bool nph;
  135. zend_bool check_shebang_line;
  136. zend_bool fix_pathinfo;
  137. zend_bool force_redirect;
  138. zend_bool discard_path;
  139. zend_bool fcgi_logging;
  140. #ifdef PHP_WIN32
  141. zend_bool impersonate;
  142. #endif
  143. } php_cgi_globals_struct;
  144. /* {{{ user_config_cache
  145. *
  146. * Key for each cache entry is dirname(PATH_TRANSLATED).
  147. *
  148. * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
  149. * the path starting from doc_root through to dirname(PATH_TRANSLATED). There is no point
  150. * storing per-file entries as it would not be possible to detect added / deleted entries
  151. * between separate files.
  152. */
  153. typedef struct _user_config_cache_entry {
  154. time_t expires;
  155. HashTable *user_config;
  156. } user_config_cache_entry;
  157. static void user_config_cache_entry_dtor(zval *el)
  158. {
  159. user_config_cache_entry *entry = (user_config_cache_entry *)Z_PTR_P(el);
  160. zend_hash_destroy(entry->user_config);
  161. free(entry->user_config);
  162. free(entry);
  163. }
  164. /* }}} */
  165. #ifdef ZTS
  166. static int php_cgi_globals_id;
  167. #define CGIG(v) ZEND_TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
  168. #if defined(PHP_WIN32)
  169. ZEND_TSRMLS_CACHE_DEFINE()
  170. #endif
  171. #else
  172. static php_cgi_globals_struct php_cgi_globals;
  173. #define CGIG(v) (php_cgi_globals.v)
  174. #endif
  175. #ifdef PHP_WIN32
  176. #define TRANSLATE_SLASHES(path) \
  177. { \
  178. char *tmp = path; \
  179. while (*tmp) { \
  180. if (*tmp == '\\') *tmp = '/'; \
  181. tmp++; \
  182. } \
  183. }
  184. #else
  185. #define TRANSLATE_SLASHES(path)
  186. #endif
  187. #ifdef PHP_WIN32
  188. #define WIN32_MAX_SPAWN_CHILDREN 64
  189. HANDLE kid_cgi_ps[WIN32_MAX_SPAWN_CHILDREN];
  190. int kids, cleaning_up = 0;
  191. HANDLE job = NULL;
  192. JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = { 0 };
  193. CRITICAL_SECTION cleanup_lock;
  194. #endif
  195. #ifndef HAVE_ATTRIBUTE_WEAK
  196. static void fcgi_log(int type, const char *format, ...) {
  197. va_list ap;
  198. va_start(ap, format);
  199. vfprintf(stderr, format, ap);
  200. va_end(ap);
  201. }
  202. #endif
  203. static int module_name_cmp(Bucket *f, Bucket *s)
  204. {
  205. return strcasecmp( ((zend_module_entry *)Z_PTR(f->val))->name,
  206. ((zend_module_entry *)Z_PTR(s->val))->name);
  207. }
  208. static void print_modules(void)
  209. {
  210. HashTable sorted_registry;
  211. zend_module_entry *module;
  212. zend_hash_init(&sorted_registry, 64, NULL, NULL, 1);
  213. zend_hash_copy(&sorted_registry, &module_registry, NULL);
  214. zend_hash_sort(&sorted_registry, module_name_cmp, 0);
  215. ZEND_HASH_FOREACH_PTR(&sorted_registry, module) {
  216. php_printf("%s\n", module->name);
  217. } ZEND_HASH_FOREACH_END();
  218. zend_hash_destroy(&sorted_registry);
  219. }
  220. static void print_extension_info(zend_extension *ext)
  221. {
  222. php_printf("%s\n", ext->name);
  223. }
  224. static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s)
  225. {
  226. zend_extension *fe = (zend_extension*)(*f)->data;
  227. zend_extension *se = (zend_extension*)(*s)->data;
  228. return strcmp(fe->name, se->name);
  229. }
  230. static void print_extensions(void)
  231. {
  232. zend_llist sorted_exts;
  233. zend_llist_copy(&sorted_exts, &zend_extensions);
  234. sorted_exts.dtor = NULL;
  235. zend_llist_sort(&sorted_exts, extension_name_cmp);
  236. zend_llist_apply(&sorted_exts, (llist_apply_func_t) print_extension_info);
  237. zend_llist_destroy(&sorted_exts);
  238. }
  239. #ifndef STDOUT_FILENO
  240. #define STDOUT_FILENO 1
  241. #endif
  242. static inline size_t sapi_cgi_single_write(const char *str, size_t str_length)
  243. {
  244. #ifdef PHP_WRITE_STDOUT
  245. int ret;
  246. ret = write(STDOUT_FILENO, str, str_length);
  247. if (ret <= 0) return 0;
  248. return ret;
  249. #else
  250. size_t ret;
  251. ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
  252. return ret;
  253. #endif
  254. }
  255. static size_t sapi_cgi_ub_write(const char *str, size_t str_length)
  256. {
  257. const char *ptr = str;
  258. size_t remaining = str_length;
  259. size_t ret;
  260. while (remaining > 0) {
  261. ret = sapi_cgi_single_write(ptr, remaining);
  262. if (!ret) {
  263. php_handle_aborted_connection();
  264. return str_length - remaining;
  265. }
  266. ptr += ret;
  267. remaining -= ret;
  268. }
  269. return str_length;
  270. }
  271. static size_t sapi_fcgi_ub_write(const char *str, size_t str_length)
  272. {
  273. const char *ptr = str;
  274. size_t remaining = str_length;
  275. fcgi_request *request = (fcgi_request*) SG(server_context);
  276. while (remaining > 0) {
  277. int to_write = remaining > INT_MAX ? INT_MAX : (int)remaining;
  278. int ret = fcgi_write(request, FCGI_STDOUT, ptr, to_write);
  279. if (ret <= 0) {
  280. php_handle_aborted_connection();
  281. return str_length - remaining;
  282. }
  283. ptr += ret;
  284. remaining -= ret;
  285. }
  286. return str_length;
  287. }
  288. static void sapi_cgi_flush(void *server_context)
  289. {
  290. if (fflush(stdout) == EOF) {
  291. php_handle_aborted_connection();
  292. }
  293. }
  294. static void sapi_fcgi_flush(void *server_context)
  295. {
  296. fcgi_request *request = (fcgi_request*) server_context;
  297. if (
  298. !parent &&
  299. request && !fcgi_flush(request, 0)) {
  300. php_handle_aborted_connection();
  301. }
  302. }
  303. #define SAPI_CGI_MAX_HEADER_LENGTH 1024
  304. static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers)
  305. {
  306. sapi_header_struct *h;
  307. zend_llist_position pos;
  308. zend_bool ignore_status = 0;
  309. int response_status = SG(sapi_headers).http_response_code;
  310. if (SG(request_info).no_headers == 1) {
  311. return SAPI_HEADER_SENT_SUCCESSFULLY;
  312. }
  313. if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
  314. {
  315. int len;
  316. zend_bool has_status = 0;
  317. char buf[SAPI_CGI_MAX_HEADER_LENGTH];
  318. if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
  319. char *s;
  320. len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
  321. if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
  322. response_status = atoi((s + 1));
  323. }
  324. if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
  325. len = SAPI_CGI_MAX_HEADER_LENGTH;
  326. }
  327. } else {
  328. char *s;
  329. if (SG(sapi_headers).http_status_line &&
  330. (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
  331. (s - SG(sapi_headers).http_status_line) >= 5 &&
  332. strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
  333. ) {
  334. len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
  335. response_status = atoi((s + 1));
  336. } else {
  337. h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
  338. while (h) {
  339. if (h->header_len > sizeof("Status:")-1 &&
  340. strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
  341. ) {
  342. has_status = 1;
  343. break;
  344. }
  345. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  346. }
  347. if (!has_status) {
  348. http_response_status_code_pair *err = (http_response_status_code_pair*)http_status_map;
  349. while (err->code != 0) {
  350. if (err->code == SG(sapi_headers).http_response_code) {
  351. break;
  352. }
  353. err++;
  354. }
  355. if (err->str) {
  356. len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->str);
  357. } else {
  358. len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
  359. }
  360. }
  361. }
  362. }
  363. if (!has_status) {
  364. PHPWRITE_H(buf, len);
  365. ignore_status = 1;
  366. }
  367. }
  368. h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
  369. while (h) {
  370. /* prevent CRLFCRLF */
  371. if (h->header_len) {
  372. if (h->header_len > sizeof("Status:")-1 &&
  373. strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
  374. ) {
  375. if (!ignore_status) {
  376. ignore_status = 1;
  377. PHPWRITE_H(h->header, h->header_len);
  378. PHPWRITE_H("\r\n", 2);
  379. }
  380. } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
  381. strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
  382. ) {
  383. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  384. continue;
  385. } else {
  386. PHPWRITE_H(h->header, h->header_len);
  387. PHPWRITE_H("\r\n", 2);
  388. }
  389. }
  390. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  391. }
  392. PHPWRITE_H("\r\n", 2);
  393. return SAPI_HEADER_SENT_SUCCESSFULLY;
  394. }
  395. #ifndef STDIN_FILENO
  396. # define STDIN_FILENO 0
  397. #endif
  398. static size_t sapi_cgi_read_post(char *buffer, size_t count_bytes)
  399. {
  400. size_t read_bytes = 0;
  401. int tmp_read_bytes;
  402. size_t remaining_bytes;
  403. assert(SG(request_info).content_length >= SG(read_post_bytes));
  404. remaining_bytes = (size_t)(SG(request_info).content_length - SG(read_post_bytes));
  405. count_bytes = MIN(count_bytes, remaining_bytes);
  406. while (read_bytes < count_bytes) {
  407. #ifdef PHP_WIN32
  408. size_t diff = count_bytes - read_bytes;
  409. unsigned int to_read = (diff > UINT_MAX) ? UINT_MAX : (unsigned int)diff;
  410. tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, to_read);
  411. #else
  412. tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes);
  413. #endif
  414. if (tmp_read_bytes <= 0) {
  415. break;
  416. }
  417. read_bytes += tmp_read_bytes;
  418. }
  419. return read_bytes;
  420. }
  421. static size_t sapi_fcgi_read_post(char *buffer, size_t count_bytes)
  422. {
  423. size_t read_bytes = 0;
  424. int tmp_read_bytes;
  425. fcgi_request *request = (fcgi_request*) SG(server_context);
  426. size_t remaining = SG(request_info).content_length - SG(read_post_bytes);
  427. if (remaining < count_bytes) {
  428. count_bytes = remaining;
  429. }
  430. while (read_bytes < count_bytes) {
  431. size_t diff = count_bytes - read_bytes;
  432. int to_read = (diff > INT_MAX) ? INT_MAX : (int)diff;
  433. tmp_read_bytes = fcgi_read(request, buffer + read_bytes, to_read);
  434. if (tmp_read_bytes <= 0) {
  435. break;
  436. }
  437. read_bytes += tmp_read_bytes;
  438. }
  439. return read_bytes;
  440. }
  441. #ifdef PHP_WIN32
  442. /* The result needs to be freed! See sapi_getenv(). */
  443. static char *cgi_getenv_win32(const char *name, size_t name_len)
  444. {
  445. char *ret = NULL;
  446. wchar_t *keyw, *valw;
  447. size_t size;
  448. int rc;
  449. keyw = php_win32_cp_conv_any_to_w(name, name_len, PHP_WIN32_CP_IGNORE_LEN_P);
  450. if (!keyw) {
  451. return NULL;
  452. }
  453. rc = _wgetenv_s(&size, NULL, 0, keyw);
  454. if (rc || 0 == size) {
  455. free(keyw);
  456. return NULL;
  457. }
  458. valw = emalloc((size + 1) * sizeof(wchar_t));
  459. rc = _wgetenv_s(&size, valw, size, keyw);
  460. if (!rc) {
  461. ret = php_win32_cp_w_to_any(valw);
  462. }
  463. free(keyw);
  464. efree(valw);
  465. return ret;
  466. }
  467. #endif
  468. static char *sapi_cgi_getenv(char *name, size_t name_len)
  469. {
  470. #ifndef PHP_WIN32
  471. return getenv(name);
  472. #else
  473. return cgi_getenv_win32(name, name_len);
  474. #endif
  475. }
  476. static char *sapi_fcgi_getenv(char *name, size_t name_len)
  477. {
  478. /* when php is started by mod_fastcgi, no regular environment
  479. * is provided to PHP. It is always sent to PHP at the start
  480. * of a request. So we have to do our own lookup to get env
  481. * vars. This could probably be faster somehow. */
  482. fcgi_request *request = (fcgi_request*) SG(server_context);
  483. char *ret = fcgi_getenv(request, name, (int)name_len);
  484. #ifndef PHP_WIN32
  485. if (ret) return ret;
  486. /* if cgi, or fastcgi and not found in fcgi env
  487. check the regular environment */
  488. return getenv(name);
  489. #else
  490. if (ret) {
  491. /* The functions outside here don't know, where does it come
  492. from. They'll need to free the returned memory as it's
  493. not necessary from the fcgi env. */
  494. return strdup(ret);
  495. }
  496. /* if cgi, or fastcgi and not found in fcgi env
  497. check the regular environment */
  498. return cgi_getenv_win32(name, name_len);
  499. #endif
  500. }
  501. static char *_sapi_cgi_putenv(char *name, size_t name_len, char *value)
  502. {
  503. #if !HAVE_SETENV || !HAVE_UNSETENV
  504. size_t len;
  505. char *buf;
  506. #endif
  507. #if HAVE_SETENV
  508. if (value) {
  509. setenv(name, value, 1);
  510. }
  511. #endif
  512. #if HAVE_UNSETENV
  513. if (!value) {
  514. unsetenv(name);
  515. }
  516. #endif
  517. #if !HAVE_SETENV || !HAVE_UNSETENV
  518. /* if cgi, or fastcgi and not found in fcgi env
  519. check the regular environment
  520. this leaks, but it's only cgi anyway, we'll fix
  521. it for 5.0
  522. */
  523. len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
  524. buf = (char *) malloc(len);
  525. if (buf == NULL) {
  526. return getenv(name);
  527. }
  528. #endif
  529. #if !HAVE_SETENV
  530. if (value) {
  531. len = slprintf(buf, len - 1, "%s=%s", name, value);
  532. putenv(buf);
  533. }
  534. #endif
  535. #if !HAVE_UNSETENV
  536. if (!value) {
  537. len = slprintf(buf, len - 1, "%s=", name);
  538. putenv(buf);
  539. }
  540. #endif
  541. return getenv(name);
  542. }
  543. static char *sapi_cgi_read_cookies(void)
  544. {
  545. return getenv("HTTP_COOKIE");
  546. }
  547. static char *sapi_fcgi_read_cookies(void)
  548. {
  549. fcgi_request *request = (fcgi_request*) SG(server_context);
  550. return FCGI_GETENV(request, "HTTP_COOKIE");
  551. }
  552. static void cgi_php_load_env_var(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg)
  553. {
  554. zval *array_ptr = (zval*)arg;
  555. int filter_arg = (Z_ARR_P(array_ptr) == Z_ARR(PG(http_globals)[TRACK_VARS_ENV]))?PARSE_ENV:PARSE_SERVER;
  556. size_t new_val_len;
  557. if (sapi_module.input_filter(filter_arg, var, &val, strlen(val), &new_val_len)) {
  558. php_register_variable_safe(var, val, new_val_len, array_ptr);
  559. }
  560. }
  561. static void cgi_php_import_environment_variables(zval *array_ptr)
  562. {
  563. if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) {
  564. if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) != IS_ARRAY) {
  565. zend_is_auto_global_str("_ENV", sizeof("_ENV")-1);
  566. }
  567. if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
  568. Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_ENV])) {
  569. zend_array_destroy(Z_ARR_P(array_ptr));
  570. Z_ARR_P(array_ptr) = zend_array_dup(Z_ARR(PG(http_globals)[TRACK_VARS_ENV]));
  571. return;
  572. }
  573. }
  574. /* call php's original import as a catch-all */
  575. php_php_import_environment_variables(array_ptr);
  576. if (fcgi_is_fastcgi()) {
  577. fcgi_request *request = (fcgi_request*) SG(server_context);
  578. fcgi_loadenv(request, cgi_php_load_env_var, array_ptr);
  579. }
  580. }
  581. static void sapi_cgi_register_variables(zval *track_vars_array)
  582. {
  583. size_t php_self_len;
  584. char *php_self;
  585. /* In CGI mode, we consider the environment to be a part of the server
  586. * variables
  587. */
  588. php_import_environment_variables(track_vars_array);
  589. if (CGIG(fix_pathinfo)) {
  590. char *script_name = SG(request_info).request_uri;
  591. char *path_info;
  592. int free_php_self;
  593. ALLOCA_FLAG(use_heap)
  594. if (fcgi_is_fastcgi()) {
  595. fcgi_request *request = (fcgi_request*) SG(server_context);
  596. path_info = FCGI_GETENV(request, "PATH_INFO");
  597. } else {
  598. path_info = getenv("PATH_INFO");
  599. }
  600. if (path_info) {
  601. size_t path_info_len = strlen(path_info);
  602. if (script_name) {
  603. size_t script_name_len = strlen(script_name);
  604. php_self_len = script_name_len + path_info_len;
  605. php_self = do_alloca(php_self_len + 1, use_heap);
  606. memcpy(php_self, script_name, script_name_len + 1);
  607. memcpy(php_self + script_name_len, path_info, path_info_len + 1);
  608. free_php_self = 1;
  609. } else {
  610. php_self = path_info;
  611. php_self_len = path_info_len;
  612. free_php_self = 0;
  613. }
  614. } else if (script_name) {
  615. php_self = script_name;
  616. php_self_len = strlen(script_name);
  617. free_php_self = 0;
  618. } else {
  619. php_self = "";
  620. php_self_len = 0;
  621. free_php_self = 0;
  622. }
  623. /* Build the special-case PHP_SELF variable for the CGI version */
  624. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
  625. php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
  626. }
  627. if (free_php_self) {
  628. free_alloca(php_self, use_heap);
  629. }
  630. } else {
  631. php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
  632. php_self_len = strlen(php_self);
  633. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
  634. php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
  635. }
  636. }
  637. }
  638. static void sapi_cgi_log_message(char *message, int syslog_type_int)
  639. {
  640. if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
  641. fcgi_request *request;
  642. request = (fcgi_request*) SG(server_context);
  643. if (request) {
  644. int ret, len = (int)strlen(message);
  645. char *buf = malloc(len+2);
  646. memcpy(buf, message, len);
  647. memcpy(buf + len, "\n", sizeof("\n"));
  648. ret = fcgi_write(request, FCGI_STDERR, buf, (int)(len + 1));
  649. free(buf);
  650. if (ret < 0) {
  651. php_handle_aborted_connection();
  652. }
  653. } else {
  654. fprintf(stderr, "%s\n", message);
  655. }
  656. /* ignore return code */
  657. } else {
  658. fprintf(stderr, "%s\n", message);
  659. }
  660. }
  661. /* {{{ php_cgi_ini_activate_user_config
  662. */
  663. static void php_cgi_ini_activate_user_config(char *path, size_t path_len, const char *doc_root, size_t doc_root_len)
  664. {
  665. user_config_cache_entry *new_entry, *entry;
  666. time_t request_time = (time_t)sapi_get_request_time();
  667. /* Find cached config entry: If not found, create one */
  668. if ((entry = zend_hash_str_find_ptr(&CGIG(user_config_cache), path, path_len)) == NULL) {
  669. new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
  670. new_entry->expires = 0;
  671. new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
  672. zend_hash_init(new_entry->user_config, 8, NULL, (dtor_func_t) config_zval_dtor, 1);
  673. entry = zend_hash_str_update_ptr(&CGIG(user_config_cache), path, path_len, new_entry);
  674. }
  675. /* Check whether cache entry has expired and rescan if it is */
  676. if (request_time > entry->expires) {
  677. char *real_path = NULL;
  678. char *s1, *s2;
  679. size_t s_len;
  680. /* Clear the expired config */
  681. zend_hash_clean(entry->user_config);
  682. if (!IS_ABSOLUTE_PATH(path, path_len)) {
  683. size_t real_path_len;
  684. real_path = tsrm_realpath(path, NULL);
  685. if (real_path == NULL) {
  686. return;
  687. }
  688. real_path_len = strlen(real_path);
  689. path = real_path;
  690. path_len = real_path_len;
  691. }
  692. if (path_len > doc_root_len) {
  693. s1 = (char *) doc_root;
  694. s2 = path;
  695. s_len = doc_root_len;
  696. } else {
  697. s1 = path;
  698. s2 = (char *) doc_root;
  699. s_len = path_len;
  700. }
  701. /* we have to test if path is part of DOCUMENT_ROOT.
  702. if it is inside the docroot, we scan the tree up to the docroot
  703. to find more user.ini, if not we only scan the current path.
  704. */
  705. #ifdef PHP_WIN32
  706. if (strnicmp(s1, s2, s_len) == 0) {
  707. #else
  708. if (strncmp(s1, s2, s_len) == 0) {
  709. #endif
  710. char *ptr = s2 + doc_root_len;
  711. while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
  712. *ptr = 0;
  713. php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
  714. *ptr = '/';
  715. ptr++;
  716. }
  717. } else {
  718. php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
  719. }
  720. if (real_path) {
  721. efree(real_path);
  722. }
  723. entry->expires = request_time + PG(user_ini_cache_ttl);
  724. }
  725. /* Activate ini entries with values from the user config hash */
  726. php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS);
  727. }
  728. /* }}} */
  729. static int sapi_cgi_activate(void)
  730. {
  731. /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
  732. if (!SG(request_info).path_translated) {
  733. return FAILURE;
  734. }
  735. if (php_ini_has_per_host_config()) {
  736. char *server_name;
  737. /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
  738. if (fcgi_is_fastcgi()) {
  739. fcgi_request *request = (fcgi_request*) SG(server_context);
  740. server_name = FCGI_GETENV(request, "SERVER_NAME");
  741. } else {
  742. server_name = getenv("SERVER_NAME");
  743. }
  744. /* SERVER_NAME should also be defined at this stage..but better check it anyway */
  745. if (server_name) {
  746. size_t server_name_len = strlen(server_name);
  747. server_name = estrndup(server_name, server_name_len);
  748. zend_str_tolower(server_name, server_name_len);
  749. php_ini_activate_per_host_config(server_name, server_name_len);
  750. efree(server_name);
  751. }
  752. }
  753. if (php_ini_has_per_dir_config() ||
  754. (PG(user_ini_filename) && *PG(user_ini_filename))
  755. ) {
  756. char *path;
  757. size_t path_len;
  758. /* Prepare search path */
  759. path_len = strlen(SG(request_info).path_translated);
  760. /* Make sure we have trailing slash! */
  761. if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
  762. path = emalloc(path_len + 2);
  763. memcpy(path, SG(request_info).path_translated, path_len + 1);
  764. path_len = zend_dirname(path, path_len);
  765. path[path_len++] = DEFAULT_SLASH;
  766. } else {
  767. path = estrndup(SG(request_info).path_translated, path_len);
  768. path_len = zend_dirname(path, path_len);
  769. }
  770. path[path_len] = 0;
  771. /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
  772. php_ini_activate_per_dir_config(path, path_len); /* Note: for global settings sake we check from root to path */
  773. /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
  774. if (PG(user_ini_filename) && *PG(user_ini_filename)) {
  775. char *doc_root;
  776. if (fcgi_is_fastcgi()) {
  777. fcgi_request *request = (fcgi_request*) SG(server_context);
  778. /* Prefer CONTEXT_DOCUMENT_ROOT if set */
  779. doc_root = FCGI_GETENV(request, "CONTEXT_DOCUMENT_ROOT");
  780. doc_root = doc_root ? doc_root : FCGI_GETENV(request, "DOCUMENT_ROOT");
  781. } else {
  782. doc_root = getenv("CONTEXT_DOCUMENT_ROOT");
  783. doc_root = doc_root ? doc_root : getenv("DOCUMENT_ROOT");
  784. }
  785. /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
  786. if (doc_root) {
  787. size_t doc_root_len = strlen(doc_root);
  788. if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
  789. --doc_root_len;
  790. }
  791. #ifdef PHP_WIN32
  792. /* paths on windows should be case-insensitive */
  793. doc_root = estrndup(doc_root, doc_root_len);
  794. zend_str_tolower(doc_root, doc_root_len);
  795. #endif
  796. php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len);
  797. #ifdef PHP_WIN32
  798. efree(doc_root);
  799. #endif
  800. }
  801. }
  802. efree(path);
  803. }
  804. return SUCCESS;
  805. }
  806. static int sapi_cgi_deactivate(void)
  807. {
  808. /* flush only when SAPI was started. The reasons are:
  809. 1. SAPI Deactivate is called from two places: module init and request shutdown
  810. 2. When the first call occurs and the request is not set up, flush fails on FastCGI.
  811. */
  812. if (SG(sapi_started)) {
  813. if (fcgi_is_fastcgi()) {
  814. if (
  815. !parent &&
  816. !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
  817. php_handle_aborted_connection();
  818. }
  819. } else {
  820. sapi_cgi_flush(SG(server_context));
  821. }
  822. }
  823. return SUCCESS;
  824. }
  825. static int php_cgi_startup(sapi_module_struct *sapi_module)
  826. {
  827. if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
  828. return FAILURE;
  829. }
  830. return SUCCESS;
  831. }
  832. /* {{{ sapi_module_struct cgi_sapi_module
  833. */
  834. static sapi_module_struct cgi_sapi_module = {
  835. "cgi-fcgi", /* name */
  836. "CGI/FastCGI", /* pretty name */
  837. php_cgi_startup, /* startup */
  838. php_module_shutdown_wrapper, /* shutdown */
  839. sapi_cgi_activate, /* activate */
  840. sapi_cgi_deactivate, /* deactivate */
  841. sapi_cgi_ub_write, /* unbuffered write */
  842. sapi_cgi_flush, /* flush */
  843. NULL, /* get uid */
  844. sapi_cgi_getenv, /* getenv */
  845. php_error, /* error handler */
  846. NULL, /* header handler */
  847. sapi_cgi_send_headers, /* send headers handler */
  848. NULL, /* send header handler */
  849. sapi_cgi_read_post, /* read POST data */
  850. sapi_cgi_read_cookies, /* read Cookies */
  851. sapi_cgi_register_variables, /* register server variables */
  852. sapi_cgi_log_message, /* Log message */
  853. NULL, /* Get request time */
  854. NULL, /* Child terminate */
  855. STANDARD_SAPI_MODULE_PROPERTIES
  856. };
  857. /* }}} */
  858. /* {{{ arginfo ext/standard/dl.c */
  859. ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
  860. ZEND_ARG_INFO(0, extension_filename)
  861. ZEND_END_ARG_INFO()
  862. /* }}} */
  863. static const zend_function_entry additional_functions[] = {
  864. ZEND_FE(dl, arginfo_dl)
  865. PHP_FE_END
  866. };
  867. /* {{{ php_cgi_usage
  868. */
  869. static void php_cgi_usage(char *argv0)
  870. {
  871. char *prog;
  872. prog = strrchr(argv0, '/');
  873. if (prog) {
  874. prog++;
  875. } else {
  876. prog = "php";
  877. }
  878. php_printf( "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
  879. " %s <file> [args...]\n"
  880. " -a Run interactively\n"
  881. " -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
  882. " -C Do not chdir to the script's directory\n"
  883. " -c <path>|<file> Look for php.ini file in this directory\n"
  884. " -n No php.ini file will be used\n"
  885. " -d foo[=bar] Define INI entry foo with value 'bar'\n"
  886. " -e Generate extended information for debugger/profiler\n"
  887. " -f <file> Parse <file>. Implies `-q'\n"
  888. " -h This help\n"
  889. " -i PHP information\n"
  890. " -l Syntax check only (lint)\n"
  891. " -m Show compiled in modules\n"
  892. " -q Quiet-mode. Suppress HTTP Header output.\n"
  893. " -s Display colour syntax highlighted source.\n"
  894. " -v Version number\n"
  895. " -w Display source with stripped comments and whitespace.\n"
  896. " -z <file> Load Zend extension <file>.\n"
  897. " -T <count> Measure execution time of script repeated <count> times.\n",
  898. prog, prog);
  899. }
  900. /* }}} */
  901. /* {{{ is_valid_path
  902. *
  903. * some server configurations allow '..' to slip through in the
  904. * translated path. We'll just refuse to handle such a path.
  905. */
  906. static int is_valid_path(const char *path)
  907. {
  908. const char *p = path;
  909. if (UNEXPECTED(!p)) {
  910. return 0;
  911. }
  912. if (UNEXPECTED(*p == '.') && *(p+1) == '.' && (!*(p+2) || IS_SLASH(*(p+2)))) {
  913. return 0;
  914. }
  915. while (*p) {
  916. if (IS_SLASH(*p)) {
  917. p++;
  918. if (UNEXPECTED(*p == '.')) {
  919. p++;
  920. if (UNEXPECTED(*p == '.')) {
  921. p++;
  922. if (UNEXPECTED(!*p) || UNEXPECTED(IS_SLASH(*p))) {
  923. return 0;
  924. }
  925. }
  926. }
  927. }
  928. p++;
  929. }
  930. return 1;
  931. }
  932. /* }}} */
  933. #define CGI_GETENV(name) \
  934. ((has_env) ? \
  935. FCGI_GETENV(request, name) : \
  936. getenv(name))
  937. #define CGI_PUTENV(name, value) \
  938. ((has_env) ? \
  939. FCGI_PUTENV(request, name, value) : \
  940. _sapi_cgi_putenv(name, sizeof(name)-1, value))
  941. /* {{{ init_request_info
  942. initializes request_info structure
  943. specifically in this section we handle proper translations
  944. for:
  945. PATH_INFO
  946. derived from the portion of the URI path following
  947. the script name but preceding any query data
  948. may be empty
  949. PATH_TRANSLATED
  950. derived by taking any path-info component of the
  951. request URI and performing any virtual-to-physical
  952. translation appropriate to map it onto the server's
  953. document repository structure
  954. empty if PATH_INFO is empty
  955. The env var PATH_TRANSLATED **IS DIFFERENT** than the
  956. request_info.path_translated variable, the latter should
  957. match SCRIPT_FILENAME instead.
  958. SCRIPT_NAME
  959. set to a URL path that could identify the CGI script
  960. rather than the interpreter. PHP_SELF is set to this
  961. REQUEST_URI
  962. uri section following the domain:port part of a URI
  963. SCRIPT_FILENAME
  964. The virtual-to-physical translation of SCRIPT_NAME (as per
  965. PATH_TRANSLATED)
  966. These settings are documented at
  967. http://cgi-spec.golux.com/
  968. Based on the following URL request:
  969. http://localhost/info.php/test?a=b
  970. should produce, which btw is the same as if
  971. we were running under mod_cgi on apache (ie. not
  972. using ScriptAlias directives):
  973. PATH_INFO=/test
  974. PATH_TRANSLATED=/docroot/test
  975. SCRIPT_NAME=/info.php
  976. REQUEST_URI=/info.php/test?a=b
  977. SCRIPT_FILENAME=/docroot/info.php
  978. QUERY_STRING=a=b
  979. but what we get is (cgi/mod_fastcgi under apache):
  980. PATH_INFO=/info.php/test
  981. PATH_TRANSLATED=/docroot/info.php/test
  982. SCRIPT_NAME=/php/php-cgi (from the Action setting I suppose)
  983. REQUEST_URI=/info.php/test?a=b
  984. SCRIPT_FILENAME=/path/to/php/bin/php-cgi (Action setting translated)
  985. QUERY_STRING=a=b
  986. Comments in the code below refer to using the above URL in a request
  987. */
  988. static void init_request_info(fcgi_request *request)
  989. {
  990. int has_env = fcgi_has_env(request);
  991. char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
  992. char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
  993. char *script_path_translated = env_script_filename;
  994. /* some broken servers do not have script_filename or argv0
  995. * an example, IIS configured in some ways. then they do more
  996. * broken stuff and set path_translated to the cgi script location */
  997. if (!script_path_translated && env_path_translated) {
  998. script_path_translated = env_path_translated;
  999. }
  1000. /* initialize the defaults */
  1001. SG(request_info).path_translated = NULL;
  1002. SG(request_info).request_method = NULL;
  1003. SG(request_info).proto_num = 1000;
  1004. SG(request_info).query_string = NULL;
  1005. SG(request_info).request_uri = NULL;
  1006. SG(request_info).content_type = NULL;
  1007. SG(request_info).content_length = 0;
  1008. SG(sapi_headers).http_response_code = 200;
  1009. /* script_path_translated being set is a good indication that
  1010. * we are running in a cgi environment, since it is always
  1011. * null otherwise. otherwise, the filename
  1012. * of the script will be retrieved later via argc/argv */
  1013. if (script_path_translated) {
  1014. const char *auth;
  1015. char *content_length = CGI_GETENV("CONTENT_LENGTH");
  1016. char *content_type = CGI_GETENV("CONTENT_TYPE");
  1017. char *env_path_info = CGI_GETENV("PATH_INFO");
  1018. char *env_script_name = CGI_GETENV("SCRIPT_NAME");
  1019. #ifdef PHP_WIN32
  1020. /* Hack for buggy IIS that sets incorrect PATH_INFO */
  1021. char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
  1022. if (env_server_software &&
  1023. env_script_name &&
  1024. env_path_info &&
  1025. strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
  1026. strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
  1027. ) {
  1028. env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
  1029. env_path_info += strlen(env_script_name);
  1030. if (*env_path_info == 0) {
  1031. env_path_info = NULL;
  1032. }
  1033. env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
  1034. }
  1035. #endif
  1036. if (CGIG(fix_pathinfo)) {
  1037. zend_stat_t st;
  1038. char *real_path = NULL;
  1039. char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
  1040. char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
  1041. char *orig_path_translated = env_path_translated;
  1042. char *orig_path_info = env_path_info;
  1043. char *orig_script_name = env_script_name;
  1044. char *orig_script_filename = env_script_filename;
  1045. size_t script_path_translated_len;
  1046. if (!env_document_root && PG(doc_root)) {
  1047. env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
  1048. /* fix docroot */
  1049. TRANSLATE_SLASHES(env_document_root);
  1050. }
  1051. if (env_path_translated != NULL && env_redirect_url != NULL &&
  1052. env_path_translated != script_path_translated &&
  1053. strcmp(env_path_translated, script_path_translated) != 0) {
  1054. /*
  1055. * pretty much apache specific. If we have a redirect_url
  1056. * then our script_filename and script_name point to the
  1057. * php executable
  1058. */
  1059. script_path_translated = env_path_translated;
  1060. /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
  1061. env_script_name = env_redirect_url;
  1062. }
  1063. #ifdef __riscos__
  1064. /* Convert path to unix format*/
  1065. __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
  1066. script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
  1067. #endif
  1068. /*
  1069. * if the file doesn't exist, try to extract PATH_INFO out
  1070. * of it by stat'ing back through the '/'
  1071. * this fixes url's like /info.php/test
  1072. */
  1073. if (script_path_translated &&
  1074. (script_path_translated_len = strlen(script_path_translated)) > 0 &&
  1075. (script_path_translated[script_path_translated_len-1] == '/' ||
  1076. #ifdef PHP_WIN32
  1077. script_path_translated[script_path_translated_len-1] == '\\' ||
  1078. #endif
  1079. (real_path = tsrm_realpath(script_path_translated, NULL)) == NULL)
  1080. ) {
  1081. char *pt = estrndup(script_path_translated, script_path_translated_len);
  1082. size_t len = script_path_translated_len;
  1083. char *ptr;
  1084. while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
  1085. *ptr = 0;
  1086. if (zend_stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
  1087. /*
  1088. * okay, we found the base script!
  1089. * work out how many chars we had to strip off;
  1090. * then we can modify PATH_INFO
  1091. * accordingly
  1092. *
  1093. * we now have the makings of
  1094. * PATH_INFO=/test
  1095. * SCRIPT_FILENAME=/docroot/info.php
  1096. *
  1097. * we now need to figure out what docroot is.
  1098. * if DOCUMENT_ROOT is set, this is easy, otherwise,
  1099. * we have to play the game of hide and seek to figure
  1100. * out what SCRIPT_NAME should be
  1101. */
  1102. size_t slen = len - strlen(pt);
  1103. size_t pilen = env_path_info ? strlen(env_path_info) : 0;
  1104. char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
  1105. if (orig_path_info != path_info) {
  1106. if (orig_path_info) {
  1107. char old;
  1108. CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
  1109. old = path_info[0];
  1110. path_info[0] = 0;
  1111. if (!orig_script_name ||
  1112. strcmp(orig_script_name, env_path_info) != 0) {
  1113. if (orig_script_name) {
  1114. CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
  1115. }
  1116. SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
  1117. } else {
  1118. SG(request_info).request_uri = orig_script_name;
  1119. }
  1120. path_info[0] = old;
  1121. }
  1122. env_path_info = CGI_PUTENV("PATH_INFO", path_info);
  1123. }
  1124. if (!orig_script_filename ||
  1125. strcmp(orig_script_filename, pt) != 0) {
  1126. if (orig_script_filename) {
  1127. CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
  1128. }
  1129. script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
  1130. }
  1131. TRANSLATE_SLASHES(pt);
  1132. /* figure out docroot
  1133. * SCRIPT_FILENAME minus SCRIPT_NAME
  1134. */
  1135. if (env_document_root) {
  1136. size_t l = strlen(env_document_root);
  1137. size_t path_translated_len = 0;
  1138. char *path_translated = NULL;
  1139. if (l && env_document_root[l - 1] == '/') {
  1140. --l;
  1141. }
  1142. /* we have docroot, so we should have:
  1143. * DOCUMENT_ROOT=/docroot
  1144. * SCRIPT_FILENAME=/docroot/info.php
  1145. */
  1146. /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
  1147. path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
  1148. path_translated = (char *) emalloc(path_translated_len + 1);
  1149. memcpy(path_translated, env_document_root, l);
  1150. if (env_path_info) {
  1151. memcpy(path_translated + l, env_path_info, (path_translated_len - l));
  1152. }
  1153. path_translated[path_translated_len] = '\0';
  1154. if (orig_path_translated) {
  1155. CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
  1156. }
  1157. env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
  1158. efree(path_translated);
  1159. } else if ( env_script_name &&
  1160. strstr(pt, env_script_name)
  1161. ) {
  1162. /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
  1163. size_t ptlen = strlen(pt) - strlen(env_script_name);
  1164. size_t path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
  1165. char *path_translated = (char *) emalloc(path_translated_len + 1);
  1166. memcpy(path_translated, pt, ptlen);
  1167. if (env_path_info) {
  1168. memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
  1169. }
  1170. path_translated[path_translated_len] = '\0';
  1171. if (orig_path_translated) {
  1172. CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
  1173. }
  1174. env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
  1175. efree(path_translated);
  1176. }
  1177. break;
  1178. }
  1179. }
  1180. if (!ptr) {
  1181. /*
  1182. * if we stripped out all the '/' and still didn't find
  1183. * a valid path... we will fail, badly. of course we would
  1184. * have failed anyway... we output 'no input file' now.
  1185. */
  1186. if (orig_script_filename) {
  1187. CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
  1188. }
  1189. script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
  1190. SG(sapi_headers).http_response_code = 404;
  1191. }
  1192. if (!SG(request_info).request_uri) {
  1193. if (!orig_script_name ||
  1194. strcmp(orig_script_name, env_script_name) != 0) {
  1195. if (orig_script_name) {
  1196. CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
  1197. }
  1198. SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
  1199. } else {
  1200. SG(request_info).request_uri = orig_script_name;
  1201. }
  1202. }
  1203. if (pt) {
  1204. efree(pt);
  1205. }
  1206. } else {
  1207. /* make sure path_info/translated are empty */
  1208. if (!orig_script_filename ||
  1209. (script_path_translated != orig_script_filename &&
  1210. strcmp(script_path_translated, orig_script_filename) != 0)) {
  1211. if (orig_script_filename) {
  1212. CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
  1213. }
  1214. script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
  1215. }
  1216. if (env_redirect_url) {
  1217. if (orig_path_info) {
  1218. CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
  1219. CGI_PUTENV("PATH_INFO", NULL);
  1220. }
  1221. if (orig_path_translated) {
  1222. CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
  1223. CGI_PUTENV("PATH_TRANSLATED", NULL);
  1224. }
  1225. }
  1226. if (env_script_name != orig_script_name) {
  1227. if (orig_script_name) {
  1228. CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
  1229. }
  1230. SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
  1231. } else {
  1232. SG(request_info).request_uri = env_script_name;
  1233. }
  1234. efree(real_path);
  1235. }
  1236. } else {
  1237. /* pre 4.3 behaviour, shouldn't be used but provides BC */
  1238. if (env_path_info) {
  1239. SG(request_info).request_uri = env_path_info;
  1240. } else {
  1241. SG(request_info).request_uri = env_script_name;
  1242. }
  1243. if (!CGIG(discard_path) && env_path_translated) {
  1244. script_path_translated = env_path_translated;
  1245. }
  1246. }
  1247. if (is_valid_path(script_path_translated)) {
  1248. SG(request_info).path_translated = estrdup(script_path_translated);
  1249. }
  1250. SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
  1251. /* FIXME - Work out proto_num here */
  1252. SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
  1253. SG(request_info).content_type = (content_type ? content_type : "" );
  1254. SG(request_info).content_length = (content_length ? atol(content_length) : 0);
  1255. /* The CGI RFC allows servers to pass on unvalidated Authorization data */
  1256. auth = CGI_GETENV("HTTP_AUTHORIZATION");
  1257. php_handle_auth_data(auth);
  1258. }
  1259. }
  1260. /* }}} */
  1261. #ifndef PHP_WIN32
  1262. /**
  1263. * Clean up child processes upon exit
  1264. */
  1265. void fastcgi_cleanup(int signal)
  1266. {
  1267. #ifdef DEBUG_FASTCGI
  1268. fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
  1269. #endif
  1270. sigaction(SIGTERM, &old_term, 0);
  1271. /* Kill all the processes in our process group */
  1272. kill(-pgroup, SIGTERM);
  1273. if (parent && parent_waiting) {
  1274. exit_signal = 1;
  1275. } else {
  1276. exit(0);
  1277. }
  1278. }
  1279. #else
  1280. BOOL WINAPI fastcgi_cleanup(DWORD sig)
  1281. {
  1282. int i = kids;
  1283. EnterCriticalSection(&cleanup_lock);
  1284. cleaning_up = 1;
  1285. LeaveCriticalSection(&cleanup_lock);
  1286. while (0 < i--) {
  1287. if (NULL == kid_cgi_ps[i]) {
  1288. continue;
  1289. }
  1290. TerminateProcess(kid_cgi_ps[i], 0);
  1291. CloseHandle(kid_cgi_ps[i]);
  1292. kid_cgi_ps[i] = NULL;
  1293. }
  1294. if (job) {
  1295. CloseHandle(job);
  1296. }
  1297. parent = 0;
  1298. return TRUE;
  1299. }
  1300. #endif
  1301. PHP_INI_BEGIN()
  1302. STD_PHP_INI_ENTRY("cgi.rfc2616_headers", "0", PHP_INI_ALL, OnUpdateBool, rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
  1303. STD_PHP_INI_ENTRY("cgi.nph", "0", PHP_INI_ALL, OnUpdateBool, nph, php_cgi_globals_struct, php_cgi_globals)
  1304. STD_PHP_INI_ENTRY("cgi.check_shebang_line", "1", PHP_INI_SYSTEM, OnUpdateBool, check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
  1305. STD_PHP_INI_ENTRY("cgi.force_redirect", "1", PHP_INI_SYSTEM, OnUpdateBool, force_redirect, php_cgi_globals_struct, php_cgi_globals)
  1306. STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
  1307. STD_PHP_INI_ENTRY("cgi.fix_pathinfo", "1", PHP_INI_SYSTEM, OnUpdateBool, fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
  1308. STD_PHP_INI_ENTRY("cgi.discard_path", "0", PHP_INI_SYSTEM, OnUpdateBool, discard_path, php_cgi_globals_struct, php_cgi_globals)
  1309. STD_PHP_INI_ENTRY("fastcgi.logging", "1", PHP_INI_SYSTEM, OnUpdateBool, fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
  1310. #ifdef PHP_WIN32
  1311. STD_PHP_INI_ENTRY("fastcgi.impersonate", "0", PHP_INI_SYSTEM, OnUpdateBool, impersonate, php_cgi_globals_struct, php_cgi_globals)
  1312. #endif
  1313. PHP_INI_END()
  1314. /* {{{ php_cgi_globals_ctor
  1315. */
  1316. static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals)
  1317. {
  1318. #if defined(ZTS) && defined(PHP_WIN32)
  1319. ZEND_TSRMLS_CACHE_UPDATE();
  1320. #endif
  1321. php_cgi_globals->rfc2616_headers = 0;
  1322. php_cgi_globals->nph = 0;
  1323. php_cgi_globals->check_shebang_line = 1;
  1324. php_cgi_globals->force_redirect = 1;
  1325. php_cgi_globals->redirect_status_env = NULL;
  1326. php_cgi_globals->fix_pathinfo = 1;
  1327. php_cgi_globals->discard_path = 0;
  1328. php_cgi_globals->fcgi_logging = 1;
  1329. #ifdef PHP_WIN32
  1330. php_cgi_globals->impersonate = 0;
  1331. #endif
  1332. zend_hash_init(&php_cgi_globals->user_config_cache, 8, NULL, user_config_cache_entry_dtor, 1);
  1333. }
  1334. /* }}} */
  1335. /* {{{ PHP_MINIT_FUNCTION
  1336. */
  1337. static PHP_MINIT_FUNCTION(cgi)
  1338. {
  1339. REGISTER_INI_ENTRIES();
  1340. return SUCCESS;
  1341. }
  1342. /* }}} */
  1343. /* {{{ PHP_MSHUTDOWN_FUNCTION
  1344. */
  1345. static PHP_MSHUTDOWN_FUNCTION(cgi)
  1346. {
  1347. zend_hash_destroy(&CGIG(user_config_cache));
  1348. UNREGISTER_INI_ENTRIES();
  1349. return SUCCESS;
  1350. }
  1351. /* }}} */
  1352. /* {{{ PHP_MINFO_FUNCTION
  1353. */
  1354. static PHP_MINFO_FUNCTION(cgi)
  1355. {
  1356. DISPLAY_INI_ENTRIES();
  1357. }
  1358. /* }}} */
  1359. PHP_FUNCTION(apache_child_terminate) /* {{{ */
  1360. {
  1361. if (zend_parse_parameters_none()) {
  1362. RETURN_THROWS();
  1363. }
  1364. if (fcgi_is_fastcgi()) {
  1365. fcgi_terminate();
  1366. }
  1367. }
  1368. /* }}} */
  1369. PHP_FUNCTION(apache_request_headers) /* {{{ */
  1370. {
  1371. if (zend_parse_parameters_none()) {
  1372. RETURN_THROWS();
  1373. }
  1374. array_init(return_value);
  1375. if (fcgi_is_fastcgi()) {
  1376. fcgi_request *request = (fcgi_request*) SG(server_context);
  1377. fcgi_loadenv(request, sapi_add_request_header, return_value);
  1378. } else {
  1379. char buf[128];
  1380. char **env, *p, *q, *var, *val, *t = buf;
  1381. size_t alloc_size = sizeof(buf);
  1382. zend_ulong var_len;
  1383. for (env = environ; env != NULL && *env != NULL; env++) {
  1384. val = strchr(*env, '=');
  1385. if (!val) { /* malformed entry? */
  1386. continue;
  1387. }
  1388. var_len = val - *env;
  1389. if (var_len >= alloc_size) {
  1390. alloc_size = var_len + 64;
  1391. t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
  1392. }
  1393. var = *env;
  1394. if (var_len > 5 &&
  1395. var[0] == 'H' &&
  1396. var[1] == 'T' &&
  1397. var[2] == 'T' &&
  1398. var[3] == 'P' &&
  1399. var[4] == '_') {
  1400. var_len -= 5;
  1401. if (var_len >= alloc_size) {
  1402. alloc_size = var_len + 64;
  1403. t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
  1404. }
  1405. p = var + 5;
  1406. var = q = t;
  1407. /* First char keep uppercase */
  1408. *q++ = *p++;
  1409. while (*p) {
  1410. if (*p == '=') {
  1411. /* End of name */
  1412. break;
  1413. } else if (*p == '_') {
  1414. *q++ = '-';
  1415. p++;
  1416. /* First char after - keep uppercase */
  1417. if (*p && *p!='=') {
  1418. *q++ = *p++;
  1419. }
  1420. } else if (*p >= 'A' && *p <= 'Z') {
  1421. /* lowercase */
  1422. *q++ = (*p++ - 'A' + 'a');
  1423. } else {
  1424. *q++ = *p++;
  1425. }
  1426. }
  1427. *q = 0;
  1428. } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
  1429. memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
  1430. var = "Content-Type";
  1431. } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
  1432. memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
  1433. var = "Content-Length";
  1434. } else {
  1435. continue;
  1436. }
  1437. val++;
  1438. add_assoc_string_ex(return_value, var, var_len, val);
  1439. }
  1440. if (t != buf && t != NULL) {
  1441. efree(t);
  1442. }
  1443. }
  1444. }
  1445. /* }}} */
  1446. static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
  1447. {
  1448. if (h->header_len > 0) {
  1449. char *s;
  1450. size_t len = 0;
  1451. ALLOCA_FLAG(use_heap)
  1452. char *p = strchr(h->header, ':');
  1453. if (NULL != p) {
  1454. len = p - h->header;
  1455. }
  1456. if (len > 0) {
  1457. while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
  1458. len--;
  1459. }
  1460. if (len) {
  1461. s = do_alloca(len + 1, use_heap);
  1462. memcpy(s, h->header, len);
  1463. s[len] = 0;
  1464. do {
  1465. p++;
  1466. } while (*p == ' ' || *p == '\t');
  1467. add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
  1468. free_alloca(s, use_heap);
  1469. }
  1470. }
  1471. }
  1472. }
  1473. /* }}} */
  1474. PHP_FUNCTION(apache_response_headers) /* {{{ */
  1475. {
  1476. if (zend_parse_parameters_none() == FAILURE) {
  1477. RETURN_THROWS();
  1478. }
  1479. array_init(return_value);
  1480. zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
  1481. }
  1482. /* }}} */
  1483. ZEND_BEGIN_ARG_INFO(arginfo_no_args, 0)
  1484. ZEND_END_ARG_INFO()
  1485. static const zend_function_entry cgi_functions[] = {
  1486. PHP_FE(apache_child_terminate, arginfo_no_args)
  1487. PHP_FE(apache_request_headers, arginfo_no_args)
  1488. PHP_FE(apache_response_headers, arginfo_no_args)
  1489. PHP_FALIAS(getallheaders, apache_request_headers, arginfo_no_args)
  1490. PHP_FE_END
  1491. };
  1492. static zend_module_entry cgi_module_entry = {
  1493. STANDARD_MODULE_HEADER,
  1494. "cgi-fcgi",
  1495. cgi_functions,
  1496. PHP_MINIT(cgi),
  1497. PHP_MSHUTDOWN(cgi),
  1498. NULL,
  1499. NULL,
  1500. PHP_MINFO(cgi),
  1501. PHP_VERSION,
  1502. STANDARD_MODULE_PROPERTIES
  1503. };
  1504. /* {{{ main
  1505. */
  1506. int main(int argc, char *argv[])
  1507. {
  1508. int free_query_string = 0;
  1509. int exit_status = SUCCESS;
  1510. int cgi = 0, c, i;
  1511. size_t len;
  1512. zend_file_handle file_handle;
  1513. char *s;
  1514. /* temporary locals */
  1515. int behavior = PHP_MODE_STANDARD;
  1516. int no_headers = 0;
  1517. int orig_optind = php_optind;
  1518. char *orig_optarg = php_optarg;
  1519. char *script_file = NULL;
  1520. size_t ini_entries_len = 0;
  1521. /* end of temporary locals */
  1522. int max_requests = 500;
  1523. int requests = 0;
  1524. int fastcgi;
  1525. char *bindpath = NULL;
  1526. int fcgi_fd = 0;
  1527. fcgi_request *request = NULL;
  1528. int warmup_repeats = 0;
  1529. int repeats = 1;
  1530. int benchmark = 0;
  1531. #if HAVE_GETTIMEOFDAY
  1532. struct timeval start, end;
  1533. #else
  1534. time_t start, end;
  1535. #endif
  1536. #ifndef PHP_WIN32
  1537. int status = 0;
  1538. #endif
  1539. char *query_string;
  1540. char *decoded_query_string;
  1541. int skip_getopt = 0;
  1542. #if defined(SIGPIPE) && defined(SIG_IGN)
  1543. signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
  1544. that sockets created via fsockopen()
  1545. don't kill PHP if the remote site
  1546. closes it. in apache|apxs mode apache
  1547. does that for us! thies@thieso.net
  1548. 20000419 */
  1549. #endif
  1550. #ifdef ZTS
  1551. php_tsrm_startup();
  1552. # ifdef PHP_WIN32
  1553. ZEND_TSRMLS_CACHE_UPDATE();
  1554. # endif
  1555. #endif
  1556. zend_signal_startup();
  1557. #ifdef ZTS
  1558. ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
  1559. #else
  1560. php_cgi_globals_ctor(&php_cgi_globals);
  1561. #endif
  1562. sapi_startup(&cgi_sapi_module);
  1563. fastcgi = fcgi_is_fastcgi();
  1564. cgi_sapi_module.php_ini_path_override = NULL;
  1565. #ifdef PHP_WIN32
  1566. _fmode = _O_BINARY; /* sets default for file streams to binary */
  1567. setmode(_f

Large files files are truncated, but you can click here to view the full file