5 * snapper@openmarket.com
7 * Copyright (c) 1996 Open Market, Inc.
9 * See the file "LICENSE" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 static const char rcsid[] = "$Id: os_unix.c,v 1.38 2003/06/22 00:16:43 robs Exp $";
17 #include "fcgi_config.h"
19 #include <sys/types.h>
21 #ifdef HAVE_NETINET_IN_H
22 #include <netinet/in.h>
25 #include <arpa/inet.h>
28 #include <fcntl.h> /* for fcntl */
30 #include <memory.h> /* for memchr() */
31 #include <netinet/tcp.h>
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h> /* for getpeername */
57 #define INADDR_NONE ((unsigned long) -1)
61 * This structure holds an entry for each oustanding async I/O operation.
64 OS_AsyncProc procPtr; /* callout completion procedure */
65 ClientData clientData; /* caller private data */
74 * Entries in the async I/O table are allocated 2 per file descriptor.
76 * Read Entry Index = fd * 2
77 * Write Entry Index = (fd * 2) + 1
79 #define AIO_RD_IX(fd) (fd * 2)
80 #define AIO_WR_IX(fd) ((fd * 2) + 1)
82 static int asyncIoInUse = FALSE;
83 static int asyncIoTableSize = 16;
84 static AioInfo *asyncIoTable = NULL;
86 static int libInitialized = FALSE;
88 static fd_set readFdSet;
89 static fd_set writeFdSet;
91 static fd_set readFdSetPost;
92 static int numRdPosted = 0;
93 static fd_set writeFdSetPost;
94 static int numWrPosted = 0;
95 static int volatile maxFd = -1;
97 static int shutdownPending = FALSE;
98 static int shutdownNow = FALSE;
100 void OS_ShutdownPending()
102 shutdownPending = TRUE;
105 static void OS_Sigusr1Handler(int signo)
107 OS_ShutdownPending();
110 static void OS_SigpipeHandler(int signo)
115 static void installSignalHandler(int signo, const struct sigaction * act, int force)
119 sigaction(signo, NULL, &sa);
121 if (force || sa.sa_handler == SIG_DFL)
123 sigaction(signo, act, NULL);
127 static void OS_InstallSignalHandlers(int force)
131 sigemptyset(&sa.sa_mask);
134 sa.sa_handler = OS_SigpipeHandler;
135 installSignalHandler(SIGPIPE, &sa, force);
137 sa.sa_handler = OS_Sigusr1Handler;
138 installSignalHandler(SIGUSR1, &sa, force);
142 *--------------------------------------------------------------
146 * Set up the OS library for use.
148 * NOTE: This function is really only needed for application
149 * asynchronous I/O. It will most likely change in the
150 * future to setup the multi-threaded environment.
153 * Returns 0 if success, -1 if not.
156 * Async I/O table allocated and initialized.
158 *--------------------------------------------------------------
160 int OS_LibInit(int stdioFds[3])
165 asyncIoTable = (AioInfo *)malloc(asyncIoTableSize * sizeof(AioInfo));
166 if(asyncIoTable == NULL) {
170 memset((char *) asyncIoTable, 0,
171 asyncIoTableSize * sizeof(AioInfo));
174 FD_ZERO(&writeFdSet);
175 FD_ZERO(&readFdSetPost);
176 FD_ZERO(&writeFdSetPost);
178 OS_InstallSignalHandlers(TRUE);
180 libInitialized = TRUE;
186 *--------------------------------------------------------------
190 * Shutdown the OS library.
196 * Memory freed, fds closed.
198 *--------------------------------------------------------------
200 void OS_LibShutdown()
207 libInitialized = FALSE;
212 *----------------------------------------------------------------------
214 * OS_BuildSockAddrUn --
216 * Using the pathname bindPath, fill in the sockaddr_un structure
217 * *servAddrPtr and the length of this structure *servAddrLen.
219 * The format of the sockaddr_un structure changed incompatibly in
220 * 4.3BSD Reno. Digital UNIX supports both formats, other systems
221 * support one or the other.
224 * 0 for normal return, -1 for failure (bindPath too long).
226 *----------------------------------------------------------------------
229 static int OS_BuildSockAddrUn(const char *bindPath,
230 struct sockaddr_un *servAddrPtr,
233 int bindPathLen = strlen(bindPath);
235 #ifdef HAVE_SOCKADDR_UN_SUN_LEN /* 4.3BSD Reno and later: BSDI, DEC */
236 if(bindPathLen >= sizeof(servAddrPtr->sun_path)) {
239 #else /* 4.3 BSD Tahoe: Solaris, HPUX, DEC, ... */
240 if(bindPathLen > sizeof(servAddrPtr->sun_path)) {
244 memset((char *) servAddrPtr, 0, sizeof(*servAddrPtr));
245 servAddrPtr->sun_family = AF_UNIX;
246 memcpy(servAddrPtr->sun_path, bindPath, bindPathLen);
247 #ifdef HAVE_SOCKADDR_UN_SUN_LEN /* 4.3BSD Reno and later: BSDI, DEC */
248 *servAddrLen = sizeof(servAddrPtr->sun_len)
249 + sizeof(servAddrPtr->sun_family)
251 servAddrPtr->sun_len = *servAddrLen;
252 #else /* 4.3 BSD Tahoe: Solaris, HPUX, DEC, ... */
253 *servAddrLen = sizeof(servAddrPtr->sun_family) + bindPathLen;
257 union SockAddrUnion {
258 struct sockaddr_un unixVariant;
259 struct sockaddr_in inetVariant;
263 * OS_CreateLocalIpcFd --
265 * This procedure is responsible for creating the listener socket
266 * on Unix for local process communication. It will create a
267 * domain socket or a TCP/IP socket bound to "localhost" and return
268 * a file descriptor to it to the caller.
271 * Listener socket created. This call returns either a valid
272 * file descriptor or -1 on error.
277 *----------------------------------------------------------------------
279 int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
281 int listenSock, servLen;
282 union SockAddrUnion sa;
284 unsigned long tcp_ia = 0;
287 char host[MAXPATHLEN];
289 strcpy(host, bindPath);
290 if((tp = strchr(host, ':')) != 0) {
292 if((port = atoi(tp)) == 0) {
299 if (!*host || !strcmp(host,"*")) {
300 tcp_ia = htonl(INADDR_ANY);
302 tcp_ia = inet_addr(host);
303 if (tcp_ia == INADDR_NONE) {
304 struct hostent * hep;
305 hep = gethostbyname(host);
306 if ((!hep) || (hep->h_addrtype != AF_INET || !hep->h_addr_list[0])) {
307 fprintf(stderr, "Cannot resolve host name %s -- exiting!\n", host);
310 if (hep->h_addr_list[1]) {
311 fprintf(stderr, "Host %s has multiple addresses ---\n", host);
312 fprintf(stderr, "you must choose one explicitly!!!\n");
315 tcp_ia = ((struct in_addr *) (hep->h_addr))->s_addr;
321 listenSock = socket(AF_INET, SOCK_STREAM, 0);
322 if(listenSock >= 0) {
324 if(setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR,
325 (char *) &flag, sizeof(flag)) < 0) {
326 fprintf(stderr, "Can't set SO_REUSEADDR.\n");
331 listenSock = socket(AF_UNIX, SOCK_STREAM, 0);
338 * Bind the listening socket.
341 memset((char *) &sa.inetVariant, 0, sizeof(sa.inetVariant));
342 sa.inetVariant.sin_family = AF_INET;
343 sa.inetVariant.sin_addr.s_addr = tcp_ia;
344 sa.inetVariant.sin_port = htons(port);
345 servLen = sizeof(sa.inetVariant);
348 if(OS_BuildSockAddrUn(bindPath, &sa.unixVariant, &servLen)) {
349 fprintf(stderr, "Listening socket's path name is too long.\n");
353 if(bind(listenSock, (struct sockaddr *) &sa.unixVariant, servLen) < 0
354 || listen(listenSock, backlog) < 0) {
355 perror("bind/listen");
363 *----------------------------------------------------------------------
367 * Create the socket and connect to the remote application if
370 * This was lifted from the cgi-fcgi application and was abstracted
371 * out because Windows NT does not have a domain socket and must
372 * use a named pipe which has a different API altogether.
375 * -1 if fail or a valid file descriptor if connection succeeds.
378 * Remote connection established.
380 *----------------------------------------------------------------------
382 int OS_FcgiConnect(char *bindPath)
384 union SockAddrUnion sa;
385 int servLen, resultSock;
388 char host[MAXPATHLEN];
392 strcpy(host, bindPath);
393 if((tp = strchr(host, ':')) != 0) {
395 if((port = atoi(tp)) == 0) {
403 if((hp = gethostbyname((*host ? host : "localhost"))) == NULL) {
404 fprintf(stderr, "Unknown host: %s\n", bindPath);
407 sa.inetVariant.sin_family = AF_INET;
408 memcpy(&sa.inetVariant.sin_addr, hp->h_addr, hp->h_length);
409 sa.inetVariant.sin_port = htons(port);
410 servLen = sizeof(sa.inetVariant);
411 resultSock = socket(AF_INET, SOCK_STREAM, 0);
413 if(OS_BuildSockAddrUn(bindPath, &sa.unixVariant, &servLen)) {
414 fprintf(stderr, "Listening socket's path name is too long.\n");
417 resultSock = socket(AF_UNIX, SOCK_STREAM, 0);
420 ASSERT(resultSock >= 0);
421 connectStatus = connect(resultSock, (struct sockaddr *) &sa.unixVariant,
423 if(connectStatus >= 0) {
427 * Most likely (errno == ENOENT || errno == ECONNREFUSED)
428 * and no FCGI application server is running.
436 *--------------------------------------------------------------
440 * Pass through to the unix read function.
443 * Returns number of byes read, 0, or -1 failure: errno
444 * contains actual error.
449 *--------------------------------------------------------------
451 int OS_Read(int fd, char * buf, size_t len)
453 if (shutdownNow) return -1;
454 return(read(fd, buf, len));
458 *--------------------------------------------------------------
462 * Pass through to unix write function.
465 * Returns number of byes read, 0, or -1 failure: errno
466 * contains actual error.
471 *--------------------------------------------------------------
473 int OS_Write(int fd, char * buf, size_t len)
475 if (shutdownNow) return -1;
476 return(write(fd, buf, len));
480 *----------------------------------------------------------------------
484 * Spawns a new FastCGI listener process.
487 * 0 if success, -1 if error.
490 * Child process spawned.
492 *----------------------------------------------------------------------
494 int OS_SpawnChild(char *appPath, int listenFd)
503 if(forkResult == 0) {
505 * Close STDIN unconditionally. It's used by the parent
506 * process for CGI communication. The FastCGI applciation
507 * will be replacing this with the FastCGI listenFd IF
508 * STDIN_FILENO is the same as FCGI_LISTENSOCK_FILENO
509 * (which it is on Unix). Regardless, STDIN, STDOUT, and
510 * STDERR will be closed as the FastCGI process uses a
511 * multiplexed socket in their place.
516 * If the listenFd is already the value of FCGI_LISTENSOCK_FILENO
517 * we're set. If not, change it so the child knows where to
518 * get the listen socket from.
520 if(listenFd != FCGI_LISTENSOCK_FILENO) {
521 dup2(listenFd, FCGI_LISTENSOCK_FILENO);
525 close(STDOUT_FILENO);
526 close(STDERR_FILENO);
529 * We're a child. Exec the application.
531 * XXX: entire environment passes through
533 execl(appPath, appPath, NULL);
535 * XXX: Can't do this as we've already closed STDERR!!!
545 *--------------------------------------------------------------
547 * OS_AsyncReadStdin --
549 * This initiates an asynchronous read on the standard
552 * The abstraction is necessary because Windows NT does not
553 * have a clean way of "select"ing a file descriptor for
557 * -1 if error, 0 otherwise.
560 * Asynchronous bit is set in the readfd variable and
561 * request is enqueued.
563 *--------------------------------------------------------------
565 int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
566 ClientData clientData)
568 int index = AIO_RD_IX(STDIN_FILENO);
571 ASSERT(asyncIoTable[index].inUse == 0);
572 asyncIoTable[index].procPtr = procPtr;
573 asyncIoTable[index].clientData = clientData;
574 asyncIoTable[index].fd = STDIN_FILENO;
575 asyncIoTable[index].len = len;
576 asyncIoTable[index].offset = 0;
577 asyncIoTable[index].buf = buf;
578 asyncIoTable[index].inUse = 1;
579 FD_SET(STDIN_FILENO, &readFdSet);
580 if(STDIN_FILENO > maxFd)
581 maxFd = STDIN_FILENO;
585 static void GrowAsyncTable(void)
587 int oldTableSize = asyncIoTableSize;
589 asyncIoTableSize = asyncIoTableSize * 2;
590 asyncIoTable = (AioInfo *)realloc(asyncIoTable, asyncIoTableSize * sizeof(AioInfo));
591 if(asyncIoTable == NULL) {
595 memset((char *) &asyncIoTable[oldTableSize], 0,
596 oldTableSize * sizeof(AioInfo));
601 *--------------------------------------------------------------
605 * This initiates an asynchronous read on the file
606 * handle which may be a socket or named pipe.
608 * We also must save the ProcPtr and ClientData, so later
609 * when the io completes, we know who to call.
611 * We don't look at any results here (the ReadFile may
612 * return data if it is cached) but do all completion
613 * processing in OS_Select when we get the io completion
614 * port done notifications. Then we call the callback.
617 * -1 if error, 0 otherwise.
620 * Asynchronous I/O operation is queued for completion.
622 *--------------------------------------------------------------
624 int OS_AsyncRead(int fd, int offset, void *buf, int len,
625 OS_AsyncProc procPtr, ClientData clientData)
627 int index = AIO_RD_IX(fd);
629 ASSERT(asyncIoTable != NULL);
635 while (index >= asyncIoTableSize) {
639 ASSERT(asyncIoTable[index].inUse == 0);
640 asyncIoTable[index].procPtr = procPtr;
641 asyncIoTable[index].clientData = clientData;
642 asyncIoTable[index].fd = fd;
643 asyncIoTable[index].len = len;
644 asyncIoTable[index].offset = offset;
645 asyncIoTable[index].buf = buf;
646 asyncIoTable[index].inUse = 1;
647 FD_SET(fd, &readFdSet);
652 *--------------------------------------------------------------
656 * This initiates an asynchronous write on the "fake" file
657 * descriptor (which may be a file, socket, or named pipe).
658 * We also must save the ProcPtr and ClientData, so later
659 * when the io completes, we know who to call.
661 * We don't look at any results here (the WriteFile generally
662 * completes immediately) but do all completion processing
663 * in OS_DoIo when we get the io completion port done
664 * notifications. Then we call the callback.
667 * -1 if error, 0 otherwise.
670 * Asynchronous I/O operation is queued for completion.
672 *--------------------------------------------------------------
674 int OS_AsyncWrite(int fd, int offset, void *buf, int len,
675 OS_AsyncProc procPtr, ClientData clientData)
677 int index = AIO_WR_IX(fd);
684 while (index >= asyncIoTableSize) {
688 ASSERT(asyncIoTable[index].inUse == 0);
689 asyncIoTable[index].procPtr = procPtr;
690 asyncIoTable[index].clientData = clientData;
691 asyncIoTable[index].fd = fd;
692 asyncIoTable[index].len = len;
693 asyncIoTable[index].offset = offset;
694 asyncIoTable[index].buf = buf;
695 asyncIoTable[index].inUse = 1;
696 FD_SET(fd, &writeFdSet);
701 *--------------------------------------------------------------
705 * Closes the descriptor. This is a pass through to the
709 * 0 for success, -1 on failure
714 *--------------------------------------------------------------
716 int OS_Close(int fd, int shutdown_ok)
722 int index = AIO_RD_IX(fd);
724 FD_CLR(fd, &readFdSet);
725 FD_CLR(fd, &readFdSetPost);
726 if (asyncIoTable[index].inUse != 0) {
727 asyncIoTable[index].inUse = 0;
730 FD_CLR(fd, &writeFdSet);
731 FD_CLR(fd, &writeFdSetPost);
732 index = AIO_WR_IX(fd);
733 if (asyncIoTable[index].inUse != 0) {
734 asyncIoTable[index].inUse = 0;
743 * shutdown() the send side and then read() from client until EOF
744 * or a timeout expires. This is done to minimize the potential
745 * that a TCP RST will be sent by our TCP stack in response to
746 * receipt of additional data from the client. The RST would
747 * cause the client to discard potentially useful response data.
752 if (shutdown(fd, 1) == 0)
766 rv = select(fd + 1, &rfds, NULL, NULL, &tv);
768 while (rv > 0 && read(fd, trash, sizeof(trash)) > 0);
776 *--------------------------------------------------------------
780 * Cancel outstanding asynchronous reads and prevent subsequent
781 * reads from completing.
784 * Socket or file is shutdown. Return values mimic Unix shutdown:
785 * 0 success, -1 failure
787 *--------------------------------------------------------------
789 int OS_CloseRead(int fd)
791 if(asyncIoTable[AIO_RD_IX(fd)].inUse != 0) {
792 asyncIoTable[AIO_RD_IX(fd)].inUse = 0;
793 FD_CLR(fd, &readFdSet);
796 return shutdown(fd, 0);
800 *--------------------------------------------------------------
804 * This function was formerly OS_Select. It's purpose is
805 * to pull I/O completion events off the queue and dispatch
806 * them to the appropriate place.
812 * Handlers are called.
814 *--------------------------------------------------------------
816 int OS_DoIo(struct timeval *tmo)
818 int fd, len, selectStatus;
819 OS_AsyncProc procPtr;
820 ClientData clientData;
823 fd_set writeFdSetCpy;
826 FD_ZERO(&readFdSetCpy);
827 FD_ZERO(&writeFdSetCpy);
829 for(fd = 0; fd <= maxFd; fd++) {
830 if(FD_ISSET(fd, &readFdSet)) {
831 FD_SET(fd, &readFdSetCpy);
833 if(FD_ISSET(fd, &writeFdSet)) {
834 FD_SET(fd, &writeFdSetCpy);
839 * If there were no completed events from a prior call, see if there's
842 if(numRdPosted == 0 && numWrPosted == 0) {
843 selectStatus = select((maxFd+1), &readFdSetCpy, &writeFdSetCpy,
845 if(selectStatus < 0) {
849 for(fd = 0; fd <= maxFd; fd++) {
851 * Build up a list of completed events. We'll work off of
852 * this list as opposed to looping through the read and write
853 * fd sets since they can be affected by a callbacl routine.
855 if(FD_ISSET(fd, &readFdSetCpy)) {
857 FD_SET(fd, &readFdSetPost);
858 FD_CLR(fd, &readFdSet);
861 if(FD_ISSET(fd, &writeFdSetCpy)) {
863 FD_SET(fd, &writeFdSetPost);
864 FD_CLR(fd, &writeFdSet);
869 if(numRdPosted == 0 && numWrPosted == 0)
872 for(fd = 0; fd <= maxFd; fd++) {
874 * Do reads and dispatch callback.
876 if(FD_ISSET(fd, &readFdSetPost)
877 && asyncIoTable[AIO_RD_IX(fd)].inUse) {
880 FD_CLR(fd, &readFdSetPost);
881 aioPtr = &asyncIoTable[AIO_RD_IX(fd)];
883 len = read(aioPtr->fd, aioPtr->buf, aioPtr->len);
885 procPtr = aioPtr->procPtr;
886 aioPtr->procPtr = NULL;
887 clientData = aioPtr->clientData;
890 (*procPtr)(clientData, len);
894 * Do writes and dispatch callback.
896 if(FD_ISSET(fd, &writeFdSetPost) &&
897 asyncIoTable[AIO_WR_IX(fd)].inUse) {
900 FD_CLR(fd, &writeFdSetPost);
901 aioPtr = &asyncIoTable[AIO_WR_IX(fd)];
903 len = write(aioPtr->fd, aioPtr->buf, aioPtr->len);
905 procPtr = aioPtr->procPtr;
906 aioPtr->procPtr = NULL;
907 clientData = aioPtr->clientData;
909 (*procPtr)(clientData, len);
916 * Not all systems have strdup().
917 * @@@ autoconf should determine whether or not this is needed, but for now..
919 static char * str_dup(const char * str)
921 char * sdup = (char *) malloc(strlen(str) + 1);
930 *----------------------------------------------------------------------
934 * Checks if a client address is in a list of allowed addresses
937 * TRUE if address list is empty or client address is present
938 * in the list, FALSE otherwise.
940 *----------------------------------------------------------------------
942 static int ClientAddrOK(struct sockaddr_in *saPtr, const char *clientList)
945 char *clientListCopy, *cur, *next;
947 if (clientList == NULL || *clientList == '\0') {
951 clientListCopy = str_dup(clientList);
953 for (cur = clientListCopy; cur != NULL; cur = next) {
954 next = strchr(cur, ',');
958 if (inet_addr(cur) == saPtr->sin_addr.s_addr) {
964 free(clientListCopy);
969 *----------------------------------------------------------------------
973 * On platforms that implement concurrent calls to accept
974 * on a shared listening ipcFd, returns 0. On other platforms,
975 * acquires an exclusive lock across all processes sharing a
976 * listening ipcFd, blocking until the lock has been acquired.
979 * 0 for successful call, -1 in case of system error (fatal).
982 * This process now has the exclusive lock.
984 *----------------------------------------------------------------------
986 static int AcquireLock(int sock, int fail_on_intr)
991 lock.l_type = F_WRLCK;
993 lock.l_whence = SEEK_SET;
996 if (fcntl(sock, F_SETLKW, &lock) != -1)
998 } while (errno == EINTR
1000 && ! shutdownPending);
1010 *----------------------------------------------------------------------
1014 * On platforms that implement concurrent calls to accept
1015 * on a shared listening ipcFd, does nothing. On other platforms,
1016 * releases an exclusive lock acquired by AcquireLock.
1019 * 0 for successful call, -1 in case of system error (fatal).
1022 * This process no longer holds the lock.
1024 *----------------------------------------------------------------------
1026 static int ReleaseLock(int sock)
1031 lock.l_type = F_UNLCK;
1033 lock.l_whence = SEEK_SET;
1036 if (fcntl(sock, F_SETLK, &lock) != -1)
1038 } while (errno == EINTR);
1047 /**********************************************************************
1048 * Determine if the errno resulting from a failed accept() warrants a
1049 * retry or exit(). Based on Apache's http_main.c accept() handling
1050 * and Stevens' Unix Network Programming Vol 1, 2nd Ed, para. 15.6.
1052 static int is_reasonable_accept_errno (const int error)
1056 /* EPROTO on certain older kernels really means ECONNABORTED, so
1057 * we need to ignore it for them. See discussion in new-httpd
1058 * archives nh.9701 search for EPROTO. Also see nh.9603, search
1059 * for EPROTO: There is potentially a bug in Solaris 2.x x<6, and
1060 * other boxes that implement tcp sockets in userland (i.e. on top of
1061 * STREAMS). On these systems, EPROTO can actually result in a fatal
1062 * loop. See PR#981 for example. It's hard to handle both uses of
1069 /* Linux generates the rest of these, other tcp stacks (i.e.
1070 * bsd) tend to hide them behind getsockopt() interfaces. They
1071 * occur when the net goes sour or the client disconnects after the
1072 * three-way handshake has been done in the kernel but before
1073 * userland has picked up the socket. */
1093 /**********************************************************************
1094 * This works around a problem on Linux 2.0.x and SCO Unixware (maybe
1095 * others?). When a connect() is made to a Unix Domain socket, but its
1096 * not accept()ed before the web server gets impatient and close()s, an
1097 * accept() results in a valid file descriptor, but no data to read.
1098 * This causes a block on the first read() - which never returns!
1100 * Another approach to this is to write() to the socket to provoke a
1101 * SIGPIPE, but this is a pain because of the FastCGI protocol, the fact
1102 * that whatever is written has to be universally ignored by all FastCGI
1103 * web servers, and a SIGPIPE handler has to be installed which returns
1104 * (or SIGPIPE is ignored).
1106 * READABLE_UNIX_FD_DROP_DEAD_TIMEVAL = 2,0 by default.
1108 * Making it shorter is probably safe, but I'll leave that to you. Making
1109 * it 0,0 doesn't work reliably. The shorter you can reliably make it,
1110 * the faster your application will be able to recover (waiting 2 seconds
1111 * may _cause_ the problem when there is a very high demand). At any rate,
1112 * this is better than perma-blocking.
1114 static int is_af_unix_keeper(const int fd)
1116 struct timeval tval = { READABLE_UNIX_FD_DROP_DEAD_TIMEVAL };
1120 FD_SET(fd, &read_fds);
1122 return select(fd + 1, &read_fds, NULL, NULL, &tval) >= 0 && FD_ISSET(fd, &read_fds);
1126 *----------------------------------------------------------------------
1130 * Accepts a new FastCGI connection. This routine knows whether
1131 * we're dealing with TCP based sockets or NT Named Pipes for IPC.
1134 * -1 if the operation fails, otherwise this is a valid IPC fd.
1137 * New IPC connection is accepted.
1139 *----------------------------------------------------------------------
1141 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
1145 struct sockaddr_un un;
1146 struct sockaddr_in in;
1150 if (AcquireLock(listen_sock, fail_on_intr))
1156 socklen_t len = sizeof(sa);
1158 int len = sizeof(sa);
1160 if (shutdownPending) break;
1161 /* There's a window here */
1163 socket = accept(listen_sock, (struct sockaddr *)&sa, &len);
1167 && ! shutdownPending);
1170 if (shutdownPending || ! is_reasonable_accept_errno(errno)) {
1171 int errnoSave = errno;
1173 ReleaseLock(listen_sock);
1175 if (! shutdownPending) {
1183 else { /* socket >= 0 */
1186 if (sa.in.sin_family != AF_INET)
1190 /* No replies to outgoing data, so disable Nagle */
1191 setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1194 /* Check that the client IP address is approved */
1195 if (ClientAddrOK(&sa.in, webServerAddrs))
1202 if (ReleaseLock(listen_sock))
1205 if (sa.in.sin_family != AF_UNIX || is_af_unix_keeper(socket))
1209 } /* while(1) - lock */
1215 *----------------------------------------------------------------------
1219 * OS IPC routine to close an IPC connection.
1225 * IPC connection is closed.
1227 *----------------------------------------------------------------------
1229 int OS_IpcClose(int ipcFd, int shutdown)
1231 return OS_Close(ipcFd, shutdown);
1235 *----------------------------------------------------------------------
1239 * Determines whether this process is a FastCGI process or not.
1242 * Returns 1 if FastCGI, 0 if not.
1247 *----------------------------------------------------------------------
1249 int OS_IsFcgi(int sock)
1252 struct sockaddr_in in;
1253 struct sockaddr_un un;
1256 socklen_t len = sizeof(sa);
1258 int len = sizeof(sa);
1263 if (getpeername(sock, (struct sockaddr *)&sa, &len) != 0 && errno == ENOTCONN) {
1272 *----------------------------------------------------------------------
1276 * Sets selected flag bits in an open file descriptor.
1278 *----------------------------------------------------------------------
1280 void OS_SetFlags(int fd, int flags)
1283 if((val = fcntl(fd, F_GETFL, 0)) < 0) {
1287 if(fcntl(fd, F_SETFL, val) < 0) {