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