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.21 2001/08/27 19:54:30 robs Exp $";
23 #define WIN32_LEAN_AND_MEAN
29 #include <sys/timeb.h>
31 #define DLLAPI __declspec(dllexport)
36 #define WIN32_OPEN_MAX 128 /* XXX: Small hack */
39 * millisecs to wait for a client connection before checking the
40 * shutdown flag (then go back to waiting for a connection, etc).
42 #define ACCEPT_TIMEOUT 1000
44 #define MUTEX_VARNAME "_FCGI_MUTEX_"
45 #define SHUTDOWN_EVENT_NAME "_FCGI_SHUTDOWN_EVENT_"
46 #define LOCALHOST "localhost"
48 static HANDLE hIoCompPort = INVALID_HANDLE_VALUE;
49 static HANDLE hStdinCompPort = INVALID_HANDLE_VALUE;
50 static HANDLE hStdinThread = INVALID_HANDLE_VALUE;
52 static HANDLE stdioHandles[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE,
53 INVALID_HANDLE_VALUE};
55 static HANDLE acceptMutex = INVALID_HANDLE_VALUE;
57 static BOOLEAN shutdownPending = FALSE;
60 * An enumeration of the file types
61 * supported by the FD_TABLE structure.
63 * XXX: Not all currently supported. This allows for future
83 * Structure used to map file handle and socket handle
84 * values into values that can be used to create unix-like
85 * select bitmaps, read/write for both sockets/files.
92 unsigned long instance;
94 int offset; /* only valid for async file writes */
95 LPDWORD offsetHighPtr; /* pointers to offset high and low words */
96 LPDWORD offsetLowPtr; /* only valid for async file writes (logs) */
97 HANDLE hMapMutex; /* mutex handle for multi-proc offset update */
98 LPVOID ovList; /* List of associated OVERLAPPED_REQUESTs */
102 * XXX Note there is no dyanmic sizing of this table, so if the
103 * number of open file descriptors exceeds WIN32_OPEN_MAX the
106 static struct FD_TABLE fdTable[WIN32_OPEN_MAX];
108 static CRITICAL_SECTION fdTableCritical;
110 struct OVERLAPPED_REQUEST {
111 OVERLAPPED overlapped;
112 unsigned long instance; /* file instance (won't match after a close) */
113 OS_AsyncProc procPtr; /* callback routine */
114 ClientData clientData; /* callback argument */
115 ClientData clientData1; /* additional clientData */
117 typedef struct OVERLAPPED_REQUEST *POVERLAPPED_REQUEST;
119 static const char *bindPathPrefix = "\\\\.\\pipe\\FastCGI\\";
121 static FILE_TYPE listenType = FD_UNUSED;
123 // XXX This should be a DESCRIPTOR
124 static HANDLE hListen = INVALID_HANDLE_VALUE;
126 static OVERLAPPED listenOverlapped;
127 static BOOLEAN libInitialized = FALSE;
130 *--------------------------------------------------------------
132 * Win32NewDescriptor --
134 * Set up for I/O descriptor masquerading.
137 * Returns "fake id" which masquerades as a UNIX-style "small
138 * non-negative integer" file/socket descriptor.
139 * Win32_* routine below will "do the right thing" based on the
140 * descriptor's actual type. -1 indicates failure.
143 * Entry in fdTable is reserved to represent the socket/file.
145 *--------------------------------------------------------------
147 static int Win32NewDescriptor(FILE_TYPE type, int fd, int desiredFd)
151 EnterCriticalSection(&fdTableCritical);
154 * If desiredFd is set, try to get this entry (this is used for
155 * mapping stdio handles). Otherwise try to get the fd entry.
156 * If this is not available, find a the first empty slot. .
158 if (desiredFd >= 0 && desiredFd < WIN32_OPEN_MAX)
160 if (fdTable[desiredFd].type == FD_UNUSED)
167 if (fd < WIN32_OPEN_MAX && fdTable[fd].type == FD_UNUSED)
175 for (i = 1; i < WIN32_OPEN_MAX; ++i)
177 if (fdTable[i].type == FD_UNUSED)
188 fdTable[index].fid.value = fd;
189 fdTable[index].type = type;
190 fdTable[index].path = NULL;
191 fdTable[index].Errno = NO_ERROR;
192 fdTable[index].status = 0;
193 fdTable[index].offset = -1;
194 fdTable[index].offsetHighPtr = fdTable[index].offsetLowPtr = NULL;
195 fdTable[index].hMapMutex = NULL;
196 fdTable[index].ovList = NULL;
199 LeaveCriticalSection(&fdTableCritical);
204 *--------------------------------------------------------------
208 * This thread performs I/O on stadard input. It is needed
209 * because you can't guarantee that all applications will
210 * create standard input with sufficient access to perform
211 * asynchronous I/O. Since we don't want to block the app
212 * reading from stdin we make it look like it's using I/O
213 * completion ports to perform async I/O.
216 * Data is read from stdin and posted to the io completion
222 *--------------------------------------------------------------
224 static void StdinThread(LPDWORD startup){
228 unsigned long bytesRead;
229 POVERLAPPED_REQUEST pOv;
231 // Touch the arg to prevent warning
236 * Block until a request to read from stdin comes in or a
237 * request to terminate the thread arrives (fd = -1).
239 if (!GetQueuedCompletionStatus(hStdinCompPort, &bytesRead, &fd,
240 (LPOVERLAPPED *)&pOv, (DWORD)-1) && !pOv) {
245 ASSERT((fd == STDIN_FILENO) || (fd == -1));
250 ASSERT(pOv->clientData1 != NULL);
252 if(ReadFile(stdioHandles[STDIN_FILENO], pOv->clientData1, bytesRead,
254 PostQueuedCompletionStatus(hIoCompPort, bytesRead,
255 STDIN_FILENO, (LPOVERLAPPED)pOv);
265 static DWORD WINAPI ShutdownRequestThread(LPVOID arg)
267 HANDLE shutdownEvent = (HANDLE) arg;
269 if (WaitForSingleObject(shutdownEvent, INFINITE) == WAIT_FAILED)
271 // Assuming it will happen again, all we can do is exit the thread
276 // "Simple reads and writes to properly-aligned 32-bit variables are atomic"
277 shutdownPending = TRUE;
279 // Before an accept() is entered the shutdownPending flag is checked.
280 // If set, OS_Accept() will return -1. If not, it waits
281 // on a connection request for one second, checks the flag, & repeats.
282 // Only one process/thread is allowed to do this at time by
283 // wrapping the accept() with mutex.
289 *--------------------------------------------------------------
293 * Set up the OS library for use.
296 * Returns 0 if success, -1 if not.
299 * Sockets initialized, pseudo file descriptors setup, etc.
301 *--------------------------------------------------------------
303 int OS_LibInit(int stdioFds[3])
310 char *cLenPtr = NULL;
316 InitializeCriticalSection(&fdTableCritical);
319 * Initialize windows sockets library.
321 wVersion = MAKEWORD(2,0);
322 err = WSAStartup( wVersion, &wsaData );
324 fprintf(stderr, "Error starting Windows Sockets. Error: %d",
330 * Create the I/O completion port to be used for our I/O queue.
332 if (hIoCompPort == INVALID_HANDLE_VALUE) {
333 hIoCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
335 if(hIoCompPort == INVALID_HANDLE_VALUE) {
336 printf("<H2>OS_LibInit Failed CreateIoCompletionPort! ERROR: %d</H2>\r\n\r\n",
343 * If a shutdown event is in the env, save it (I don't see any to
344 * remove it from the environment out from under the application).
345 * Spawn a thread to wait on the shutdown request.
347 val = getenv(SHUTDOWN_EVENT_NAME);
350 HANDLE shutdownEvent = (HANDLE) atoi(val);
352 if (! CreateThread(NULL, 0, ShutdownRequestThread,
353 shutdownEvent, 0, NULL))
360 * If an accept mutex is in the env, save it and remove it.
362 val = getenv(MUTEX_VARNAME);
365 acceptMutex = (HANDLE) atoi(val);
370 * Determine if this library is being used to listen for FastCGI
371 * connections. This is communicated by STDIN containing a
372 * valid handle to a listener object. In this case, both the
373 * "stdout" and "stderr" handles will be INVALID (ie. closed) by
374 * the starting process.
376 * The trick is determining if this is a pipe or a socket...
378 * XXX: Add the async accept test to determine socket or handle to a
381 if((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
382 (GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) &&
383 (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) )
385 DWORD pipeMode = PIPE_READMODE_BYTE | PIPE_WAIT;
386 HANDLE oldStdIn = GetStdHandle(STD_INPUT_HANDLE);
388 // Move the handle to a "low" number
389 if (! DuplicateHandle(GetCurrentProcess(), oldStdIn,
390 GetCurrentProcess(), &hListen,
391 0, TRUE, DUPLICATE_SAME_ACCESS))
396 if (! SetStdHandle(STD_INPUT_HANDLE, hListen))
401 CloseHandle(oldStdIn);
404 * Set the pipe handle state so that it operates in wait mode.
406 * NOTE: The listenFd is not mapped to a pseudo file descriptor
407 * as all work done on it is contained to the OS library.
409 * XXX: Initial assumption is that SetNamedPipeHandleState will
410 * fail if this is an IP socket...
412 if (SetNamedPipeHandleState(hListen, &pipeMode, NULL, NULL))
414 listenType = FD_PIPE_SYNC;
415 listenOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
419 listenType = FD_SOCKET_SYNC;
424 * If there are no stdioFds passed in, we're done.
426 if(stdioFds == NULL) {
432 * Setup standard input asynchronous I/O. There is actually a separate
433 * thread spawned for this purpose. The reason for this is that some
434 * web servers use anonymous pipes for the connection between itself
435 * and a CGI application. Anonymous pipes can't perform asynchronous
436 * I/O or use I/O completion ports. Therefore in order to present a
437 * consistent I/O dispatch model to an application we emulate I/O
438 * completion port behavior by having the standard input thread posting
439 * messages to the hIoCompPort which look like a complete overlapped
440 * I/O structure. This keeps the event dispatching simple from the
441 * application perspective.
443 stdioHandles[STDIN_FILENO] = GetStdHandle(STD_INPUT_HANDLE);
445 if(!SetHandleInformation(stdioHandles[STDIN_FILENO],
446 HANDLE_FLAG_INHERIT, 0)) {
448 * XXX: Causes error when run from command line. Check KB
449 err = GetLastError();
455 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
456 (int)stdioHandles[STDIN_FILENO],
457 STDIN_FILENO)) == -1) {
461 * Set stdin equal to our pseudo FD and create the I/O completion
462 * port to be used for async I/O.
464 stdioFds[STDIN_FILENO] = fakeFd;
468 * Create the I/O completion port to be used for communicating with
469 * the thread doing I/O on standard in. This port will carry read
470 * and possibly thread termination requests to the StdinThread.
472 if (hStdinCompPort == INVALID_HANDLE_VALUE) {
473 hStdinCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
475 if(hStdinCompPort == INVALID_HANDLE_VALUE) {
476 printf("<H2>OS_LibInit Failed CreateIoCompletionPort: STDIN! ERROR: %d</H2>\r\n\r\n",
483 * Create the thread that will read stdin if the CONTENT_LENGTH
486 if((cLenPtr = getenv("CONTENT_LENGTH")) != NULL &&
488 hStdinThread = CreateThread(NULL, 8192,
489 (LPTHREAD_START_ROUTINE)&StdinThread,
491 if (hStdinThread == NULL) {
492 printf("<H2>OS_LibInit Failed to create STDIN thread! ERROR: %d</H2>\r\n\r\n",
499 * STDOUT will be used synchronously.
501 * XXX: May want to convert this so that it could be used for OVERLAPPED
502 * I/O later. If so, model it after the Stdin I/O as stdout is
503 * also incapable of async I/O on some servers.
505 stdioHandles[STDOUT_FILENO] = GetStdHandle(STD_OUTPUT_HANDLE);
506 if(!SetHandleInformation(stdioHandles[STDOUT_FILENO],
507 HANDLE_FLAG_INHERIT, FALSE)) {
512 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
513 (int)stdioHandles[STDOUT_FILENO],
514 STDOUT_FILENO)) == -1) {
518 * Set stdout equal to our pseudo FD
520 stdioFds[STDOUT_FILENO] = fakeFd;
523 stdioHandles[STDERR_FILENO] = GetStdHandle(STD_ERROR_HANDLE);
524 if(!SetHandleInformation(stdioHandles[STDERR_FILENO],
525 HANDLE_FLAG_INHERIT, FALSE)) {
529 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
530 (int)stdioHandles[STDERR_FILENO],
531 STDERR_FILENO)) == -1) {
535 * Set stderr equal to our pseudo FD
537 stdioFds[STDERR_FILENO] = fakeFd;
544 *--------------------------------------------------------------
548 * Shutdown the OS library.
554 * Memory freed, handles closed.
556 *--------------------------------------------------------------
558 void OS_LibShutdown()
561 if (hIoCompPort != INVALID_HANDLE_VALUE)
563 CloseHandle(hIoCompPort);
564 hIoCompPort = INVALID_HANDLE_VALUE;
567 if (hStdinCompPort != INVALID_HANDLE_VALUE)
569 CloseHandle(hStdinCompPort);
570 hStdinCompPort = INVALID_HANDLE_VALUE;
573 if (acceptMutex != INVALID_HANDLE_VALUE)
575 ReleaseMutex(acceptMutex);
578 DisconnectNamedPipe(hListen);
587 *--------------------------------------------------------------
589 * Win32FreeDescriptor --
591 * Free I/O descriptor entry in fdTable.
594 * Frees I/O descriptor entry in fdTable.
599 *--------------------------------------------------------------
601 static void Win32FreeDescriptor(int fd)
603 /* Catch it if fd is a bogus value */
604 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
606 EnterCriticalSection(&fdTableCritical);
608 if (fdTable[fd].type != FD_UNUSED)
610 switch (fdTable[fd].type)
615 /* Free file path string */
616 ASSERT(fdTable[fd].path != NULL);
617 free(fdTable[fd].path);
618 fdTable[fd].path = NULL;
625 ASSERT(fdTable[fd].path == NULL);
627 fdTable[fd].type = FD_UNUSED;
628 fdTable[fd].path = NULL;
629 fdTable[fd].Errno = NO_ERROR;
630 fdTable[fd].offsetHighPtr = fdTable[fd].offsetLowPtr = NULL;
632 if (fdTable[fd].hMapMutex != NULL)
634 CloseHandle(fdTable[fd].hMapMutex);
635 fdTable[fd].hMapMutex = NULL;
639 LeaveCriticalSection(&fdTableCritical);
644 static short getPort(const char * bindPath)
647 char * p = strchr(bindPath, ':');
656 port = (short) atoi(buf);
663 * OS_CreateLocalIpcFd --
665 * This procedure is responsible for creating the listener pipe
666 * on Windows NT for local process communication. It will create a
667 * named pipe and return a file descriptor to it to the caller.
670 * Listener pipe created. This call returns either a valid
671 * pseudo file descriptor or -1 on error.
674 * Listener pipe and IPC address are stored in the FCGI info
676 * 'errno' will set on errors (-1 is returned).
678 *----------------------------------------------------------------------
680 int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
683 short port = getPort(bindPath);
684 HANDLE mutex = CreateMutex(NULL, FALSE, NULL);
685 char * mutexEnvString;
692 if (! SetHandleInformation(mutex, HANDLE_FLAG_INHERIT, TRUE))
697 // This is a nail for listening to more than one port..
698 // This should really be handled by the caller.
700 mutexEnvString = malloc(strlen(MUTEX_VARNAME) + 7);
701 sprintf(mutexEnvString, MUTEX_VARNAME "=%d", (int) mutex);
702 putenv(mutexEnvString);
704 // There's nothing to be gained (at the moment) by a shutdown Event
706 if (port && *bindPath != ':' && strncmp(bindPath, LOCALHOST, strlen(LOCALHOST)))
708 fprintf(stderr, "To start a service on a TCP port can not "
709 "specify a host name.\n"
710 "You should either use \"localhost:<port>\" or "
711 " just use \":<port>.\"\n");
715 listenType = (port) ? FD_SOCKET_SYNC : FD_PIPE_ASYNC;
720 struct sockaddr_in sockAddr;
721 int sockLen = sizeof(sockAddr);
723 memset(&sockAddr, 0, sizeof(sockAddr));
724 sockAddr.sin_family = AF_INET;
725 sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
726 sockAddr.sin_port = htons(port);
728 listenSock = socket(AF_INET, SOCK_STREAM, 0);
729 if (listenSock == INVALID_SOCKET)
734 if (! bind(listenSock, (struct sockaddr *) &sockAddr, sockLen)
735 || ! listen(listenSock, backlog))
740 pseudoFd = Win32NewDescriptor(listenType, listenSock, -1);
744 closesocket(listenSock);
748 hListen = (HANDLE) listenSock;
752 HANDLE hListenPipe = INVALID_HANDLE_VALUE;
753 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
760 strcpy(pipePath, bindPathPrefix);
761 strcat(pipePath, bindPath);
763 hListenPipe = CreateNamedPipe(pipePath,
764 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
765 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
766 PIPE_UNLIMITED_INSTANCES,
767 4096, 4096, 0, NULL);
771 if (hListenPipe == INVALID_HANDLE_VALUE)
776 if (! SetHandleInformation(hListenPipe, HANDLE_FLAG_INHERIT, TRUE))
781 pseudoFd = Win32NewDescriptor(listenType, (int) hListenPipe, -1);
785 CloseHandle(hListenPipe);
789 hListen = (HANDLE) hListenPipe;
796 *----------------------------------------------------------------------
800 * Create the pipe pathname connect to the remote application if
804 * -1 if fail or a valid handle if connection succeeds.
807 * Remote connection established.
809 *----------------------------------------------------------------------
811 int OS_FcgiConnect(char *bindPath)
813 short port = getPort(bindPath);
820 struct sockaddr_in sockAddr;
821 int sockLen = sizeof(sockAddr);
824 if (*bindPath != ':')
826 char * p = strchr(bindPath, ':');
827 int len = p - bindPath + 1;
830 strncpy(host, bindPath, len);
834 hp = gethostbyname(host ? host : LOCALHOST);
843 fprintf(stderr, "Unknown host: %s\n", bindPath);
847 memset(&sockAddr, 0, sizeof(sockAddr));
848 sockAddr.sin_family = AF_INET;
849 memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
850 sockAddr.sin_port = htons(port);
852 sock = socket(AF_INET, SOCK_STREAM, 0);
853 if (sock == INVALID_SOCKET)
858 if (! connect(sock, (struct sockaddr *) &sockAddr, sockLen))
864 pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, sock, -1);
873 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
881 strcpy(pipePath, bindPathPrefix);
882 strcat(pipePath, bindPath);
884 hPipe = CreateFile(pipePath,
885 GENERIC_WRITE | GENERIC_READ,
886 FILE_SHARE_READ | FILE_SHARE_WRITE,
889 FILE_FLAG_OVERLAPPED,
894 if( hPipe == INVALID_HANDLE_VALUE)
899 pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int) hPipe, -1);
908 * Set stdin equal to our pseudo FD and create the I/O completion
909 * port to be used for async I/O.
911 if (! CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1))
913 Win32FreeDescriptor(pseudoFd);
923 *--------------------------------------------------------------
927 * Pass through to the appropriate NT read function.
930 * Returns number of byes read. Mimics unix read:.
931 * n bytes read, 0 or -1 failure: errno contains actual error
936 *--------------------------------------------------------------
938 int OS_Read(int fd, char * buf, size_t len)
943 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
945 switch (fdTable[fd].type)
952 if (ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead, NULL))
958 fdTable[fd].Errno = GetLastError();
964 case FD_SOCKET_ASYNC:
966 ret = recv(fdTable[fd].fid.sock, buf, len, 0);
967 if (ret == SOCKET_ERROR)
969 fdTable[fd].Errno = WSAGetLastError();
984 *--------------------------------------------------------------
988 * Perform a synchronous OS write.
991 * Returns number of bytes written. Mimics unix write:
992 * n bytes written, 0 or -1 failure (??? couldn't find man page).
997 *--------------------------------------------------------------
999 int OS_Write(int fd, char * buf, size_t len)
1004 ASSERT(fd >= 0 && fd < WIN32_OPEN_MAX);
1006 switch (fdTable[fd].type)
1013 if (WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten, NULL))
1019 fdTable[fd].Errno = GetLastError();
1024 case FD_SOCKET_SYNC:
1025 case FD_SOCKET_ASYNC:
1027 ret = send(fdTable[fd].fid.sock, buf, len, 0);
1028 if (ret == SOCKET_ERROR)
1030 fdTable[fd].Errno = WSAGetLastError();
1045 *----------------------------------------------------------------------
1049 * Spawns a new server listener process, and stores the information
1050 * relating to the child in the supplied record. A wait handler is
1051 * registered on the child's completion. This involves creating
1052 * a process on NT and preparing a command line with the required
1053 * state (currently a -childproc flag and the server socket to use
1054 * for accepting connections).
1057 * 0 if success, -1 if error.
1060 * Child process spawned.
1062 *----------------------------------------------------------------------
1064 int OS_SpawnChild(char *execPath, int listenFd)
1066 STARTUPINFO StartupInfo;
1067 PROCESS_INFORMATION pInfo;
1070 memset((void *)&StartupInfo, 0, sizeof(STARTUPINFO));
1071 StartupInfo.cb = sizeof (STARTUPINFO);
1072 StartupInfo.lpReserved = NULL;
1073 StartupInfo.lpReserved2 = NULL;
1074 StartupInfo.cbReserved2 = 0;
1075 StartupInfo.lpDesktop = NULL;
1078 * FastCGI on NT will set the listener pipe HANDLE in the stdin of
1079 * the new process. The fact that there is a stdin and NULL handles
1080 * for stdout and stderr tells the FastCGI process that this is a
1081 * FastCGI process and not a CGI process.
1083 StartupInfo.dwFlags = STARTF_USESTDHANDLES;
1085 * XXX: Do I have to dup the handle before spawning the process or is
1086 * it sufficient to use the handle as it's reference counted
1089 StartupInfo.hStdInput = fdTable[listenFd].fid.fileHandle;
1090 StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
1091 StartupInfo.hStdError = INVALID_HANDLE_VALUE;
1094 * Make the listener socket inheritable.
1096 success = SetHandleInformation(StartupInfo.hStdInput, HANDLE_FLAG_INHERIT,
1103 * XXX: Might want to apply some specific security attributes to the
1106 success = CreateProcess(execPath, /* LPCSTR address of module name */
1107 NULL, /* LPCSTR address of command line */
1108 NULL, /* Process security attributes */
1109 NULL, /* Thread security attributes */
1110 TRUE, /* Inheritable Handes inherited. */
1111 0, /* DWORD creation flags */
1112 NULL, /* Use parent environment block */
1113 NULL, /* Address of current directory name */
1114 &StartupInfo, /* Address of STARTUPINFO */
1115 &pInfo); /* Address of PROCESS_INFORMATION */
1124 *--------------------------------------------------------------
1126 * OS_AsyncReadStdin --
1128 * This initiates an asynchronous read on the standard
1129 * input handle. This handle is not guaranteed to be
1130 * capable of performing asynchronous I/O so we send a
1131 * message to the StdinThread to do the synchronous read.
1134 * -1 if error, 0 otherwise.
1137 * Asynchronous message is queued to the StdinThread and an
1138 * overlapped structure is allocated/initialized.
1140 *--------------------------------------------------------------
1142 int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
1143 ClientData clientData)
1145 POVERLAPPED_REQUEST pOv;
1147 ASSERT(fdTable[STDIN_FILENO].type != FD_UNUSED);
1149 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1151 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1152 pOv->clientData1 = (ClientData)buf;
1153 pOv->instance = fdTable[STDIN_FILENO].instance;
1154 pOv->procPtr = procPtr;
1155 pOv->clientData = clientData;
1157 PostQueuedCompletionStatus(hStdinCompPort, len, STDIN_FILENO,
1163 *--------------------------------------------------------------
1167 * This initiates an asynchronous read on the file
1168 * handle which may be a socket or named pipe.
1170 * We also must save the ProcPtr and ClientData, so later
1171 * when the io completes, we know who to call.
1173 * We don't look at any results here (the ReadFile may
1174 * return data if it is cached) but do all completion
1175 * processing in OS_Select when we get the io completion
1176 * port done notifications. Then we call the callback.
1179 * -1 if error, 0 otherwise.
1182 * Asynchronous I/O operation is queued for completion.
1184 *--------------------------------------------------------------
1186 int OS_AsyncRead(int fd, int offset, void *buf, int len,
1187 OS_AsyncProc procPtr, ClientData clientData)
1190 POVERLAPPED_REQUEST pOv;
1193 * Catch any bogus fd values
1195 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1197 * Confirm that this is an async fd
1199 ASSERT(fdTable[fd].type != FD_UNUSED);
1200 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1201 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1202 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1204 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1206 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1208 * Only file offsets should be non-zero, but make sure.
1210 if (fdTable[fd].type == FD_FILE_ASYNC)
1211 if (fdTable[fd].offset >= 0)
1212 pOv->overlapped.Offset = fdTable[fd].offset;
1214 pOv->overlapped.Offset = offset;
1215 pOv->instance = fdTable[fd].instance;
1216 pOv->procPtr = procPtr;
1217 pOv->clientData = clientData;
1220 * ReadFile returns: TRUE success, FALSE failure
1222 if (!ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead,
1223 (LPOVERLAPPED)pOv)) {
1224 fdTable[fd].Errno = GetLastError();
1225 if(fdTable[fd].Errno == ERROR_NO_DATA ||
1226 fdTable[fd].Errno == ERROR_PIPE_NOT_CONNECTED) {
1227 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1230 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1231 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1234 fdTable[fd].Errno = 0;
1240 *--------------------------------------------------------------
1244 * This initiates an asynchronous write on the "fake" file
1245 * descriptor (which may be a file, socket, or named pipe).
1246 * We also must save the ProcPtr and ClientData, so later
1247 * when the io completes, we know who to call.
1249 * We don't look at any results here (the WriteFile generally
1250 * completes immediately) but do all completion processing
1251 * in OS_DoIo when we get the io completion port done
1252 * notifications. Then we call the callback.
1255 * -1 if error, 0 otherwise.
1258 * Asynchronous I/O operation is queued for completion.
1260 *--------------------------------------------------------------
1262 int OS_AsyncWrite(int fd, int offset, void *buf, int len,
1263 OS_AsyncProc procPtr, ClientData clientData)
1266 POVERLAPPED_REQUEST pOv;
1269 * Catch any bogus fd values
1271 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1273 * Confirm that this is an async fd
1275 ASSERT(fdTable[fd].type != FD_UNUSED);
1276 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1277 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1278 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1280 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1282 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1284 * Only file offsets should be non-zero, but make sure.
1286 if (fdTable[fd].type == FD_FILE_ASYNC)
1288 * Only file opened via OS_AsyncWrite with
1289 * O_APPEND will have an offset != -1.
1291 if (fdTable[fd].offset >= 0)
1293 * If the descriptor has a memory mapped file
1294 * handle, take the offsets from there.
1296 if (fdTable[fd].hMapMutex != NULL) {
1298 * Wait infinitely; this *should* not cause problems.
1300 WaitForSingleObject(fdTable[fd].hMapMutex, INFINITE);
1303 * Retrieve the shared offset values.
1305 pOv->overlapped.OffsetHigh = *(fdTable[fd].offsetHighPtr);
1306 pOv->overlapped.Offset = *(fdTable[fd].offsetLowPtr);
1309 * Update the shared offset values for the next write
1311 *(fdTable[fd].offsetHighPtr) += 0; /* XXX How do I handle overflow */
1312 *(fdTable[fd].offsetLowPtr) += len;
1314 ReleaseMutex(fdTable[fd].hMapMutex);
1316 pOv->overlapped.Offset = fdTable[fd].offset;
1318 pOv->overlapped.Offset = offset;
1319 pOv->instance = fdTable[fd].instance;
1320 pOv->procPtr = procPtr;
1321 pOv->clientData = clientData;
1324 * WriteFile returns: TRUE success, FALSE failure
1326 if (!WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten,
1327 (LPOVERLAPPED)pOv)) {
1328 fdTable[fd].Errno = GetLastError();
1329 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1330 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1333 fdTable[fd].Errno = 0;
1335 if (fdTable[fd].offset >= 0)
1336 fdTable[fd].offset += len;
1341 *--------------------------------------------------------------
1345 * Closes the descriptor with routine appropriate for
1346 * descriptor's type.
1349 * Socket or file is closed. Return values mimic Unix close:
1350 * 0 success, -1 failure
1353 * Entry in fdTable is marked as free.
1355 *--------------------------------------------------------------
1357 int OS_Close(int fd)
1362 * Catch it if fd is a bogus value
1364 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1365 ASSERT(fdTable[fd].type != FD_UNUSED);
1367 switch (fdTable[fd].type) {
1374 case FD_SOCKET_SYNC:
1375 case FD_SOCKET_ASYNC:
1377 * Closing a socket that has an async read outstanding causes a
1378 * tcp reset and possible data loss. The shutdown call seems to
1381 shutdown(fdTable[fd].fid.sock, 2);
1383 * closesocket returns: 0 success, SOCKET_ERROR failure
1385 if (closesocket(fdTable[fd].fid.sock) == SOCKET_ERROR)
1389 return -1; /* fake failure */
1392 Win32FreeDescriptor(fd);
1397 *--------------------------------------------------------------
1401 * Cancel outstanding asynchronous reads and prevent subsequent
1402 * reads from completing.
1405 * Socket or file is shutdown. Return values mimic Unix shutdown:
1406 * 0 success, -1 failure
1408 *--------------------------------------------------------------
1410 int OS_CloseRead(int fd)
1415 * Catch it if fd is a bogus value
1417 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1418 ASSERT(fdTable[fd].type == FD_SOCKET_ASYNC
1419 || fdTable[fd].type == FD_SOCKET_SYNC);
1421 if (shutdown(fdTable[fd].fid.sock,0) == SOCKET_ERROR)
1427 *--------------------------------------------------------------
1431 * This function was formerly OS_Select. It's purpose is
1432 * to pull I/O completion events off the queue and dispatch
1433 * them to the appropriate place.
1439 * Handlers are called.
1441 *--------------------------------------------------------------
1443 int OS_DoIo(struct timeval *tmo)
1446 unsigned long bytes;
1447 POVERLAPPED_REQUEST pOv;
1454 * We can loop in here, but not too long, as wait handlers
1456 * For cgi stdin, apparently select returns when io completion
1457 * ports don't, so don't wait the full timeout.
1460 ms = (tmo->tv_sec*1000 + tmo->tv_usec/1000) / 2;
1464 ms_last = tb.time*1000 + tb.millitm;
1466 if(tmo && (ms = tmo->tv_sec*1000 + tmo->tv_usec/1000)> 100)
1468 if (!GetQueuedCompletionStatus(hIoCompPort, &bytes, &fd,
1469 (LPOVERLAPPED *)&pOv, ms) && !pOv) {
1470 err = WSAGetLastError();
1471 return 0; /* timeout */
1474 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1475 /* call callback if descriptor still valid */
1477 if(pOv->instance == fdTable[fd].instance)
1478 (*pOv->procPtr)(pOv->clientData, bytes);
1482 ms -= (tb.time*1000 + tb.millitm - ms_last);
1483 ms_last = tb.time*1000 + tb.millitm;
1489 static int CALLBACK isAddrOK(LPWSABUF lpCallerId,
1496 DWORD dwCallbackData)
1498 const char *okAddrs = (char *) dwCallbackData;
1499 struct sockaddr *sockaddr = (struct sockaddr *) lpCallerId->buf;
1501 // Touch the args to avoid warnings
1502 dc0 = NULL; dc1 = NULL; dc2 = NULL; dc3 = NULL; dc4 = NULL; dc5 = NULL;
1504 if (okAddrs == NULL || sockaddr->sa_family != AF_INET)
1510 static const char *token = " ,;:\t";
1511 struct sockaddr_in * inet_sockaddr = (struct sockaddr_in *) sockaddr;
1512 char *ipaddr = inet_ntoa(inet_sockaddr->sin_addr);
1513 char *p = strstr(okAddrs, ipaddr);
1519 else if (p == okAddrs)
1521 p += strlen(ipaddr);
1522 return (strchr(token, *p) != NULL);
1524 else if (strchr(token, *--p))
1526 p += strlen(ipaddr) + 1;
1527 return (strchr(token, *p) != NULL);
1536 static printLastError(const char * text)
1541 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1542 FORMAT_MESSAGE_FROM_SYSTEM |
1543 FORMAT_MESSAGE_IGNORE_INSERTS,
1552 fprintf(stderr, "%s: %s\n", text, (LPCTSTR) buf);
1556 static int acceptNamedPipe()
1560 if (! ConnectNamedPipe(hListen, &listenOverlapped))
1562 switch (GetLastError())
1564 case ERROR_PIPE_CONNECTED:
1566 // A client connected after CreateNamedPipe but
1567 // before ConnectNamedPipe. Its a good connection.
1571 case ERROR_IO_PENDING:
1573 // Wait for a connection to complete.
1575 while (WaitForSingleObject(listenOverlapped.hEvent,
1576 ACCEPT_TIMEOUT) == WAIT_TIMEOUT)
1578 if (shutdownPending)
1587 case ERROR_PIPE_LISTENING:
1589 // The pipe handle is in nonblocking mode.
1593 // The previous client closed its handle (and we failed
1594 // to call DisconnectNamedPipe)
1598 printLastError("unexpected ConnectNamedPipe() error");
1602 ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
1605 DisconnectNamedPipe(hListen);
1611 static int acceptSocket(const char *webServerAddrs)
1613 struct sockaddr sockaddr;
1614 int sockaddrLen = sizeof(sockaddr);
1616 const struct timeval timeout = {1, 0};
1621 FD_SET((unsigned int) hListen, &readfds);
1623 while (select(0, &readfds, NULL, NULL, &timeout) == 0)
1625 if (shutdownPending)
1632 hSock = (webServerAddrs == NULL)
1633 ? accept((SOCKET) hListen,
1636 : WSAAccept((unsigned int) hListen,
1640 (DWORD) webServerAddrs);
1643 if (hSock == INVALID_SOCKET)
1645 // Can I use FormatMessage()?
1646 fprintf(stderr, "accept()/WSAAccept() failed: %d", WSAGetLastError());
1650 ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
1660 *----------------------------------------------------------------------
1664 * Accepts a new FastCGI connection. This routine knows whether
1665 * we're dealing with TCP based sockets or NT Named Pipes for IPC.
1667 * fail_on_intr is ignored in the Win lib.
1670 * -1 if the operation fails, otherwise this is a valid IPC fd.
1672 *----------------------------------------------------------------------
1674 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
1678 // Touch args to prevent warnings
1679 listen_sock = 0; fail_on_intr = 0;
1681 // @todo Muliple listen sockets and sockets other than 0 are not
1682 // supported due to the use of globals.
1684 if (shutdownPending)
1690 // The mutex is to keep other processes (and threads, when supported)
1691 // from going into the accept cycle. The accept cycle needs to
1692 // periodically break out to check the state of the shutdown flag
1693 // and there's no point to having more than one thread do that.
1695 if (acceptMutex != INVALID_HANDLE_VALUE)
1697 if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED)
1699 printLastError("WaitForSingleObject() failed");
1704 if (shutdownPending)
1708 else if (listenType == FD_PIPE_SYNC)
1710 ipcFd = acceptNamedPipe();
1712 else if (listenType == FD_SOCKET_SYNC)
1714 ipcFd = acceptSocket(webServerAddrs);
1718 fprintf(stderr, "unknown listenType (%d)\n", listenType);
1721 if (acceptMutex != INVALID_HANDLE_VALUE)
1723 ReleaseMutex(acceptMutex);
1730 *----------------------------------------------------------------------
1734 * OS IPC routine to close an IPC connection.
1740 * IPC connection is closed.
1742 *----------------------------------------------------------------------
1744 int OS_IpcClose(int ipcFd)
1750 * Catch it if fd is a bogus value
1752 ASSERT((ipcFd >= 0) && (ipcFd < WIN32_OPEN_MAX));
1753 ASSERT(fdTable[ipcFd].type != FD_UNUSED);
1755 switch(listenType) {
1759 * Make sure that the client (ie. a Web Server in this case) has
1760 * read all data from the pipe before we disconnect.
1762 if(!FlushFileBuffers(fdTable[ipcFd].fid.fileHandle))
1764 if(DisconnectNamedPipe(fdTable[ipcFd].fid.fileHandle)) {
1772 case FD_SOCKET_SYNC:
1785 *----------------------------------------------------------------------
1789 * Determines whether this process is a FastCGI process or not.
1792 * Returns 1 if FastCGI, 0 if not.
1797 *----------------------------------------------------------------------
1799 int OS_IsFcgi(int sock)
1801 // Touch args to prevent warnings
1804 /* XXX This is broken for sock */
1806 return (listenType != FD_UNUSED);
1810 *----------------------------------------------------------------------
1814 * Sets selected flag bits in an open file descriptor. Currently
1815 * this is only to put a SOCKET into non-blocking mode.
1817 *----------------------------------------------------------------------
1819 void OS_SetFlags(int fd, int flags)
1821 unsigned long pLong = 1L;
1824 if (fdTable[fd].type == FD_SOCKET_SYNC && flags == O_NONBLOCK) {
1825 if (ioctlsocket(fdTable[fd].fid.sock, FIONBIO, &pLong) ==
1827 exit(WSAGetLastError());
1829 if (!CreateIoCompletionPort((HANDLE)fdTable[fd].fid.sock,
1830 hIoCompPort, fd, 1)) {
1831 err = GetLastError();
1835 fdTable[fd].type = FD_SOCKET_ASYNC;