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