xref: /PHP-7.0/main/fastcgi.c (revision d9dfac90)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2017 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 >= 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 		if (safe_read(req, buf, len+padding) != len+padding) {
1092 			return 0;
1093 		}
1094 
1095 		req->keep = (((fcgi_begin_request*)buf)->flags & FCGI_KEEP_CONN);
1096 #ifdef TCP_NODELAY
1097 		if (req->keep && req->tcp && !req->nodelay) {
1098 # ifdef _WIN32
1099 			BOOL on = 1;
1100 # else
1101 			int on = 1;
1102 # endif
1103 
1104 			setsockopt(req->fd, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on));
1105 			req->nodelay = 1;
1106 		}
1107 #endif
1108 		switch ((((fcgi_begin_request*)buf)->roleB1 << 8) + ((fcgi_begin_request*)buf)->roleB0) {
1109 			case FCGI_RESPONDER:
1110 				fcgi_hash_set(&req->env, FCGI_HASH_FUNC("FCGI_ROLE", sizeof("FCGI_ROLE")-1), "FCGI_ROLE", sizeof("FCGI_ROLE")-1, "RESPONDER", sizeof("RESPONDER")-1);
1111 				break;
1112 			case FCGI_AUTHORIZER:
1113 				fcgi_hash_set(&req->env, FCGI_HASH_FUNC("FCGI_ROLE", sizeof("FCGI_ROLE")-1), "FCGI_ROLE", sizeof("FCGI_ROLE")-1, "AUTHORIZER", sizeof("AUTHORIZER")-1);
1114 				break;
1115 			case FCGI_FILTER:
1116 				fcgi_hash_set(&req->env, FCGI_HASH_FUNC("FCGI_ROLE", sizeof("FCGI_ROLE")-1), "FCGI_ROLE", sizeof("FCGI_ROLE")-1, "FILTER", sizeof("FILTER")-1);
1117 				break;
1118 			default:
1119 				return 0;
1120 		}
1121 
1122 		if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1123 		    hdr.version < FCGI_VERSION_1) {
1124 			return 0;
1125 		}
1126 
1127 		len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1128 		padding = hdr.paddingLength;
1129 
1130 		while (hdr.type == FCGI_PARAMS && len > 0) {
1131 			if (len + padding > FCGI_MAX_LENGTH) {
1132 				return 0;
1133 			}
1134 
1135 			if (safe_read(req, buf, len+padding) != len+padding) {
1136 				req->keep = 0;
1137 				return 0;
1138 			}
1139 
1140 			if (!fcgi_get_params(req, buf, buf+len)) {
1141 				req->keep = 0;
1142 				return 0;
1143 			}
1144 
1145 			if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1146 			    hdr.version < FCGI_VERSION_1) {
1147 				req->keep = 0;
1148 				return 0;
1149 			}
1150 			len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1151 			padding = hdr.paddingLength;
1152 		}
1153 	} else if (hdr.type == FCGI_GET_VALUES) {
1154 		unsigned char *p = buf + sizeof(fcgi_header);
1155 		zval *value;
1156 		unsigned int zlen;
1157 		fcgi_hash_bucket *q;
1158 
1159 		if (safe_read(req, buf, len+padding) != len+padding) {
1160 			req->keep = 0;
1161 			return 0;
1162 		}
1163 
1164 		if (!fcgi_get_params(req, buf, buf+len)) {
1165 			req->keep = 0;
1166 			return 0;
1167 		}
1168 
1169 		q = req->env.list;
1170 		while (q != NULL) {
1171 			if ((value = zend_hash_str_find(&fcgi_mgmt_vars, q->var, q->var_len)) == NULL) {
1172 				q = q->list_next;
1173 				continue;
1174 			}
1175 			zlen = (unsigned int)Z_STRLEN_P(value);
1176 			if ((p + 4 + 4 + q->var_len + zlen) >= (buf + sizeof(buf))) {
1177 				break;
1178 			}
1179 			if (q->var_len < 0x80) {
1180 				*p++ = q->var_len;
1181 			} else {
1182 				*p++ = ((q->var_len >> 24) & 0xff) | 0x80;
1183 				*p++ = (q->var_len >> 16) & 0xff;
1184 				*p++ = (q->var_len >> 8) & 0xff;
1185 				*p++ = q->var_len & 0xff;
1186 			}
1187 			if (zlen < 0x80) {
1188 				*p++ = zlen;
1189 			} else {
1190 				*p++ = ((zlen >> 24) & 0xff) | 0x80;
1191 				*p++ = (zlen >> 16) & 0xff;
1192 				*p++ = (zlen >> 8) & 0xff;
1193 				*p++ = zlen & 0xff;
1194 			}
1195 			memcpy(p, q->var, q->var_len);
1196 			p += q->var_len;
1197 			memcpy(p, Z_STRVAL_P(value), zlen);
1198 			p += zlen;
1199 			q = q->list_next;
1200 		}
1201 		len = (int)(p - buf - sizeof(fcgi_header));
1202 		len += fcgi_make_header((fcgi_header*)buf, FCGI_GET_VALUES_RESULT, 0, len);
1203 		if (safe_write(req, buf, sizeof(fcgi_header) + len) != (ssize_t)sizeof(fcgi_header)+len) {
1204 			req->keep = 0;
1205 			return 0;
1206 		}
1207 		return 0;
1208 	} else {
1209 		return 0;
1210 	}
1211 
1212 	return 1;
1213 }
1214 
fcgi_read(fcgi_request * req,char * str,int len)1215 int fcgi_read(fcgi_request *req, char *str, int len)
1216 {
1217 	int ret, n, rest;
1218 	fcgi_header hdr;
1219 	unsigned char buf[255];
1220 
1221 	n = 0;
1222 	rest = len;
1223 	while (rest > 0) {
1224 		if (req->in_len == 0) {
1225 			if (safe_read(req, &hdr, sizeof(fcgi_header)) != sizeof(fcgi_header) ||
1226 			    hdr.version < FCGI_VERSION_1 ||
1227 			    hdr.type != FCGI_STDIN) {
1228 				req->keep = 0;
1229 				return 0;
1230 			}
1231 			req->in_len = (hdr.contentLengthB1 << 8) | hdr.contentLengthB0;
1232 			req->in_pad = hdr.paddingLength;
1233 			if (req->in_len == 0) {
1234 				return n;
1235 			}
1236 		}
1237 
1238 		if (req->in_len >= rest) {
1239 			ret = (int)safe_read(req, str, rest);
1240 		} else {
1241 			ret = (int)safe_read(req, str, req->in_len);
1242 		}
1243 		if (ret < 0) {
1244 			req->keep = 0;
1245 			return ret;
1246 		} else if (ret > 0) {
1247 			req->in_len -= ret;
1248 			rest -= ret;
1249 			n += ret;
1250 			str += ret;
1251 			if (req->in_len == 0) {
1252 				if (req->in_pad) {
1253 					if (safe_read(req, buf, req->in_pad) != req->in_pad) {
1254 						req->keep = 0;
1255 						return ret;
1256 					}
1257 				}
1258 			} else {
1259 				return n;
1260 			}
1261 		} else {
1262 			return n;
1263 		}
1264 	}
1265 	return n;
1266 }
1267 
fcgi_close(fcgi_request * req,int force,int destroy)1268 void fcgi_close(fcgi_request *req, int force, int destroy)
1269 {
1270 	if (destroy && req->has_env) {
1271 		fcgi_hash_clean(&req->env);
1272 		req->has_env = 0;
1273 	}
1274 
1275 #ifdef _WIN32
1276 	if (is_impersonate && !req->tcp) {
1277 		RevertToSelf();
1278 	}
1279 #endif
1280 
1281 	if ((force || !req->keep) && req->fd >= 0) {
1282 #ifdef _WIN32
1283 		if (!req->tcp) {
1284 			HANDLE pipe = (HANDLE)_get_osfhandle(req->fd);
1285 
1286 			if (!force) {
1287 				FlushFileBuffers(pipe);
1288 			}
1289 			DisconnectNamedPipe(pipe);
1290 		} else {
1291 			if (!force) {
1292 				char buf[8];
1293 
1294 				shutdown(req->fd, 1);
1295 				/* read any remaining data, it may be omitted */
1296 				while (recv(req->fd, buf, sizeof(buf), 0) > 0) {}
1297 			}
1298 			closesocket(req->fd);
1299 		}
1300 #else
1301 		if (!force) {
1302 			char buf[8];
1303 
1304 			shutdown(req->fd, 1);
1305 			/* read any remaining data, it may be omitted */
1306 			while (recv(req->fd, buf, sizeof(buf), 0) > 0) {}
1307 		}
1308 		close(req->fd);
1309 #endif
1310 #ifdef TCP_NODELAY
1311 		req->nodelay = 0;
1312 #endif
1313 		req->fd = -1;
1314 
1315 		req->hook.on_close();
1316 	}
1317 }
1318 
fcgi_is_closed(fcgi_request * req)1319 int fcgi_is_closed(fcgi_request *req)
1320 {
1321 	return (req->fd < 0);
1322 }
1323 
fcgi_is_allowed()1324 static int fcgi_is_allowed() {
1325 	int i;
1326 
1327 	if (client_sa.sa.sa_family == AF_UNIX) {
1328 		return 1;
1329 	}
1330 	if (!allowed_clients) {
1331 		return 1;
1332 	}
1333 	if (client_sa.sa.sa_family == AF_INET) {
1334 		for (i = 0; allowed_clients[i].sa.sa_family ; i++) {
1335 			if (allowed_clients[i].sa.sa_family == AF_INET
1336 				&& !memcmp(&client_sa.sa_inet.sin_addr, &allowed_clients[i].sa_inet.sin_addr, 4)) {
1337 				return 1;
1338 			}
1339 		}
1340 	}
1341 #ifdef HAVE_IPV6
1342 	if (client_sa.sa.sa_family == AF_INET6) {
1343 		for (i = 0; allowed_clients[i].sa.sa_family ; i++) {
1344 			if (allowed_clients[i].sa.sa_family == AF_INET6
1345 				&& !memcmp(&client_sa.sa_inet6.sin6_addr, &allowed_clients[i].sa_inet6.sin6_addr, 12)) {
1346 				return 1;
1347 			}
1348 #ifdef IN6_IS_ADDR_V4MAPPED
1349 			if (allowed_clients[i].sa.sa_family == AF_INET
1350 			    && IN6_IS_ADDR_V4MAPPED(&client_sa.sa_inet6.sin6_addr)
1351 				&& !memcmp(((char *)&client_sa.sa_inet6.sin6_addr)+12, &allowed_clients[i].sa_inet.sin_addr, 4)) {
1352 				return 1;
1353 			}
1354 #endif
1355 		}
1356 	}
1357 #endif
1358 
1359 	return 0;
1360 }
1361 
fcgi_accept_request(fcgi_request * req)1362 int fcgi_accept_request(fcgi_request *req)
1363 {
1364 #ifdef _WIN32
1365 	HANDLE pipe;
1366 	OVERLAPPED ov;
1367 #endif
1368 
1369 	while (1) {
1370 		if (req->fd < 0) {
1371 			while (1) {
1372 				if (in_shutdown) {
1373 					return -1;
1374 				}
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 					req->hook.on_accept();
1406 
1407 					FCGI_LOCK(req->listen_socket);
1408 					req->fd = accept(listen_socket, (struct sockaddr *)&sa, &len);
1409 					FCGI_UNLOCK(req->listen_socket);
1410 
1411 					client_sa = sa;
1412 					if (req->fd >= 0 && !fcgi_is_allowed()) {
1413 						fcgi_log(FCGI_ERROR, "Connection disallowed: IP address '%s' has been dropped.", fcgi_get_last_client_ip());
1414 						closesocket(req->fd);
1415 						req->fd = -1;
1416 						continue;
1417 					}
1418 				}
1419 
1420 #ifdef _WIN32
1421 				if (req->fd < 0 && (in_shutdown || errno != EINTR)) {
1422 #else
1423 				if (req->fd < 0 && (in_shutdown || (errno != EINTR && errno != ECONNABORTED))) {
1424 #endif
1425 					return -1;
1426 				}
1427 
1428 #ifdef _WIN32
1429 				break;
1430 #else
1431 				if (req->fd >= 0) {
1432 #if defined(HAVE_POLL)
1433 					struct pollfd fds;
1434 					int ret;
1435 
1436 					fds.fd = req->fd;
1437 					fds.events = POLLIN;
1438 					fds.revents = 0;
1439 					do {
1440 						errno = 0;
1441 						ret = poll(&fds, 1, 5000);
1442 					} while (ret < 0 && errno == EINTR);
1443 					if (ret > 0 && (fds.revents & POLLIN)) {
1444 						break;
1445 					}
1446 					fcgi_close(req, 1, 0);
1447 #else
1448 					if (req->fd < FD_SETSIZE) {
1449 						struct timeval tv = {5,0};
1450 						fd_set set;
1451 						int ret;
1452 
1453 						FD_ZERO(&set);
1454 						FD_SET(req->fd, &set);
1455 						do {
1456 							errno = 0;
1457 							ret = select(req->fd + 1, &set, NULL, NULL, &tv) >= 0;
1458 						} while (ret < 0 && errno == EINTR);
1459 						if (ret > 0 && FD_ISSET(req->fd, &set)) {
1460 							break;
1461 						}
1462 						fcgi_close(req, 1, 0);
1463 					} else {
1464 						fcgi_log(FCGI_ERROR, "Too many open file descriptors. FD_SETSIZE limit exceeded.");
1465 						fcgi_close(req, 1, 0);
1466 					}
1467 #endif
1468 				}
1469 #endif
1470 			}
1471 		} else if (in_shutdown) {
1472 			return -1;
1473 		}
1474 		req->hook.on_read();
1475 		if (fcgi_read_request(req)) {
1476 #ifdef _WIN32
1477 			if (is_impersonate && !req->tcp) {
1478 				pipe = (HANDLE)_get_osfhandle(req->fd);
1479 				if (!ImpersonateNamedPipeClient(pipe)) {
1480 					fcgi_close(req, 1, 1);
1481 					continue;
1482 				}
1483 			}
1484 #endif
1485 			return req->fd;
1486 		} else {
1487 			fcgi_close(req, 1, 1);
1488 		}
1489 	}
1490 }
1491 
1492 static inline fcgi_header* open_packet(fcgi_request *req, fcgi_request_type type)
1493 {
1494 	req->out_hdr = (fcgi_header*) req->out_pos;
1495 	req->out_hdr->type = type;
1496 	req->out_pos += sizeof(fcgi_header);
1497 	return req->out_hdr;
1498 }
1499 
1500 static inline void close_packet(fcgi_request *req)
1501 {
1502 	if (req->out_hdr) {
1503 		int len = (int)(req->out_pos - ((unsigned char*)req->out_hdr + sizeof(fcgi_header)));
1504 
1505 		req->out_pos += fcgi_make_header(req->out_hdr, (fcgi_request_type)req->out_hdr->type, req->id, len);
1506 		req->out_hdr = NULL;
1507 	}
1508 }
1509 
1510 int fcgi_flush(fcgi_request *req, int end)
1511 {
1512 	int len;
1513 
1514 	close_packet(req);
1515 
1516 	len = (int)(req->out_pos - req->out_buf);
1517 
1518 	if (end) {
1519 		fcgi_end_request_rec *rec = (fcgi_end_request_rec*)(req->out_pos);
1520 
1521 		fcgi_make_header(&rec->hdr, FCGI_END_REQUEST, req->id, sizeof(fcgi_end_request));
1522 		rec->body.appStatusB3 = 0;
1523 		rec->body.appStatusB2 = 0;
1524 		rec->body.appStatusB1 = 0;
1525 		rec->body.appStatusB0 = 0;
1526 		rec->body.protocolStatus = FCGI_REQUEST_COMPLETE;
1527 		len += sizeof(fcgi_end_request_rec);
1528 	}
1529 
1530 	if (safe_write(req, req->out_buf, len) != len) {
1531 		req->keep = 0;
1532 		req->out_pos = req->out_buf;
1533 		return 0;
1534 	}
1535 
1536 	req->out_pos = req->out_buf;
1537 	return 1;
1538 }
1539 
1540 int fcgi_write(fcgi_request *req, fcgi_request_type type, const char *str, int len)
1541 {
1542 	int limit, rest;
1543 
1544 	if (len <= 0) {
1545 		return 0;
1546 	}
1547 
1548 	if (req->out_hdr && req->out_hdr->type != type) {
1549 		close_packet(req);
1550 	}
1551 #if 0
1552 	/* Unoptimized, but clear version */
1553 	rest = len;
1554 	while (rest > 0) {
1555 		limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
1556 
1557 		if (!req->out_hdr) {
1558 			if (limit < sizeof(fcgi_header)) {
1559 				if (!fcgi_flush(req, 0)) {
1560 					return -1;
1561 				}
1562 			}
1563 			open_packet(req, type);
1564 		}
1565 		limit = sizeof(req->out_buf) - (req->out_pos - req->out_buf);
1566 		if (rest < limit) {
1567 			memcpy(req->out_pos, str, rest);
1568 			req->out_pos += rest;
1569 			return len;
1570 		} else {
1571 			memcpy(req->out_pos, str, limit);
1572 			req->out_pos += limit;
1573 			rest -= limit;
1574 			str += limit;
1575 			if (!fcgi_flush(req, 0)) {
1576 				return -1;
1577 			}
1578 		}
1579 	}
1580 #else
1581 	/* Optimized version */
1582 	limit = (int)(sizeof(req->out_buf) - (req->out_pos - req->out_buf));
1583 	if (!req->out_hdr) {
1584 		limit -= sizeof(fcgi_header);
1585 		if (limit < 0) limit = 0;
1586 	}
1587 
1588 	if (len < limit) {
1589 		if (!req->out_hdr) {
1590 			open_packet(req, type);
1591 		}
1592 		memcpy(req->out_pos, str, len);
1593 		req->out_pos += len;
1594 	} else if (len - limit < sizeof(req->out_buf) - sizeof(fcgi_header)) {
1595 		if (!req->out_hdr) {
1596 			open_packet(req, type);
1597 		}
1598 		if (limit > 0) {
1599 			memcpy(req->out_pos, str, limit);
1600 			req->out_pos += limit;
1601 		}
1602 		if (!fcgi_flush(req, 0)) {
1603 			return -1;
1604 		}
1605 		if (len > limit) {
1606 			open_packet(req, type);
1607 			memcpy(req->out_pos, str + limit, len - limit);
1608 			req->out_pos += len - limit;
1609 		}
1610 	} else {
1611 		int pos = 0;
1612 		int pad;
1613 
1614 		close_packet(req);
1615 		while ((len - pos) > 0xffff) {
1616 			open_packet(req, type);
1617 			fcgi_make_header(req->out_hdr, type, req->id, 0xfff8);
1618 			req->out_hdr = NULL;
1619 			if (!fcgi_flush(req, 0)) {
1620 				return -1;
1621 			}
1622 			if (safe_write(req, str + pos, 0xfff8) != 0xfff8) {
1623 				req->keep = 0;
1624 				return -1;
1625 			}
1626 			pos += 0xfff8;
1627 		}
1628 
1629 		pad = (((len - pos) + 7) & ~7) - (len - pos);
1630 		rest = pad ? 8 - pad : 0;
1631 
1632 		open_packet(req, type);
1633 		fcgi_make_header(req->out_hdr, type, req->id, (len - pos) - rest);
1634 		req->out_hdr = NULL;
1635 		if (!fcgi_flush(req, 0)) {
1636 			return -1;
1637 		}
1638 		if (safe_write(req, str + pos, (len - pos) - rest) != (len - pos) - rest) {
1639 			req->keep = 0;
1640 			return -1;
1641 		}
1642 		if (pad) {
1643 			open_packet(req, type);
1644 			memcpy(req->out_pos, str + len - rest,  rest);
1645 			req->out_pos += rest;
1646 		}
1647 	}
1648 #endif
1649 	return len;
1650 }
1651 
1652 int fcgi_end(fcgi_request *req) {
1653 	int ret = 1;
1654 	if (!req->ended) {
1655 		ret = fcgi_flush(req, 1);
1656 		req->ended = 1;
1657 	}
1658 	return ret;
1659 }
1660 
1661 int fcgi_finish_request(fcgi_request *req, int force_close)
1662 {
1663 	int ret = 1;
1664 
1665 	if (req->fd >= 0) {
1666 		ret = fcgi_end(req);
1667 		fcgi_close(req, force_close, 1);
1668 	}
1669 	return ret;
1670 }
1671 
1672 int fcgi_has_env(fcgi_request *req)
1673 {
1674 	return req && req->has_env;
1675 }
1676 
1677 char* fcgi_getenv(fcgi_request *req, const char* var, int var_len)
1678 {
1679 	unsigned int val_len;
1680 
1681 	if (!req) return NULL;
1682 
1683 	return fcgi_hash_get(&req->env, FCGI_HASH_FUNC(var, var_len), (char*)var, var_len, &val_len);
1684 }
1685 
1686 char* fcgi_quick_getenv(fcgi_request *req, const char* var, int var_len, unsigned int hash_value)
1687 {
1688 	unsigned int val_len;
1689 
1690 	return fcgi_hash_get(&req->env, hash_value, (char*)var, var_len, &val_len);
1691 }
1692 
1693 char* fcgi_putenv(fcgi_request *req, char* var, int var_len, char* val)
1694 {
1695 	if (!req) return NULL;
1696 	if (val == NULL) {
1697 		fcgi_hash_del(&req->env, FCGI_HASH_FUNC(var, var_len), var, var_len);
1698 		return NULL;
1699 	} else {
1700 		return fcgi_hash_set(&req->env, FCGI_HASH_FUNC(var, var_len), var, var_len, val, (unsigned int)strlen(val));
1701 	}
1702 }
1703 
1704 char* fcgi_quick_putenv(fcgi_request *req, char* var, int var_len, unsigned int hash_value, char* val)
1705 {
1706 	if (val == NULL) {
1707 		fcgi_hash_del(&req->env, hash_value, var, var_len);
1708 		return NULL;
1709 	} else {
1710 		return fcgi_hash_set(&req->env, hash_value, var, var_len, val, (unsigned int)strlen(val));
1711 	}
1712 }
1713 
1714 void fcgi_loadenv(fcgi_request *req, fcgi_apply_func func, zval *array)
1715 {
1716 	fcgi_hash_apply(&req->env, func, array);
1717 }
1718 
1719 #ifdef _WIN32
1720 void fcgi_impersonate(void)
1721 {
1722 	char *os_name;
1723 
1724 	os_name = getenv("OS");
1725 	if (os_name && stricmp(os_name, "Windows_NT") == 0) {
1726 		is_impersonate = 1;
1727 	}
1728 }
1729 #endif
1730 
1731 void fcgi_set_mgmt_var(const char * name, size_t name_len, const char * value, size_t value_len)
1732 {
1733 	zval zvalue;
1734 	ZVAL_NEW_STR(&zvalue, zend_string_init(value, value_len, 1));
1735 	zend_hash_str_add(&fcgi_mgmt_vars, name, name_len, &zvalue);
1736 }
1737 
1738 void fcgi_free_mgmt_var_cb(zval *zv)
1739 {
1740 	pefree(Z_STR_P(zv), 1);
1741 }
1742 
1743 const char *fcgi_get_last_client_ip()
1744 {
1745 	static char str[INET6_ADDRSTRLEN];
1746 
1747 	/* Ipv4 */
1748 	if (client_sa.sa.sa_family == AF_INET) {
1749 		return inet_ntop(client_sa.sa.sa_family, &client_sa.sa_inet.sin_addr, str, INET6_ADDRSTRLEN);
1750 	}
1751 #ifdef HAVE_IPV6
1752 #ifdef IN6_IS_ADDR_V4MAPPED
1753 	/* Ipv4-Mapped-Ipv6 */
1754 	if (client_sa.sa.sa_family == AF_INET6
1755 		&& IN6_IS_ADDR_V4MAPPED(&client_sa.sa_inet6.sin6_addr)) {
1756 		return inet_ntop(AF_INET, ((char *)&client_sa.sa_inet6.sin6_addr)+12, str, INET6_ADDRSTRLEN);
1757 	}
1758 #endif
1759 	/* Ipv6 */
1760 	if (client_sa.sa.sa_family == AF_INET6) {
1761 		return inet_ntop(client_sa.sa.sa_family, &client_sa.sa_inet6.sin6_addr, str, INET6_ADDRSTRLEN);
1762 	}
1763 #endif
1764 	/* Unix socket */
1765 	return NULL;
1766 }
1767 
1768 /*
1769  * Local variables:
1770  * tab-width: 4
1771  * c-basic-offset: 4
1772  * End:
1773  * vim600: sw=4 ts=4 fdm=marker
1774  * vim<600: sw=4 ts=4
1775  */
1776