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 if (strlen(bindPath) >= MAXPATHLEN) {
291 "Listening socket path is longer than %d bytes -- exiting!\n",
295 strcpy(host, bindPath);
296 if((tp = strchr(host, ':')) != 0) {
298 if((port = atoi(tp)) == 0) {
305 if (!*host || !strcmp(host,"*")) {
306 tcp_ia = htonl(INADDR_ANY);
308 tcp_ia = inet_addr(host);
309 if (tcp_ia == INADDR_NONE) {
310 struct hostent * hep;
311 hep = gethostbyname(host);
312 if ((!hep) || (hep->h_addrtype != AF_INET || !hep->h_addr_list[0])) {
313 fprintf(stderr, "Cannot resolve host name %s -- exiting!\n", host);
316 if (hep->h_addr_list[1]) {
317 fprintf(stderr, "Host %s has multiple addresses ---\n", host);
318 fprintf(stderr, "you must choose one explicitly!!!\n");
321 tcp_ia = ((struct in_addr *) (hep->h_addr))->s_addr;
327 listenSock = socket(AF_INET, SOCK_STREAM, 0);
328 if(listenSock >= 0) {
330 if(setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR,
331 (char *) &flag, sizeof(flag)) < 0) {
332 fprintf(stderr, "Can't set SO_REUSEADDR.\n");
337 listenSock = socket(AF_UNIX, SOCK_STREAM, 0);
344 * Bind the listening socket.
347 memset((char *) &sa.inetVariant, 0, sizeof(sa.inetVariant));
348 sa.inetVariant.sin_family = AF_INET;
349 sa.inetVariant.sin_addr.s_addr = tcp_ia;
350 sa.inetVariant.sin_port = htons(port);
351 servLen = sizeof(sa.inetVariant);
354 if(OS_BuildSockAddrUn(bindPath, &sa.unixVariant, &servLen)) {
355 fprintf(stderr, "Listening socket's path name is too long.\n");
359 if(bind(listenSock, (struct sockaddr *) &sa.unixVariant, servLen) < 0
360 || listen(listenSock, backlog) < 0) {
361 perror("bind/listen");
369 *----------------------------------------------------------------------
373 * Create the socket and connect to the remote application if
376 * This was lifted from the cgi-fcgi application and was abstracted
377 * out because Windows NT does not have a domain socket and must
378 * use a named pipe which has a different API altogether.
381 * -1 if fail or a valid file descriptor if connection succeeds.
384 * Remote connection established.
386 *----------------------------------------------------------------------
388 int OS_FcgiConnect(char *bindPath)
390 union SockAddrUnion sa;
391 int servLen, resultSock;
394 char host[MAXPATHLEN];
398 if (strlen(bindPath) >= MAXPATHLEN) {
399 fprintf(stderr, "Listening socket path is too long\n");
402 strcpy(host, bindPath);
403 if((tp = strchr(host, ':')) != 0) {
405 if((port = atoi(tp)) == 0) {
413 if((hp = gethostbyname((*host ? host : "localhost"))) == NULL) {
414 fprintf(stderr, "Unknown host: %s\n", bindPath);
417 sa.inetVariant.sin_family = AF_INET;
418 memcpy(&sa.inetVariant.sin_addr, hp->h_addr, hp->h_length);
419 sa.inetVariant.sin_port = htons(port);
420 servLen = sizeof(sa.inetVariant);
421 resultSock = socket(AF_INET, SOCK_STREAM, 0);
423 if(OS_BuildSockAddrUn(bindPath, &sa.unixVariant, &servLen)) {
424 fprintf(stderr, "Listening socket's path name is too long.\n");
427 resultSock = socket(AF_UNIX, SOCK_STREAM, 0);
430 ASSERT(resultSock >= 0);
431 connectStatus = connect(resultSock, (struct sockaddr *) &sa.unixVariant,
433 if(connectStatus >= 0) {
437 * Most likely (errno == ENOENT || errno == ECONNREFUSED)
438 * and no FCGI application server is running.
446 *--------------------------------------------------------------
450 * Pass through to the unix read function.
453 * Returns number of byes read, 0, or -1 failure: errno
454 * contains actual error.
459 *--------------------------------------------------------------
461 int OS_Read(int fd, char * buf, size_t len)
463 if (shutdownNow) return -1;
464 return(read(fd, buf, len));
468 *--------------------------------------------------------------
472 * Pass through to unix write function.
475 * Returns number of byes read, 0, or -1 failure: errno
476 * contains actual error.
481 *--------------------------------------------------------------
483 int OS_Write(int fd, char * buf, size_t len)
485 if (shutdownNow) return -1;
486 return(write(fd, buf, len));
490 *----------------------------------------------------------------------
494 * Spawns a new FastCGI listener process.
497 * 0 if success, -1 if error.
500 * Child process spawned.
502 *----------------------------------------------------------------------
504 int OS_SpawnChild(char *appPath, int listenFd)
513 if(forkResult == 0) {
515 * Close STDIN unconditionally. It's used by the parent
516 * process for CGI communication. The FastCGI applciation
517 * will be replacing this with the FastCGI listenFd IF
518 * STDIN_FILENO is the same as FCGI_LISTENSOCK_FILENO
519 * (which it is on Unix). Regardless, STDIN, STDOUT, and
520 * STDERR will be closed as the FastCGI process uses a
521 * multiplexed socket in their place.
526 * If the listenFd is already the value of FCGI_LISTENSOCK_FILENO
527 * we're set. If not, change it so the child knows where to
528 * get the listen socket from.
530 if(listenFd != FCGI_LISTENSOCK_FILENO) {
531 dup2(listenFd, FCGI_LISTENSOCK_FILENO);
535 close(STDOUT_FILENO);
536 close(STDERR_FILENO);
539 * We're a child. Exec the application.
541 * XXX: entire environment passes through
543 execl(appPath, appPath, NULL);
545 * XXX: Can't do this as we've already closed STDERR!!!
555 *--------------------------------------------------------------
557 * OS_AsyncReadStdin --
559 * This initiates an asynchronous read on the standard
562 * The abstraction is necessary because Windows NT does not
563 * have a clean way of "select"ing a file descriptor for
567 * -1 if error, 0 otherwise.
570 * Asynchronous bit is set in the readfd variable and
571 * request is enqueued.
573 *--------------------------------------------------------------
575 int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
576 ClientData clientData)
578 int index = AIO_RD_IX(STDIN_FILENO);
581 ASSERT(asyncIoTable[index].inUse == 0);
582 asyncIoTable[index].procPtr = procPtr;
583 asyncIoTable[index].clientData = clientData;
584 asyncIoTable[index].fd = STDIN_FILENO;
585 asyncIoTable[index].len = len;
586 asyncIoTable[index].offset = 0;
587 asyncIoTable[index].buf = buf;
588 asyncIoTable[index].inUse = 1;
589 FD_SET(STDIN_FILENO, &readFdSet);
590 if(STDIN_FILENO > maxFd)
591 maxFd = STDIN_FILENO;
595 static void GrowAsyncTable(void)
597 int oldTableSize = asyncIoTableSize;
599 asyncIoTableSize = asyncIoTableSize * 2;
600 asyncIoTable = (AioInfo *)realloc(asyncIoTable, asyncIoTableSize * sizeof(AioInfo));
601 if(asyncIoTable == NULL) {
605 memset((char *) &asyncIoTable[oldTableSize], 0,
606 oldTableSize * sizeof(AioInfo));
611 *--------------------------------------------------------------
615 * This initiates an asynchronous read on the file
616 * handle which may be a socket or named pipe.
618 * We also must save the ProcPtr and ClientData, so later
619 * when the io completes, we know who to call.
621 * We don't look at any results here (the ReadFile may
622 * return data if it is cached) but do all completion
623 * processing in OS_Select when we get the io completion
624 * port done notifications. Then we call the callback.
627 * -1 if error, 0 otherwise.
630 * Asynchronous I/O operation is queued for completion.
632 *--------------------------------------------------------------
634 int OS_AsyncRead(int fd, int offset, void *buf, int len,
635 OS_AsyncProc procPtr, ClientData clientData)
637 int index = AIO_RD_IX(fd);
639 ASSERT(asyncIoTable != NULL);
645 while (index >= asyncIoTableSize) {
649 ASSERT(asyncIoTable[index].inUse == 0);
650 asyncIoTable[index].procPtr = procPtr;
651 asyncIoTable[index].clientData = clientData;
652 asyncIoTable[index].fd = fd;
653 asyncIoTable[index].len = len;
654 asyncIoTable[index].offset = offset;
655 asyncIoTable[index].buf = buf;
656 asyncIoTable[index].inUse = 1;
657 FD_SET(fd, &readFdSet);
662 *--------------------------------------------------------------
666 * This initiates an asynchronous write on the "fake" file
667 * descriptor (which may be a file, socket, or named pipe).
668 * We also must save the ProcPtr and ClientData, so later
669 * when the io completes, we know who to call.
671 * We don't look at any results here (the WriteFile generally
672 * completes immediately) but do all completion processing
673 * in OS_DoIo when we get the io completion port done
674 * notifications. Then we call the callback.
677 * -1 if error, 0 otherwise.
680 * Asynchronous I/O operation is queued for completion.
682 *--------------------------------------------------------------
684 int OS_AsyncWrite(int fd, int offset, void *buf, int len,
685 OS_AsyncProc procPtr, ClientData clientData)
687 int index = AIO_WR_IX(fd);
694 while (index >= asyncIoTableSize) {
698 ASSERT(asyncIoTable[index].inUse == 0);
699 asyncIoTable[index].procPtr = procPtr;
700 asyncIoTable[index].clientData = clientData;
701 asyncIoTable[index].fd = fd;
702 asyncIoTable[index].len = len;
703 asyncIoTable[index].offset = offset;
704 asyncIoTable[index].buf = buf;
705 asyncIoTable[index].inUse = 1;
706 FD_SET(fd, &writeFdSet);
711 *--------------------------------------------------------------
715 * Closes the descriptor. This is a pass through to the
719 * 0 for success, -1 on failure
724 *--------------------------------------------------------------
726 int OS_Close(int fd, int shutdown_ok)
732 int index = AIO_RD_IX(fd);
734 FD_CLR(fd, &readFdSet);
735 FD_CLR(fd, &readFdSetPost);
736 if (asyncIoTable[index].inUse != 0) {
737 asyncIoTable[index].inUse = 0;
740 FD_CLR(fd, &writeFdSet);
741 FD_CLR(fd, &writeFdSetPost);
742 index = AIO_WR_IX(fd);
743 if (asyncIoTable[index].inUse != 0) {
744 asyncIoTable[index].inUse = 0;
753 * shutdown() the send side and then read() from client until EOF
754 * or a timeout expires. This is done to minimize the potential
755 * that a TCP RST will be sent by our TCP stack in response to
756 * receipt of additional data from the client. The RST would
757 * cause the client to discard potentially useful response data.
762 if (shutdown(fd, 1) == 0)
776 rv = select(fd + 1, &rfds, NULL, NULL, &tv);
778 while (rv > 0 && read(fd, trash, sizeof(trash)) > 0);
786 *--------------------------------------------------------------
790 * Cancel outstanding asynchronous reads and prevent subsequent
791 * reads from completing.
794 * Socket or file is shutdown. Return values mimic Unix shutdown:
795 * 0 success, -1 failure
797 *--------------------------------------------------------------
799 int OS_CloseRead(int fd)
801 if(asyncIoTable[AIO_RD_IX(fd)].inUse != 0) {
802 asyncIoTable[AIO_RD_IX(fd)].inUse = 0;
803 FD_CLR(fd, &readFdSet);
806 return shutdown(fd, 0);
810 *--------------------------------------------------------------
814 * This function was formerly OS_Select. It's purpose is
815 * to pull I/O completion events off the queue and dispatch
816 * them to the appropriate place.
822 * Handlers are called.
824 *--------------------------------------------------------------
826 int OS_DoIo(struct timeval *tmo)
828 int fd, len, selectStatus;
829 OS_AsyncProc procPtr;
830 ClientData clientData;
833 fd_set writeFdSetCpy;
836 FD_ZERO(&readFdSetCpy);
837 FD_ZERO(&writeFdSetCpy);
839 for(fd = 0; fd <= maxFd; fd++) {
840 if(FD_ISSET(fd, &readFdSet)) {
841 FD_SET(fd, &readFdSetCpy);
843 if(FD_ISSET(fd, &writeFdSet)) {
844 FD_SET(fd, &writeFdSetCpy);
849 * If there were no completed events from a prior call, see if there's
852 if(numRdPosted == 0 && numWrPosted == 0) {
853 selectStatus = select((maxFd+1), &readFdSetCpy, &writeFdSetCpy,
855 if(selectStatus < 0) {
859 for(fd = 0; fd <= maxFd; fd++) {
861 * Build up a list of completed events. We'll work off of
862 * this list as opposed to looping through the read and write
863 * fd sets since they can be affected by a callbacl routine.
865 if(FD_ISSET(fd, &readFdSetCpy)) {
867 FD_SET(fd, &readFdSetPost);
868 FD_CLR(fd, &readFdSet);
871 if(FD_ISSET(fd, &writeFdSetCpy)) {
873 FD_SET(fd, &writeFdSetPost);
874 FD_CLR(fd, &writeFdSet);
879 if(numRdPosted == 0 && numWrPosted == 0)
882 for(fd = 0; fd <= maxFd; fd++) {
884 * Do reads and dispatch callback.
886 if(FD_ISSET(fd, &readFdSetPost)
887 && asyncIoTable[AIO_RD_IX(fd)].inUse) {
890 FD_CLR(fd, &readFdSetPost);
891 aioPtr = &asyncIoTable[AIO_RD_IX(fd)];
893 len = read(aioPtr->fd, aioPtr->buf, aioPtr->len);
895 procPtr = aioPtr->procPtr;
896 aioPtr->procPtr = NULL;
897 clientData = aioPtr->clientData;
900 (*procPtr)(clientData, len);
904 * Do writes and dispatch callback.
906 if(FD_ISSET(fd, &writeFdSetPost) &&
907 asyncIoTable[AIO_WR_IX(fd)].inUse) {
910 FD_CLR(fd, &writeFdSetPost);
911 aioPtr = &asyncIoTable[AIO_WR_IX(fd)];
913 len = write(aioPtr->fd, aioPtr->buf, aioPtr->len);
915 procPtr = aioPtr->procPtr;
916 aioPtr->procPtr = NULL;
917 clientData = aioPtr->clientData;
919 (*procPtr)(clientData, len);
926 * Not all systems have strdup().
927 * @@@ autoconf should determine whether or not this is needed, but for now..
929 static char * str_dup(const char * str)
931 char * sdup = (char *) malloc(strlen(str) + 1);
940 *----------------------------------------------------------------------
944 * Checks if a client address is in a list of allowed addresses
947 * TRUE if address list is empty or client address is present
948 * in the list, FALSE otherwise.
950 *----------------------------------------------------------------------
952 static int ClientAddrOK(struct sockaddr_in *saPtr, const char *clientList)
955 char *clientListCopy, *cur, *next;
957 if (clientList == NULL || *clientList == '\0') {
961 clientListCopy = str_dup(clientList);
963 for (cur = clientListCopy; cur != NULL; cur = next) {
964 next = strchr(cur, ',');
968 if (inet_addr(cur) == saPtr->sin_addr.s_addr) {
974 free(clientListCopy);
979 *----------------------------------------------------------------------
983 * On platforms that implement concurrent calls to accept
984 * on a shared listening ipcFd, returns 0. On other platforms,
985 * acquires an exclusive lock across all processes sharing a
986 * listening ipcFd, blocking until the lock has been acquired.
989 * 0 for successful call, -1 in case of system error (fatal).
992 * This process now has the exclusive lock.
994 *----------------------------------------------------------------------
996 static int AcquireLock(int sock, int fail_on_intr)
1001 lock.l_type = F_WRLCK;
1003 lock.l_whence = SEEK_SET;
1006 if (fcntl(sock, F_SETLKW, &lock) != -1)
1008 } while (errno == EINTR
1010 && ! shutdownPending);
1020 *----------------------------------------------------------------------
1024 * On platforms that implement concurrent calls to accept
1025 * on a shared listening ipcFd, does nothing. On other platforms,
1026 * releases an exclusive lock acquired by AcquireLock.
1029 * 0 for successful call, -1 in case of system error (fatal).
1032 * This process no longer holds the lock.
1034 *----------------------------------------------------------------------
1036 static int ReleaseLock(int sock)
1041 lock.l_type = F_UNLCK;
1043 lock.l_whence = SEEK_SET;
1046 if (fcntl(sock, F_SETLK, &lock) != -1)
1048 } while (errno == EINTR);
1057 /**********************************************************************
1058 * Determine if the errno resulting from a failed accept() warrants a
1059 * retry or exit(). Based on Apache's http_main.c accept() handling
1060 * and Stevens' Unix Network Programming Vol 1, 2nd Ed, para. 15.6.
1062 static int is_reasonable_accept_errno (const int error)
1066 /* EPROTO on certain older kernels really means ECONNABORTED, so
1067 * we need to ignore it for them. See discussion in new-httpd
1068 * archives nh.9701 search for EPROTO. Also see nh.9603, search
1069 * for EPROTO: There is potentially a bug in Solaris 2.x x<6, and
1070 * other boxes that implement tcp sockets in userland (i.e. on top of
1071 * STREAMS). On these systems, EPROTO can actually result in a fatal
1072 * loop. See PR#981 for example. It's hard to handle both uses of
1079 /* Linux generates the rest of these, other tcp stacks (i.e.
1080 * bsd) tend to hide them behind getsockopt() interfaces. They
1081 * occur when the net goes sour or the client disconnects after the
1082 * three-way handshake has been done in the kernel but before
1083 * userland has picked up the socket. */
1103 /**********************************************************************
1104 * This works around a problem on Linux 2.0.x and SCO Unixware (maybe
1105 * others?). When a connect() is made to a Unix Domain socket, but its
1106 * not accept()ed before the web server gets impatient and close()s, an
1107 * accept() results in a valid file descriptor, but no data to read.
1108 * This causes a block on the first read() - which never returns!
1110 * Another approach to this is to write() to the socket to provoke a
1111 * SIGPIPE, but this is a pain because of the FastCGI protocol, the fact
1112 * that whatever is written has to be universally ignored by all FastCGI
1113 * web servers, and a SIGPIPE handler has to be installed which returns
1114 * (or SIGPIPE is ignored).
1116 * READABLE_UNIX_FD_DROP_DEAD_TIMEVAL = 2,0 by default.
1118 * Making it shorter is probably safe, but I'll leave that to you. Making
1119 * it 0,0 doesn't work reliably. The shorter you can reliably make it,
1120 * the faster your application will be able to recover (waiting 2 seconds
1121 * may _cause_ the problem when there is a very high demand). At any rate,
1122 * this is better than perma-blocking.
1124 static int is_af_unix_keeper(const int fd)
1126 struct timeval tval = { READABLE_UNIX_FD_DROP_DEAD_TIMEVAL };
1130 FD_SET(fd, &read_fds);
1132 return select(fd + 1, &read_fds, NULL, NULL, &tval) >= 0 && FD_ISSET(fd, &read_fds);
1136 *----------------------------------------------------------------------
1140 * Accepts a new FastCGI connection. This routine knows whether
1141 * we're dealing with TCP based sockets or NT Named Pipes for IPC.
1144 * -1 if the operation fails, otherwise this is a valid IPC fd.
1147 * New IPC connection is accepted.
1149 *----------------------------------------------------------------------
1151 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
1155 struct sockaddr_un un;
1156 struct sockaddr_in in;
1160 if (AcquireLock(listen_sock, fail_on_intr))
1166 socklen_t len = sizeof(sa);
1168 int len = sizeof(sa);
1170 if (shutdownPending) break;
1171 /* There's a window here */
1173 socket = accept(listen_sock, (struct sockaddr *)&sa, &len);
1177 && ! shutdownPending);
1180 if (shutdownPending || ! is_reasonable_accept_errno(errno)) {
1181 int errnoSave = errno;
1183 ReleaseLock(listen_sock);
1185 if (! shutdownPending) {
1193 else { /* socket >= 0 */
1196 if (sa.in.sin_family != AF_INET)
1200 /* No replies to outgoing data, so disable Nagle */
1201 setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set));
1204 /* Check that the client IP address is approved */
1205 if (ClientAddrOK(&sa.in, webServerAddrs))
1212 if (ReleaseLock(listen_sock))
1215 if (sa.in.sin_family != AF_UNIX || is_af_unix_keeper(socket))
1219 } /* while(1) - lock */
1225 *----------------------------------------------------------------------
1229 * OS IPC routine to close an IPC connection.
1235 * IPC connection is closed.
1237 *----------------------------------------------------------------------
1239 int OS_IpcClose(int ipcFd, int shutdown)
1241 return OS_Close(ipcFd, shutdown);
1245 *----------------------------------------------------------------------
1249 * Determines whether this process is a FastCGI process or not.
1252 * Returns 1 if FastCGI, 0 if not.
1257 *----------------------------------------------------------------------
1259 int OS_IsFcgi(int sock)
1262 struct sockaddr_in in;
1263 struct sockaddr_un un;
1266 socklen_t len = sizeof(sa);
1268 int len = sizeof(sa);
1273 if (getpeername(sock, (struct sockaddr *)&sa, &len) != 0 && errno == ENOTCONN) {
1282 *----------------------------------------------------------------------
1286 * Sets selected flag bits in an open file descriptor.
1288 *----------------------------------------------------------------------
1290 void OS_SetFlags(int fd, int flags)
1293 if((val = fcntl(fd, F_GETFL, 0)) < 0) {
1297 if(fcntl(fd, F_SETFL, val) < 0) {