5 * Copyright (c) 1995 Open Market, Inc.
8 * This file contains proprietary and confidential information and
9 * remains the unpublished property of Open Market, Inc. Use,
10 * disclosure, or reproduction is prohibited except as permitted by
11 * express written license agreement with Open Market, Inc.
14 * snapper@openmarket.com
16 * (Special thanks to Karen and Bill. They made my job much easier and
17 * significantly more enjoyable.)
20 static const char rcsid[] = "$Id: os_win32.c,v 1.18 2001/06/20 17:02:09 robs Exp $";
23 #define WIN32_LEAN_AND_MEAN
29 #include <sys/timeb.h>
31 #define DLLAPI __declspec(dllexport)
35 #define WIN32_OPEN_MAX 128 /* XXX: Small hack */
38 * millisecs to wait for a client connection before checking the
39 * shutdown flag (then go back to waiting for a connection, etc).
41 #define ACCEPT_TIMEOUT 1000
43 #define MUTEX_VARNAME "_FCGI_MUTEX_"
44 #define SHUTDOWN_EVENT_NAME "_FCGI_SHUTDOWN_EVENT_"
45 #define LOCALHOST "localhost"
47 static HANDLE hIoCompPort = INVALID_HANDLE_VALUE;
48 static HANDLE hStdinCompPort = INVALID_HANDLE_VALUE;
49 static HANDLE hStdinThread = INVALID_HANDLE_VALUE;
51 static HANDLE stdioHandles[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE,
52 INVALID_HANDLE_VALUE};
54 static HANDLE acceptMutex = INVALID_HANDLE_VALUE;
56 static BOOLEAN shutdownPending = FALSE;
59 * An enumeration of the file types
60 * supported by the FD_TABLE structure.
62 * XXX: Not all currently supported. This allows for future
82 * Structure used to map file handle and socket handle
83 * values into values that can be used to create unix-like
84 * select bitmaps, read/write for both sockets/files.
91 unsigned long instance;
93 int offset; /* only valid for async file writes */
94 LPDWORD offsetHighPtr; /* pointers to offset high and low words */
95 LPDWORD offsetLowPtr; /* only valid for async file writes (logs) */
96 HANDLE hMapMutex; /* mutex handle for multi-proc offset update */
97 LPVOID ovList; /* List of associated OVERLAPPED_REQUESTs */
101 * XXX Note there is no dyanmic sizing of this table, so if the
102 * number of open file descriptors exceeds WIN32_OPEN_MAX the
105 static struct FD_TABLE fdTable[WIN32_OPEN_MAX];
107 static CRITICAL_SECTION fdTableCritical;
109 struct OVERLAPPED_REQUEST {
110 OVERLAPPED overlapped;
111 unsigned long instance; /* file instance (won't match after a close) */
112 OS_AsyncProc procPtr; /* callback routine */
113 ClientData clientData; /* callback argument */
114 ClientData clientData1; /* additional clientData */
116 typedef struct OVERLAPPED_REQUEST *POVERLAPPED_REQUEST;
118 static const char *bindPathPrefix = "\\\\.\\pipe\\FastCGI\\";
120 static enum FILE_TYPE listenType = FD_UNUSED;
122 // XXX This should be a DESCRIPTOR
123 static HANDLE hListen = INVALID_HANDLE_VALUE;
125 static OVERLAPPED listenOverlapped;
126 static BOOLEAN libInitialized = FALSE;
129 *--------------------------------------------------------------
131 * Win32NewDescriptor --
133 * Set up for I/O descriptor masquerading.
136 * Returns "fake id" which masquerades as a UNIX-style "small
137 * non-negative integer" file/socket descriptor.
138 * Win32_* routine below will "do the right thing" based on the
139 * descriptor's actual type. -1 indicates failure.
142 * Entry in fdTable is reserved to represent the socket/file.
144 *--------------------------------------------------------------
146 static int Win32NewDescriptor(FILE_TYPE type, int fd, int desiredFd)
150 EnterCriticalSection(&fdTableCritical);
153 * If desiredFd is set, try to get this entry (this is used for
154 * mapping stdio handles). Otherwise try to get the fd entry.
155 * If this is not available, find a the first empty slot. .
157 if (desiredFd >= 0 && desiredFd < WIN32_OPEN_MAX)
159 if (fdTable[desiredFd].type == FD_UNUSED)
166 if (fd < WIN32_OPEN_MAX && fdTable[fd].type == FD_UNUSED)
174 for (i = 1; i < WIN32_OPEN_MAX; ++i)
176 if (fdTable[i].type == FD_UNUSED)
187 fdTable[index].fid.value = fd;
188 fdTable[index].type = type;
189 fdTable[index].path = NULL;
190 fdTable[index].Errno = NO_ERROR;
191 fdTable[index].status = 0;
192 fdTable[index].offset = -1;
193 fdTable[index].offsetHighPtr = fdTable[index].offsetLowPtr = NULL;
194 fdTable[index].hMapMutex = NULL;
195 fdTable[index].ovList = NULL;
198 LeaveCriticalSection(&fdTableCritical);
203 *--------------------------------------------------------------
207 * This thread performs I/O on stadard input. It is needed
208 * because you can't guarantee that all applications will
209 * create standard input with sufficient access to perform
210 * asynchronous I/O. Since we don't want to block the app
211 * reading from stdin we make it look like it's using I/O
212 * completion ports to perform async I/O.
215 * Data is read from stdin and posted to the io completion
221 *--------------------------------------------------------------
223 static void StdinThread(LPDWORD startup){
227 unsigned long bytesRead;
228 POVERLAPPED_REQUEST pOv;
230 // Touch the arg to prevent warning
235 * Block until a request to read from stdin comes in or a
236 * request to terminate the thread arrives (fd = -1).
238 if (!GetQueuedCompletionStatus(hStdinCompPort, &bytesRead, &fd,
239 (LPOVERLAPPED *)&pOv, (DWORD)-1) && !pOv) {
244 ASSERT((fd == STDIN_FILENO) || (fd == -1));
249 ASSERT(pOv->clientData1 != NULL);
251 if(ReadFile(stdioHandles[STDIN_FILENO], pOv->clientData1, bytesRead,
253 PostQueuedCompletionStatus(hIoCompPort, bytesRead,
254 STDIN_FILENO, (LPOVERLAPPED)pOv);
264 static DWORD WINAPI ShutdownRequestThread(LPVOID arg)
266 HANDLE shutdownEvent = (HANDLE) arg;
268 if (WaitForSingleObject(shutdownEvent, INFINITE) == WAIT_FAILED)
270 // Assuming it will happen again, all we can do is exit the thread
275 // "Simple reads and writes to properly-aligned 32-bit variables are atomic"
276 shutdownPending = TRUE;
278 // Before an accept() is entered the shutdownPending flag is checked.
279 // If set, OS_Accept() will return -1. If not, it waits
280 // on a connection request for one second, checks the flag, & repeats.
281 // Only one process/thread is allowed to do this at time by
282 // wrapping the accept() with mutex.
288 *--------------------------------------------------------------
292 * Set up the OS library for use.
295 * Returns 0 if success, -1 if not.
298 * Sockets initialized, pseudo file descriptors setup, etc.
300 *--------------------------------------------------------------
302 int OS_LibInit(int stdioFds[3])
309 char *cLenPtr = NULL;
315 InitializeCriticalSection(&fdTableCritical);
318 * Initialize windows sockets library.
320 wVersion = MAKEWORD(2,0);
321 err = WSAStartup( wVersion, &wsaData );
323 fprintf(stderr, "Error starting Windows Sockets. Error: %d",
329 * Create the I/O completion port to be used for our I/O queue.
331 if (hIoCompPort == INVALID_HANDLE_VALUE) {
332 hIoCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
334 if(hIoCompPort == INVALID_HANDLE_VALUE) {
335 printf("<H2>OS_LibInit Failed CreateIoCompletionPort! ERROR: %d</H2>\r\n\r\n",
342 * If a shutdown event is in the env, save it (I don't see any to
343 * remove it from the environment out from under the application).
344 * Spawn a thread to wait on the shutdown request.
346 val = getenv(SHUTDOWN_EVENT_NAME);
349 HANDLE shutdownEvent = (HANDLE) atoi(val);
351 putenv(SHUTDOWN_EVENT_NAME"=");
353 if (! CreateThread(NULL, 0, ShutdownRequestThread,
354 shutdownEvent, 0, NULL))
361 * If an accept mutex is in the env, save it and remove it.
363 val = getenv(MUTEX_VARNAME);
366 acceptMutex = (HANDLE) atoi(val);
371 * Determine if this library is being used to listen for FastCGI
372 * connections. This is communicated by STDIN containing a
373 * valid handle to a listener object. In this case, both the
374 * "stdout" and "stderr" handles will be INVALID (ie. closed) by
375 * the starting process.
377 * The trick is determining if this is a pipe or a socket...
379 * XXX: Add the async accept test to determine socket or handle to a
382 if((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
383 (GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) &&
384 (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) )
386 DWORD pipeMode = PIPE_READMODE_BYTE | PIPE_WAIT;
387 HANDLE oldStdIn = GetStdHandle(STD_INPUT_HANDLE);
389 // Move the handle to a "low" number
390 if (! DuplicateHandle(GetCurrentProcess(), oldStdIn,
391 GetCurrentProcess(), &hListen,
392 0, TRUE, DUPLICATE_SAME_ACCESS))
397 if (! SetStdHandle(STD_INPUT_HANDLE, hListen))
402 CloseHandle(oldStdIn);
405 * Set the pipe handle state so that it operates in wait mode.
407 * NOTE: The listenFd is not mapped to a pseudo file descriptor
408 * as all work done on it is contained to the OS library.
410 * XXX: Initial assumption is that SetNamedPipeHandleState will
411 * fail if this is an IP socket...
413 if (SetNamedPipeHandleState(hListen, &pipeMode, NULL, NULL))
415 listenType = FD_PIPE_SYNC;
416 listenOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
420 listenType = FD_SOCKET_SYNC;
425 * If there are no stdioFds passed in, we're done.
427 if(stdioFds == NULL) {
433 * Setup standard input asynchronous I/O. There is actually a separate
434 * thread spawned for this purpose. The reason for this is that some
435 * web servers use anonymous pipes for the connection between itself
436 * and a CGI application. Anonymous pipes can't perform asynchronous
437 * I/O or use I/O completion ports. Therefore in order to present a
438 * consistent I/O dispatch model to an application we emulate I/O
439 * completion port behavior by having the standard input thread posting
440 * messages to the hIoCompPort which look like a complete overlapped
441 * I/O structure. This keeps the event dispatching simple from the
442 * application perspective.
444 stdioHandles[STDIN_FILENO] = GetStdHandle(STD_INPUT_HANDLE);
446 if(!SetHandleInformation(stdioHandles[STDIN_FILENO],
447 HANDLE_FLAG_INHERIT, 0)) {
449 * XXX: Causes error when run from command line. Check KB
450 err = GetLastError();
456 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
457 (int)stdioHandles[STDIN_FILENO],
458 STDIN_FILENO)) == -1) {
462 * Set stdin equal to our pseudo FD and create the I/O completion
463 * port to be used for async I/O.
465 stdioFds[STDIN_FILENO] = fakeFd;
469 * Create the I/O completion port to be used for communicating with
470 * the thread doing I/O on standard in. This port will carry read
471 * and possibly thread termination requests to the StdinThread.
473 if (hStdinCompPort == INVALID_HANDLE_VALUE) {
474 hStdinCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
476 if(hStdinCompPort == INVALID_HANDLE_VALUE) {
477 printf("<H2>OS_LibInit Failed CreateIoCompletionPort: STDIN! ERROR: %d</H2>\r\n\r\n",
484 * Create the thread that will read stdin if the CONTENT_LENGTH
487 if((cLenPtr = getenv("CONTENT_LENGTH")) != NULL &&
489 hStdinThread = CreateThread(NULL, 8192,
490 (LPTHREAD_START_ROUTINE)&StdinThread,
492 if (hStdinThread == NULL) {
493 printf("<H2>OS_LibInit Failed to create STDIN thread! ERROR: %d</H2>\r\n\r\n",
500 * STDOUT will be used synchronously.
502 * XXX: May want to convert this so that it could be used for OVERLAPPED
503 * I/O later. If so, model it after the Stdin I/O as stdout is
504 * also incapable of async I/O on some servers.
506 stdioHandles[STDOUT_FILENO] = GetStdHandle(STD_OUTPUT_HANDLE);
507 if(!SetHandleInformation(stdioHandles[STDOUT_FILENO],
508 HANDLE_FLAG_INHERIT, FALSE)) {
513 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
514 (int)stdioHandles[STDOUT_FILENO],
515 STDOUT_FILENO)) == -1) {
519 * Set stdout equal to our pseudo FD
521 stdioFds[STDOUT_FILENO] = fakeFd;
524 stdioHandles[STDERR_FILENO] = GetStdHandle(STD_ERROR_HANDLE);
525 if(!SetHandleInformation(stdioHandles[STDERR_FILENO],
526 HANDLE_FLAG_INHERIT, FALSE)) {
530 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
531 (int)stdioHandles[STDERR_FILENO],
532 STDERR_FILENO)) == -1) {
536 * Set stderr equal to our pseudo FD
538 stdioFds[STDERR_FILENO] = fakeFd;
545 *--------------------------------------------------------------
549 * Shutdown the OS library.
555 * Memory freed, handles closed.
557 *--------------------------------------------------------------
559 void OS_LibShutdown()
562 if (hIoCompPort != INVALID_HANDLE_VALUE)
564 CloseHandle(hIoCompPort);
565 hIoCompPort = INVALID_HANDLE_VALUE;
568 if (hStdinCompPort != INVALID_HANDLE_VALUE)
570 CloseHandle(hStdinCompPort);
571 hStdinCompPort = INVALID_HANDLE_VALUE;
574 if (acceptMutex != INVALID_HANDLE_VALUE)
576 ReleaseMutex(acceptMutex);
579 DisconnectNamedPipe(hListen);
588 *--------------------------------------------------------------
590 * Win32FreeDescriptor --
592 * Free I/O descriptor entry in fdTable.
595 * Frees I/O descriptor entry in fdTable.
600 *--------------------------------------------------------------
602 static void Win32FreeDescriptor(int fd)
604 /* Catch it if fd is a bogus value */
605 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
607 EnterCriticalSection(&fdTableCritical);
609 if (fdTable[fd].type != FD_UNUSED)
611 switch (fdTable[fd].type)
616 /* Free file path string */
617 ASSERT(fdTable[fd].path != NULL);
618 free(fdTable[fd].path);
619 fdTable[fd].path = NULL;
626 ASSERT(fdTable[fd].path == NULL);
628 fdTable[fd].type = FD_UNUSED;
629 fdTable[fd].path = NULL;
630 fdTable[fd].Errno = NO_ERROR;
631 fdTable[fd].offsetHighPtr = fdTable[fd].offsetLowPtr = NULL;
633 if (fdTable[fd].hMapMutex != NULL)
635 CloseHandle(fdTable[fd].hMapMutex);
636 fdTable[fd].hMapMutex = NULL;
640 LeaveCriticalSection(&fdTableCritical);
645 static short getPort(const char * bindPath)
648 char * p = strchr(bindPath, ':');
657 port = (short) atoi(buf);
664 * OS_CreateLocalIpcFd --
666 * This procedure is responsible for creating the listener pipe
667 * on Windows NT for local process communication. It will create a
668 * named pipe and return a file descriptor to it to the caller.
671 * Listener pipe created. This call returns either a valid
672 * pseudo file descriptor or -1 on error.
675 * Listener pipe and IPC address are stored in the FCGI info
677 * 'errno' will set on errors (-1 is returned).
679 *----------------------------------------------------------------------
681 int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
684 short port = getPort(bindPath);
685 HANDLE mutex = CreateMutex(NULL, FALSE, NULL);
686 char * mutexEnvString;
693 if (! SetHandleInformation(mutex, HANDLE_FLAG_INHERIT, TRUE))
698 // This is a nail for listening to more than one port..
699 // This should really be handled by the caller.
701 mutexEnvString = malloc(strlen(MUTEX_VARNAME) + 7);
702 sprintf(mutexEnvString, MUTEX_VARNAME "=%d", (int) mutex);
703 putenv(mutexEnvString);
705 // There's nothing to be gained (at the moment) by a shutdown Event
707 if (port && *bindPath != ':' && strncmp(bindPath, LOCALHOST, strlen(LOCALHOST)))
709 fprintf(stderr, "To start a service on a TCP port can not "
710 "specify a host name.\n"
711 "You should either use \"localhost:<port>\" or "
712 " just use \":<port>.\"\n");
716 listenType = (port) ? FD_SOCKET_SYNC : FD_PIPE_ASYNC;
721 struct sockaddr_in sockAddr;
722 int sockLen = sizeof(sockAddr);
724 memset(&sockAddr, 0, sizeof(sockAddr));
725 sockAddr.sin_family = AF_INET;
726 sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
727 sockAddr.sin_port = htons(port);
729 listenSock = socket(AF_INET, SOCK_STREAM, 0);
730 if (listenSock == INVALID_SOCKET)
735 if (! bind(listenSock, (struct sockaddr *) &sockAddr, sockLen)
736 || ! listen(listenSock, backlog))
741 pseudoFd = Win32NewDescriptor(listenType, listenSock, -1);
745 closesocket(listenSock);
749 hListen = (HANDLE) listenSock;
753 HANDLE hListenPipe = INVALID_HANDLE_VALUE;
754 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
761 strcpy(pipePath, bindPathPrefix);
762 strcat(pipePath, bindPath);
764 hListenPipe = CreateNamedPipe(pipePath,
765 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
766 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
767 PIPE_UNLIMITED_INSTANCES,
768 4096, 4096, 0, NULL);
772 if (hListenPipe == INVALID_HANDLE_VALUE)
777 if (! SetHandleInformation(hListenPipe, HANDLE_FLAG_INHERIT, TRUE))
782 pseudoFd = Win32NewDescriptor(listenType, (int) hListenPipe, -1);
786 CloseHandle(hListenPipe);
790 hListen = (HANDLE) hListenPipe;
797 *----------------------------------------------------------------------
801 * Create the pipe pathname connect to the remote application if
805 * -1 if fail or a valid handle if connection succeeds.
808 * Remote connection established.
810 *----------------------------------------------------------------------
812 int OS_FcgiConnect(char *bindPath)
814 short port = getPort(bindPath);
821 struct sockaddr_in sockAddr;
822 int sockLen = sizeof(sockAddr);
825 if (*bindPath != ':')
827 char * p = strchr(bindPath, ':');
828 int len = p - bindPath + 1;
831 strncpy(host, bindPath, len);
835 hp = gethostbyname(host ? host : LOCALHOST);
844 fprintf(stderr, "Unknown host: %s\n", bindPath);
848 memset(&sockAddr, 0, sizeof(sockAddr));
849 sockAddr.sin_family = AF_INET;
850 memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
851 sockAddr.sin_port = htons(port);
853 sock = socket(AF_INET, SOCK_STREAM, 0);
854 if (sock == INVALID_SOCKET)
859 if (! connect(sock, (struct sockaddr *) &sockAddr, sockLen))
865 pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, sock, -1);
874 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
882 strcpy(pipePath, bindPathPrefix);
883 strcat(pipePath, bindPath);
885 hPipe = CreateFile(pipePath,
886 GENERIC_WRITE | GENERIC_READ,
887 FILE_SHARE_READ | FILE_SHARE_WRITE,
890 FILE_FLAG_OVERLAPPED,
895 if( hPipe == INVALID_HANDLE_VALUE)
900 pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int) hPipe, -1);
909 * Set stdin equal to our pseudo FD and create the I/O completion
910 * port to be used for async I/O.
912 if (! CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1))
914 Win32FreeDescriptor(pseudoFd);
924 *--------------------------------------------------------------
928 * Pass through to the appropriate NT read function.
931 * Returns number of byes read. Mimics unix read:.
932 * n bytes read, 0 or -1 failure: errno contains actual error
937 *--------------------------------------------------------------
939 int OS_Read(int fd, char * buf, size_t len)
944 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
946 switch (fdTable[fd].type)
953 if (ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead, NULL))
959 fdTable[fd].Errno = GetLastError();
965 case FD_SOCKET_ASYNC:
967 ret = recv(fdTable[fd].fid.sock, buf, len, 0);
968 if (ret == SOCKET_ERROR)
970 fdTable[fd].Errno = WSAGetLastError();
985 *--------------------------------------------------------------
989 * Perform a synchronous OS write.
992 * Returns number of bytes written. Mimics unix write:
993 * n bytes written, 0 or -1 failure (??? couldn't find man page).
998 *--------------------------------------------------------------
1000 int OS_Write(int fd, char * buf, size_t len)
1005 ASSERT(fd >= 0 && fd < WIN32_OPEN_MAX);
1007 switch (fdTable[fd].type)
1014 if (WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten, NULL))
1020 fdTable[fd].Errno = GetLastError();
1025 case FD_SOCKET_SYNC:
1026 case FD_SOCKET_ASYNC:
1028 ret = send(fdTable[fd].fid.sock, buf, len, 0);
1029 if (ret == SOCKET_ERROR)
1031 fdTable[fd].Errno = WSAGetLastError();
1046 *----------------------------------------------------------------------
1050 * Spawns a new server listener process, and stores the information
1051 * relating to the child in the supplied record. A wait handler is
1052 * registered on the child's completion. This involves creating
1053 * a process on NT and preparing a command line with the required
1054 * state (currently a -childproc flag and the server socket to use
1055 * for accepting connections).
1058 * 0 if success, -1 if error.
1061 * Child process spawned.
1063 *----------------------------------------------------------------------
1065 int OS_SpawnChild(char *execPath, int listenFd)
1067 STARTUPINFO StartupInfo;
1068 PROCESS_INFORMATION pInfo;
1071 memset((void *)&StartupInfo, 0, sizeof(STARTUPINFO));
1072 StartupInfo.cb = sizeof (STARTUPINFO);
1073 StartupInfo.lpReserved = NULL;
1074 StartupInfo.lpReserved2 = NULL;
1075 StartupInfo.cbReserved2 = 0;
1076 StartupInfo.lpDesktop = NULL;
1079 * FastCGI on NT will set the listener pipe HANDLE in the stdin of
1080 * the new process. The fact that there is a stdin and NULL handles
1081 * for stdout and stderr tells the FastCGI process that this is a
1082 * FastCGI process and not a CGI process.
1084 StartupInfo.dwFlags = STARTF_USESTDHANDLES;
1086 * XXX: Do I have to dup the handle before spawning the process or is
1087 * it sufficient to use the handle as it's reference counted
1090 StartupInfo.hStdInput = fdTable[listenFd].fid.fileHandle;
1091 StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
1092 StartupInfo.hStdError = INVALID_HANDLE_VALUE;
1095 * Make the listener socket inheritable.
1097 success = SetHandleInformation(StartupInfo.hStdInput, HANDLE_FLAG_INHERIT,
1104 * XXX: Might want to apply some specific security attributes to the
1107 success = CreateProcess(execPath, /* LPCSTR address of module name */
1108 NULL, /* LPCSTR address of command line */
1109 NULL, /* Process security attributes */
1110 NULL, /* Thread security attributes */
1111 TRUE, /* Inheritable Handes inherited. */
1112 0, /* DWORD creation flags */
1113 NULL, /* Use parent environment block */
1114 NULL, /* Address of current directory name */
1115 &StartupInfo, /* Address of STARTUPINFO */
1116 &pInfo); /* Address of PROCESS_INFORMATION */
1125 *--------------------------------------------------------------
1127 * OS_AsyncReadStdin --
1129 * This initiates an asynchronous read on the standard
1130 * input handle. This handle is not guaranteed to be
1131 * capable of performing asynchronous I/O so we send a
1132 * message to the StdinThread to do the synchronous read.
1135 * -1 if error, 0 otherwise.
1138 * Asynchronous message is queued to the StdinThread and an
1139 * overlapped structure is allocated/initialized.
1141 *--------------------------------------------------------------
1143 int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
1144 ClientData clientData)
1146 POVERLAPPED_REQUEST pOv;
1148 ASSERT(fdTable[STDIN_FILENO].type != FD_UNUSED);
1150 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1152 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1153 pOv->clientData1 = (ClientData)buf;
1154 pOv->instance = fdTable[STDIN_FILENO].instance;
1155 pOv->procPtr = procPtr;
1156 pOv->clientData = clientData;
1158 PostQueuedCompletionStatus(hStdinCompPort, len, STDIN_FILENO,
1164 *--------------------------------------------------------------
1168 * This initiates an asynchronous read on the file
1169 * handle which may be a socket or named pipe.
1171 * We also must save the ProcPtr and ClientData, so later
1172 * when the io completes, we know who to call.
1174 * We don't look at any results here (the ReadFile may
1175 * return data if it is cached) but do all completion
1176 * processing in OS_Select when we get the io completion
1177 * port done notifications. Then we call the callback.
1180 * -1 if error, 0 otherwise.
1183 * Asynchronous I/O operation is queued for completion.
1185 *--------------------------------------------------------------
1187 int OS_AsyncRead(int fd, int offset, void *buf, int len,
1188 OS_AsyncProc procPtr, ClientData clientData)
1191 POVERLAPPED_REQUEST pOv;
1194 * Catch any bogus fd values
1196 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1198 * Confirm that this is an async fd
1200 ASSERT(fdTable[fd].type != FD_UNUSED);
1201 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1202 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1203 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1205 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1207 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1209 * Only file offsets should be non-zero, but make sure.
1211 if (fdTable[fd].type == FD_FILE_ASYNC)
1212 if (fdTable[fd].offset >= 0)
1213 pOv->overlapped.Offset = fdTable[fd].offset;
1215 pOv->overlapped.Offset = offset;
1216 pOv->instance = fdTable[fd].instance;
1217 pOv->procPtr = procPtr;
1218 pOv->clientData = clientData;
1221 * ReadFile returns: TRUE success, FALSE failure
1223 if (!ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead,
1224 (LPOVERLAPPED)pOv)) {
1225 fdTable[fd].Errno = GetLastError();
1226 if(fdTable[fd].Errno == ERROR_NO_DATA ||
1227 fdTable[fd].Errno == ERROR_PIPE_NOT_CONNECTED) {
1228 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1231 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1232 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1235 fdTable[fd].Errno = 0;
1241 *--------------------------------------------------------------
1245 * This initiates an asynchronous write on the "fake" file
1246 * descriptor (which may be a file, socket, or named pipe).
1247 * We also must save the ProcPtr and ClientData, so later
1248 * when the io completes, we know who to call.
1250 * We don't look at any results here (the WriteFile generally
1251 * completes immediately) but do all completion processing
1252 * in OS_DoIo when we get the io completion port done
1253 * notifications. Then we call the callback.
1256 * -1 if error, 0 otherwise.
1259 * Asynchronous I/O operation is queued for completion.
1261 *--------------------------------------------------------------
1263 int OS_AsyncWrite(int fd, int offset, void *buf, int len,
1264 OS_AsyncProc procPtr, ClientData clientData)
1267 POVERLAPPED_REQUEST pOv;
1270 * Catch any bogus fd values
1272 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1274 * Confirm that this is an async fd
1276 ASSERT(fdTable[fd].type != FD_UNUSED);
1277 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1278 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1279 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1281 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1283 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1285 * Only file offsets should be non-zero, but make sure.
1287 if (fdTable[fd].type == FD_FILE_ASYNC)
1289 * Only file opened via OS_AsyncWrite with
1290 * O_APPEND will have an offset != -1.
1292 if (fdTable[fd].offset >= 0)
1294 * If the descriptor has a memory mapped file
1295 * handle, take the offsets from there.
1297 if (fdTable[fd].hMapMutex != NULL) {
1299 * Wait infinitely; this *should* not cause problems.
1301 WaitForSingleObject(fdTable[fd].hMapMutex, INFINITE);
1304 * Retrieve the shared offset values.
1306 pOv->overlapped.OffsetHigh = *(fdTable[fd].offsetHighPtr);
1307 pOv->overlapped.Offset = *(fdTable[fd].offsetLowPtr);
1310 * Update the shared offset values for the next write
1312 *(fdTable[fd].offsetHighPtr) += 0; /* XXX How do I handle overflow */
1313 *(fdTable[fd].offsetLowPtr) += len;
1315 ReleaseMutex(fdTable[fd].hMapMutex);
1317 pOv->overlapped.Offset = fdTable[fd].offset;
1319 pOv->overlapped.Offset = offset;
1320 pOv->instance = fdTable[fd].instance;
1321 pOv->procPtr = procPtr;
1322 pOv->clientData = clientData;
1325 * WriteFile returns: TRUE success, FALSE failure
1327 if (!WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten,
1328 (LPOVERLAPPED)pOv)) {
1329 fdTable[fd].Errno = GetLastError();
1330 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1331 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1334 fdTable[fd].Errno = 0;
1336 if (fdTable[fd].offset >= 0)
1337 fdTable[fd].offset += len;
1342 *--------------------------------------------------------------
1346 * Closes the descriptor with routine appropriate for
1347 * descriptor's type.
1350 * Socket or file is closed. Return values mimic Unix close:
1351 * 0 success, -1 failure
1354 * Entry in fdTable is marked as free.
1356 *--------------------------------------------------------------
1358 int OS_Close(int fd)
1363 * Catch it if fd is a bogus value
1365 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1366 ASSERT(fdTable[fd].type != FD_UNUSED);
1368 switch (fdTable[fd].type) {
1375 case FD_SOCKET_SYNC:
1376 case FD_SOCKET_ASYNC:
1378 * Closing a socket that has an async read outstanding causes a
1379 * tcp reset and possible data loss. The shutdown call seems to
1382 shutdown(fdTable[fd].fid.sock, 2);
1384 * closesocket returns: 0 success, SOCKET_ERROR failure
1386 if (closesocket(fdTable[fd].fid.sock) == SOCKET_ERROR)
1390 return -1; /* fake failure */
1393 Win32FreeDescriptor(fd);
1398 *--------------------------------------------------------------
1402 * Cancel outstanding asynchronous reads and prevent subsequent
1403 * reads from completing.
1406 * Socket or file is shutdown. Return values mimic Unix shutdown:
1407 * 0 success, -1 failure
1409 *--------------------------------------------------------------
1411 int OS_CloseRead(int fd)
1416 * Catch it if fd is a bogus value
1418 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1419 ASSERT(fdTable[fd].type == FD_SOCKET_ASYNC
1420 || fdTable[fd].type == FD_SOCKET_SYNC);
1422 if (shutdown(fdTable[fd].fid.sock,0) == SOCKET_ERROR)
1428 *--------------------------------------------------------------
1432 * This function was formerly OS_Select. It's purpose is
1433 * to pull I/O completion events off the queue and dispatch
1434 * them to the appropriate place.
1440 * Handlers are called.
1442 *--------------------------------------------------------------
1444 int OS_DoIo(struct timeval *tmo)
1447 unsigned long bytes;
1448 POVERLAPPED_REQUEST pOv;
1455 * We can loop in here, but not too long, as wait handlers
1457 * For cgi stdin, apparently select returns when io completion
1458 * ports don't, so don't wait the full timeout.
1461 ms = (tmo->tv_sec*1000 + tmo->tv_usec/1000) / 2;
1465 ms_last = tb.time*1000 + tb.millitm;
1467 if(tmo && (ms = tmo->tv_sec*1000 + tmo->tv_usec/1000)> 100)
1469 if (!GetQueuedCompletionStatus(hIoCompPort, &bytes, &fd,
1470 (LPOVERLAPPED *)&pOv, ms) && !pOv) {
1471 err = WSAGetLastError();
1472 return 0; /* timeout */
1475 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1476 /* call callback if descriptor still valid */
1478 if(pOv->instance == fdTable[fd].instance)
1479 (*pOv->procPtr)(pOv->clientData, bytes);
1483 ms -= (tb.time*1000 + tb.millitm - ms_last);
1484 ms_last = tb.time*1000 + tb.millitm;
1490 static int CALLBACK isAddrOK(LPWSABUF lpCallerId,
1497 DWORD dwCallbackData)
1499 const char *okAddrs = (char *) dwCallbackData;
1500 struct sockaddr *sockaddr = (struct sockaddr *) lpCallerId->buf;
1502 // Touch the args to avoid warnings
1503 dc0 = NULL; dc1 = NULL; dc2 = NULL; dc3 = NULL; dc4 = NULL; dc5 = NULL;
1505 if (okAddrs == NULL || sockaddr->sa_family != AF_INET)
1511 static const char *token = " ,;:\t";
1512 struct sockaddr_in * inet_sockaddr = (struct sockaddr_in *) sockaddr;
1513 char *ipaddr = inet_ntoa(inet_sockaddr->sin_addr);
1514 char *p = strstr(okAddrs, ipaddr);
1520 else if (p == okAddrs)
1522 p += strlen(ipaddr);
1523 return (strchr(token, *p) != NULL);
1525 else if (strchr(token, *--p))
1527 p += strlen(ipaddr) + 1;
1528 return (strchr(token, *p) != NULL);
1537 static printLastError(const char * text)
1542 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1543 FORMAT_MESSAGE_FROM_SYSTEM |
1544 FORMAT_MESSAGE_IGNORE_INSERTS,
1553 fprintf(stderr, "%s: %s\n", text, (LPCTSTR) buf);
1557 static int acceptNamedPipe()
1561 if (! ConnectNamedPipe(hListen, &listenOverlapped))
1563 switch (GetLastError())
1565 case ERROR_PIPE_CONNECTED:
1567 // A client connected after CreateNamedPipe but
1568 // before ConnectNamedPipe. Its a good connection.
1572 case ERROR_IO_PENDING:
1574 // Wait for a connection to complete.
1576 while (WaitForSingleObject(listenOverlapped.hEvent,
1577 ACCEPT_TIMEOUT) == WAIT_TIMEOUT)
1579 if (shutdownPending)
1588 case ERROR_PIPE_LISTENING:
1590 // The pipe handle is in nonblocking mode.
1594 // The previous client closed its handle (and we failed
1595 // to call DisconnectNamedPipe)
1599 printLastError("unexpected ConnectNamedPipe() error");
1603 ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
1606 DisconnectNamedPipe(hListen);
1612 static int acceptSocket(const char *webServerAddrs)
1614 struct sockaddr sockaddr;
1615 int sockaddrLen = sizeof(sockaddr);
1617 const struct timeval timeout = {1, 0};
1622 FD_SET((unsigned int) hListen, &readfds);
1624 while (select(0, &readfds, NULL, NULL, &timeout) == 0)
1626 if (shutdownPending)
1633 hSock = (webServerAddrs == NULL)
1634 ? accept((SOCKET) hListen,
1637 : WSAAccept((unsigned int) hListen,
1641 (DWORD) webServerAddrs);
1644 if (hSock == INVALID_SOCKET)
1646 // Can I use FormatMessage()?
1647 fprintf(stderr, "accept()/WSAAccept() failed: %d", WSAGetLastError());
1651 ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
1661 *----------------------------------------------------------------------
1665 * Accepts a new FastCGI connection. This routine knows whether
1666 * we're dealing with TCP based sockets or NT Named Pipes for IPC.
1668 * fail_on_intr is ignored in the Win lib.
1671 * -1 if the operation fails, otherwise this is a valid IPC fd.
1673 *----------------------------------------------------------------------
1675 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
1679 // Touch args to prevent warnings
1680 listen_sock = 0; fail_on_intr = 0;
1682 // @todo Muliple listen sockets and sockets other than 0 are not
1683 // supported due to the use of globals.
1685 if (shutdownPending)
1691 // The mutex is to keep other processes (and threads, when supported)
1692 // from going into the accept cycle. The accept cycle needs to
1693 // periodically break out to check the state of the shutdown flag
1694 // and there's no point to having more than one thread do that.
1696 if (acceptMutex != INVALID_HANDLE_VALUE)
1698 if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED)
1700 printLastError("WaitForSingleObject() failed");
1705 if (shutdownPending)
1709 else if (listenType == FD_PIPE_SYNC)
1711 ipcFd = acceptNamedPipe();
1713 else if (listenType == FD_SOCKET_SYNC)
1715 ipcFd = acceptSocket(webServerAddrs);
1719 fprintf(stderr, "unknown listenType (%d)\n", listenType);
1722 if (acceptMutex != INVALID_HANDLE_VALUE)
1724 ReleaseMutex(acceptMutex);
1731 *----------------------------------------------------------------------
1735 * OS IPC routine to close an IPC connection.
1741 * IPC connection is closed.
1743 *----------------------------------------------------------------------
1745 int OS_IpcClose(int ipcFd)
1751 * Catch it if fd is a bogus value
1753 ASSERT((ipcFd >= 0) && (ipcFd < WIN32_OPEN_MAX));
1754 ASSERT(fdTable[ipcFd].type != FD_UNUSED);
1756 switch(listenType) {
1760 * Make sure that the client (ie. a Web Server in this case) has
1761 * read all data from the pipe before we disconnect.
1763 if(!FlushFileBuffers(fdTable[ipcFd].fid.fileHandle))
1765 if(DisconnectNamedPipe(fdTable[ipcFd].fid.fileHandle)) {
1773 case FD_SOCKET_SYNC:
1786 *----------------------------------------------------------------------
1790 * Determines whether this process is a FastCGI process or not.
1793 * Returns 1 if FastCGI, 0 if not.
1798 *----------------------------------------------------------------------
1800 int OS_IsFcgi(int sock)
1802 // Touch args to prevent warnings
1805 /* XXX This is broken for sock */
1807 return (listenType != FD_UNUSED);
1811 *----------------------------------------------------------------------
1815 * Sets selected flag bits in an open file descriptor. Currently
1816 * this is only to put a SOCKET into non-blocking mode.
1818 *----------------------------------------------------------------------
1820 void OS_SetFlags(int fd, int flags)
1822 unsigned long pLong = 1L;
1825 if (fdTable[fd].type == FD_SOCKET_SYNC && flags == O_NONBLOCK) {
1826 if (ioctlsocket(fdTable[fd].fid.sock, FIONBIO, &pLong) ==
1828 exit(WSAGetLastError());
1830 if (!CreateIoCompletionPort((HANDLE)fdTable[fd].fid.sock,
1831 hIoCompPort, fd, 1)) {
1832 err = GetLastError();
1836 fdTable[fd].type = FD_SOCKET_ASYNC;