xref: /PHP-8.2/main/fastcgi.c (revision ad5138a3)
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    | https://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: Dmitry Stogov <dmitry@php.net>                              |
14    +----------------------------------------------------------------------+
15 */
16 
17 #include "php.h"
18 #include "php_network.h"
19 
20 #include <string.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdarg.h>
24 #include <errno.h>
25 
26 #ifndef MAXFQDNLEN
27 #define MAXFQDNLEN 255
28 #endif
29 
30 #ifdef _WIN32
31 
32 #include <windows.h>
33 
34 typedef unsigned int in_addr_t;
35 
36 struct sockaddr_un {
37 	short   sun_family;
38 	char    sun_path[MAXPATHLEN];
39 };
40 
41 static HANDLE fcgi_accept_mutex = INVALID_HANDLE_VALUE;
42 static int is_impersonate = 0;
43 
44 #define FCGI_LOCK(fd) \
45 	if (fcgi_accept_mutex != INVALID_HANDLE_VALUE) { \
46 		DWORD ret; \
47 		while ((ret = WaitForSingleObject(fcgi_accept_mutex, 1000)) == WAIT_TIMEOUT) { \
48 			if (in_shutdown) return -1; \
49 		} \
50 		if (ret == WAIT_FAILED) { \
51 			fprintf(stderr, "WaitForSingleObject() failed\n"); \
52 			return -1; \
53 		} \
54 	}
55 
56 #define FCGI_UNLOCK(fd) \
57 	if (fcgi_accept_mutex != INVALID_HANDLE_VALUE) { \
58 		ReleaseMutex(fcgi_accept_mutex); \
59 	}
60 
61 #else
62 
63 # include <sys/types.h>
64 # include <sys/stat.h>
65 # include <unistd.h>
66 # include <fcntl.h>
67 # include <sys/socket.h>
68 # include <sys/un.h>
69 # include <netinet/in.h>
70 # include <netinet/tcp.h>
71 # include <arpa/inet.h>
72 # include <netdb.h>
73 # include <signal.h>
74 
75 # if defined(HAVE_POLL_H) && defined(HAVE_POLL)
76 #  include <poll.h>
77 # elif defined(HAVE_SYS_POLL_H) && defined(HAVE_POLL)
78 #  include <sys/poll.h>
79 # endif
80 # if defined(HAVE_SYS_SELECT_H)
81 #  include <sys/select.h>
82 # endif
83 
84 #ifndef INADDR_NONE
85 #define INADDR_NONE ((unsigned long) -1)
86 #endif
87 
88 # ifndef HAVE_SOCKLEN_T
89 	typedef unsigned int socklen_t;
90 # endif
91 
92 # ifdef USE_LOCKING
93 #  define FCGI_LOCK(fd)								\
94 	do {											\
95 		struct flock lock;							\
96 		lock.l_type = F_WRLCK;						\
97 		lock.l_start = 0;							\
98 		lock.l_whence = SEEK_SET;					\
99 		lock.l_len = 0;								\
100 		if (fcntl(fd, F_SETLKW, &lock) != -1) {		\
101 			break;									\
102 		} else if (errno != EINTR || in_shutdown) {	\
103 			return -1;								\
104 		}											\
105 	} while (1)
106 
107 #  define FCGI_UNLOCK(fd)							\
108 	do {											\
109 		int orig_errno = errno;						\
110 		while (1) {									\
111 			struct flock lock;						\
112 			lock.l_type = F_UNLCK;					\
113 			lock.l_start = 0;						\
114 			lock.l_whence = SEEK_SET;				\
115 			lock.l_len = 0;							\
116 			if (fcntl(fd, F_SETLK, &lock) != -1) {	\
117 				break;								\
118 			} else if (errno != EINTR) {			\
119 				return -1;							\
120 			}										\
121 		}											\
122 		errno = orig_errno;							\
123 	} while (0)
124 # else
125 #  define FCGI_LOCK(fd)
126 #  define FCGI_UNLOCK(fd)
127 # endif
128 
129 #endif
130 
131 #include "fastcgi.h"
132 
133 typedef struct _fcgi_header {
134 	unsigned char version;
135 	unsigned char type;
136 	unsigned char requestIdB1;
137 	unsigned char requestIdB0;
138 	unsigned char contentLengthB1;
139 	unsigned char contentLengthB0;
140 	unsigned char paddingLength;
141 	unsigned char reserved;
142 } fcgi_header;
143 
144 typedef struct _fcgi_begin_request {
145 	unsigned char roleB1;
146 	unsigned char roleB0;
147 	unsigned char flags;
148 	unsigned char reserved[5];
149 } fcgi_begin_request;
150 
151 typedef struct _fcgi_begin_request_rec {
152 	fcgi_header hdr;
153 	fcgi_begin_request body;
154 } fcgi_begin_request_rec;
155 
156 typedef struct _fcgi_end_request {
157 	unsigned char appStatusB3;
158 	unsigned char appStatusB2;
159 	unsigned char appStatusB1;
160 	unsigned char appStatusB0;
161 	unsigned char protocolStatus;
162 	unsigned char reserved[3];
163 } fcgi_end_request;
164 
165 typedef struct _fcgi_end_request_rec {
166 	fcgi_header hdr;
167 	fcgi_end_request body;
168 } fcgi_end_request_rec;
169 
170 typedef struct _fcgi_hash_bucket {
171 	unsigned int              hash_value;
172 	unsigned int              var_len;
173 	char                     *var;
174 	unsigned int              val_len;
175 	char                     *val;
176 	struct _fcgi_hash_bucket *next;
177 	struct _fcgi_hash_bucket *list_next;
178 } fcgi_hash_bucket;
179 
180 typedef struct _fcgi_hash_buckets {
181 	unsigned int	           idx;
182 	struct _fcgi_hash_buckets *next;
183 	struct _fcgi_hash_bucket   data[FCGI_HASH_TABLE_SIZE];
184 } fcgi_hash_buckets;
185 
186 typedef struct _fcgi_data_seg {
187 	char                  *pos;
188 	char                  *end;
189 	struct _fcgi_data_seg *next;
190 	char                   data[1];
191 } fcgi_data_seg;
192 
193 typedef struct _fcgi_hash {
194 	fcgi_hash_bucket  *hash_table[FCGI_HASH_TABLE_SIZE];
195 	fcgi_hash_bucket  *list;
196 	fcgi_hash_buckets *buckets;
197 	fcgi_data_seg     *data;
198 } fcgi_hash;
199 
200 typedef struct _fcgi_req_hook 	fcgi_req_hook;
201 
202 struct _fcgi_req_hook {
203 	void(*on_accept)(void);
204 	void(*on_read)(void);
205 	void(*on_close)(void);
206 };
207 
208 struct _fcgi_request {
209 	int            listen_socket;
210 	int            tcp;
211 	int            fd;
212 	int            id;
213 	int            keep;
214 #ifdef TCP_NODELAY
215 	int            nodelay;
216 #endif
217 	int            ended;
218 	int            in_len;
219 	int            in_pad;
220 
221 	fcgi_header   *out_hdr;
222 
223 	unsigned char *out_pos;
224 	unsigned char  out_buf[1024*8];
225 	unsigned char  reserved[sizeof(fcgi_end_request_rec)];
226 
227 	fcgi_req_hook  hook;
228 
229 	int            has_env;
230 	fcgi_hash      env;
231 };
232 
233 /* maybe it's better to use weak name instead */
234 #ifndef HAVE_ATTRIBUTE_WEAK
235 static fcgi_logger fcgi_log;
236 #endif
237 
238 typedef union _sa_t {
239 	struct sockaddr     sa;
240 	struct sockaddr_un  sa_unix;
241 	struct sockaddr_in  sa_inet;
242 	struct sockaddr_in6 sa_inet6;
243 } sa_t;
244 
245 static HashTable fcgi_mgmt_vars;
246 
247 static int is_initialized = 0;
248 static int is_fastcgi = 0;
249 static int in_shutdown = 0;
250 static sa_t *allowed_clients = NULL;
251 static sa_t client_sa;
252 
253 /* hash table */
fcgi_hash_init(fcgi_hash * h)254 static void fcgi_hash_init(fcgi_hash *h)
255 {
256 	memset(h->hash_table, 0, sizeof(h->hash_table));
257 	h->list = NULL;
258 	h->buckets = (fcgi_hash_buckets*)malloc(sizeof(fcgi_hash_buckets));
259 	h->buckets->idx = 0;
260 	h->buckets->next = NULL;
261 	h->data = (fcgi_data_seg*)malloc(sizeof(fcgi_data_seg) - 1 + FCGI_HASH_SEG_SIZE);
262 	h->data->pos = h->data->data;
263 	h->data->end = h->data->pos + FCGI_HASH_SEG_SIZE;
264 	h->data->next = NULL;
265 }
266 
fcgi_hash_destroy(fcgi_hash * h)267 static void fcgi_hash_destroy(fcgi_hash *h)
268 {
269 	fcgi_hash_buckets *b;
270 	fcgi_data_seg *p;
271 
272 	b = h->buckets;
273 	while (b) {
274 		fcgi_hash_buckets *q = b;
275 		b = b->next;
276 		free(q);
277 	}
278 	p = h->data;
279 	while (p) {
280 		fcgi_data_seg *q = p;
281 		p = p->next;
282 		free(q);
283 	}
284 }
285 
fcgi_hash_clean(fcgi_hash * h)286 static void fcgi_hash_clean(fcgi_hash *h)
287 {
288 	memset(h->hash_table, 0, sizeof(h->hash_table));
289 	h->list = NULL;
290 	/* delete all bucket blocks except the first one */
291 	while (h->buckets->next) {
292 		fcgi_hash_buckets *q = h->buckets;
293 
294 		h->buckets = h->buckets->next;
295 		free(q);
296 	}
297 	h->buckets->idx = 0;
298 	/* delete all data segments except the first one */
299 	while (h->data->next) {
300 		fcgi_data_seg *q = h->data;
301 
302 		h->data = h->data->next;
303 		free(q);
304 	}
305 	h->data->pos = h->data->data;
306 }
307 
fcgi_hash_strndup(fcgi_hash * h,char * str,unsigned int str_len)308 static inline char* fcgi_hash_strndup(fcgi_hash *h, char *str, unsigned int str_len)
309 {
310 	char *ret;
311 
312 	if (UNEXPECTED(h->data->pos + str_len + 1 >= h->data->end)) {
313 		unsigned int seg_size = (str_len + 1 > FCGI_HASH_SEG_SIZE) ? str_len + 1 : FCGI_HASH_SEG_SIZE;
314 		fcgi_data_seg *p = (fcgi_data_seg*)malloc(sizeof(fcgi_data_seg) - 1 + seg_size);
315 
316 		p->pos = p->data;
317 		p->end = p->pos + seg_size;
318 		p->next = h->data;
319 		h->data = p;
320 	}
321 	ret = h->data->pos;
322 	memcpy(ret, str, str_len);
323 	ret[str_len] = 0;
324 	h->data->pos += str_len + 1;
325 	return ret;
326 }
327 
fcgi_hash_set(fcgi_hash * h,unsigned int hash_value,char * var,unsigned int var_len,char * val,unsigned int val_len)328 static char* fcgi_hash_set(fcgi_hash *h, unsigned int hash_value, char *var, unsigned int var_len, char *val, unsigned int val_len)
329 {
330 	unsigned int      idx = hash_value & FCGI_HASH_TABLE_MASK;
331 	fcgi_hash_bucket *p = h->hash_table[idx];
332 
333 	while (UNEXPECTED(p != NULL)) {
334 		if (UNEXPECTED(p->hash_value == hash_value) &&
335 		    p->var_len == var_len &&
336 		    memcmp(p->var, var, var_len) == 0) {
337 
338 			p->val_len = val_len;
339 			p->val = fcgi_hash_strndup(h, val, val_len);
340 			return p->val;
341 		}
342 		p = p->next;
343 	}
344 
345 	if (UNEXPECTED(h->buckets->idx >= FCGI_HASH_TABLE_SIZE)) {
346 		fcgi_hash_buckets *b = (fcgi_hash_buckets*)malloc(sizeof(fcgi_hash_buckets));
347 		b->idx = 0;
348 		b->next = h->buckets;
349 		h->buckets = b;
350 	}
351 	p = h->buckets->data + h->buckets->idx;
352 	h->buckets->idx++;
353 	p->next = h->hash_table[idx];
354 	h->hash_table[idx] = p;
355 	p->list_next = h->list;
356 	h->list = p;
357 	p->hash_value = hash_value;
358 	p->var_len = var_len;
359 	p->var = fcgi_hash_strndup(h, var, var_len);
360 	p->val_len = val_len;
361 	p->val = fcgi_hash_strndup(h, val, val_len);
362 	return p->val;
363 }
364 
fcgi_hash_del(fcgi_hash * h,unsigned int hash_value,char * var,unsigned int var_len)365 static void fcgi_hash_del(fcgi_hash *h, unsigned int hash_value, char *var, unsigned int var_len)
366 {
367 	unsigned int      idx = hash_value & FCGI_HASH_TABLE_MASK;
368 	fcgi_hash_bucket **p = &h->hash_table[idx];
369 
370 	while (*p != NULL) {
371 		if ((*p)->hash_value == hash_value &&
372 		    (*p)->var_len == var_len &&
373 		    memcmp((*p)->var, var, var_len) == 0) {
374 
375 		    (*p)->val = NULL; /* NULL value means deleted */
376 		    (*p)->val_len = 0;
377 			*p = (*p)->next;
378 		    return;
379 		}
380 		p = &(*p)->next;
381 	}
382 }
383 
fcgi_hash_get(fcgi_hash * h,unsigned int hash_value,char * var,unsigned int var_len,unsigned int * val_len)384 static char *fcgi_hash_get(fcgi_hash *h, unsigned int hash_value, char *var, unsigned int var_len, unsigned int *val_len)
385 {
386 	unsigned int      idx = hash_value & FCGI_HASH_TABLE_MASK;
387 	fcgi_hash_bucket *p = h->hash_table[idx];
388 
389 	while (p != NULL) {
390 		if (p->hash_value == hash_value &&
391 		    p->var_len == var_len &&
392 		    memcmp(p->var, var, var_len) == 0) {
393 		    *val_len = p->val_len;
394 		    return p->val;
395 		}
396 		p = p->next;
397 	}
398 	return NULL;
399 }
400 
fcgi_hash_apply(fcgi_hash * h,fcgi_apply_func func,void * arg)401 static void fcgi_hash_apply(fcgi_hash *h, fcgi_apply_func func, void *arg)
402 {
403 	fcgi_hash_bucket *p	= h->list;
404 
405 	while (p) {
406 		if (EXPECTED(p->val != NULL)) {
407 			func(p->var, p->var_len, p->val, p->val_len, arg);
408 		}
409 		p = p->list_next;
410 	}
411 }
412 
413 #ifdef _WIN32
414 
fcgi_shutdown_thread(LPVOID arg)415 static DWORD WINAPI fcgi_shutdown_thread(LPVOID arg)
416 {
417 	HANDLE shutdown_event = (HANDLE) arg;
418 	WaitForSingleObject(shutdown_event, INFINITE);
419 	in_shutdown = 1;
420 	return 0;
421 }
422 
423 #else
424 
fcgi_signal_handler(int signo)425 static void fcgi_signal_handler(int signo)
426 {
427 	if (signo == SIGUSR1 || signo == SIGTERM) {
428 		in_shutdown = 1;
429 	}
430 }
431 
fcgi_setup_signals(void)432 static void fcgi_setup_signals(void)
433 {
434 	struct sigaction new_sa, old_sa;
435 
436 	sigemptyset(&new_sa.sa_mask);
437 	new_sa.sa_flags = 0;
438 	new_sa.sa_handler = fcgi_signal_handler;
439 	sigaction(SIGUSR1, &new_sa, NULL);
440 	sigaction(SIGTERM, &new_sa, NULL);
441 	sigaction(SIGPIPE, NULL, &old_sa);
442 	if (old_sa.sa_handler == SIG_DFL) {
443 		sigaction(SIGPIPE, &new_sa, NULL);
444 	}
445 }
446 #endif
447 
fcgi_set_in_shutdown(int new_value)448 void fcgi_set_in_shutdown(int new_value)
449 {
450 	in_shutdown = new_value;
451 }
452 
fcgi_in_shutdown(void)453 int fcgi_in_shutdown(void)
454 {
455 	return in_shutdown;
456 }
457 
fcgi_terminate(void)458 void fcgi_terminate(void)
459 {
460 	in_shutdown = 1;
461 }
462 
fcgi_request_set_keep(fcgi_request * req,int new_value)463 void fcgi_request_set_keep(fcgi_request *req, int new_value)
464 {
465 	req->keep = new_value;
466 }
467 
468 #ifndef HAVE_ATTRIBUTE_WEAK
fcgi_set_logger(fcgi_logger lg)469 void fcgi_set_logger(fcgi_logger lg) {
470 	fcgi_log = lg;
471 }
472 #else
fcgi_log(int type,const char * format,...)473 void __attribute__((weak)) fcgi_log(int type, const char *format, ...) {
474 	va_list ap;
475 
476 	va_start(ap, format);
477 	vfprintf(stderr, format, ap);
478 	va_end(ap);
479 }
480 #endif
481 
fcgi_init(void)482 int fcgi_init(void)
483 {
484 	if (!is_initialized) {
485 #ifndef _WIN32
486 		sa_t sa;
487 		socklen_t len = sizeof(sa);
488 #endif
489 		zend_hash_init(&fcgi_mgmt_vars, 8, NULL, fcgi_free_mgmt_var_cb, 1);
490 		fcgi_set_mgmt_var("FCGI_MPXS_CONNS", sizeof("FCGI_MPXS_CONNS")-1, "0", sizeof("0")-1);
491 
492 		is_initialized = 1;
493 #ifdef _WIN32
494 # if 0
495 		/* TODO: Support for TCP sockets */
496 		WSADATA wsaData;
497 
498 		if (WSAStartup(MAKEWORD(2,0), &wsaData)) {
499 			fprintf(stderr, "Error starting Windows Sockets.  Error: %d", WSAGetLastError());
500 			return 0;
501 		}
502 # endif
503 		if ((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
504 		    (GetStdHandle(STD_ERROR_HANDLE)  == INVALID_HANDLE_VALUE) &&
505 		    (GetStdHandle(STD_INPUT_HANDLE)  != INVALID_HANDLE_VALUE)) {
506 			char *str;
507 			DWORD pipe_mode = PIPE_READMODE_BYTE | PIPE_WAIT;
508 			HANDLE pipe = GetStdHandle(STD_INPUT_HANDLE);
509 
510 			SetNamedPipeHandleState(pipe, &pipe_mode, NULL, NULL);
511 
512 			str = getenv("_FCGI_SHUTDOWN_EVENT_");
513 			if (str != NULL) {
514 				zend_long ev = ZEND_ATOL(str);
515 				HANDLE shutdown_event = (HANDLE) ev;
516 				if (!CreateThread(NULL, 0, fcgi_shutdown_thread,
517 				                  shutdown_event, 0, NULL)) {
518 					return -1;
519 				}
520 			}
521 			str = getenv("_FCGI_MUTEX_");
522 			if (str != NULL) {
523 				fcgi_accept_mutex = (HANDLE) ZEND_ATOL(str);
524 			}
525 			return is_fastcgi = 1;
526 		} else {
527 			return is_fastcgi = 0;
528 		}
529 #else
530 		errno = 0;
531 		if (getpeername(0, (struct sockaddr *)&sa, &len) != 0 && errno == ENOTCONN) {
532 			fcgi_setup_signals();
533 			return is_fastcgi = 1;
534 		} else {
535 			return is_fastcgi = 0;
536 		}
537 #endif
538 	}
539 	return is_fastcgi;
540 }
541 
542 
fcgi_is_fastcgi(void)543 int fcgi_is_fastcgi(void)
544 {
545 	if (!is_initialized) {
546 		return fcgi_init();
547 	} else {
548 		return is_fastcgi;
549 	}
550 }
551 
fcgi_shutdown(void)552 void fcgi_shutdown(void)
553 {
554 	if (is_initialized) {
555 		zend_hash_destroy(&fcgi_mgmt_vars);
556 	}
557 	is_fastcgi = 0;
558 	if (allowed_clients) {
559 		free(allowed_clients);
560 	}
561 }
562 
563 #ifdef _WIN32
564 /* Do some black magic with the NT security API.
565  * We prepare a DACL (Discretionary Access Control List) so that
566  * we, the creator, are allowed all access, while "Everyone Else"
567  * is only allowed to read and write to the pipe.
568  * This avoids security issues on shared hosts where a luser messes
569  * with the lower-level pipe settings and screws up the FastCGI service.
570  */
prepare_named_pipe_acl(PSECURITY_DESCRIPTOR sd,LPSECURITY_ATTRIBUTES sa)571 static PACL prepare_named_pipe_acl(PSECURITY_DESCRIPTOR sd, LPSECURITY_ATTRIBUTES sa)
572 {
573 	DWORD req_acl_size;
574 	char everyone_buf[32], owner_buf[32];
575 	PSID sid_everyone, sid_owner;
576 	SID_IDENTIFIER_AUTHORITY
577 		siaWorld = SECURITY_WORLD_SID_AUTHORITY,
578 		siaCreator = SECURITY_CREATOR_SID_AUTHORITY;
579 	PACL acl;
580 
581 	sid_everyone = (PSID)&everyone_buf;
582 	sid_owner = (PSID)&owner_buf;
583 
584 	req_acl_size = sizeof(ACL) +
585 		(2 * ((sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + GetSidLengthRequired(1)));
586 
587 	acl = malloc(req_acl_size);
588 
589 	if (acl == NULL) {
590 		return NULL;
591 	}
592 
593 	if (!InitializeSid(sid_everyone, &siaWorld, 1)) {
594 		goto out_fail;
595 	}
596 	*GetSidSubAuthority(sid_everyone, 0) = SECURITY_WORLD_RID;
597 
598 	if (!InitializeSid(sid_owner, &siaCreator, 1)) {
599 		goto out_fail;
600 	}
601 	*GetSidSubAuthority(sid_owner, 0) = SECURITY_CREATOR_OWNER_RID;
602 
603 	if (!InitializeAcl(acl, req_acl_size, ACL_REVISION)) {
604 		goto out_fail;
605 	}
606 
607 	if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_GENERIC_READ | FILE_GENERIC_WRITE, sid_everyone)) {
608 		goto out_fail;
609 	}
610 
611 	if (!AddAccessAllowedAce(acl, ACL_REVISION, FILE_ALL_ACCESS, sid_owner)) {
612 		goto out_fail;
613 	}
614 
615 	if (!InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION)) {
616 		goto out_fail;
617 	}
618 
619 	if (!SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE)) {
620 		goto out_fail;
621 	}
622 
623 	sa->lpSecurityDescriptor = sd;
624 
625 	return acl;
626 
627 out_fail:
628 	free(acl);
629 	return NULL;
630 }
631 #endif
632 
is_port_number(const char * bindpath)633 static int is_port_number(const char *bindpath)
634 {
635 	while (*bindpath) {
636 		if (*bindpath < '0' || *bindpath > '9') {
637 			return 0;
638 		}
639 		bindpath++;
640 	}
641 	return 1;
642 }
643 
fcgi_listen(const char * path,int backlog)644 int fcgi_listen(const char *path, int backlog)
645 {
646 	char     *s;
647 	int       tcp = 0;
648 	char      host[MAXPATHLEN];
649 	short     port = 0;
650 	int       listen_socket;
651 	sa_t      sa;
652 	socklen_t sock_len;
653 #ifdef SO_REUSEADDR
654 # ifdef _WIN32
655 	BOOL reuse = 1;
656 # else
657 	int reuse = 1;
658 # endif
659 #endif
660 
661 	if ((s = strchr(path, ':'))) {
662 		port = atoi(s+1);
663 		if (port != 0 && (s-path) < MAXPATHLEN) {
664 			strncpy(host, path, s-path);
665 			host[s-path] = '\0';
666 			tcp = 1;
667 		}
668 	} else if (is_port_number(path)) {
669 		port = atoi(path);
670 		if (port != 0) {
671 			host[0] = '\0';
672 			tcp = 1;
673 		}
674 	}
675 
676 	/* Prepare socket address */
677 	if (tcp) {
678 		memset(&sa.sa_inet, 0, sizeof(sa.sa_inet));
679 		sa.sa_inet.sin_family = AF_INET;
680 		sa.sa_inet.sin_port = htons(port);
681 		sock_len = sizeof(sa.sa_inet);
682 
683 		if (!*host || !strncmp(host, "*", sizeof("*")-1)) {
684 			sa.sa_inet.sin_addr.s_addr = htonl(INADDR_ANY);
685 		} else {
686 #ifdef HAVE_INET_PTON
687 			if (!inet_pton(AF_INET, host, &sa.sa_inet.sin_addr)) {
688 #else
689 			sa.sa_inet.sin_addr.s_addr = inet_addr(host);
690 			if (sa.sa_inet.sin_addr.s_addr == INADDR_NONE) {
691 #endif
692 				struct hostent *hep;
693 
694 				if(strlen(host) > MAXFQDNLEN) {
695 					hep = NULL;
696 				} else {
697 					hep = php_network_gethostbyname(host);
698 				}
699 				if (!hep || hep->h_addrtype != AF_INET || !hep->h_addr_list[0]) {
700 					fcgi_log(FCGI_ERROR, "Cannot resolve host name '%s'!\n", host);
701 					return -1;
702 				} else if (hep->h_addr_list[1]) {
703 					fcgi_log(FCGI_ERROR, "Host '%s' has multiple addresses. You must choose one explicitly!\n", host);
704 					return -1;
705 				}
706 				sa.sa_inet.sin_addr.s_addr = ((struct in_addr*)hep->h_addr_list[0])->s_addr;
707 			}
708 		}
709 	} else {
710 #ifdef _WIN32
711 		SECURITY_DESCRIPTOR  sd;
712 		SECURITY_ATTRIBUTES  saw;
713 		PACL                 acl;
714 		HANDLE namedPipe;
715 
716 		memset(&sa, 0, sizeof(saw));
717 		saw.nLength = sizeof(saw);
718 		saw.bInheritHandle = FALSE;
719 		acl = prepare_named_pipe_acl(&sd, &saw);
720 
721 		namedPipe = CreateNamedPipe(path,
722 			PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
723 			PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
724 			PIPE_UNLIMITED_INSTANCES,
725 			8192, 8192, 0, &saw);
726 		if (namedPipe == INVALID_HANDLE_VALUE) {
727 			return -1;
728 		}
729 		listen_socket = _open_osfhandle((intptr_t)namedPipe, 0);
730 		if (!is_initialized) {
731 			fcgi_init();
732 		}
733 		is_fastcgi = 1;
734 		return listen_socket;
735 
736 #else
737 		size_t path_len = strlen(path);
738 
739 		if (path_len >= sizeof(sa.sa_unix.sun_path)) {
740 			fcgi_log(FCGI_ERROR, "Listening socket's path name is too long.\n");
741 			return -1;
742 		}
743 
744 		memset(&sa.sa_unix, 0, sizeof(sa.sa_unix));
745 		sa.sa_unix.sun_family = AF_UNIX;
746 		memcpy(sa.sa_unix.sun_path, path, path_len + 1);
747 		sock_len = XtOffsetOf(struct sockaddr_un, sun_path) + path_len;
748 #ifdef HAVE_SOCKADDR_UN_SUN_LEN
749 		sa.sa_unix.sun_len = sock_len;
750 #endif
751 		unlink(path);
752 #endif
753 	}
754 
755 	/* Create, bind socket and start listen on it */
756 	if ((listen_socket = socket(sa.sa.sa_family, SOCK_STREAM, 0)) < 0 ||
757 #ifdef SO_REUSEADDR
758 	    setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)) < 0 ||
759 #endif
760 	    bind(listen_socket, (struct sockaddr *) &sa, sock_len) < 0 ||
761 	    listen(listen_socket, backlog) < 0) {
762 		close(listen_socket);
763 		fcgi_log(FCGI_ERROR, "Cannot bind/listen socket - [%d] %s.\n",errno, strerror(errno));
764 		return -1;
765 	}
766 
767 	if (!tcp) {
768 		chmod(path, 0777);
769 	} else {
770 		char *ip = getenv("FCGI_WEB_SERVER_ADDRS");
771 		char *cur, *end;
772 		int n;
773 
774 		if (ip) {
775 			ip = strdup(ip);
776 			cur = ip;
777 			n = 0;
778 			while (*cur) {
779 				if (*cur == ',') n++;
780 				cur++;
781 			}
782 			allowed_clients = malloc(sizeof(sa_t) * (n+2));
783 			n = 0;
784 			cur = ip;
785 			while (cur) {
786 				end = strchr(cur, ',');
787 				if (end) {
788 					*end = 0;
789 					end++;
790 				}
791 				if (inet_pton(AF_INET, cur, &allowed_clients[n].sa_inet.sin_addr)>0) {
792 					allowed_clients[n].sa.sa_family = AF_INET;
793 					n++;
794 #ifdef HAVE_IPV6
795 				} else if (inet_pton(AF_INET6, cur, &allowed_clients[n].sa_inet6.sin6_addr)>0) {
796 					allowed_clients[n].sa.sa_family = AF_INET6;
797 					n++;
798 #endif
799 				} else {
800 					fcgi_log(FCGI_ERROR, "Wrong IP address '%s' in listen.allowed_clients", cur);
801 				}
802 				cur = end;
803 			}
804 			allowed_clients[n].sa.sa_family = 0;
805 			free(ip);
806 			if (!n) {
807 				fcgi_log(FCGI_ERROR, "There are no allowed addresses");
808 				/* don't clear allowed_clients as it will create an "open for all" security issue */
809 			}
810 		}
811 	}
812 
813 	if (!is_initialized) {
814 		fcgi_init();
815 	}
816 	is_fastcgi = 1;
817 
818 #ifdef _WIN32
819 	if (tcp) {
820 		listen_socket = _open_osfhandle((intptr_t)listen_socket, 0);
821 	}
822 #else
823 	fcgi_setup_signals();
824 #endif
825 	return listen_socket;
826 }
827 
828 void fcgi_set_allowed_clients(char *ip)
829 {
830 	char *cur, *end;
831 	int n;
832 
833 	if (ip) {
834 		ip = strdup(ip);
835 		cur = ip;
836 		n = 0;
837 		while (*cur) {
838 			if (*cur == ',') n++;
839 			cur++;
840 		}
841 		if (allowed_clients) free(allowed_clients);
842 		allowed_clients = malloc(sizeof(sa_t) * (n+2));
843 		n = 0;
844 		cur = ip;
845 		while (cur) {
846 			end = strchr(cur, ',');
847 			if (end) {
848 				*end = 0;
849 				end++;
850 			}
851 			if (inet_pton(AF_INET, cur, &allowed_clients[n].sa_inet.sin_addr)>0) {
852 				allowed_clients[n].sa.sa_family = AF_INET;
853 				n++;
854 #ifdef HAVE_IPV6
855 			} else if (inet_pton(AF_INET6, cur, &allowed_clients[n].sa_inet6.sin6_addr)>0) {
856 				allowed_clients[n].sa.sa_family = AF_INET6;
857 				n++;
858 #endif
859 			} else {
860 				fcgi_log(FCGI_ERROR, "Wrong IP address '%s' in listen.allowed_clients", cur);
861 			}
862 			cur = end;
863 		}
864 		allowed_clients[n].sa.sa_family = 0;
865 		free(ip);
866 		if (!n) {
867 			fcgi_log(FCGI_ERROR, "There are no allowed addresses");
868 			/* don't clear allowed_clients as it will create an "open for all" security issue */
869 		}
870 	}
871 }
872 
873 static void fcgi_hook_dummy(void) {
874 	return;
875 }
876 
877 fcgi_request *fcgi_init_request(int listen_socket, void(*on_accept)(void), void(*on_read)(void), void(*on_close)(void))
878 {
879 	fcgi_request *req = calloc(1, sizeof(fcgi_request));
880 	req->listen_socket = listen_socket;
881 	req->fd = -1;
882 	req->id = -1;
883 
884 	/*
885 	req->in_len = 0;
886 	req->in_pad = 0;
887 
888 	req->out_hdr = NULL;
889 
890 #ifdef TCP_NODELAY
891 	req->nodelay = 0;
892 #endif
893 
894 	req->env = NULL;
895 	req->has_env = 0;
896 
897 	*/
898 	req->out_pos = req->out_buf;
899 	req->hook.on_accept = on_accept ? on_accept : fcgi_hook_dummy;
900 	req->hook.on_read = on_read ? on_read : fcgi_hook_dummy;
901 	req->hook.on_close = on_close ? on_close : fcgi_hook_dummy;
902 
903 #ifdef _WIN32
904 	req->tcp = !GetNamedPipeInfo((HANDLE)_get_osfhandle(req->listen_socket), NULL, NULL, NULL, NULL);
905 #endif
906 
907 	fcgi_hash_init(&req->env);
908 
909 	return req;
910 }
911 
912 void fcgi_destroy_request(fcgi_request *req) {
913 	fcgi_hash_destroy(&req->env);
914 	free(req);
915 }
916 
917 static inline ssize_t safe_write(fcgi_request *req, const void *buf, size_t count)
918 {
919 	int    ret;
920 	size_t n = 0;
921 
922 	do {
923 #ifdef _WIN32
924 		size_t tmp;
925 #endif
926 		errno = 0;
927 #ifdef _WIN32
928 		tmp = count - n;
929 
930 		if (!req->tcp) {
931 			unsigned int out_len = tmp > UINT_MAX ? UINT_MAX : (unsigned int)tmp;
932 
933 			ret = write(req->fd, ((char*)buf)+n, out_len);
934 		} else {
935 			int out_len = tmp > INT_MAX ? INT_MAX : (int)tmp;
936 
937 			ret = send(req->fd, ((char*)buf)+n, out_len, 0);
938 			if (ret <= 0) {
939 				errno = WSAGetLastError();
940 			}
941 		}
942 #else
943 		ret = write(req->fd, ((char*)buf)+n, count-n);
944 #endif
945 		if (ret > 0) {
946 			n += ret;
947 		} else if (ret <= 0 && errno != 0 && errno != EINTR) {
948 			return ret;
949 		}
950 	} while (n != count);
951 	return n;
952 }
953 
954 static inline ssize_t safe_read(fcgi_request *req, const void *buf, size_t count)
955 {
956 	int    ret;
957 	size_t n = 0;
958 
959 	do {
960 #ifdef _WIN32
961 		size_t tmp;
962 #endif
963 		errno = 0;
964 #ifdef _WIN32
965 		tmp = count - n;
966 
967 		if (!req->tcp) {
968 			unsigned int in_len = tmp > INT_MAX ? INT_MAX : (unsigned int)tmp;
969 
970 			ret = _read(req->fd, ((char*)buf)+n, in_len);
971 		} else {
972 			int in_len = tmp > INT_MAX ? INT_MAX : (int)tmp;
973 
974 			ret = recv(req->fd, ((char*)buf)+n, in_len, 0);
975 			if (ret <= 0) {
976 				errno = WSAGetLastError();
977 			}
978 		}
979 #else
980 		ret = read(req->fd, ((char*)buf)+n, count-n);
981 #endif
982 		if (ret > 0) {
983 			n += ret;
984 		} else if (ret == 0 && errno == 0) {
985 			return n;
986 		} else if (ret <= 0 && errno != 0 && errno != EINTR) {
987 			return ret;
988 		}
989 	} while (n != count);
990 	return n;
991 }
992 
993 static inline int fcgi_make_header(fcgi_header *hdr, fcgi_request_type type, int req_id, int len)
994 {
995 	int pad = ((len + 7) & ~7) - len;
996 
997 	hdr->contentLengthB0 = (unsigned char)(len & 0xff);
998 	hdr->contentLengthB1 = (unsigned char)((len >> 8) & 0xff);
999 	hdr->paddingLength = (unsigned char)pad;
1000 	hdr->requestIdB0 = (unsigned char)(req_id & 0xff);
1001 	hdr->requestIdB1 = (unsigned char)((req_id >> 8) & 0xff);
1002 	hdr->reserved = 0;
1003 	hdr->type = type;
1004 	hdr->version = FCGI_VERSION_1;
1005 	if (pad) {
1006 		memset(((unsigned char*)hdr) + sizeof(fcgi_header) + len, 0, pad);
1007 	}
1008 	return pad;
1009 }
1010 
1011 static int fcgi_get_params(fcgi_request *req, unsigned char *p, unsigned char *end)
1012 {
1013 	unsigned int name_len, val_len;
1014 
1015 	while (p < end) {
1016 		name_len = *p++;
1017 		if (UNEXPECTED(name_len >= 128)) {
1018 			if (UNEXPECTED(p + 3 >= end)) return 0;
1019 			name_len = ((name_len & 0x7f) << 24);
1020 			name_len |= (*p++ << 16);
1021 			name_len |= (*p++ << 8);
1022 			name_len |= *p++;
1023 		}
1024 		if (UNEXPECTED(p >= end)) return 0;
1025 		val_len = *p++;
1026 		if (UNEXPECTED(val_len >= 128)) {
1027 			if (UNEXPECTED(p + 3 >= end)) return 0;
1028 			val_len = ((val_len & 0x7f) << 24);
1029 			val_len |= (*p++ << 16);
1030 			val_len |= (*p++ << 8);
1031 			val_len |= *p++;
1032 		}
1033 		if (UNEXPECTED(name_len + val_len > (unsigned int) (end - p))) {
1034 			/* Malformed request */
1035 			return 0;
1036 		}
1037 		fcgi_hash_set(&req->env, FCGI_HASH_FUNC(p, name_len), (char*)p, name_len, (char*)p + name_len, val_len);
1038 		p += name_len + val_len;
1039 	}
1040 	return 1;
1041 }
1042 
1043 static int fcgi_read_request(fcgi_request *req)
1044 {
1045 	fcgi_header hdr;
1046 	int len, padding;
1047 	unsigned char buf[FCGI_MAX_LENGTH+8];
1048 
1049 	req->keep = 0;
1050 	req->ended = 0;
1051 	req->in_len = 0;
1052 	req->out_hdr = NULL;
1053 	req->out_pos = req->out_buf;
1054 
1055 	if (req->has_env) {
1056 		fcgi_hash_clean(&req->env);
1057 	} else {
1058 		req->has_env = 1;
1059 	}
1060 
1061 	if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1062 	    hdr.version < FCGI_VERSION_1) {
1063 		return 0;
1064 	}
1065 
1066 	len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1067 	padding = hdr.paddingLength;
1068 
1069 	while (hdr.type == FCGI_STDIN && len == 0) {
1070 		if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1071 		    hdr.version < FCGI_VERSION_1) {
1072 			return 0;
1073 		}
1074 
1075 		len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1076 		padding = hdr.paddingLength;
1077 	}
1078 
1079 	if (len + padding > FCGI_MAX_LENGTH) {
1080 		return 0;
1081 	}
1082 
1083 	req->id = (hdr.requestIdB1 << 8) + hdr.requestIdB0;
1084 
1085 	if (hdr.type == FCGI_BEGIN_REQUEST && len == sizeof(fcgi_begin_request)) {
1086 		fcgi_begin_request *b;
1087 
1088 		if (safe_read(req, buf, len+padding) != len+padding) {
1089 			return 0;
1090 		}
1091 
1092 		b = (fcgi_begin_request*)buf;
1093 		req->keep = (b->flags & FCGI_KEEP_CONN);
1094 #ifdef TCP_NODELAY
1095 		if (req->keep && req->tcp && !req->nodelay) {
1096 # ifdef _WIN32
1097 			BOOL on = 1;
1098 # else
1099 			int on = 1;
1100 # endif
1101 
1102 			setsockopt(req->fd, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on));
1103 			req->nodelay = 1;
1104 		}
1105 #endif
1106 		switch ((b->roleB1 << 8) + b->roleB0) {
1107 			case FCGI_RESPONDER:
1108 				fcgi_hash_set(&req->env, FCGI_HASH_FUNC("FCGI_ROLE", sizeof("FCGI_ROLE")-1), "FCGI_ROLE", sizeof("FCGI_ROLE")-1, "RESPONDER", sizeof("RESPONDER")-1);
1109 				break;
1110 			case FCGI_AUTHORIZER:
1111 				fcgi_hash_set(&req->env, FCGI_HASH_FUNC("FCGI_ROLE", sizeof("FCGI_ROLE")-1), "FCGI_ROLE", sizeof("FCGI_ROLE")-1, "AUTHORIZER", sizeof("AUTHORIZER")-1);
1112 				break;
1113 			case FCGI_FILTER:
1114 				fcgi_hash_set(&req->env, FCGI_HASH_FUNC("FCGI_ROLE", sizeof("FCGI_ROLE")-1), "FCGI_ROLE", sizeof("FCGI_ROLE")-1, "FILTER", sizeof("FILTER")-1);
1115 				break;
1116 			default:
1117 				return 0;
1118 		}
1119 
1120 		if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1121 		    hdr.version < FCGI_VERSION_1) {
1122 			return 0;
1123 		}
1124 
1125 		len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1126 		padding = hdr.paddingLength;
1127 
1128 		while (hdr.type == FCGI_PARAMS && len > 0) {
1129 			if (len + padding > FCGI_MAX_LENGTH) {
1130 				return 0;
1131 			}
1132 
1133 			if (safe_read(req, buf, len+padding) != len+padding) {
1134 				req->keep = 0;
1135 				return 0;
1136 			}
1137 
1138 			if (!fcgi_get_params(req, buf, buf+len)) {
1139 				req->keep = 0;
1140 				return 0;
1141 			}
1142 
1143 			if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1144 			    hdr.version < FCGI_VERSION_1) {
1145 				req->keep = 0;
1146 				return 0;
1147 			}
1148 			len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1149 			padding = hdr.paddingLength;
1150 		}
1151 	} else if (hdr.type == FCGI_GET_VALUES) {
1152 		unsigned char *p = buf + sizeof(fcgi_header);
1153 		zval *value;
1154 		unsigned int zlen;
1155 		fcgi_hash_bucket *q;
1156 
1157 		if (safe_read(req, buf, len+padding) != len+padding) {
1158 			req->keep = 0;
1159 			return 0;
1160 		}
1161 
1162 		if (!fcgi_get_params(req, buf, buf+len)) {
1163 			req->keep = 0;
1164 			return 0;
1165 		}
1166 
1167 		q = req->env.list;
1168 		while (q != NULL) {
1169 			if ((value = zend_hash_str_find(&fcgi_mgmt_vars, q->var, q->var_len)) == NULL) {
1170 				q = q->list_next;
1171 				continue;
1172 			}
1173 			zlen = (unsigned int)Z_STRLEN_P(value);
1174 			if ((p + 4 + 4 + q->var_len + zlen) >= (buf + sizeof(buf))) {
1175 				break;
1176 			}
1177 			if (q->var_len < 0x80) {
1178 				*p++ = q->var_len;
1179 			} else {
1180 				*p++ = ((q->var_len >> 24) & 0xff) | 0x80;
1181 				*p++ = (q->var_len >> 16) & 0xff;
1182 				*p++ = (q->var_len >> 8) & 0xff;
1183 				*p++ = q->var_len & 0xff;
1184 			}
1185 			if (zlen < 0x80) {
1186 				*p++ = zlen;
1187 			} else {
1188 				*p++ = ((zlen >> 24) & 0xff) | 0x80;
1189 				*p++ = (zlen >> 16) & 0xff;
1190 				*p++ = (zlen >> 8) & 0xff;
1191 				*p++ = zlen & 0xff;
1192 			}
1193 			memcpy(p, q->var, q->var_len);
1194 			p += q->var_len;
1195 			memcpy(p, Z_STRVAL_P(value), zlen);
1196 			p += zlen;
1197 			q = q->list_next;
1198 		}
1199 		len = (int)(p - buf - sizeof(fcgi_header));
1200 		len += fcgi_make_header((fcgi_header*)buf, FCGI_GET_VALUES_RESULT, 0, len);
1201 		if (safe_write(req, buf, sizeof(fcgi_header) + len) != (ssize_t)sizeof(fcgi_header)+len) {
1202 			req->keep = 0;
1203 			return 0;
1204 		}
1205 		return 2;
1206 	} else {
1207 		return 0;
1208 	}
1209 
1210 	return 1;
1211 }
1212 
1213 int fcgi_read(fcgi_request *req, char *str, int len)
1214 {
1215 	int ret, n, rest;
1216 	fcgi_header hdr;
1217 	unsigned char buf[255];
1218 
1219 	n = 0;
1220 	rest = len;
1221 	while (rest > 0) {
1222 		if (req->in_len == 0) {
1223 			if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1224 			    hdr.version < FCGI_VERSION_1 ||
1225 			    hdr.type != FCGI_STDIN) {
1226 				req->keep = 0;
1227 				return 0;
1228 			}
1229 			req->in_len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1230 			req->in_pad = hdr.paddingLength;
1231 			if (req->in_len == 0) {
1232 				return n;
1233 			}
1234 		}
1235 
1236 		if (req->in_len >= rest) {
1237 			ret = (int)safe_read(req, str, rest);
1238 		} else {
1239 			ret = (int)safe_read(req, str, req->in_len);
1240 		}
1241 		if (ret < 0) {
1242 			req->keep = 0;
1243 			return ret;
1244 		} else if (ret > 0) {
1245 			req->in_len -= ret;
1246 			rest -= ret;
1247 			n += ret;
1248 			str += ret;
1249 			if (req->in_len == 0) {
1250 				if (req->in_pad) {
1251 					if (safe_read(req, buf, req->in_pad) != req->in_pad) {
1252 						req->keep = 0;
1253 						return ret;
1254 					}
1255 				}
1256 			} else {
1257 				return n;
1258 			}
1259 		} else {
1260 			return n;
1261 		}
1262 	}
1263 	return n;
1264 }
1265 
1266 void fcgi_close(fcgi_request *req, int force, int destroy)
1267 {
1268 	if (destroy && req->has_env) {
1269 		fcgi_hash_clean(&req->env);
1270 		req->has_env = 0;
1271 	}
1272 
1273 #ifdef _WIN32
1274 	if (is_impersonate && !req->tcp) {
1275 		RevertToSelf();
1276 	}
1277 #endif
1278 
1279 	if ((force || !req->keep) && req->fd >= 0) {
1280 #ifdef _WIN32
1281 		if (!req->tcp) {
1282 			HANDLE pipe = (HANDLE)_get_osfhandle(req->fd);
1283 
1284 			if (!force) {
1285 				FlushFileBuffers(pipe);
1286 			}
1287 			DisconnectNamedPipe(pipe);
1288 		} else {
1289 			if (!force) {
1290 				char buf[8];
1291 
1292 				shutdown(req->fd, 1);
1293 				/* read any remaining data, it may be omitted */
1294 				while (recv(req->fd, buf, sizeof(buf), 0) > 0) {}
1295 			}
1296 			closesocket(req->fd);
1297 		}
1298 #else
1299 		if (!force) {
1300 			char buf[8];
1301 
1302 			shutdown(req->fd, 1);
1303 			/* read any remaining data, it may be omitted */
1304 			while (recv(req->fd, buf, sizeof(buf), 0) > 0) {}
1305 		}
1306 		close(req->fd);
1307 #endif
1308 #ifdef TCP_NODELAY
1309 		req->nodelay = 0;
1310 #endif
1311 		req->fd = -1;
1312 
1313 		req->hook.on_close();
1314 	}
1315 }
1316 
1317 int fcgi_is_closed(fcgi_request *req)
1318 {
1319 	return (req->fd < 0);
1320 }
1321 
1322 static int fcgi_is_allowed(void) {
1323 	int i;
1324 
1325 	if (client_sa.sa.sa_family == AF_UNIX) {
1326 		return 1;
1327 	}
1328 	if (!allowed_clients) {
1329 		return 1;
1330 	}
1331 	if (client_sa.sa.sa_family == AF_INET) {
1332 		for (i = 0; allowed_clients[i].sa.sa_family ; i++) {
1333 			if (allowed_clients[i].sa.sa_family == AF_INET
1334 				&& !memcmp(&client_sa.sa_inet.sin_addr, &allowed_clients[i].sa_inet.sin_addr, 4)) {
1335 				return 1;
1336 			}
1337 		}
1338 	}
1339 #ifdef HAVE_IPV6
1340 	if (client_sa.sa.sa_family == AF_INET6) {
1341 		for (i = 0; allowed_clients[i].sa.sa_family ; i++) {
1342 			if (allowed_clients[i].sa.sa_family == AF_INET6
1343 				&& !memcmp(&client_sa.sa_inet6.sin6_addr, &allowed_clients[i].sa_inet6.sin6_addr, 12)) {
1344 				return 1;
1345 			}
1346 #ifdef IN6_IS_ADDR_V4MAPPED
1347 			if (allowed_clients[i].sa.sa_family == AF_INET
1348 			    && IN6_IS_ADDR_V4MAPPED(&client_sa.sa_inet6.sin6_addr)
1349 				&& !memcmp(((char *)&client_sa.sa_inet6.sin6_addr)+12, &allowed_clients[i].sa_inet.sin_addr, 4)) {
1350 				return 1;
1351 			}
1352 #endif
1353 		}
1354 	}
1355 #endif
1356 
1357 	return 0;
1358 }
1359 
1360 int fcgi_accept_request(fcgi_request *req)
1361 {
1362 #ifdef _WIN32
1363 	HANDLE pipe;
1364 	OVERLAPPED ov;
1365 #endif
1366 
1367 	while (1) {
1368 		if (req->fd < 0) {
1369 			while (1) {
1370 				if (in_shutdown) {
1371 					return -1;
1372 				}
1373 
1374 				req->hook.on_accept();
1375 #ifdef _WIN32
1376 				if (!req->tcp) {
1377 					pipe = (HANDLE)_get_osfhandle(req->listen_socket);
1378 					FCGI_LOCK(req->listen_socket);
1379 					ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1380 					if (!ConnectNamedPipe(pipe, &ov)) {
1381 						errno = GetLastError();
1382 						if (errno == ERROR_IO_PENDING) {
1383 							while (WaitForSingleObject(ov.hEvent, 1000) == WAIT_TIMEOUT) {
1384 								if (in_shutdown) {
1385 									CloseHandle(ov.hEvent);
1386 									FCGI_UNLOCK(req->listen_socket);
1387 									return -1;
1388 								}
1389 							}
1390 						} else if (errno != ERROR_PIPE_CONNECTED) {
1391 						}
1392 					}
1393 					CloseHandle(ov.hEvent);
1394 					req->fd = req->listen_socket;
1395 					FCGI_UNLOCK(req->listen_socket);
1396 				} else {
1397 					SOCKET listen_socket = (SOCKET)_get_osfhandle(req->listen_socket);
1398 #else
1399 				{
1400 					int listen_socket = req->listen_socket;
1401 #endif
1402 					sa_t sa;
1403 					socklen_t len = sizeof(sa);
1404 
1405 					FCGI_LOCK(req->listen_socket);
1406 					req->fd = accept(listen_socket, (struct sockaddr *)&sa, &len);
1407 					FCGI_UNLOCK(req->listen_socket);
1408 
1409 					client_sa = sa;
1410 					if (req->fd >= 0 && !fcgi_is_allowed()) {
1411 						fcgi_log(FCGI_ERROR, "Connection disallowed: IP address '%s' has been dropped.", fcgi_get_last_client_ip());
1412 						closesocket(req->fd);
1413 						req->fd = -1;
1414 						continue;
1415 					}
1416 				}
1417 
1418 #ifdef _WIN32
1419 				if (req->fd < 0 && (in_shutdown || errno != EINTR)) {
1420 #else
1421 				if (req->fd < 0 && (in_shutdown || (errno != EINTR && errno != ECONNABORTED))) {
1422 #endif
1423 					return -1;
1424 				}
1425 
1426 #ifdef _WIN32
1427 				break;
1428 #else
1429 				if (req->fd >= 0) {
1430 #if defined(HAVE_POLL)
1431 					struct pollfd fds;
1432 					int ret;
1433 
1434 					fds.fd = req->fd;
1435 					fds.events = POLLIN;
1436 					fds.revents = 0;
1437 					do {
1438 						errno = 0;
1439 						ret = poll(&fds, 1, 5000);
1440 					} while (ret < 0 && errno == EINTR);
1441 					if (ret > 0 && (fds.revents & POLLIN)) {
1442 						break;
1443 					}
1444 					fcgi_close(req, 1, 0);
1445 #else
1446 					if (req->fd < FD_SETSIZE) {
1447 						struct timeval tv = {5,0};
1448 						fd_set set;
1449 						int ret;
1450 
1451 						FD_ZERO(&set);
1452 						FD_SET(req->fd, &set);
1453 						do {
1454 							errno = 0;
1455 							ret = select(req->fd + 1, &set, NULL, NULL, &tv) >= 0;
1456 						} while (ret < 0 && errno == EINTR);
1457 						if (ret > 0 && FD_ISSET(req->fd, &set)) {
1458 							break;
1459 						}
1460 						fcgi_close(req, 1, 0);
1461 					} else {
1462 						fcgi_log(FCGI_ERROR, "Too many open file descriptors. FD_SETSIZE limit exceeded.");
1463 						fcgi_close(req, 1, 0);
1464 					}
1465 #endif
1466 				}
1467 #endif
1468 			}
1469 		} else if (in_shutdown) {
1470 			return -1;
1471 		}
1472 		req->hook.on_read();
1473 		int read_result = fcgi_read_request(req);
1474 		if (read_result == 1) {
1475 #ifdef _WIN32
1476 			if (is_impersonate && !req->tcp) {
1477 				pipe = (HANDLE)_get_osfhandle(req->fd);
1478 				if (!ImpersonateNamedPipeClient(pipe)) {
1479 					fcgi_close(req, 1, 1);
1480 					continue;
1481 				}
1482 			}
1483 #endif
1484 			return req->fd;
1485 		} else if (read_result == 0) {
1486 			fcgi_close(req, 1, 1);
1487 		}
1488 	}
1489 }
1490 
1491 static inline fcgi_header* open_packet(fcgi_request *req, fcgi_request_type type)
1492 {
1493 	req->out_hdr = (fcgi_header*) req->out_pos;
1494 	req->out_hdr->type = type;
1495 	req->out_pos += sizeof(fcgi_header);
1496 	return req->out_hdr;
1497 }
1498 
1499 static inline void close_packet(fcgi_request *req)
1500 {
1501 	if (req->out_hdr) {
1502 		int len = (int)(req->out_pos - ((unsigned char*)req->out_hdr + sizeof(fcgi_header)));
1503 
1504 		req->out_pos += fcgi_make_header(req->out_hdr, (fcgi_request_type)req->out_hdr->type, req->id, len);
1505 		req->out_hdr = NULL;
1506 	}
1507 }
1508 
1509 int fcgi_flush(fcgi_request *req, int end)
1510 {
1511 	int len;
1512 
1513 	close_packet(req);
1514 
1515 	len = (int)(req->out_pos - req->out_buf);
1516 
1517 	if (end) {
1518 		fcgi_end_request_rec *rec = (fcgi_end_request_rec*)(req->out_pos);
1519 
1520 		fcgi_make_header(&rec->hdr, FCGI_END_REQUEST, req->id, sizeof(fcgi_end_request));
1521 		rec->body.appStatusB3 = 0;
1522 		rec->body.appStatusB2 = 0;
1523 		rec->body.appStatusB1 = 0;
1524 		rec->body.appStatusB0 = 0;
1525 		rec->body.protocolStatus = FCGI_REQUEST_COMPLETE;
1526 		len += sizeof(fcgi_end_request_rec);
1527 	}
1528 
1529 	if (safe_write(req, req->out_buf, len) != len) {
1530 		req->keep = 0;
1531 		req->out_pos = req->out_buf;
1532 		return 0;
1533 	}
1534 
1535 	req->out_pos = req->out_buf;
1536 	return 1;
1537 }
1538 
1539 int fcgi_write(fcgi_request *req, fcgi_request_type type, const char *str, int len)
1540 {
1541 	int limit, rest;
1542 
1543 	if (len <= 0) {
1544 		return 0;
1545 	}
1546 
1547 	if (req->out_hdr && req->out_hdr->type != type) {
1548 		close_packet(req);
1549 	}
1550 #if 0
1551 	/* Unoptimized, but clear version */
1552 	rest = len;
1553 	while (rest > 0) {
1554 		limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
1555 
1556 		if (!req->out_hdr) {
1557 			if (limit < sizeof(fcgi_header)) {
1558 				if (!fcgi_flush(req, 0)) {
1559 					return -1;
1560 				}
1561 			}
1562 			open_packet(req, type);
1563 		}
1564 		limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
1565 		if (rest < limit) {
1566 			memcpy(req->out_pos, str, rest);
1567 			req->out_pos += rest;
1568 			return len;
1569 		} else {
1570 			memcpy(req->out_pos, str, limit);
1571 			req->out_pos += limit;
1572 			rest -= limit;
1573 			str += limit;
1574 			if (!fcgi_flush(req, 0)) {
1575 				return -1;
1576 			}
1577 		}
1578 	}
1579 #else
1580 	/* Optimized version */
1581 	limit = (int)(sizeof(req->out_buf) - (req->out_pos - req->out_buf));
1582 	if (!req->out_hdr) {
1583 		limit -= sizeof(fcgi_header);
1584 		if (limit < 0) limit = 0;
1585 	}
1586 
1587 	if (len < limit) {
1588 		if (!req->out_hdr) {
1589 			open_packet(req, type);
1590 		}
1591 		memcpy(req->out_pos, str, len);
1592 		req->out_pos += len;
1593 	} else if (len - limit < (int)(sizeof(req->out_buf) - sizeof(fcgi_header))) {
1594 		if (limit > 0) {
1595 			if (!req->out_hdr) {
1596 				open_packet(req, type);
1597 			}
1598 			memcpy(req->out_pos, str, limit);
1599 			req->out_pos += limit;
1600 		}
1601 		if (!fcgi_flush(req, 0)) {
1602 			return -1;
1603 		}
1604 		if (len > limit) {
1605 			open_packet(req, type);
1606 			memcpy(req->out_pos, str + limit, len - limit);
1607 			req->out_pos += len - limit;
1608 		}
1609 	} else {
1610 		int pos = 0;
1611 		int pad;
1612 
1613 		close_packet(req);
1614 		while ((len - pos) > 0xffff) {
1615 			open_packet(req, type);
1616 			fcgi_make_header(req->out_hdr, type, req->id, 0xfff8);
1617 			req->out_hdr = NULL;
1618 			if (!fcgi_flush(req, 0)) {
1619 				return -1;
1620 			}
1621 			if (safe_write(req, str + pos, 0xfff8) != 0xfff8) {
1622 				req->keep = 0;
1623 				return -1;
1624 			}
1625 			pos += 0xfff8;
1626 		}
1627 
1628 		pad = (((len - pos) + 7) & ~7) - (len - pos);
1629 		rest = pad ? 8 - pad : 0;
1630 
1631 		open_packet(req, type);
1632 		fcgi_make_header(req->out_hdr, type, req->id, (len - pos) - rest);
1633 		req->out_hdr = NULL;
1634 		if (!fcgi_flush(req, 0)) {
1635 			return -1;
1636 		}
1637 		if (safe_write(req, str + pos, (len - pos) - rest) != (len - pos) - rest) {
1638 			req->keep = 0;
1639 			return -1;
1640 		}
1641 		if (pad) {
1642 			open_packet(req, type);
1643 			memcpy(req->out_pos, str + len - rest,  rest);
1644 			req->out_pos += rest;
1645 		}
1646 	}
1647 #endif
1648 	return len;
1649 }
1650 
1651 int fcgi_end(fcgi_request *req) {
1652 	int ret = 1;
1653 	if (!req->ended) {
1654 		ret = fcgi_flush(req, 1);
1655 		req->ended = 1;
1656 	}
1657 	return ret;
1658 }
1659 
1660 int fcgi_finish_request(fcgi_request *req, int force_close)
1661 {
1662 	int ret = 1;
1663 
1664 	if (req->fd >= 0) {
1665 		ret = fcgi_end(req);
1666 		fcgi_close(req, force_close, 1);
1667 	}
1668 	return ret;
1669 }
1670 
1671 int fcgi_has_env(fcgi_request *req)
1672 {
1673 	return req && req->has_env;
1674 }
1675 
1676 char* fcgi_getenv(fcgi_request *req, const char* var, int var_len)
1677 {
1678 	unsigned int val_len;
1679 
1680 	if (!req) return NULL;
1681 
1682 	return fcgi_hash_get(&req->env, FCGI_HASH_FUNC(var, var_len), (char*)var, var_len, &val_len);
1683 }
1684 
1685 char* fcgi_quick_getenv(fcgi_request *req, const char* var, int var_len, unsigned int hash_value)
1686 {
1687 	unsigned int val_len;
1688 
1689 	return fcgi_hash_get(&req->env, hash_value, (char*)var, var_len, &val_len);
1690 }
1691 
1692 char* fcgi_putenv(fcgi_request *req, char* var, int var_len, char* val)
1693 {
1694 	if (!req) return NULL;
1695 	if (val == NULL) {
1696 		fcgi_hash_del(&req->env, FCGI_HASH_FUNC(var, var_len), var, var_len);
1697 		return NULL;
1698 	} else {
1699 		return fcgi_hash_set(&req->env, FCGI_HASH_FUNC(var, var_len), var, var_len, val, (unsigned int)strlen(val));
1700 	}
1701 }
1702 
1703 char* fcgi_quick_putenv(fcgi_request *req, char* var, int var_len, unsigned int hash_value, char* val)
1704 {
1705 	if (val == NULL) {
1706 		fcgi_hash_del(&req->env, hash_value, var, var_len);
1707 		return NULL;
1708 	} else {
1709 		return fcgi_hash_set(&req->env, hash_value, var, var_len, val, (unsigned int)strlen(val));
1710 	}
1711 }
1712 
1713 void fcgi_loadenv(fcgi_request *req, fcgi_apply_func func, zval *array)
1714 {
1715 	fcgi_hash_apply(&req->env, func, array);
1716 }
1717 
1718 #ifdef _WIN32
1719 void fcgi_impersonate(void)
1720 {
1721 	char *os_name;
1722 
1723 	os_name = getenv("OS");
1724 	if (os_name && stricmp(os_name, "Windows_NT") == 0) {
1725 		is_impersonate = 1;
1726 	}
1727 }
1728 #endif
1729 
1730 void fcgi_set_mgmt_var(const char * name, size_t name_len, const char * value, size_t value_len)
1731 {
1732 	zval zvalue;
1733 	zend_string *key = zend_string_init(name, name_len, 1);
1734 	ZVAL_NEW_STR(&zvalue, zend_string_init(value, value_len, 1));
1735 	GC_MAKE_PERSISTENT_LOCAL(key);
1736 	GC_MAKE_PERSISTENT_LOCAL(Z_STR(zvalue));
1737 	zend_hash_add(&fcgi_mgmt_vars, key, &zvalue);
1738 	zend_string_release_ex(key, 1);
1739 }
1740 
1741 void fcgi_free_mgmt_var_cb(zval *zv)
1742 {
1743 	pefree(Z_STR_P(zv), 1);
1744 }
1745 
1746 const char *fcgi_get_last_client_ip(void)
1747 {
1748 	static char str[INET6_ADDRSTRLEN];
1749 
1750 	/* Ipv4 */
1751 	if (client_sa.sa.sa_family == AF_INET) {
1752 		return inet_ntop(client_sa.sa.sa_family, &client_sa.sa_inet.sin_addr, str, INET6_ADDRSTRLEN);
1753 	}
1754 #ifdef HAVE_IPV6
1755 #ifdef IN6_IS_ADDR_V4MAPPED
1756 	/* Ipv4-Mapped-Ipv6 */
1757 	if (client_sa.sa.sa_family == AF_INET6
1758 		&& IN6_IS_ADDR_V4MAPPED(&client_sa.sa_inet6.sin6_addr)) {
1759 		return inet_ntop(AF_INET, ((char *)&client_sa.sa_inet6.sin6_addr)+12, str, INET6_ADDRSTRLEN);
1760 	}
1761 #endif
1762 	/* Ipv6 */
1763 	if (client_sa.sa.sa_family == AF_INET6) {
1764 		return inet_ntop(client_sa.sa.sa_family, &client_sa.sa_inet6.sin6_addr, str, INET6_ADDRSTRLEN);
1765 	}
1766 #endif
1767 	/* Unix socket */
1768 	return NULL;
1769 }
1770