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