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.29 2002/02/24 15:07:03 robs Exp $";
23 #define WIN32_LEAN_AND_MEAN
29 #include <sys/timeb.h>
32 #define DLLAPI __declspec(dllexport)
37 #define WIN32_OPEN_MAX 128 /* XXX: Small hack */
40 * millisecs to wait for a client connection before checking the
41 * shutdown flag (then go back to waiting for a connection, etc).
43 #define ACCEPT_TIMEOUT 1000
45 #define MUTEX_VARNAME "_FCGI_MUTEX_"
46 #define SHUTDOWN_EVENT_NAME "_FCGI_SHUTDOWN_EVENT_"
47 #define LOCALHOST "localhost"
49 static HANDLE hIoCompPort = INVALID_HANDLE_VALUE;
50 static HANDLE hStdinCompPort = INVALID_HANDLE_VALUE;
51 static HANDLE hStdinThread = INVALID_HANDLE_VALUE;
53 static HANDLE stdioHandles[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE,
54 INVALID_HANDLE_VALUE};
56 // This is a nail for listening to more than one port..
57 static HANDLE acceptMutex = INVALID_HANDLE_VALUE;
59 static BOOLEAN shutdownPending = FALSE;
60 static BOOLEAN shutdownNow = FALSE;
63 * An enumeration of the file types
64 * supported by the FD_TABLE structure.
66 * XXX: Not all currently supported. This allows for future
86 * Structure used to map file handle and socket handle
87 * values into values that can be used to create unix-like
88 * select bitmaps, read/write for both sockets/files.
95 unsigned long instance;
97 int offset; /* only valid for async file writes */
98 LPDWORD offsetHighPtr; /* pointers to offset high and low words */
99 LPDWORD offsetLowPtr; /* only valid for async file writes (logs) */
100 HANDLE hMapMutex; /* mutex handle for multi-proc offset update */
101 LPVOID ovList; /* List of associated OVERLAPPED_REQUESTs */
105 * XXX Note there is no dyanmic sizing of this table, so if the
106 * number of open file descriptors exceeds WIN32_OPEN_MAX the
109 static struct FD_TABLE fdTable[WIN32_OPEN_MAX];
111 static CRITICAL_SECTION fdTableCritical;
113 struct OVERLAPPED_REQUEST {
114 OVERLAPPED overlapped;
115 unsigned long instance; /* file instance (won't match after a close) */
116 OS_AsyncProc procPtr; /* callback routine */
117 ClientData clientData; /* callback argument */
118 ClientData clientData1; /* additional clientData */
120 typedef struct OVERLAPPED_REQUEST *POVERLAPPED_REQUEST;
122 static const char *bindPathPrefix = "\\\\.\\pipe\\FastCGI\\";
124 static FILE_TYPE listenType = FD_UNUSED;
126 // XXX This should be a DESCRIPTOR
127 static HANDLE hListen = INVALID_HANDLE_VALUE;
129 static BOOLEAN libInitialized = FALSE;
132 *--------------------------------------------------------------
134 * Win32NewDescriptor --
136 * Set up for I/O descriptor masquerading.
139 * Returns "fake id" which masquerades as a UNIX-style "small
140 * non-negative integer" file/socket descriptor.
141 * Win32_* routine below will "do the right thing" based on the
142 * descriptor's actual type. -1 indicates failure.
145 * Entry in fdTable is reserved to represent the socket/file.
147 *--------------------------------------------------------------
149 static int Win32NewDescriptor(FILE_TYPE type, int fd, int desiredFd)
153 EnterCriticalSection(&fdTableCritical);
156 * If desiredFd is set, try to get this entry (this is used for
157 * mapping stdio handles). Otherwise try to get the fd entry.
158 * If this is not available, find a the first empty slot. .
160 if (desiredFd >= 0 && desiredFd < WIN32_OPEN_MAX)
162 if (fdTable[desiredFd].type == FD_UNUSED)
169 if (fd < WIN32_OPEN_MAX && fdTable[fd].type == FD_UNUSED)
177 for (i = 1; i < WIN32_OPEN_MAX; ++i)
179 if (fdTable[i].type == FD_UNUSED)
190 fdTable[index].fid.value = fd;
191 fdTable[index].type = type;
192 fdTable[index].path = NULL;
193 fdTable[index].Errno = NO_ERROR;
194 fdTable[index].status = 0;
195 fdTable[index].offset = -1;
196 fdTable[index].offsetHighPtr = fdTable[index].offsetLowPtr = NULL;
197 fdTable[index].hMapMutex = NULL;
198 fdTable[index].ovList = NULL;
201 LeaveCriticalSection(&fdTableCritical);
206 *--------------------------------------------------------------
210 * This thread performs I/O on stadard input. It is needed
211 * because you can't guarantee that all applications will
212 * create standard input with sufficient access to perform
213 * asynchronous I/O. Since we don't want to block the app
214 * reading from stdin we make it look like it's using I/O
215 * completion ports to perform async I/O.
218 * Data is read from stdin and posted to the io completion
224 *--------------------------------------------------------------
226 static void StdinThread(LPDWORD startup){
230 unsigned long bytesRead;
231 POVERLAPPED_REQUEST pOv;
233 // Touch the arg to prevent warning
238 * Block until a request to read from stdin comes in or a
239 * request to terminate the thread arrives (fd = -1).
241 if (!GetQueuedCompletionStatus(hStdinCompPort, &bytesRead, &fd,
242 (LPOVERLAPPED *)&pOv, (DWORD)-1) && !pOv) {
247 ASSERT((fd == STDIN_FILENO) || (fd == -1));
252 ASSERT(pOv->clientData1 != NULL);
254 if(ReadFile(stdioHandles[STDIN_FILENO], pOv->clientData1, bytesRead,
256 PostQueuedCompletionStatus(hIoCompPort, bytesRead,
257 STDIN_FILENO, (LPOVERLAPPED)pOv);
267 void OS_ShutdownPending(void)
269 shutdownPending = TRUE;
272 /* XXX Need a shutdown now event */
273 static void ShutdownRequestThread(void * arg)
275 HANDLE shutdownEvent = (HANDLE) arg;
277 if (WaitForSingleObject(shutdownEvent, INFINITE) == WAIT_FAILED)
279 // Assuming it will happen again, all we can do is exit the thread
283 // "Simple reads and writes to properly-aligned 32-bit variables are atomic"
284 shutdownPending = TRUE;
286 // Before an accept() is entered the shutdownPending flag is checked.
287 // If set, OS_Accept() will return -1. If not, it waits
288 // on a connection request for one second, checks the flag, & repeats.
289 // Only one process/thread is allowed to do this at time by
290 // wrapping the accept() with mutex.
295 *--------------------------------------------------------------
299 * Set up the OS library for use.
302 * Returns 0 if success, -1 if not.
305 * Sockets initialized, pseudo file descriptors setup, etc.
307 *--------------------------------------------------------------
309 int OS_LibInit(int stdioFds[3])
315 char *cLenPtr = NULL;
321 InitializeCriticalSection(&fdTableCritical);
324 * Initialize windows sockets library.
326 wVersion = MAKEWORD(2,0);
327 err = WSAStartup( wVersion, &wsaData );
329 fprintf(stderr, "Error starting Windows Sockets. Error: %d",
335 * Create the I/O completion port to be used for our I/O queue.
337 if (hIoCompPort == INVALID_HANDLE_VALUE) {
338 hIoCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
340 if(hIoCompPort == INVALID_HANDLE_VALUE) {
341 printf("<H2>OS_LibInit Failed CreateIoCompletionPort! ERROR: %d</H2>\r\n\r\n",
348 * If a shutdown event is in the env, save it (I don't see any to
349 * remove it from the environment out from under the application).
350 * Spawn a thread to wait on the shutdown request.
352 val = getenv(SHUTDOWN_EVENT_NAME);
355 HANDLE shutdownEvent = (HANDLE) atoi(val);
357 if (_beginthread(ShutdownRequestThread, 0, shutdownEvent) == -1)
363 if (acceptMutex == INVALID_HANDLE_VALUE)
365 /* If an accept mutex is in the env, use it */
366 val = getenv(MUTEX_VARNAME);
369 acceptMutex = (HANDLE) atoi(val);
374 * Determine if this library is being used to listen for FastCGI
375 * connections. This is communicated by STDIN containing a
376 * valid handle to a listener object. In this case, both the
377 * "stdout" and "stderr" handles will be INVALID (ie. closed) by
378 * the starting process.
380 * The trick is determining if this is a pipe or a socket...
382 * XXX: Add the async accept test to determine socket or handle to a
385 if((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
386 (GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) &&
387 (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) )
389 DWORD pipeMode = PIPE_READMODE_BYTE | PIPE_WAIT;
390 HANDLE oldStdIn = GetStdHandle(STD_INPUT_HANDLE);
392 // Move the handle to a "low" number
393 if (! DuplicateHandle(GetCurrentProcess(), oldStdIn,
394 GetCurrentProcess(), &hListen,
395 0, TRUE, DUPLICATE_SAME_ACCESS))
400 if (! SetStdHandle(STD_INPUT_HANDLE, hListen))
405 CloseHandle(oldStdIn);
408 * Set the pipe handle state so that it operates in wait mode.
410 * NOTE: The listenFd is not mapped to a pseudo file descriptor
411 * as all work done on it is contained to the OS library.
413 * XXX: Initial assumption is that SetNamedPipeHandleState will
414 * fail if this is an IP socket...
416 if (SetNamedPipeHandleState(hListen, &pipeMode, NULL, NULL))
418 listenType = FD_PIPE_SYNC;
422 listenType = FD_SOCKET_SYNC;
427 * If there are no stdioFds passed in, we're done.
429 if(stdioFds == NULL) {
435 * Setup standard input asynchronous I/O. There is actually a separate
436 * thread spawned for this purpose. The reason for this is that some
437 * web servers use anonymous pipes for the connection between itself
438 * and a CGI application. Anonymous pipes can't perform asynchronous
439 * I/O or use I/O completion ports. Therefore in order to present a
440 * consistent I/O dispatch model to an application we emulate I/O
441 * completion port behavior by having the standard input thread posting
442 * messages to the hIoCompPort which look like a complete overlapped
443 * I/O structure. This keeps the event dispatching simple from the
444 * application perspective.
446 stdioHandles[STDIN_FILENO] = GetStdHandle(STD_INPUT_HANDLE);
448 if(!SetHandleInformation(stdioHandles[STDIN_FILENO],
449 HANDLE_FLAG_INHERIT, 0)) {
451 * XXX: Causes error when run from command line. Check KB
452 err = GetLastError();
458 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
459 (int)stdioHandles[STDIN_FILENO],
460 STDIN_FILENO)) == -1) {
464 * Set stdin equal to our pseudo FD and create the I/O completion
465 * port to be used for async I/O.
467 stdioFds[STDIN_FILENO] = fakeFd;
471 * Create the I/O completion port to be used for communicating with
472 * the thread doing I/O on standard in. This port will carry read
473 * and possibly thread termination requests to the StdinThread.
475 if (hStdinCompPort == INVALID_HANDLE_VALUE) {
476 hStdinCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
478 if(hStdinCompPort == INVALID_HANDLE_VALUE) {
479 printf("<H2>OS_LibInit Failed CreateIoCompletionPort: STDIN! ERROR: %d</H2>\r\n\r\n",
486 * Create the thread that will read stdin if the CONTENT_LENGTH
489 if((cLenPtr = getenv("CONTENT_LENGTH")) != NULL &&
491 hStdinThread = (HANDLE) _beginthread(StdinThread, 0, NULL);
492 if (hStdinThread == (HANDLE) -1) {
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);
686 if (acceptMutex == INVALID_HANDLE_VALUE)
688 acceptMutex = CreateMutex(NULL, FALSE, NULL);
689 if (acceptMutex == NULL) return -2;
690 if (! SetHandleInformation(acceptMutex, HANDLE_FLAG_INHERIT, TRUE)) return -3;
693 // There's nothing to be gained (at the moment) by a shutdown Event
695 if (port && *bindPath != ':' && strncmp(bindPath, LOCALHOST, strlen(LOCALHOST)))
697 fprintf(stderr, "To start a service on a TCP port can not "
698 "specify a host name.\n"
699 "You should either use \"localhost:<port>\" or "
700 " just use \":<port>.\"\n");
704 listenType = (port) ? FD_SOCKET_SYNC : FD_PIPE_ASYNC;
709 struct sockaddr_in sockAddr;
710 int sockLen = sizeof(sockAddr);
712 memset(&sockAddr, 0, sizeof(sockAddr));
713 sockAddr.sin_family = AF_INET;
714 sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
715 sockAddr.sin_port = htons(port);
717 listenSock = socket(AF_INET, SOCK_STREAM, 0);
718 if (listenSock == INVALID_SOCKET)
723 if (bind(listenSock, (struct sockaddr *) &sockAddr, sockLen) )
728 if (listen(listenSock, backlog))
733 pseudoFd = Win32NewDescriptor(listenType, listenSock, -1);
737 closesocket(listenSock);
741 hListen = (HANDLE) listenSock;
745 HANDLE hListenPipe = INVALID_HANDLE_VALUE;
746 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
753 strcpy(pipePath, bindPathPrefix);
754 strcat(pipePath, bindPath);
756 hListenPipe = CreateNamedPipe(pipePath,
758 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
759 PIPE_UNLIMITED_INSTANCES,
760 4096, 4096, 0, NULL);
764 if (hListenPipe == INVALID_HANDLE_VALUE)
769 if (! SetHandleInformation(hListenPipe, HANDLE_FLAG_INHERIT, TRUE))
774 pseudoFd = Win32NewDescriptor(listenType, (int) hListenPipe, -1);
778 CloseHandle(hListenPipe);
782 hListen = (HANDLE) hListenPipe;
789 *----------------------------------------------------------------------
793 * Create the pipe pathname connect to the remote application if
797 * -1 if fail or a valid handle if connection succeeds.
800 * Remote connection established.
802 *----------------------------------------------------------------------
804 int OS_FcgiConnect(char *bindPath)
806 short port = getPort(bindPath);
813 struct sockaddr_in sockAddr;
814 int sockLen = sizeof(sockAddr);
817 if (*bindPath != ':')
819 char * p = strchr(bindPath, ':');
820 int len = p - bindPath + 1;
823 strncpy(host, bindPath, len);
827 hp = gethostbyname(host ? host : LOCALHOST);
836 fprintf(stderr, "Unknown host: %s\n", bindPath);
840 memset(&sockAddr, 0, sizeof(sockAddr));
841 sockAddr.sin_family = AF_INET;
842 memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
843 sockAddr.sin_port = htons(port);
845 sock = socket(AF_INET, SOCK_STREAM, 0);
846 if (sock == INVALID_SOCKET)
851 if (! connect(sock, (struct sockaddr *) &sockAddr, sockLen))
857 pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, sock, -1);
866 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
874 strcpy(pipePath, bindPathPrefix);
875 strcat(pipePath, bindPath);
877 hPipe = CreateFile(pipePath,
878 GENERIC_WRITE | GENERIC_READ,
879 FILE_SHARE_READ | FILE_SHARE_WRITE,
882 FILE_FLAG_OVERLAPPED,
887 if( hPipe == INVALID_HANDLE_VALUE)
892 pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int) hPipe, -1);
901 * Set stdin equal to our pseudo FD and create the I/O completion
902 * port to be used for async I/O.
904 if (! CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1))
906 Win32FreeDescriptor(pseudoFd);
916 *--------------------------------------------------------------
920 * Pass through to the appropriate NT read function.
923 * Returns number of byes read. Mimics unix read:.
924 * n bytes read, 0 or -1 failure: errno contains actual error
929 *--------------------------------------------------------------
931 int OS_Read(int fd, char * buf, size_t len)
936 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
938 if (shutdownNow) return -1;
940 switch (fdTable[fd].type)
947 if (ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead, NULL))
953 fdTable[fd].Errno = GetLastError();
959 case FD_SOCKET_ASYNC:
961 ret = recv(fdTable[fd].fid.sock, buf, len, 0);
962 if (ret == SOCKET_ERROR)
964 fdTable[fd].Errno = WSAGetLastError();
979 *--------------------------------------------------------------
983 * Perform a synchronous OS write.
986 * Returns number of bytes written. Mimics unix write:
987 * n bytes written, 0 or -1 failure (??? couldn't find man page).
992 *--------------------------------------------------------------
994 int OS_Write(int fd, char * buf, size_t len)
999 ASSERT(fd >= 0 && fd < WIN32_OPEN_MAX);
1001 if (shutdownNow) return -1;
1003 switch (fdTable[fd].type)
1010 if (WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten, NULL))
1016 fdTable[fd].Errno = GetLastError();
1021 case FD_SOCKET_SYNC:
1022 case FD_SOCKET_ASYNC:
1024 ret = send(fdTable[fd].fid.sock, buf, len, 0);
1025 if (ret == SOCKET_ERROR)
1027 fdTable[fd].Errno = WSAGetLastError();
1042 *----------------------------------------------------------------------
1046 * Spawns a new server listener process, and stores the information
1047 * relating to the child in the supplied record. A wait handler is
1048 * registered on the child's completion. This involves creating
1049 * a process on NT and preparing a command line with the required
1050 * state (currently a -childproc flag and the server socket to use
1051 * for accepting connections).
1054 * 0 if success, -1 if error.
1057 * Child process spawned.
1059 *----------------------------------------------------------------------
1061 int OS_SpawnChild(char *execPath, int listenFd)
1063 STARTUPINFO StartupInfo;
1064 PROCESS_INFORMATION pInfo;
1067 memset((void *)&StartupInfo, 0, sizeof(STARTUPINFO));
1068 StartupInfo.cb = sizeof (STARTUPINFO);
1069 StartupInfo.lpReserved = NULL;
1070 StartupInfo.lpReserved2 = NULL;
1071 StartupInfo.cbReserved2 = 0;
1072 StartupInfo.lpDesktop = NULL;
1075 * FastCGI on NT will set the listener pipe HANDLE in the stdin of
1076 * the new process. The fact that there is a stdin and NULL handles
1077 * for stdout and stderr tells the FastCGI process that this is a
1078 * FastCGI process and not a CGI process.
1080 StartupInfo.dwFlags = STARTF_USESTDHANDLES;
1082 * XXX: Do I have to dup the handle before spawning the process or is
1083 * it sufficient to use the handle as it's reference counted
1086 StartupInfo.hStdInput = fdTable[listenFd].fid.fileHandle;
1087 StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
1088 StartupInfo.hStdError = INVALID_HANDLE_VALUE;
1091 * Make the listener socket inheritable.
1093 success = SetHandleInformation(StartupInfo.hStdInput, HANDLE_FLAG_INHERIT,
1100 * XXX: Might want to apply some specific security attributes to the
1103 success = CreateProcess(execPath, /* LPCSTR address of module name */
1104 NULL, /* LPCSTR address of command line */
1105 NULL, /* Process security attributes */
1106 NULL, /* Thread security attributes */
1107 TRUE, /* Inheritable Handes inherited. */
1108 0, /* DWORD creation flags */
1109 NULL, /* Use parent environment block */
1110 NULL, /* Address of current directory name */
1111 &StartupInfo, /* Address of STARTUPINFO */
1112 &pInfo); /* Address of PROCESS_INFORMATION */
1121 *--------------------------------------------------------------
1123 * OS_AsyncReadStdin --
1125 * This initiates an asynchronous read on the standard
1126 * input handle. This handle is not guaranteed to be
1127 * capable of performing asynchronous I/O so we send a
1128 * message to the StdinThread to do the synchronous read.
1131 * -1 if error, 0 otherwise.
1134 * Asynchronous message is queued to the StdinThread and an
1135 * overlapped structure is allocated/initialized.
1137 *--------------------------------------------------------------
1139 int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
1140 ClientData clientData)
1142 POVERLAPPED_REQUEST pOv;
1144 ASSERT(fdTable[STDIN_FILENO].type != FD_UNUSED);
1146 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1148 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1149 pOv->clientData1 = (ClientData)buf;
1150 pOv->instance = fdTable[STDIN_FILENO].instance;
1151 pOv->procPtr = procPtr;
1152 pOv->clientData = clientData;
1154 PostQueuedCompletionStatus(hStdinCompPort, len, STDIN_FILENO,
1160 *--------------------------------------------------------------
1164 * This initiates an asynchronous read on the file
1165 * handle which may be a socket or named pipe.
1167 * We also must save the ProcPtr and ClientData, so later
1168 * when the io completes, we know who to call.
1170 * We don't look at any results here (the ReadFile may
1171 * return data if it is cached) but do all completion
1172 * processing in OS_Select when we get the io completion
1173 * port done notifications. Then we call the callback.
1176 * -1 if error, 0 otherwise.
1179 * Asynchronous I/O operation is queued for completion.
1181 *--------------------------------------------------------------
1183 int OS_AsyncRead(int fd, int offset, void *buf, int len,
1184 OS_AsyncProc procPtr, ClientData clientData)
1187 POVERLAPPED_REQUEST pOv;
1190 * Catch any bogus fd values
1192 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1194 * Confirm that this is an async fd
1196 ASSERT(fdTable[fd].type != FD_UNUSED);
1197 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1198 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1199 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1201 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1203 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1205 * Only file offsets should be non-zero, but make sure.
1207 if (fdTable[fd].type == FD_FILE_ASYNC)
1208 if (fdTable[fd].offset >= 0)
1209 pOv->overlapped.Offset = fdTable[fd].offset;
1211 pOv->overlapped.Offset = offset;
1212 pOv->instance = fdTable[fd].instance;
1213 pOv->procPtr = procPtr;
1214 pOv->clientData = clientData;
1217 * ReadFile returns: TRUE success, FALSE failure
1219 if (!ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead,
1220 (LPOVERLAPPED)pOv)) {
1221 fdTable[fd].Errno = GetLastError();
1222 if(fdTable[fd].Errno == ERROR_NO_DATA ||
1223 fdTable[fd].Errno == ERROR_PIPE_NOT_CONNECTED) {
1224 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1227 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1228 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1231 fdTable[fd].Errno = 0;
1237 *--------------------------------------------------------------
1241 * This initiates an asynchronous write on the "fake" file
1242 * descriptor (which may be a file, socket, or named pipe).
1243 * We also must save the ProcPtr and ClientData, so later
1244 * when the io completes, we know who to call.
1246 * We don't look at any results here (the WriteFile generally
1247 * completes immediately) but do all completion processing
1248 * in OS_DoIo when we get the io completion port done
1249 * notifications. Then we call the callback.
1252 * -1 if error, 0 otherwise.
1255 * Asynchronous I/O operation is queued for completion.
1257 *--------------------------------------------------------------
1259 int OS_AsyncWrite(int fd, int offset, void *buf, int len,
1260 OS_AsyncProc procPtr, ClientData clientData)
1263 POVERLAPPED_REQUEST pOv;
1266 * Catch any bogus fd values
1268 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1270 * Confirm that this is an async fd
1272 ASSERT(fdTable[fd].type != FD_UNUSED);
1273 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1274 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1275 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1277 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1279 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1281 * Only file offsets should be non-zero, but make sure.
1283 if (fdTable[fd].type == FD_FILE_ASYNC)
1285 * Only file opened via OS_AsyncWrite with
1286 * O_APPEND will have an offset != -1.
1288 if (fdTable[fd].offset >= 0)
1290 * If the descriptor has a memory mapped file
1291 * handle, take the offsets from there.
1293 if (fdTable[fd].hMapMutex != NULL) {
1295 * Wait infinitely; this *should* not cause problems.
1297 WaitForSingleObject(fdTable[fd].hMapMutex, INFINITE);
1300 * Retrieve the shared offset values.
1302 pOv->overlapped.OffsetHigh = *(fdTable[fd].offsetHighPtr);
1303 pOv->overlapped.Offset = *(fdTable[fd].offsetLowPtr);
1306 * Update the shared offset values for the next write
1308 *(fdTable[fd].offsetHighPtr) += 0; /* XXX How do I handle overflow */
1309 *(fdTable[fd].offsetLowPtr) += len;
1311 ReleaseMutex(fdTable[fd].hMapMutex);
1313 pOv->overlapped.Offset = fdTable[fd].offset;
1315 pOv->overlapped.Offset = offset;
1316 pOv->instance = fdTable[fd].instance;
1317 pOv->procPtr = procPtr;
1318 pOv->clientData = clientData;
1321 * WriteFile returns: TRUE success, FALSE failure
1323 if (!WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten,
1324 (LPOVERLAPPED)pOv)) {
1325 fdTable[fd].Errno = GetLastError();
1326 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1327 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1330 fdTable[fd].Errno = 0;
1332 if (fdTable[fd].offset >= 0)
1333 fdTable[fd].offset += len;
1338 *--------------------------------------------------------------
1342 * Closes the descriptor with routine appropriate for
1343 * descriptor's type.
1346 * Socket or file is closed. Return values mimic Unix close:
1347 * 0 success, -1 failure
1350 * Entry in fdTable is marked as free.
1352 *--------------------------------------------------------------
1354 int OS_Close(int fd)
1359 * Catch it if fd is a bogus value
1361 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1362 ASSERT(fdTable[fd].type != FD_UNUSED);
1364 switch (fdTable[fd].type) {
1371 case FD_SOCKET_SYNC:
1372 case FD_SOCKET_ASYNC:
1374 * Closing a socket that has an async read outstanding causes a
1375 * tcp reset and possible data loss. The shutdown call seems to
1378 shutdown(fdTable[fd].fid.sock, 2);
1380 * closesocket returns: 0 success, SOCKET_ERROR failure
1382 if (closesocket(fdTable[fd].fid.sock) == SOCKET_ERROR)
1386 return -1; /* fake failure */
1389 Win32FreeDescriptor(fd);
1394 *--------------------------------------------------------------
1398 * Cancel outstanding asynchronous reads and prevent subsequent
1399 * reads from completing.
1402 * Socket or file is shutdown. Return values mimic Unix shutdown:
1403 * 0 success, -1 failure
1405 *--------------------------------------------------------------
1407 int OS_CloseRead(int fd)
1412 * Catch it if fd is a bogus value
1414 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1415 ASSERT(fdTable[fd].type == FD_SOCKET_ASYNC
1416 || fdTable[fd].type == FD_SOCKET_SYNC);
1418 if (shutdown(fdTable[fd].fid.sock,0) == SOCKET_ERROR)
1424 *--------------------------------------------------------------
1428 * This function was formerly OS_Select. It's purpose is
1429 * to pull I/O completion events off the queue and dispatch
1430 * them to the appropriate place.
1436 * Handlers are called.
1438 *--------------------------------------------------------------
1440 int OS_DoIo(struct timeval *tmo)
1443 unsigned long bytes;
1444 POVERLAPPED_REQUEST pOv;
1451 * We can loop in here, but not too long, as wait handlers
1453 * For cgi stdin, apparently select returns when io completion
1454 * ports don't, so don't wait the full timeout.
1457 ms = (tmo->tv_sec*1000 + tmo->tv_usec/1000) / 2;
1461 ms_last = tb.time*1000 + tb.millitm;
1463 if(tmo && (ms = tmo->tv_sec*1000 + tmo->tv_usec/1000)> 100)
1465 if (!GetQueuedCompletionStatus(hIoCompPort, &bytes, &fd,
1466 (LPOVERLAPPED *)&pOv, ms) && !pOv) {
1467 err = WSAGetLastError();
1468 return 0; /* timeout */
1471 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1472 /* call callback if descriptor still valid */
1474 if(pOv->instance == fdTable[fd].instance)
1475 (*pOv->procPtr)(pOv->clientData, bytes);
1479 ms -= (tb.time*1000 + tb.millitm - ms_last);
1480 ms_last = tb.time*1000 + tb.millitm;
1485 static int isAddrOK(struct sockaddr_in * inet_sockaddr, const char * okAddrs)
1487 static const char *token = " ,;:\t";
1491 if (okAddrs == NULL) return TRUE;
1493 ipaddr = inet_ntoa(inet_sockaddr->sin_addr);
1494 p = strstr(okAddrs, ipaddr);
1496 if (p == NULL) return FALSE;
1500 p += strlen(ipaddr);
1501 return (strchr(token, *p) != NULL);
1504 if (strchr(token, *--p) != NULL)
1506 p += strlen(ipaddr) + 1;
1507 return (strchr(token, *p) != NULL);
1514 static int CALLBACK isAddrOKCallback(LPWSABUF lpCallerId,
1523 struct sockaddr_in *sockaddr = (struct sockaddr_in *) lpCallerId->buf;
1525 // Touch the args to avoid warnings
1526 dc0 = NULL; dc1 = NULL; dc2 = NULL; dc3 = NULL; dc4 = NULL; dc5 = NULL;
1528 if ((void *) data == NULL) return CF_ACCEPT;
1530 if (sockaddr->sin_family != AF_INET) return CF_ACCEPT;
1532 return isAddrOK(sockaddr, (const char *) data) ? CF_ACCEPT : CF_REJECT;
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, NULL))
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 // The NamedPipe was opened with an Overlapped structure
1574 // and there is a pending io operation. mod_fastcgi
1575 // did this in 2.2.12 (fcgi_pm.c v1.52).
1577 case ERROR_PIPE_LISTENING:
1579 // The pipe handle is in nonblocking mode.
1583 // The previous client closed its handle (and we failed
1584 // to call DisconnectNamedPipe)
1588 printLastError("unexpected ConnectNamedPipe() error");
1592 ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
1595 DisconnectNamedPipe(hListen);
1601 static int acceptSocket(const char *webServerAddrs)
1608 struct sockaddr sockaddr;
1609 int sockaddrLen = sizeof(sockaddr);
1613 const struct timeval timeout = {1, 0};
1618 #pragma warning( disable : 4127 )
1619 FD_SET((unsigned int) hListen, &readfds);
1620 #pragma warning( default : 4127 )
1622 if (select(0, &readfds, NULL, NULL, &timeout) == 0)
1624 if (shutdownPending)
1637 hSock = accept((SOCKET) hListen, &sockaddr, &sockaddrLen);
1639 if (hSock == INVALID_SOCKET)
1644 if (isAddrOK((struct sockaddr_in *) &sockaddr, webServerAddrs))
1651 hSock = WSAAccept((unsigned int) hListen,
1655 (DWORD) webServerAddrs);
1657 if (hSock != INVALID_SOCKET)
1662 if (WSAGetLastError() != WSAECONNREFUSED)
1669 if (hSock == INVALID_SOCKET)
1671 /* Use FormatMessage() */
1672 fprintf(stderr, "accept()/WSAAccept() failed: %d", WSAGetLastError());
1676 ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
1686 *----------------------------------------------------------------------
1690 * Accepts a new FastCGI connection. This routine knows whether
1691 * we're dealing with TCP based sockets or NT Named Pipes for IPC.
1693 * fail_on_intr is ignored in the Win lib.
1696 * -1 if the operation fails, otherwise this is a valid IPC fd.
1698 *----------------------------------------------------------------------
1700 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
1704 // Touch args to prevent warnings
1705 listen_sock = 0; fail_on_intr = 0;
1707 // @todo Muliple listen sockets and sockets other than 0 are not
1708 // supported due to the use of globals.
1710 if (shutdownPending)
1716 // The mutex is to keep other processes (and threads, when supported)
1717 // from going into the accept cycle. The accept cycle needs to
1718 // periodically break out to check the state of the shutdown flag
1719 // and there's no point to having more than one thread do that.
1721 if (acceptMutex != INVALID_HANDLE_VALUE)
1723 if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED)
1725 printLastError("WaitForSingleObject() failed");
1730 if (shutdownPending)
1734 else if (listenType == FD_PIPE_SYNC)
1736 ipcFd = acceptNamedPipe();
1738 else if (listenType == FD_SOCKET_SYNC)
1740 ipcFd = acceptSocket(webServerAddrs);
1744 fprintf(stderr, "unknown listenType (%d)\n", listenType);
1747 if (acceptMutex != INVALID_HANDLE_VALUE)
1749 ReleaseMutex(acceptMutex);
1756 *----------------------------------------------------------------------
1760 * OS IPC routine to close an IPC connection.
1766 * IPC connection is closed.
1768 *----------------------------------------------------------------------
1770 int OS_IpcClose(int ipcFd)
1776 * Catch it if fd is a bogus value
1778 ASSERT((ipcFd >= 0) && (ipcFd < WIN32_OPEN_MAX));
1779 ASSERT(fdTable[ipcFd].type != FD_UNUSED);
1781 switch(listenType) {
1785 * Make sure that the client (ie. a Web Server in this case) has
1786 * read all data from the pipe before we disconnect.
1788 if(!FlushFileBuffers(fdTable[ipcFd].fid.fileHandle))
1790 if(DisconnectNamedPipe(fdTable[ipcFd].fid.fileHandle)) {
1798 case FD_SOCKET_SYNC:
1811 *----------------------------------------------------------------------
1815 * Determines whether this process is a FastCGI process or not.
1818 * Returns 1 if FastCGI, 0 if not.
1823 *----------------------------------------------------------------------
1825 int OS_IsFcgi(int sock)
1827 // Touch args to prevent warnings
1830 /* XXX This is broken for sock */
1832 return (listenType != FD_UNUSED);
1836 *----------------------------------------------------------------------
1840 * Sets selected flag bits in an open file descriptor. Currently
1841 * this is only to put a SOCKET into non-blocking mode.
1843 *----------------------------------------------------------------------
1845 void OS_SetFlags(int fd, int flags)
1847 unsigned long pLong = 1L;
1850 if (fdTable[fd].type == FD_SOCKET_SYNC && flags == O_NONBLOCK) {
1851 if (ioctlsocket(fdTable[fd].fid.sock, FIONBIO, &pLong) ==
1853 exit(WSAGetLastError());
1855 if (!CreateIoCompletionPort((HANDLE)fdTable[fd].fid.sock,
1856 hIoCompPort, fd, 1)) {
1857 err = GetLastError();
1861 fdTable[fd].type = FD_SOCKET_ASYNC;