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.34 2003/06/22 00:16:43 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(void * 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 static void ShutdownRequestThread(void * arg)
274 HANDLE shutdownEvent = (HANDLE) arg;
276 WaitForSingleObject(shutdownEvent, INFINITE);
278 shutdownPending = TRUE;
280 if (listenType == FD_PIPE_SYNC)
282 // Its a hassle to get ConnectNamedPipe to return early,
283 // so just wack the whole process - yes, this will toast
284 // any requests in progress, but at least its a clean
285 // shutdown (its better than TerminateProcess())
289 // FD_SOCKET_SYNC: When in Accept(), select() is used to poll
290 // the shutdownPending flag - yeah this isn't pretty either
291 // but its only one process doing it if an Accept mutex is used.
292 // This at least buys no toasted requests.
296 *--------------------------------------------------------------
300 * Set up the OS library for use.
303 * Returns 0 if success, -1 if not.
306 * Sockets initialized, pseudo file descriptors setup, etc.
308 *--------------------------------------------------------------
310 int OS_LibInit(int stdioFds[3])
316 char *cLenPtr = NULL;
322 InitializeCriticalSection(&fdTableCritical);
325 * Initialize windows sockets library.
327 wVersion = MAKEWORD(2,0);
328 err = WSAStartup( wVersion, &wsaData );
330 fprintf(stderr, "Error starting Windows Sockets. Error: %d",
336 * Create the I/O completion port to be used for our I/O queue.
338 if (hIoCompPort == INVALID_HANDLE_VALUE) {
339 hIoCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
341 if(hIoCompPort == INVALID_HANDLE_VALUE) {
342 printf("<H2>OS_LibInit Failed CreateIoCompletionPort! ERROR: %d</H2>\r\n\r\n",
349 * If a shutdown event is in the env, save it (I don't see any to
350 * remove it from the environment out from under the application).
351 * Spawn a thread to wait on the shutdown request.
353 val = getenv(SHUTDOWN_EVENT_NAME);
356 HANDLE shutdownEvent = (HANDLE) atoi(val);
358 if (_beginthread(ShutdownRequestThread, 0, shutdownEvent) == -1)
364 if (acceptMutex == INVALID_HANDLE_VALUE)
366 /* If an accept mutex is in the env, use it */
367 val = getenv(MUTEX_VARNAME);
370 acceptMutex = (HANDLE) atoi(val);
375 * Determine if this library is being used to listen for FastCGI
376 * connections. This is communicated by STDIN containing a
377 * valid handle to a listener object. In this case, both the
378 * "stdout" and "stderr" handles will be INVALID (ie. closed) by
379 * the starting process.
381 * The trick is determining if this is a pipe or a socket...
383 * XXX: Add the async accept test to determine socket or handle to a
386 if((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
387 (GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) &&
388 (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) )
390 DWORD pipeMode = PIPE_READMODE_BYTE | PIPE_WAIT;
391 HANDLE oldStdIn = GetStdHandle(STD_INPUT_HANDLE);
393 // Move the handle to a "low" number
394 if (! DuplicateHandle(GetCurrentProcess(), oldStdIn,
395 GetCurrentProcess(), &hListen,
396 0, TRUE, DUPLICATE_SAME_ACCESS))
401 if (! SetStdHandle(STD_INPUT_HANDLE, hListen))
406 CloseHandle(oldStdIn);
409 * Set the pipe handle state so that it operates in wait mode.
411 * NOTE: The listenFd is not mapped to a pseudo file descriptor
412 * as all work done on it is contained to the OS library.
414 * XXX: Initial assumption is that SetNamedPipeHandleState will
415 * fail if this is an IP socket...
417 if (SetNamedPipeHandleState(hListen, &pipeMode, NULL, NULL))
419 listenType = FD_PIPE_SYNC;
423 listenType = FD_SOCKET_SYNC;
428 * If there are no stdioFds passed in, we're done.
430 if(stdioFds == NULL) {
436 * Setup standard input asynchronous I/O. There is actually a separate
437 * thread spawned for this purpose. The reason for this is that some
438 * web servers use anonymous pipes for the connection between itself
439 * and a CGI application. Anonymous pipes can't perform asynchronous
440 * I/O or use I/O completion ports. Therefore in order to present a
441 * consistent I/O dispatch model to an application we emulate I/O
442 * completion port behavior by having the standard input thread posting
443 * messages to the hIoCompPort which look like a complete overlapped
444 * I/O structure. This keeps the event dispatching simple from the
445 * application perspective.
447 stdioHandles[STDIN_FILENO] = GetStdHandle(STD_INPUT_HANDLE);
449 if(!SetHandleInformation(stdioHandles[STDIN_FILENO],
450 HANDLE_FLAG_INHERIT, 0)) {
452 * XXX: Causes error when run from command line. Check KB
453 err = GetLastError();
459 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
460 (int)stdioHandles[STDIN_FILENO],
461 STDIN_FILENO)) == -1) {
465 * Set stdin equal to our pseudo FD and create the I/O completion
466 * port to be used for async I/O.
468 stdioFds[STDIN_FILENO] = fakeFd;
472 * Create the I/O completion port to be used for communicating with
473 * the thread doing I/O on standard in. This port will carry read
474 * and possibly thread termination requests to the StdinThread.
476 if (hStdinCompPort == INVALID_HANDLE_VALUE) {
477 hStdinCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
479 if(hStdinCompPort == INVALID_HANDLE_VALUE) {
480 printf("<H2>OS_LibInit Failed CreateIoCompletionPort: STDIN! ERROR: %d</H2>\r\n\r\n",
487 * Create the thread that will read stdin if the CONTENT_LENGTH
490 if((cLenPtr = getenv("CONTENT_LENGTH")) != NULL &&
492 hStdinThread = (HANDLE) _beginthread(StdinThread, 0, NULL);
493 if (hStdinThread == (HANDLE) -1) {
494 printf("<H2>OS_LibInit Failed to create STDIN thread! ERROR: %d</H2>\r\n\r\n",
501 * STDOUT will be used synchronously.
503 * XXX: May want to convert this so that it could be used for OVERLAPPED
504 * I/O later. If so, model it after the Stdin I/O as stdout is
505 * also incapable of async I/O on some servers.
507 stdioHandles[STDOUT_FILENO] = GetStdHandle(STD_OUTPUT_HANDLE);
508 if(!SetHandleInformation(stdioHandles[STDOUT_FILENO],
509 HANDLE_FLAG_INHERIT, FALSE)) {
514 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
515 (int)stdioHandles[STDOUT_FILENO],
516 STDOUT_FILENO)) == -1) {
520 * Set stdout equal to our pseudo FD
522 stdioFds[STDOUT_FILENO] = fakeFd;
525 stdioHandles[STDERR_FILENO] = GetStdHandle(STD_ERROR_HANDLE);
526 if(!SetHandleInformation(stdioHandles[STDERR_FILENO],
527 HANDLE_FLAG_INHERIT, FALSE)) {
531 if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
532 (int)stdioHandles[STDERR_FILENO],
533 STDERR_FILENO)) == -1) {
537 * Set stderr equal to our pseudo FD
539 stdioFds[STDERR_FILENO] = fakeFd;
546 *--------------------------------------------------------------
550 * Shutdown the OS library.
556 * Memory freed, handles closed.
558 *--------------------------------------------------------------
560 void OS_LibShutdown()
563 if (hIoCompPort != INVALID_HANDLE_VALUE)
565 CloseHandle(hIoCompPort);
566 hIoCompPort = INVALID_HANDLE_VALUE;
569 if (hStdinCompPort != INVALID_HANDLE_VALUE)
571 CloseHandle(hStdinCompPort);
572 hStdinCompPort = INVALID_HANDLE_VALUE;
575 if (acceptMutex != INVALID_HANDLE_VALUE)
577 ReleaseMutex(acceptMutex);
580 DisconnectNamedPipe(hListen);
589 *--------------------------------------------------------------
591 * Win32FreeDescriptor --
593 * Free I/O descriptor entry in fdTable.
596 * Frees I/O descriptor entry in fdTable.
601 *--------------------------------------------------------------
603 static void Win32FreeDescriptor(int fd)
605 /* Catch it if fd is a bogus value */
606 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
608 EnterCriticalSection(&fdTableCritical);
610 if (fdTable[fd].type != FD_UNUSED)
612 switch (fdTable[fd].type)
617 /* Free file path string */
618 ASSERT(fdTable[fd].path != NULL);
619 free(fdTable[fd].path);
620 fdTable[fd].path = NULL;
627 ASSERT(fdTable[fd].path == NULL);
629 fdTable[fd].type = FD_UNUSED;
630 fdTable[fd].path = NULL;
631 fdTable[fd].Errno = NO_ERROR;
632 fdTable[fd].offsetHighPtr = fdTable[fd].offsetLowPtr = NULL;
634 if (fdTable[fd].hMapMutex != NULL)
636 CloseHandle(fdTable[fd].hMapMutex);
637 fdTable[fd].hMapMutex = NULL;
641 LeaveCriticalSection(&fdTableCritical);
646 static short getPort(const char * bindPath)
649 char * p = strchr(bindPath, ':');
658 port = (short) atoi(buf);
665 * OS_CreateLocalIpcFd --
667 * This procedure is responsible for creating the listener pipe
668 * on Windows NT for local process communication. It will create a
669 * named pipe and return a file descriptor to it to the caller.
672 * Listener pipe created. This call returns either a valid
673 * pseudo file descriptor or -1 on error.
676 * Listener pipe and IPC address are stored in the FCGI info
678 * 'errno' will set on errors (-1 is returned).
680 *----------------------------------------------------------------------
682 int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
685 short port = getPort(bindPath);
687 if (acceptMutex == INVALID_HANDLE_VALUE)
689 acceptMutex = CreateMutex(NULL, FALSE, NULL);
690 if (acceptMutex == NULL) return -2;
691 if (! SetHandleInformation(acceptMutex, HANDLE_FLAG_INHERIT, TRUE)) return -3;
694 // There's nothing to be gained (at the moment) by a shutdown Event
696 if (port && *bindPath != ':' && strncmp(bindPath, LOCALHOST, strlen(LOCALHOST)))
698 fprintf(stderr, "To start a service on a TCP port can not "
699 "specify a host name.\n"
700 "You should either use \"localhost:<port>\" or "
701 " just use \":<port>.\"\n");
705 listenType = (port) ? FD_SOCKET_SYNC : FD_PIPE_ASYNC;
710 struct sockaddr_in sockAddr;
711 int sockLen = sizeof(sockAddr);
713 memset(&sockAddr, 0, sizeof(sockAddr));
714 sockAddr.sin_family = AF_INET;
715 sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
716 sockAddr.sin_port = htons(port);
718 listenSock = socket(AF_INET, SOCK_STREAM, 0);
719 if (listenSock == INVALID_SOCKET)
724 if (bind(listenSock, (struct sockaddr *) &sockAddr, sockLen) )
729 if (listen(listenSock, backlog))
734 pseudoFd = Win32NewDescriptor(listenType, listenSock, -1);
738 closesocket(listenSock);
742 hListen = (HANDLE) listenSock;
746 HANDLE hListenPipe = INVALID_HANDLE_VALUE;
747 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
754 strcpy(pipePath, bindPathPrefix);
755 strcat(pipePath, bindPath);
757 hListenPipe = CreateNamedPipe(pipePath,
759 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
760 PIPE_UNLIMITED_INSTANCES,
761 4096, 4096, 0, NULL);
765 if (hListenPipe == INVALID_HANDLE_VALUE)
770 if (! SetHandleInformation(hListenPipe, HANDLE_FLAG_INHERIT, TRUE))
775 pseudoFd = Win32NewDescriptor(listenType, (int) hListenPipe, -1);
779 CloseHandle(hListenPipe);
783 hListen = (HANDLE) hListenPipe;
790 *----------------------------------------------------------------------
794 * Create the pipe pathname connect to the remote application if
798 * -1 if fail or a valid handle if connection succeeds.
801 * Remote connection established.
803 *----------------------------------------------------------------------
805 int OS_FcgiConnect(char *bindPath)
807 short port = getPort(bindPath);
814 struct sockaddr_in sockAddr;
815 int sockLen = sizeof(sockAddr);
818 if (*bindPath != ':')
820 char * p = strchr(bindPath, ':');
821 int len = p - bindPath + 1;
824 strncpy(host, bindPath, len);
828 hp = gethostbyname(host ? host : LOCALHOST);
837 fprintf(stderr, "Unknown host: %s\n", bindPath);
841 memset(&sockAddr, 0, sizeof(sockAddr));
842 sockAddr.sin_family = AF_INET;
843 memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
844 sockAddr.sin_port = htons(port);
846 sock = socket(AF_INET, SOCK_STREAM, 0);
847 if (sock == INVALID_SOCKET)
852 if (! connect(sock, (struct sockaddr *) &sockAddr, sockLen))
858 pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, sock, -1);
867 char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
875 strcpy(pipePath, bindPathPrefix);
876 strcat(pipePath, bindPath);
878 hPipe = CreateFile(pipePath,
879 GENERIC_WRITE | GENERIC_READ,
880 FILE_SHARE_READ | FILE_SHARE_WRITE,
883 FILE_FLAG_OVERLAPPED,
888 if( hPipe == INVALID_HANDLE_VALUE)
893 pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int) hPipe, -1);
902 * Set stdin equal to our pseudo FD and create the I/O completion
903 * port to be used for async I/O.
905 if (! CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1))
907 Win32FreeDescriptor(pseudoFd);
917 *--------------------------------------------------------------
921 * Pass through to the appropriate NT read function.
924 * Returns number of byes read. Mimics unix read:.
925 * n bytes read, 0 or -1 failure: errno contains actual error
930 *--------------------------------------------------------------
932 int OS_Read(int fd, char * buf, size_t len)
937 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
939 if (shutdownNow) return -1;
941 switch (fdTable[fd].type)
948 if (ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead, NULL))
954 fdTable[fd].Errno = GetLastError();
960 case FD_SOCKET_ASYNC:
962 ret = recv(fdTable[fd].fid.sock, buf, len, 0);
963 if (ret == SOCKET_ERROR)
965 fdTable[fd].Errno = WSAGetLastError();
980 *--------------------------------------------------------------
984 * Perform a synchronous OS write.
987 * Returns number of bytes written. Mimics unix write:
988 * n bytes written, 0 or -1 failure (??? couldn't find man page).
993 *--------------------------------------------------------------
995 int OS_Write(int fd, char * buf, size_t len)
1000 ASSERT(fd >= 0 && fd < WIN32_OPEN_MAX);
1002 if (shutdownNow) return -1;
1004 switch (fdTable[fd].type)
1011 if (WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten, NULL))
1017 fdTable[fd].Errno = GetLastError();
1022 case FD_SOCKET_SYNC:
1023 case FD_SOCKET_ASYNC:
1025 ret = send(fdTable[fd].fid.sock, buf, len, 0);
1026 if (ret == SOCKET_ERROR)
1028 fdTable[fd].Errno = WSAGetLastError();
1043 *----------------------------------------------------------------------
1047 * Spawns a new server listener process, and stores the information
1048 * relating to the child in the supplied record. A wait handler is
1049 * registered on the child's completion. This involves creating
1050 * a process on NT and preparing a command line with the required
1051 * state (currently a -childproc flag and the server socket to use
1052 * for accepting connections).
1055 * 0 if success, -1 if error.
1058 * Child process spawned.
1060 *----------------------------------------------------------------------
1062 int OS_SpawnChild(char *execPath, int listenFd)
1064 STARTUPINFO StartupInfo;
1065 PROCESS_INFORMATION pInfo;
1068 memset((void *)&StartupInfo, 0, sizeof(STARTUPINFO));
1069 StartupInfo.cb = sizeof (STARTUPINFO);
1070 StartupInfo.lpReserved = NULL;
1071 StartupInfo.lpReserved2 = NULL;
1072 StartupInfo.cbReserved2 = 0;
1073 StartupInfo.lpDesktop = NULL;
1076 * FastCGI on NT will set the listener pipe HANDLE in the stdin of
1077 * the new process. The fact that there is a stdin and NULL handles
1078 * for stdout and stderr tells the FastCGI process that this is a
1079 * FastCGI process and not a CGI process.
1081 StartupInfo.dwFlags = STARTF_USESTDHANDLES;
1083 * XXX: Do I have to dup the handle before spawning the process or is
1084 * it sufficient to use the handle as it's reference counted
1087 StartupInfo.hStdInput = fdTable[listenFd].fid.fileHandle;
1088 StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
1089 StartupInfo.hStdError = INVALID_HANDLE_VALUE;
1092 * Make the listener socket inheritable.
1094 success = SetHandleInformation(StartupInfo.hStdInput, HANDLE_FLAG_INHERIT,
1101 * XXX: Might want to apply some specific security attributes to the
1104 success = CreateProcess(execPath, /* LPCSTR address of module name */
1105 NULL, /* LPCSTR address of command line */
1106 NULL, /* Process security attributes */
1107 NULL, /* Thread security attributes */
1108 TRUE, /* Inheritable Handes inherited. */
1109 0, /* DWORD creation flags */
1110 NULL, /* Use parent environment block */
1111 NULL, /* Address of current directory name */
1112 &StartupInfo, /* Address of STARTUPINFO */
1113 &pInfo); /* Address of PROCESS_INFORMATION */
1122 *--------------------------------------------------------------
1124 * OS_AsyncReadStdin --
1126 * This initiates an asynchronous read on the standard
1127 * input handle. This handle is not guaranteed to be
1128 * capable of performing asynchronous I/O so we send a
1129 * message to the StdinThread to do the synchronous read.
1132 * -1 if error, 0 otherwise.
1135 * Asynchronous message is queued to the StdinThread and an
1136 * overlapped structure is allocated/initialized.
1138 *--------------------------------------------------------------
1140 int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
1141 ClientData clientData)
1143 POVERLAPPED_REQUEST pOv;
1145 ASSERT(fdTable[STDIN_FILENO].type != FD_UNUSED);
1147 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1149 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1150 pOv->clientData1 = (ClientData)buf;
1151 pOv->instance = fdTable[STDIN_FILENO].instance;
1152 pOv->procPtr = procPtr;
1153 pOv->clientData = clientData;
1155 PostQueuedCompletionStatus(hStdinCompPort, len, STDIN_FILENO,
1161 *--------------------------------------------------------------
1165 * This initiates an asynchronous read on the file
1166 * handle which may be a socket or named pipe.
1168 * We also must save the ProcPtr and ClientData, so later
1169 * when the io completes, we know who to call.
1171 * We don't look at any results here (the ReadFile may
1172 * return data if it is cached) but do all completion
1173 * processing in OS_Select when we get the io completion
1174 * port done notifications. Then we call the callback.
1177 * -1 if error, 0 otherwise.
1180 * Asynchronous I/O operation is queued for completion.
1182 *--------------------------------------------------------------
1184 int OS_AsyncRead(int fd, int offset, void *buf, int len,
1185 OS_AsyncProc procPtr, ClientData clientData)
1188 POVERLAPPED_REQUEST pOv;
1191 * Catch any bogus fd values
1193 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1195 * Confirm that this is an async fd
1197 ASSERT(fdTable[fd].type != FD_UNUSED);
1198 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1199 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1200 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1202 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1204 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1206 * Only file offsets should be non-zero, but make sure.
1208 if (fdTable[fd].type == FD_FILE_ASYNC)
1209 if (fdTable[fd].offset >= 0)
1210 pOv->overlapped.Offset = fdTable[fd].offset;
1212 pOv->overlapped.Offset = offset;
1213 pOv->instance = fdTable[fd].instance;
1214 pOv->procPtr = procPtr;
1215 pOv->clientData = clientData;
1218 * ReadFile returns: TRUE success, FALSE failure
1220 if (!ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead,
1221 (LPOVERLAPPED)pOv)) {
1222 fdTable[fd].Errno = GetLastError();
1223 if(fdTable[fd].Errno == ERROR_NO_DATA ||
1224 fdTable[fd].Errno == ERROR_PIPE_NOT_CONNECTED) {
1225 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1228 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1229 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1232 fdTable[fd].Errno = 0;
1238 *--------------------------------------------------------------
1242 * This initiates an asynchronous write on the "fake" file
1243 * descriptor (which may be a file, socket, or named pipe).
1244 * We also must save the ProcPtr and ClientData, so later
1245 * when the io completes, we know who to call.
1247 * We don't look at any results here (the WriteFile generally
1248 * completes immediately) but do all completion processing
1249 * in OS_DoIo when we get the io completion port done
1250 * notifications. Then we call the callback.
1253 * -1 if error, 0 otherwise.
1256 * Asynchronous I/O operation is queued for completion.
1258 *--------------------------------------------------------------
1260 int OS_AsyncWrite(int fd, int offset, void *buf, int len,
1261 OS_AsyncProc procPtr, ClientData clientData)
1264 POVERLAPPED_REQUEST pOv;
1267 * Catch any bogus fd values
1269 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1271 * Confirm that this is an async fd
1273 ASSERT(fdTable[fd].type != FD_UNUSED);
1274 ASSERT(fdTable[fd].type != FD_FILE_SYNC);
1275 ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
1276 ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
1278 pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
1280 memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
1282 * Only file offsets should be non-zero, but make sure.
1284 if (fdTable[fd].type == FD_FILE_ASYNC)
1286 * Only file opened via OS_AsyncWrite with
1287 * O_APPEND will have an offset != -1.
1289 if (fdTable[fd].offset >= 0)
1291 * If the descriptor has a memory mapped file
1292 * handle, take the offsets from there.
1294 if (fdTable[fd].hMapMutex != NULL) {
1296 * Wait infinitely; this *should* not cause problems.
1298 WaitForSingleObject(fdTable[fd].hMapMutex, INFINITE);
1301 * Retrieve the shared offset values.
1303 pOv->overlapped.OffsetHigh = *(fdTable[fd].offsetHighPtr);
1304 pOv->overlapped.Offset = *(fdTable[fd].offsetLowPtr);
1307 * Update the shared offset values for the next write
1309 *(fdTable[fd].offsetHighPtr) += 0; /* XXX How do I handle overflow */
1310 *(fdTable[fd].offsetLowPtr) += len;
1312 ReleaseMutex(fdTable[fd].hMapMutex);
1314 pOv->overlapped.Offset = fdTable[fd].offset;
1316 pOv->overlapped.Offset = offset;
1317 pOv->instance = fdTable[fd].instance;
1318 pOv->procPtr = procPtr;
1319 pOv->clientData = clientData;
1322 * WriteFile returns: TRUE success, FALSE failure
1324 if (!WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten,
1325 (LPOVERLAPPED)pOv)) {
1326 fdTable[fd].Errno = GetLastError();
1327 if(fdTable[fd].Errno != ERROR_IO_PENDING) {
1328 PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
1331 fdTable[fd].Errno = 0;
1333 if (fdTable[fd].offset >= 0)
1334 fdTable[fd].offset += len;
1339 *--------------------------------------------------------------
1343 * Closes the descriptor with routine appropriate for
1344 * descriptor's type.
1347 * Socket or file is closed. Return values mimic Unix close:
1348 * 0 success, -1 failure
1351 * Entry in fdTable is marked as free.
1353 *--------------------------------------------------------------
1355 int OS_Close(int fd, int shutdown_ok)
1360 * Catch it if fd is a bogus value
1362 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1363 ASSERT(fdTable[fd].type != FD_UNUSED);
1365 switch (fdTable[fd].type) {
1373 case FD_SOCKET_SYNC:
1374 case FD_SOCKET_ASYNC:
1377 * shutdown() the send side and then read() from client until EOF
1378 * or a timeout expires. This is done to minimize the potential
1379 * that a TCP RST will be sent by our TCP stack in response to
1380 * receipt of additional data from the client. The RST would
1381 * cause the client to discard potentially useful response data.
1386 if (shutdown(fdTable[fd].fid.sock, SD_SEND) == 0)
1390 int sock = fdTable[fd].fid.sock;
1398 #pragma warning( disable : 4127 )
1399 FD_SET((unsigned) sock, &rfds);
1400 #pragma warning( default : 4127 )
1404 rv = select(sock + 1, &rfds, NULL, NULL, &tv);
1406 while (rv > 0 && recv(sock, trash, sizeof(trash), 0) > 0);
1410 closesocket(fdTable[fd].fid.sock);
1416 ret = -1; /* fake failure */
1419 Win32FreeDescriptor(fd);
1424 *--------------------------------------------------------------
1428 * Cancel outstanding asynchronous reads and prevent subsequent
1429 * reads from completing.
1432 * Socket or file is shutdown. Return values mimic Unix shutdown:
1433 * 0 success, -1 failure
1435 *--------------------------------------------------------------
1437 int OS_CloseRead(int fd)
1442 * Catch it if fd is a bogus value
1444 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1445 ASSERT(fdTable[fd].type == FD_SOCKET_ASYNC
1446 || fdTable[fd].type == FD_SOCKET_SYNC);
1448 if (shutdown(fdTable[fd].fid.sock,0) == SOCKET_ERROR)
1454 *--------------------------------------------------------------
1458 * This function was formerly OS_Select. It's purpose is
1459 * to pull I/O completion events off the queue and dispatch
1460 * them to the appropriate place.
1466 * Handlers are called.
1468 *--------------------------------------------------------------
1470 int OS_DoIo(struct timeval *tmo)
1473 unsigned long bytes;
1474 POVERLAPPED_REQUEST pOv;
1481 * We can loop in here, but not too long, as wait handlers
1483 * For cgi stdin, apparently select returns when io completion
1484 * ports don't, so don't wait the full timeout.
1487 ms = (tmo->tv_sec*1000 + tmo->tv_usec/1000) / 2;
1491 ms_last = tb.time*1000 + tb.millitm;
1493 if(tmo && (ms = tmo->tv_sec*1000 + tmo->tv_usec/1000)> 100)
1495 if (!GetQueuedCompletionStatus(hIoCompPort, &bytes, &fd,
1496 (LPOVERLAPPED *)&pOv, ms) && !pOv) {
1497 err = WSAGetLastError();
1498 return 0; /* timeout */
1501 ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
1502 /* call callback if descriptor still valid */
1504 if(pOv->instance == fdTable[fd].instance)
1505 (*pOv->procPtr)(pOv->clientData, bytes);
1509 ms -= (tb.time*1000 + tb.millitm - ms_last);
1510 ms_last = tb.time*1000 + tb.millitm;
1515 static int isAddrOK(struct sockaddr_in * inet_sockaddr, const char * okAddrs)
1517 static const char *token = " ,;:\t";
1521 if (okAddrs == NULL) return TRUE;
1523 ipaddr = inet_ntoa(inet_sockaddr->sin_addr);
1524 p = strstr(okAddrs, ipaddr);
1526 if (p == NULL) return FALSE;
1530 p += strlen(ipaddr);
1531 return (strchr(token, *p) != NULL);
1534 if (strchr(token, *--p) != NULL)
1536 p += strlen(ipaddr) + 1;
1537 return (strchr(token, *p) != NULL);
1544 static int CALLBACK isAddrOKCallback(LPWSABUF lpCallerId,
1553 struct sockaddr_in *sockaddr = (struct sockaddr_in *) lpCallerId->buf;
1555 // Touch the args to avoid warnings
1556 dc0 = NULL; dc1 = NULL; dc2 = NULL; dc3 = NULL; dc4 = NULL; dc5 = NULL;
1558 if ((void *) data == NULL) return CF_ACCEPT;
1560 if (sockaddr->sin_family != AF_INET) return CF_ACCEPT;
1562 return isAddrOK(sockaddr, (const char *) data) ? CF_ACCEPT : CF_REJECT;
1566 static void printLastError(const char * text)
1571 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1572 FORMAT_MESSAGE_FROM_SYSTEM |
1573 FORMAT_MESSAGE_IGNORE_INSERTS,
1582 fprintf(stderr, "%s: %s\n", text, (LPCTSTR) buf);
1586 static int acceptNamedPipe()
1590 if (! ConnectNamedPipe(hListen, NULL))
1592 switch (GetLastError())
1594 case ERROR_PIPE_CONNECTED:
1596 // A client connected after CreateNamedPipe but
1597 // before ConnectNamedPipe. Its a good connection.
1601 case ERROR_IO_PENDING:
1603 // The NamedPipe was opened with an Overlapped structure
1604 // and there is a pending io operation. mod_fastcgi
1605 // did this in 2.2.12 (fcgi_pm.c v1.52).
1607 case ERROR_PIPE_LISTENING:
1609 // The pipe handle is in nonblocking mode.
1613 // The previous client closed its handle (and we failed
1614 // to call DisconnectNamedPipe)
1618 printLastError("unexpected ConnectNamedPipe() error");
1622 ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
1625 DisconnectNamedPipe(hListen);
1631 static int acceptSocket(const char *webServerAddrs)
1638 struct sockaddr sockaddr;
1639 int sockaddrLen = sizeof(sockaddr);
1643 const struct timeval timeout = {1, 0};
1648 #pragma warning( disable : 4127 )
1649 FD_SET((unsigned int) hListen, &readfds);
1650 #pragma warning( default : 4127 )
1652 if (select(0, &readfds, NULL, NULL, &timeout) == 0)
1654 if (shutdownPending)
1667 hSock = accept((SOCKET) hListen, &sockaddr, &sockaddrLen);
1669 if (hSock == INVALID_SOCKET)
1674 if (isAddrOK((struct sockaddr_in *) &sockaddr, webServerAddrs))
1681 hSock = WSAAccept((unsigned int) hListen,
1685 (DWORD) webServerAddrs);
1687 if (hSock != INVALID_SOCKET)
1692 if (WSAGetLastError() != WSAECONNREFUSED)
1699 if (hSock == INVALID_SOCKET)
1701 /* Use FormatMessage() */
1702 fprintf(stderr, "accept()/WSAAccept() failed: %d", WSAGetLastError());
1706 ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
1716 *----------------------------------------------------------------------
1720 * Accepts a new FastCGI connection. This routine knows whether
1721 * we're dealing with TCP based sockets or NT Named Pipes for IPC.
1723 * fail_on_intr is ignored in the Win lib.
1726 * -1 if the operation fails, otherwise this is a valid IPC fd.
1728 *----------------------------------------------------------------------
1730 int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
1734 // Touch args to prevent warnings
1735 listen_sock = 0; fail_on_intr = 0;
1737 // @todo Muliple listen sockets and sockets other than 0 are not
1738 // supported due to the use of globals.
1740 if (shutdownPending)
1746 // The mutex is to keep other processes (and threads, when supported)
1747 // from going into the accept cycle. The accept cycle needs to
1748 // periodically break out to check the state of the shutdown flag
1749 // and there's no point to having more than one thread do that.
1751 if (acceptMutex != INVALID_HANDLE_VALUE)
1753 if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED)
1755 printLastError("WaitForSingleObject() failed");
1760 if (shutdownPending)
1764 else if (listenType == FD_PIPE_SYNC)
1766 ipcFd = acceptNamedPipe();
1768 else if (listenType == FD_SOCKET_SYNC)
1770 ipcFd = acceptSocket(webServerAddrs);
1774 fprintf(stderr, "unknown listenType (%d)\n", listenType);
1777 if (acceptMutex != INVALID_HANDLE_VALUE)
1779 ReleaseMutex(acceptMutex);
1786 *----------------------------------------------------------------------
1790 * OS IPC routine to close an IPC connection.
1796 * IPC connection is closed.
1798 *----------------------------------------------------------------------
1800 int OS_IpcClose(int ipcFd, int shutdown)
1802 if (ipcFd == -1) return 0;
1805 * Catch it if fd is a bogus value
1807 ASSERT((ipcFd >= 0) && (ipcFd < WIN32_OPEN_MAX));
1808 ASSERT(fdTable[ipcFd].type != FD_UNUSED);
1814 * Make sure that the client (ie. a Web Server in this case) has
1815 * read all data from the pipe before we disconnect.
1817 if (! FlushFileBuffers(fdTable[ipcFd].fid.fileHandle)) return -1;
1819 if (! DisconnectNamedPipe(fdTable[ipcFd].fid.fileHandle)) return -1;
1823 case FD_SOCKET_SYNC:
1825 OS_Close(ipcFd, shutdown);
1839 *----------------------------------------------------------------------
1843 * Determines whether this process is a FastCGI process or not.
1846 * Returns 1 if FastCGI, 0 if not.
1851 *----------------------------------------------------------------------
1853 int OS_IsFcgi(int sock)
1855 // Touch args to prevent warnings
1858 /* XXX This is broken for sock */
1860 return (listenType != FD_UNUSED);
1864 *----------------------------------------------------------------------
1868 * Sets selected flag bits in an open file descriptor. Currently
1869 * this is only to put a SOCKET into non-blocking mode.
1871 *----------------------------------------------------------------------
1873 void OS_SetFlags(int fd, int flags)
1875 unsigned long pLong = 1L;
1878 if (fdTable[fd].type == FD_SOCKET_SYNC && flags == O_NONBLOCK) {
1879 if (ioctlsocket(fdTable[fd].fid.sock, FIONBIO, &pLong) ==
1881 exit(WSAGetLastError());
1883 if (!CreateIoCompletionPort((HANDLE)fdTable[fd].fid.sock,
1884 hIoCompPort, fd, 1)) {
1885 err = GetLastError();
1889 fdTable[fd].type = FD_SOCKET_ASYNC;