PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/sapi/cgi/fastcgi.c

http://github.com/infusion/PHP
C | 1302 lines | 1113 code | 150 blank | 39 comment | 330 complexity | 34956d2674b1f555382a2576b896e04b MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2011 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: Dmitry Stogov <dmitry@zend.com> |
  16. +----------------------------------------------------------------------+
  17. */
  18. /* $Id: fastcgi.c 307579 2011-01-19 08:38:25Z dmitry $ */
  19. #include "php.h"
  20. #include "fastcgi.h"
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <stdarg.h>
  25. #include <errno.h>
  26. #ifdef _WIN32
  27. #include <windows.h>
  28. typedef unsigned int in_addr_t;
  29. struct sockaddr_un {
  30. short sun_family;
  31. char sun_path[MAXPATHLEN];
  32. };
  33. static HANDLE fcgi_accept_mutex = INVALID_HANDLE_VALUE;
  34. static int is_impersonate = 0;
  35. #define FCGI_LOCK(fd) \
  36. if (fcgi_accept_mutex != INVALID_HANDLE_VALUE) { \
  37. DWORD ret; \
  38. while ((ret = WaitForSingleObject(fcgi_accept_mutex, 1000)) == WAIT_TIMEOUT) { \
  39. if (in_shutdown) return -1; \
  40. } \
  41. if (ret == WAIT_FAILED) { \
  42. fprintf(stderr, "WaitForSingleObject() failed\n"); \
  43. return -1; \
  44. } \
  45. }
  46. #define FCGI_UNLOCK(fd) \
  47. if (fcgi_accept_mutex != INVALID_HANDLE_VALUE) { \
  48. ReleaseMutex(fcgi_accept_mutex); \
  49. }
  50. #else
  51. # include <sys/types.h>
  52. # include <sys/stat.h>
  53. # include <unistd.h>
  54. # include <fcntl.h>
  55. # include <sys/socket.h>
  56. # include <sys/un.h>
  57. # include <netinet/in.h>
  58. # include <arpa/inet.h>
  59. # include <netdb.h>
  60. # include <signal.h>
  61. # define closesocket(s) close(s)
  62. # if defined(HAVE_SYS_POLL_H) && defined(HAVE_POLL)
  63. # include <sys/poll.h>
  64. # endif
  65. # if defined(HAVE_SYS_SELECT_H)
  66. # include <sys/select.h>
  67. # endif
  68. #ifndef INADDR_NONE
  69. #define INADDR_NONE ((unsigned long) -1)
  70. #endif
  71. # ifndef HAVE_SOCKLEN_T
  72. typedef unsigned int socklen_t;
  73. # endif
  74. # ifdef USE_LOCKING
  75. # define FCGI_LOCK(fd) \
  76. do { \
  77. struct flock lock; \
  78. lock.l_type = F_WRLCK; \
  79. lock.l_start = 0; \
  80. lock.l_whence = SEEK_SET; \
  81. lock.l_len = 0; \
  82. if (fcntl(fd, F_SETLKW, &lock) != -1) { \
  83. break; \
  84. } else if (errno != EINTR || in_shutdown) { \
  85. return -1; \
  86. } \
  87. } while (1)
  88. # define FCGI_UNLOCK(fd) \
  89. do { \
  90. int orig_errno = errno; \
  91. while (1) { \
  92. struct flock lock; \
  93. lock.l_type = F_UNLCK; \
  94. lock.l_start = 0; \
  95. lock.l_whence = SEEK_SET; \
  96. lock.l_len = 0; \
  97. if (fcntl(fd, F_SETLK, &lock) != -1) { \
  98. break; \
  99. } else if (errno != EINTR) { \
  100. return -1; \
  101. } \
  102. } \
  103. errno = orig_errno; \
  104. } while (0)
  105. # else
  106. # define FCGI_LOCK(fd)
  107. # define FCGI_UNLOCK(fd)
  108. # endif
  109. #endif
  110. typedef union _sa_t {
  111. struct sockaddr sa;
  112. struct sockaddr_un sa_unix;
  113. struct sockaddr_in sa_inet;
  114. } sa_t;
  115. static HashTable fcgi_mgmt_vars;
  116. static int is_initialized = 0;
  117. static int is_fastcgi = 0;
  118. static int in_shutdown = 0;
  119. static in_addr_t *allowed_clients = NULL;
  120. #ifdef _WIN32
  121. static DWORD WINAPI fcgi_shutdown_thread(LPVOID arg)
  122. {
  123. HANDLE shutdown_event = (HANDLE) arg;
  124. WaitForSingleObject(shutdown_event, INFINITE);
  125. in_shutdown = 1;
  126. return 0;
  127. }
  128. #else
  129. static void fcgi_signal_handler(int signo)
  130. {
  131. if (signo == SIGUSR1 || signo == SIGTERM) {
  132. in_shutdown = 1;
  133. }
  134. }
  135. static void fcgi_setup_signals(void)
  136. {
  137. struct sigaction new_sa, old_sa;
  138. sigemptyset(&new_sa.sa_mask);
  139. new_sa.sa_flags = 0;
  140. new_sa.sa_handler = fcgi_signal_handler;
  141. sigaction(SIGUSR1, &new_sa, NULL);
  142. sigaction(SIGTERM, &new_sa, NULL);
  143. sigaction(SIGPIPE, NULL, &old_sa);
  144. if (old_sa.sa_handler == SIG_DFL) {
  145. sigaction(SIGPIPE, &new_sa, NULL);
  146. }
  147. }
  148. #endif
  149. int fcgi_in_shutdown(void)
  150. {
  151. return in_shutdown;
  152. }
  153. int fcgi_init(void)
  154. {
  155. if (!is_initialized) {
  156. #ifndef _WIN32
  157. sa_t sa;
  158. socklen_t len = sizeof(sa);
  159. #endif
  160. zend_hash_init(&fcgi_mgmt_vars, 0, NULL, fcgi_free_mgmt_var_cb, 1);
  161. fcgi_set_mgmt_var("FCGI_MPXS_CONNS", sizeof("FCGI_MPXS_CONNS")-1, "0", sizeof("0")-1);
  162. is_initialized = 1;
  163. #ifdef _WIN32
  164. # if 0
  165. /* TODO: Support for TCP sockets */
  166. WSADATA wsaData;
  167. if (WSAStartup(MAKEWORD(2,0), &wsaData)) {
  168. fprintf(stderr, "Error starting Windows Sockets. Error: %d", WSAGetLastError());
  169. return 0;
  170. }
  171. # endif
  172. if ((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
  173. (GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) &&
  174. (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE)) {
  175. char *str;
  176. DWORD pipe_mode = PIPE_READMODE_BYTE | PIPE_WAIT;
  177. HANDLE pipe = GetStdHandle(STD_INPUT_HANDLE);
  178. SetNamedPipeHandleState(pipe, &pipe_mode, NULL, NULL);
  179. str = getenv("_FCGI_SHUTDOWN_EVENT_");
  180. if (str != NULL) {
  181. HANDLE shutdown_event = (HANDLE) atoi(str);
  182. if (!CreateThread(NULL, 0, fcgi_shutdown_thread,
  183. shutdown_event, 0, NULL)) {
  184. return -1;
  185. }
  186. }
  187. str = getenv("_FCGI_MUTEX_");
  188. if (str != NULL) {
  189. fcgi_accept_mutex = (HANDLE) atoi(str);
  190. }
  191. return is_fastcgi = 1;
  192. } else {
  193. return is_fastcgi = 0;
  194. }
  195. #else
  196. errno = 0;
  197. if (getpeername(0, (struct sockaddr *)&sa, &len) != 0 && errno == ENOTCONN) {
  198. fcgi_setup_signals();
  199. return is_fastcgi = 1;
  200. } else {
  201. return is_fastcgi = 0;
  202. }
  203. #endif
  204. }
  205. return is_fastcgi;
  206. }
  207. int fcgi_is_fastcgi(void)
  208. {
  209. if (!is_initialized) {
  210. return fcgi_init();
  211. } else {
  212. return is_fastcgi;
  213. }
  214. }
  215. void fcgi_shutdown(void)
  216. {
  217. if (is_initialized) {
  218. zend_hash_destroy(&fcgi_mgmt_vars);
  219. }
  220. is_fastcgi = 0;
  221. if (allowed_clients) {
  222. free(allowed_clients);
  223. }
  224. }
  225. #ifdef _WIN32
  226. /* Do some black magic with the NT security API.
  227. * We prepare a DACL (Discretionary Access Control List) so that
  228. * we, the creator, are allowed all access, while "Everyone Else"
  229. * is only allowed to read and write to the pipe.
  230. * This avoids security issues on shared hosts where a luser messes
  231. * with the lower-level pipe settings and screws up the FastCGI service.
  232. */
  233. static PACL prepare_named_pipe_acl(PSECURITY_DESCRIPTOR sd, LPSECURITY_ATTRIBUTES sa)
  234. {
  235. DWORD req_acl_size;
  236. char everyone_buf[32], owner_buf[32];
  237. PSID sid_everyone, sid_owner;
  238. SID_IDENTIFIER_AUTHORITY
  239. siaWorld = SECURITY_WORLD_SID_AUTHORITY,
  240. siaCreator = SECURITY_CREATOR_SID_AUTHORITY;
  241. PACL acl;
  242. sid_everyone = (PSID)&everyone_buf;
  243. sid_owner = (PSID)&owner_buf;
  244. req_acl_size = sizeof(ACL) +
  245. (2 * ((sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + GetSidLengthRequired(1)));
  246. acl = malloc(req_acl_size);
  247. if (acl == NULL) {
  248. return NULL;
  249. }
  250. if (!InitializeSid(sid_everyone, &siaWorld, 1)) {
  251. goto out_fail;
  252. }
  253. *GetSidSubAuthority(sid_everyone, 0) = SECURITY_WORLD_RID;
  254. if (!InitializeSid(sid_owner, &siaCreator, 1)) {
  255. goto out_fail;
  256. }
  257. *GetSidSubAuthority(sid_owner, 0) = SECURITY_CREATOR_OWNER_RID;
  258. if (!InitializeAcl(acl, req_acl_size, ACL_REVISION)) {
  259. goto out_fail;
  260. }
  261. if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_GENERIC_READ | FILE_GENERIC_WRITE, sid_everyone)) {
  262. goto out_fail;
  263. }
  264. if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_ALL_ACCESS, sid_owner)) {
  265. goto out_fail;
  266. }
  267. if (!InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION)) {
  268. goto out_fail;
  269. }
  270. if (!SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE)) {
  271. goto out_fail;
  272. }
  273. sa->lpSecurityDescriptor = sd;
  274. return acl;
  275. out_fail:
  276. free(acl);
  277. return NULL;
  278. }
  279. #endif
  280. static int is_port_number(const char *bindpath)
  281. {
  282. while (*bindpath) {
  283. if (*bindpath < '0' || *bindpath > '9') {
  284. return 0;
  285. }
  286. bindpath++;
  287. }
  288. return 1;
  289. }
  290. int fcgi_listen(const char *path, int backlog)
  291. {
  292. char *s;
  293. int tcp = 0;
  294. char host[MAXPATHLEN];
  295. short port = 0;
  296. int listen_socket;
  297. sa_t sa;
  298. socklen_t sock_len;
  299. #ifdef SO_REUSEADDR
  300. # ifdef _WIN32
  301. BOOL reuse = 1;
  302. # else
  303. int reuse = 1;
  304. # endif
  305. #endif
  306. if ((s = strchr(path, ':'))) {
  307. port = atoi(s+1);
  308. if (port != 0 && (s-path) < MAXPATHLEN) {
  309. strncpy(host, path, s-path);
  310. host[s-path] = '\0';
  311. tcp = 1;
  312. }
  313. } else if (is_port_number(path)) {
  314. port = atoi(path);
  315. if (port != 0) {
  316. host[0] = '\0';
  317. tcp = 1;
  318. }
  319. }
  320. /* Prepare socket address */
  321. if (tcp) {
  322. memset(&sa.sa_inet, 0, sizeof(sa.sa_inet));
  323. sa.sa_inet.sin_family = AF_INET;
  324. sa.sa_inet.sin_port = htons(port);
  325. sock_len = sizeof(sa.sa_inet);
  326. if (!*host || !strncmp(host, "*", sizeof("*")-1)) {
  327. sa.sa_inet.sin_addr.s_addr = htonl(INADDR_ANY);
  328. } else {
  329. sa.sa_inet.sin_addr.s_addr = inet_addr(host);
  330. if (sa.sa_inet.sin_addr.s_addr == INADDR_NONE) {
  331. struct hostent *hep;
  332. hep = gethostbyname(host);
  333. if (!hep || hep->h_addrtype != AF_INET || !hep->h_addr_list[0]) {
  334. fprintf(stderr, "Cannot resolve host name '%s'!\n", host);
  335. return -1;
  336. } else if (hep->h_addr_list[1]) {
  337. fprintf(stderr, "Host '%s' has multiple addresses. You must choose one explicitly!\n", host);
  338. return -1;
  339. }
  340. sa.sa_inet.sin_addr.s_addr = ((struct in_addr*)hep->h_addr_list[0])->s_addr;
  341. }
  342. }
  343. } else {
  344. #ifdef _WIN32
  345. SECURITY_DESCRIPTOR sd;
  346. SECURITY_ATTRIBUTES saw;
  347. PACL acl;
  348. HANDLE namedPipe;
  349. memset(&sa, 0, sizeof(saw));
  350. saw.nLength = sizeof(saw);
  351. saw.bInheritHandle = FALSE;
  352. acl = prepare_named_pipe_acl(&sd, &saw);
  353. namedPipe = CreateNamedPipe(path,
  354. PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
  355. PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
  356. PIPE_UNLIMITED_INSTANCES,
  357. 8192, 8192, 0, &saw);
  358. if (namedPipe == INVALID_HANDLE_VALUE) {
  359. return -1;
  360. }
  361. listen_socket = _open_osfhandle((long)namedPipe, 0);
  362. if (!is_initialized) {
  363. fcgi_init();
  364. }
  365. is_fastcgi = 1;
  366. return listen_socket;
  367. #else
  368. int path_len = strlen(path);
  369. if (path_len >= sizeof(sa.sa_unix.sun_path)) {
  370. fprintf(stderr, "Listening socket's path name is too long.\n");
  371. return -1;
  372. }
  373. memset(&sa.sa_unix, 0, sizeof(sa.sa_unix));
  374. sa.sa_unix.sun_family = AF_UNIX;
  375. memcpy(sa.sa_unix.sun_path, path, path_len + 1);
  376. sock_len = (size_t)(((struct sockaddr_un *)0)->sun_path) + path_len;
  377. #ifdef HAVE_SOCKADDR_UN_SUN_LEN
  378. sa.sa_unix.sun_len = sock_len;
  379. #endif
  380. unlink(path);
  381. #endif
  382. }
  383. /* Create, bind socket and start listen on it */
  384. if ((listen_socket = socket(sa.sa.sa_family, SOCK_STREAM, 0)) < 0 ||
  385. #ifdef SO_REUSEADDR
  386. setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)) < 0 ||
  387. #endif
  388. bind(listen_socket, (struct sockaddr *) &sa, sock_len) < 0 ||
  389. listen(listen_socket, backlog) < 0) {
  390. fprintf(stderr, "Cannot bind/listen socket - [%d] %s.\n",errno, strerror(errno));
  391. return -1;
  392. }
  393. if (!tcp) {
  394. chmod(path, 0777);
  395. } else {
  396. char *ip = getenv("FCGI_WEB_SERVER_ADDRS");
  397. char *cur, *end;
  398. int n;
  399. if (ip) {
  400. ip = strdup(ip);
  401. cur = ip;
  402. n = 0;
  403. while (*cur) {
  404. if (*cur == ',') n++;
  405. cur++;
  406. }
  407. allowed_clients = malloc(sizeof(in_addr_t) * (n+2));
  408. n = 0;
  409. cur = ip;
  410. while (cur) {
  411. end = strchr(cur, ',');
  412. if (end) {
  413. *end = 0;
  414. end++;
  415. }
  416. allowed_clients[n] = inet_addr(cur);
  417. if (allowed_clients[n] == INADDR_NONE) {
  418. fprintf(stderr, "Wrong IP address '%s' in FCGI_WEB_SERVER_ADDRS\n", cur);
  419. }
  420. n++;
  421. cur = end;
  422. }
  423. allowed_clients[n] = INADDR_NONE;
  424. free(ip);
  425. }
  426. }
  427. if (!is_initialized) {
  428. fcgi_init();
  429. }
  430. is_fastcgi = 1;
  431. #ifdef _WIN32
  432. if (tcp) {
  433. listen_socket = _open_osfhandle((long)listen_socket, 0);
  434. }
  435. #else
  436. fcgi_setup_signals();
  437. #endif
  438. return listen_socket;
  439. }
  440. void fcgi_init_request(fcgi_request *req, int listen_socket)
  441. {
  442. memset(req, 0, sizeof(fcgi_request));
  443. req->listen_socket = listen_socket;
  444. req->fd = -1;
  445. req->id = -1;
  446. req->in_len = 0;
  447. req->in_pad = 0;
  448. req->out_hdr = NULL;
  449. req->out_pos = req->out_buf;
  450. #ifdef _WIN32
  451. req->tcp = !GetNamedPipeInfo((HANDLE)_get_osfhandle(req->listen_socket), NULL, NULL, NULL, NULL);
  452. #endif
  453. }
  454. static inline ssize_t safe_write(fcgi_request *req, const void *buf, size_t count)
  455. {
  456. int ret;
  457. size_t n = 0;
  458. do {
  459. errno = 0;
  460. #ifdef _WIN32
  461. if (!req->tcp) {
  462. ret = write(req->fd, ((char*)buf)+n, count-n);
  463. } else {
  464. ret = send(req->fd, ((char*)buf)+n, count-n, 0);
  465. if (ret <= 0) {
  466. errno = WSAGetLastError();
  467. }
  468. }
  469. #else
  470. ret = write(req->fd, ((char*)buf)+n, count-n);
  471. #endif
  472. if (ret > 0) {
  473. n += ret;
  474. } else if (ret <= 0 && errno != 0 && errno != EINTR) {
  475. return ret;
  476. }
  477. } while (n != count);
  478. return n;
  479. }
  480. static inline ssize_t safe_read(fcgi_request *req, const void *buf, size_t count)
  481. {
  482. int ret;
  483. size_t n = 0;
  484. do {
  485. errno = 0;
  486. #ifdef _WIN32
  487. if (!req->tcp) {
  488. ret = read(req->fd, ((char*)buf)+n, count-n);
  489. } else {
  490. ret = recv(req->fd, ((char*)buf)+n, count-n, 0);
  491. if (ret <= 0) {
  492. errno = WSAGetLastError();
  493. }
  494. }
  495. #else
  496. ret = read(req->fd, ((char*)buf)+n, count-n);
  497. #endif
  498. if (ret > 0) {
  499. n += ret;
  500. } else if (ret == 0 && errno == 0) {
  501. return n;
  502. } else if (ret <= 0 && errno != 0 && errno != EINTR) {
  503. return ret;
  504. }
  505. } while (n != count);
  506. return n;
  507. }
  508. static inline int fcgi_make_header(fcgi_header *hdr, fcgi_request_type type, int req_id, int len)
  509. {
  510. int pad = ((len + 7) & ~7) - len;
  511. hdr->contentLengthB0 = (unsigned char)(len & 0xff);
  512. hdr->contentLengthB1 = (unsigned char)((len >> 8) & 0xff);
  513. hdr->paddingLength = (unsigned char)pad;
  514. hdr->requestIdB0 = (unsigned char)(req_id & 0xff);
  515. hdr->requestIdB1 = (unsigned char)((req_id >> 8) & 0xff);
  516. hdr->reserved = 0;
  517. hdr->type = type;
  518. hdr->version = FCGI_VERSION_1;
  519. if (pad) {
  520. memset(((unsigned char*)hdr) + sizeof(fcgi_header) + len, 0, pad);
  521. }
  522. return pad;
  523. }
  524. static int fcgi_get_params(fcgi_request *req, unsigned char *p, unsigned char *end)
  525. {
  526. char buf[128];
  527. char *tmp = buf;
  528. size_t buf_size = sizeof(buf);
  529. unsigned int name_len, val_len;
  530. char *s;
  531. int ret = 1;
  532. while (p < end) {
  533. name_len = *p++;
  534. if (name_len >= 128) {
  535. if (p + 3 >= end) {
  536. ret = 0;
  537. break;
  538. }
  539. name_len = ((name_len & 0x7f) << 24);
  540. name_len |= (*p++ << 16);
  541. name_len |= (*p++ << 8);
  542. name_len |= *p++;
  543. }
  544. if (p >= end) {
  545. ret = 0;
  546. break;
  547. }
  548. val_len = *p++;
  549. if (val_len >= 128) {
  550. if (p + 3 >= end) {
  551. ret = 0;
  552. break;
  553. }
  554. val_len = ((val_len & 0x7f) << 24);
  555. val_len |= (*p++ << 16);
  556. val_len |= (*p++ << 8);
  557. val_len |= *p++;
  558. }
  559. if (name_len + val_len > end - p) {
  560. /* Malformated request */
  561. ret = 0;
  562. break;
  563. }
  564. if (name_len+1 >= buf_size) {
  565. buf_size = name_len + 64;
  566. tmp = (tmp == buf ? emalloc(buf_size): erealloc(tmp, buf_size));
  567. }
  568. memcpy(tmp, p, name_len);
  569. tmp[name_len] = 0;
  570. s = estrndup((char*)p + name_len, val_len);
  571. zend_hash_update(req->env, tmp, name_len+1, &s, sizeof(char*), NULL);
  572. p += name_len + val_len;
  573. }
  574. if (tmp != buf && tmp != NULL) {
  575. efree(tmp);
  576. }
  577. return ret;
  578. }
  579. static void fcgi_free_var(char **s)
  580. {
  581. efree(*s);
  582. }
  583. static int fcgi_read_request(fcgi_request *req)
  584. {
  585. fcgi_header hdr;
  586. int len, padding;
  587. unsigned char buf[FCGI_MAX_LENGTH+8];
  588. req->keep = 0;
  589. req->closed = 0;
  590. req->in_len = 0;
  591. req->out_hdr = NULL;
  592. req->out_pos = req->out_buf;
  593. ALLOC_HASHTABLE(req->env);
  594. zend_hash_init(req->env, 0, NULL, (void (*)(void *)) fcgi_free_var, 0);
  595. if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
  596. hdr.version < FCGI_VERSION_1) {
  597. return 0;
  598. }
  599. len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
  600. padding = hdr.paddingLength;
  601. while (hdr.type == FCGI_STDIN && len == 0) {
  602. if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
  603. hdr.version < FCGI_VERSION_1) {
  604. return 0;
  605. }
  606. len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
  607. padding = hdr.paddingLength;
  608. }
  609. if (len + padding > FCGI_MAX_LENGTH) {
  610. return 0;
  611. }
  612. req->id = (hdr.requestIdB1 << 8) + hdr.requestIdB0;
  613. if (hdr.type == FCGI_BEGIN_REQUEST && len == sizeof(fcgi_begin_request)) {
  614. char *val;
  615. if (safe_read(req, buf, len+padding) != len+padding) {
  616. return 0;
  617. }
  618. req->keep = (((fcgi_begin_request*)buf)->flags & FCGI_KEEP_CONN);
  619. switch ((((fcgi_begin_request*)buf)->roleB1 << 8) + ((fcgi_begin_request*)buf)->roleB0) {
  620. case FCGI_RESPONDER:
  621. val = estrdup("RESPONDER");
  622. zend_hash_update(req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
  623. break;
  624. case FCGI_AUTHORIZER:
  625. val = estrdup("AUTHORIZER");
  626. zend_hash_update(req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
  627. break;
  628. case FCGI_FILTER:
  629. val = estrdup("FILTER");
  630. zend_hash_update(req->env, "FCGI_ROLE", sizeof("FCGI_ROLE"), &val, sizeof(char*), NULL);
  631. break;
  632. default:
  633. return 0;
  634. }
  635. if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
  636. hdr.version < FCGI_VERSION_1) {
  637. return 0;
  638. }
  639. len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
  640. padding = hdr.paddingLength;
  641. while (hdr.type == FCGI_PARAMS && len > 0) {
  642. if (len + padding > FCGI_MAX_LENGTH) {
  643. return 0;
  644. }
  645. if (safe_read(req, buf, len+padding) != len+padding) {
  646. req->keep = 0;
  647. return 0;
  648. }
  649. if (!fcgi_get_params(req, buf, buf+len)) {
  650. req->keep = 0;
  651. return 0;
  652. }
  653. if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
  654. hdr.version < FCGI_VERSION_1) {
  655. req->keep = 0;
  656. return 0;
  657. }
  658. len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
  659. padding = hdr.paddingLength;
  660. }
  661. } else if (hdr.type == FCGI_GET_VALUES) {
  662. unsigned char *p = buf + sizeof(fcgi_header);
  663. HashPosition pos;
  664. char * str_index;
  665. uint str_length;
  666. ulong num_index;
  667. int key_type;
  668. zval ** value;
  669. if (safe_read(req, buf, len+padding) != len+padding) {
  670. req->keep = 0;
  671. return 0;
  672. }
  673. if (!fcgi_get_params(req, buf, buf+len)) {
  674. req->keep = 0;
  675. return 0;
  676. }
  677. zend_hash_internal_pointer_reset_ex(req->env, &pos);
  678. while ((key_type = zend_hash_get_current_key_ex(req->env, &str_index, &str_length, &num_index, 0, &pos)) != HASH_KEY_NON_EXISTANT) {
  679. int zlen;
  680. zend_hash_move_forward_ex(req->env, &pos);
  681. if (key_type != HASH_KEY_IS_STRING) {
  682. continue;
  683. }
  684. if (zend_hash_find(&fcgi_mgmt_vars, str_index, str_length, (void**) &value) != SUCCESS) {
  685. continue;
  686. }
  687. --str_length;
  688. zlen = Z_STRLEN_PP(value);
  689. if ((p + 4 + 4 + str_length + zlen) >= (buf + sizeof(buf))) {
  690. break;
  691. }
  692. if (str_length < 0x80) {
  693. *p++ = str_length;
  694. } else {
  695. *p++ = ((str_length >> 24) & 0xff) | 0x80;
  696. *p++ = (str_length >> 16) & 0xff;
  697. *p++ = (str_length >> 8) & 0xff;
  698. *p++ = str_length & 0xff;
  699. }
  700. if (zlen < 0x80) {
  701. *p++ = zlen;
  702. } else {
  703. *p++ = ((zlen >> 24) & 0xff) | 0x80;
  704. *p++ = (zlen >> 16) & 0xff;
  705. *p++ = (zlen >> 8) & 0xff;
  706. *p++ = zlen & 0xff;
  707. }
  708. memcpy(p, str_index, str_length);
  709. p += str_length;
  710. memcpy(p, Z_STRVAL_PP(value), zlen);
  711. p += zlen;
  712. }
  713. len = p - buf - sizeof(fcgi_header);
  714. len += fcgi_make_header((fcgi_header*)buf, FCGI_GET_VALUES_RESULT, 0, len);
  715. if (safe_write(req, buf, sizeof(fcgi_header)+len) != (int)sizeof(fcgi_header)+len) {
  716. req->keep = 0;
  717. return 0;
  718. }
  719. return 0;
  720. } else {
  721. return 0;
  722. }
  723. return 1;
  724. }
  725. int fcgi_read(fcgi_request *req, char *str, int len)
  726. {
  727. int ret, n, rest;
  728. fcgi_header hdr;
  729. unsigned char buf[255];
  730. n = 0;
  731. rest = len;
  732. while (rest > 0) {
  733. if (req->in_len == 0) {
  734. if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
  735. hdr.version < FCGI_VERSION_1 ||
  736. hdr.type != FCGI_STDIN) {
  737. req->keep = 0;
  738. return 0;
  739. }
  740. req->in_len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
  741. req->in_pad = hdr.paddingLength;
  742. if (req->in_len == 0) {
  743. return n;
  744. }
  745. }
  746. if (req->in_len >= rest) {
  747. ret = safe_read(req, str, rest);
  748. } else {
  749. ret = safe_read(req, str, req->in_len);
  750. }
  751. if (ret < 0) {
  752. req->keep = 0;
  753. return ret;
  754. } else if (ret > 0) {
  755. req->in_len -= ret;
  756. rest -= ret;
  757. n += ret;
  758. str += ret;
  759. if (req->in_len == 0) {
  760. if (req->in_pad) {
  761. if (safe_read(req, buf, req->in_pad) != req->in_pad) {
  762. req->keep = 0;
  763. return ret;
  764. }
  765. }
  766. } else {
  767. return n;
  768. }
  769. } else {
  770. return n;
  771. }
  772. }
  773. return n;
  774. }
  775. static inline void fcgi_close(fcgi_request *req, int force, int destroy)
  776. {
  777. if (destroy && req->env) {
  778. zend_hash_destroy(req->env);
  779. FREE_HASHTABLE(req->env);
  780. req->env = NULL;
  781. }
  782. #ifdef _WIN32
  783. if (is_impersonate && !req->tcp) {
  784. RevertToSelf();
  785. }
  786. #endif
  787. if ((force || !req->keep) && req->fd >= 0) {
  788. #ifdef _WIN32
  789. if (!req->tcp) {
  790. HANDLE pipe = (HANDLE)_get_osfhandle(req->fd);
  791. if (!force) {
  792. FlushFileBuffers(pipe);
  793. }
  794. DisconnectNamedPipe(pipe);
  795. } else {
  796. if (!force) {
  797. char buf[8];
  798. shutdown(req->fd, 1);
  799. while (recv(req->fd, buf, sizeof(buf), 0) > 0) {}
  800. }
  801. closesocket(req->fd);
  802. }
  803. #else
  804. if (!force) {
  805. char buf[8];
  806. shutdown(req->fd, 1);
  807. while (recv(req->fd, buf, sizeof(buf), 0) > 0) {}
  808. }
  809. close(req->fd);
  810. #endif
  811. req->fd = -1;
  812. }
  813. }
  814. int fcgi_accept_request(fcgi_request *req)
  815. {
  816. #ifdef _WIN32
  817. HANDLE pipe;
  818. OVERLAPPED ov;
  819. #endif
  820. while (1) {
  821. if (req->fd < 0) {
  822. while (1) {
  823. if (in_shutdown) {
  824. return -1;
  825. }
  826. #ifdef _WIN32
  827. if (!req->tcp) {
  828. pipe = (HANDLE)_get_osfhandle(req->listen_socket);
  829. FCGI_LOCK(req->listen_socket);
  830. ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  831. if (!ConnectNamedPipe(pipe, &ov)) {
  832. errno = GetLastError();
  833. if (errno == ERROR_IO_PENDING) {
  834. while (WaitForSingleObject(ov.hEvent, 1000) == WAIT_TIMEOUT) {
  835. if (in_shutdown) {
  836. CloseHandle(ov.hEvent);
  837. FCGI_UNLOCK(req->listen_socket);
  838. return -1;
  839. }
  840. }
  841. } else if (errno != ERROR_PIPE_CONNECTED) {
  842. }
  843. }
  844. CloseHandle(ov.hEvent);
  845. req->fd = req->listen_socket;
  846. FCGI_UNLOCK(req->listen_socket);
  847. } else {
  848. SOCKET listen_socket = (SOCKET)_get_osfhandle(req->listen_socket);
  849. #else
  850. {
  851. int listen_socket = req->listen_socket;
  852. #endif
  853. sa_t sa;
  854. socklen_t len = sizeof(sa);
  855. FCGI_LOCK(req->listen_socket);
  856. req->fd = accept(listen_socket, (struct sockaddr *)&sa, &len);
  857. FCGI_UNLOCK(req->listen_socket);
  858. if (req->fd >= 0 && allowed_clients) {
  859. int n = 0;
  860. int allowed = 0;
  861. while (allowed_clients[n] != INADDR_NONE) {
  862. if (allowed_clients[n] == sa.sa_inet.sin_addr.s_addr) {
  863. allowed = 1;
  864. break;
  865. }
  866. n++;
  867. }
  868. if (!allowed) {
  869. fprintf(stderr, "Connection from disallowed IP address '%s' is dropped.\n", inet_ntoa(sa.sa_inet.sin_addr));
  870. closesocket(req->fd);
  871. req->fd = -1;
  872. continue;
  873. }
  874. }
  875. }
  876. #ifdef _WIN32
  877. if (req->fd < 0 && (in_shutdown || errno != EINTR)) {
  878. #else
  879. if (req->fd < 0 && (in_shutdown || (errno != EINTR && errno != ECONNABORTED))) {
  880. #endif
  881. return -1;
  882. }
  883. #ifdef _WIN32
  884. break;
  885. #else
  886. if (req->fd >= 0) {
  887. #if defined(HAVE_SYS_POLL_H) && defined(HAVE_POLL)
  888. struct pollfd fds;
  889. int ret;
  890. fds.fd = req->fd;
  891. fds.events = POLLIN;
  892. fds.revents = 0;
  893. do {
  894. errno = 0;
  895. ret = poll(&fds, 1, 5000);
  896. } while (ret < 0 && errno == EINTR);
  897. if (ret > 0 && (fds.revents & POLLIN)) {
  898. break;
  899. }
  900. fcgi_close(req, 1, 0);
  901. #else
  902. if (req->fd < FD_SETSIZE) {
  903. struct timeval tv = {5,0};
  904. fd_set set;
  905. int ret;
  906. FD_ZERO(&set);
  907. FD_SET(req->fd, &set);
  908. do {
  909. errno = 0;
  910. ret = select(req->fd + 1, &set, NULL, NULL, &tv) >= 0;
  911. } while (ret < 0 && errno == EINTR);
  912. if (ret > 0 && FD_ISSET(req->fd, &set)) {
  913. break;
  914. }
  915. fcgi_close(req, 1, 0);
  916. } else {
  917. fprintf(stderr, "Too many open file descriptors. FD_SETSIZE limit exceeded.");
  918. fcgi_close(req, 1, 0);
  919. }
  920. #endif
  921. }
  922. #endif
  923. }
  924. } else if (in_shutdown) {
  925. return -1;
  926. }
  927. if (fcgi_read_request(req)) {
  928. #ifdef _WIN32
  929. if (is_impersonate && !req->tcp) {
  930. pipe = (HANDLE)_get_osfhandle(req->fd);
  931. if (!ImpersonateNamedPipeClient(pipe)) {
  932. fcgi_close(req, 1, 1);
  933. continue;
  934. }
  935. }
  936. #endif
  937. return req->fd;
  938. } else {
  939. fcgi_close(req, 1, 1);
  940. }
  941. }
  942. }
  943. static inline fcgi_header* open_packet(fcgi_request *req, fcgi_request_type type)
  944. {
  945. req->out_hdr = (fcgi_header*) req->out_pos;
  946. req->out_hdr->type = type;
  947. req->out_pos += sizeof(fcgi_header);
  948. return req->out_hdr;
  949. }
  950. static inline void close_packet(fcgi_request *req)
  951. {
  952. if (req->out_hdr) {
  953. int len = req->out_pos - ((unsigned char*)req->out_hdr + sizeof(fcgi_header));
  954. req->out_pos += fcgi_make_header(req->out_hdr, (fcgi_request_type)req->out_hdr->type, req->id, len);
  955. req->out_hdr = NULL;
  956. }
  957. }
  958. int fcgi_flush(fcgi_request *req, int close)
  959. {
  960. int len;
  961. close_packet(req);
  962. len = req->out_pos - req->out_buf;
  963. if (close) {
  964. fcgi_end_request_rec *rec = (fcgi_end_request_rec*)(req->out_pos);
  965. fcgi_make_header(&rec->hdr, FCGI_END_REQUEST, req->id, sizeof(fcgi_end_request));
  966. rec->body.appStatusB3 = 0;
  967. rec->body.appStatusB2 = 0;
  968. rec->body.appStatusB1 = 0;
  969. rec->body.appStatusB0 = 0;
  970. rec->body.protocolStatus = FCGI_REQUEST_COMPLETE;
  971. len += sizeof(fcgi_end_request_rec);
  972. }
  973. if (safe_write(req, req->out_buf, len) != len) {
  974. req->keep = 0;
  975. return 0;
  976. }
  977. req->out_pos = req->out_buf;
  978. return 1;
  979. }
  980. int fcgi_write(fcgi_request *req, fcgi_request_type type, const char *str, int len)
  981. {
  982. int limit, rest;
  983. if (len <= 0) {
  984. return 0;
  985. }
  986. if (req->out_hdr && req->out_hdr->type != type) {
  987. close_packet(req);
  988. }
  989. #if 0
  990. /* Unoptimized, but clear version */
  991. rest = len;
  992. while (rest > 0) {
  993. limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
  994. if (!req->out_hdr) {
  995. if (limit < sizeof(fcgi_header)) {
  996. if (!fcgi_flush(req, 0)) {
  997. return -1;
  998. }
  999. }
  1000. open_packet(req, type);
  1001. }
  1002. limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
  1003. if (rest < limit) {
  1004. memcpy(req->out_pos, str, rest);
  1005. req->out_pos += rest;
  1006. return len;
  1007. } else {
  1008. memcpy(req->out_pos, str, limit);
  1009. req->out_pos += limit;
  1010. rest -= limit;
  1011. str += limit;
  1012. if (!fcgi_flush(req, 0)) {
  1013. return -1;
  1014. }
  1015. }
  1016. }
  1017. #else
  1018. /* Optimized version */
  1019. limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
  1020. if (!req->out_hdr) {
  1021. limit -= sizeof(fcgi_header);
  1022. if (limit < 0) limit = 0;
  1023. }
  1024. if (len < limit) {
  1025. if (!req->out_hdr) {
  1026. open_packet(req, type);
  1027. }
  1028. memcpy(req->out_pos, str, len);
  1029. req->out_pos += len;
  1030. } else if (len - limit < sizeof(req->out_buf) - sizeof(fcgi_header)) {
  1031. if (!req->out_hdr) {
  1032. open_packet(req, type);
  1033. }
  1034. if (limit > 0) {
  1035. memcpy(req->out_pos, str, limit);
  1036. req->out_pos += limit;
  1037. }
  1038. if (!fcgi_flush(req, 0)) {
  1039. return -1;
  1040. }
  1041. if (len > limit) {
  1042. open_packet(req, type);
  1043. memcpy(req->out_pos, str + limit, len - limit);
  1044. req->out_pos += len - limit;
  1045. }
  1046. } else {
  1047. int pos = 0;
  1048. int pad;
  1049. close_packet(req);
  1050. while ((len - pos) > 0xffff) {
  1051. open_packet(req, type);
  1052. fcgi_make_header(req->out_hdr, type, req->id, 0xfff8);
  1053. req->out_hdr = NULL;
  1054. if (!fcgi_flush(req, 0)) {
  1055. return -1;
  1056. }
  1057. if (safe_write(req, str + pos, 0xfff8) != 0xfff8) {
  1058. req->keep = 0;
  1059. return -1;
  1060. }
  1061. pos += 0xfff8;
  1062. }
  1063. pad = (((len - pos) + 7) & ~7) - (len - pos);
  1064. rest = pad ? 8 - pad : 0;
  1065. open_packet(req, type);
  1066. fcgi_make_header(req->out_hdr, type, req->id, (len - pos) - rest);
  1067. req->out_hdr = NULL;
  1068. if (!fcgi_flush(req, 0)) {
  1069. return -1;
  1070. }
  1071. if (safe_write(req, str + pos, (len - pos) - rest) != (len - pos) - rest) {
  1072. req->keep = 0;
  1073. return -1;
  1074. }
  1075. if (pad) {
  1076. open_packet(req, type);
  1077. memcpy(req->out_pos, str + len - rest, rest);
  1078. req->out_pos += rest;
  1079. }
  1080. }
  1081. #endif
  1082. return len;
  1083. }
  1084. int fcgi_finish_request(fcgi_request *req, int force_close)
  1085. {
  1086. int ret = 1;
  1087. if (req->fd >= 0) {
  1088. if (!req->closed) {
  1089. ret = fcgi_flush(req, 1);
  1090. req->closed = 1;
  1091. }
  1092. fcgi_close(req, force_close, 1);
  1093. }
  1094. return ret;
  1095. }
  1096. char* fcgi_getenv(fcgi_request *req, const char* var, int var_len)
  1097. {
  1098. char **val;
  1099. if (!req) return NULL;
  1100. if (zend_hash_find(req->env, (char*)var, var_len+1, (void**)&val) == SUCCESS) {
  1101. return *val;
  1102. }
  1103. return NULL;
  1104. }
  1105. char* fcgi_putenv(fcgi_request *req, char* var, int var_len, char* val)
  1106. {
  1107. if (var && req) {
  1108. if (val == NULL) {
  1109. zend_hash_del(req->env, var, var_len+1);
  1110. } else {
  1111. char **ret;
  1112. val = estrdup(val);
  1113. if (zend_hash_update(req->env, var, var_len+1, &val, sizeof(char*), (void**)&ret) == SUCCESS) {
  1114. return *ret;
  1115. }
  1116. }
  1117. }
  1118. return NULL;
  1119. }
  1120. #ifdef _WIN32
  1121. void fcgi_impersonate(void)
  1122. {
  1123. char *os_name;
  1124. os_name = getenv("OS");
  1125. if (os_name && stricmp(os_name, "Windows_NT") == 0) {
  1126. is_impersonate = 1;
  1127. }
  1128. }
  1129. #endif
  1130. void fcgi_set_mgmt_var(const char * name, size_t name_len, const char * value, size_t value_len)
  1131. {
  1132. zval * zvalue;
  1133. zvalue = pemalloc(sizeof(*zvalue), 1);
  1134. Z_TYPE_P(zvalue) = IS_STRING;
  1135. Z_STRVAL_P(zvalue) = pestrndup(value, value_len, 1);
  1136. Z_STRLEN_P(zvalue) = value_len;
  1137. zend_hash_add(&fcgi_mgmt_vars, name, name_len + 1, &zvalue, sizeof(zvalue), NULL);
  1138. }
  1139. void fcgi_free_mgmt_var_cb(void * ptr)
  1140. {
  1141. zval ** var = (zval **)ptr;
  1142. pefree(Z_STRVAL_PP(var), 1);
  1143. pefree(*var, 1);
  1144. }
  1145. /*
  1146. * Local variables:
  1147. * tab-width: 4
  1148. * c-basic-offset: 4
  1149. * End:
  1150. * vim600: sw=4 ts=4 fdm=marker
  1151. * vim<600: sw=4 ts=4
  1152. */