#ifndef lint
static const char rcsid[] = "$Id: os_win32.c,v 1.6.2.1.4.4 2007/04/19 13:41:37 dmitry Exp $";
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <sys/timeb.h>
#include <process.h>
#define DLLAPI __declspec(dllexport)
#include "fcgimisc.h"
#include "fcgios.h"
#define WIN32_OPEN_MAX 128
#define ACCEPT_TIMEOUT 1000
#define MUTEX_VARNAME "_FCGI_MUTEX_"
#define SHUTDOWN_EVENT_NAME "_FCGI_SHUTDOWN_EVENT_"
#define LOCALHOST "localhost"
static HANDLE hIoCompPort = INVALID_HANDLE_VALUE;
static HANDLE hStdinCompPort = INVALID_HANDLE_VALUE;
static HANDLE hStdinThread = INVALID_HANDLE_VALUE;
static HANDLE stdioHandles[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE,
INVALID_HANDLE_VALUE};
static HANDLE acceptMutex = INVALID_HANDLE_VALUE;
static BOOLEAN shutdownPending = FALSE;
static BOOLEAN shutdownNow = FALSE;
static BOOLEAN bImpersonate = FALSE;
static BOOLEAN bImpersonated = FALSE;
typedef enum {
FD_UNUSED,
FD_FILE_SYNC,
FD_FILE_ASYNC,
FD_SOCKET_SYNC,
FD_SOCKET_ASYNC,
FD_PIPE_SYNC,
FD_PIPE_ASYNC
} FILE_TYPE;
typedef union {
HANDLE fileHandle;
SOCKET sock;
unsigned int value;
} DESCRIPTOR;
struct FD_TABLE {
DESCRIPTOR fid;
FILE_TYPE type;
char *path;
DWORD Errno;
unsigned long instance;
int status;
int offset;
LPDWORD offsetHighPtr;
LPDWORD offsetLowPtr;
HANDLE hMapMutex;
LPVOID ovList;
};
static struct FD_TABLE fdTable[WIN32_OPEN_MAX];
static CRITICAL_SECTION fdTableCritical;
struct OVERLAPPED_REQUEST {
OVERLAPPED overlapped;
unsigned long instance;
OS_AsyncProc procPtr;
ClientData clientData;
ClientData clientData1;
};
typedef struct OVERLAPPED_REQUEST *POVERLAPPED_REQUEST;
static const char *bindPathPrefix = "\\\\.\\pipe\\FastCGI\\";
static FILE_TYPE listenType = FD_UNUSED;
static HANDLE hListen = INVALID_HANDLE_VALUE;
static BOOLEAN libInitialized = FALSE;
static int Win32NewDescriptor(FILE_TYPE type, int fd, int desiredFd)
{
int index = -1;
EnterCriticalSection(&fdTableCritical);
if (desiredFd >= 0 && desiredFd < WIN32_OPEN_MAX)
{
if (fdTable[desiredFd].type == FD_UNUSED)
{
index = desiredFd;
}
}
else if (fd > 0)
{
if (fd < WIN32_OPEN_MAX && fdTable[fd].type == FD_UNUSED)
{
index = fd;
}
else
{
int i;
for (i = 1; i < WIN32_OPEN_MAX; ++i)
{
if (fdTable[i].type == FD_UNUSED)
{
index = i;
break;
}
}
}
}
if (index != -1)
{
fdTable[index].fid.value = fd;
fdTable[index].type = type;
fdTable[index].path = NULL;
fdTable[index].Errno = NO_ERROR;
fdTable[index].status = 0;
fdTable[index].offset = -1;
fdTable[index].offsetHighPtr = fdTable[index].offsetLowPtr = NULL;
fdTable[index].hMapMutex = NULL;
fdTable[index].ovList = NULL;
}
LeaveCriticalSection(&fdTableCritical);
return index;
}
static void StdinThread(void * startup)
{
int doIo = TRUE;
unsigned long fd;
unsigned long bytesRead;
POVERLAPPED_REQUEST pOv;
startup = NULL;
while(doIo) {
if (!GetQueuedCompletionStatus(hStdinCompPort, &bytesRead, &fd,
(LPOVERLAPPED *)&pOv, (DWORD)-1) && !pOv) {
doIo = 0;
break;
}
ASSERT((fd == STDIN_FILENO) || (fd == -1));
if(fd == -1) {
doIo = 0;
break;
}
ASSERT(pOv->clientData1 != NULL);
if(ReadFile(stdioHandles[STDIN_FILENO], pOv->clientData1, bytesRead,
&bytesRead, NULL)) {
PostQueuedCompletionStatus(hIoCompPort, bytesRead,
STDIN_FILENO, (LPOVERLAPPED)pOv);
} else {
doIo = 0;
break;
}
}
ExitThread(0);
}
void OS_ShutdownPending(void)
{
shutdownPending = TRUE;
}
static void ShutdownRequestThread(void * arg)
{
HANDLE shutdownEvent = (HANDLE) arg;
WaitForSingleObject(shutdownEvent, INFINITE);
shutdownPending = TRUE;
if (listenType == FD_PIPE_SYNC)
{
exit(0);
}
}
int OS_SetImpersonate(void)
{
char *os_name = NULL;
os_name = getenv("OS");
if (os_name && stricmp(os_name, "Windows_NT") == 0) {
bImpersonate = TRUE;
return 1;
}
return 0;
}
int OS_StartImpersonation(void)
{
if (!bImpersonate) {
return 1;
} else if (hListen == INVALID_HANDLE_VALUE) {
return 1;
} else {
if (ImpersonateNamedPipeClient(hListen)) {
bImpersonated = TRUE;
return 1;
}
}
return 0;
}
void OS_StopImpersonation(void)
{
if (bImpersonated) {
bImpersonated = FALSE;
RevertToSelf();
}
}
int OS_LibInit(int stdioFds[3])
{
WORD wVersion;
WSADATA wsaData;
int err;
int fakeFd;
char *cLenPtr = NULL;
char *val = NULL;
if(libInitialized)
return 0;
InitializeCriticalSection(&fdTableCritical);
wVersion = MAKEWORD(2,0);
err = WSAStartup( wVersion, &wsaData );
if (err) {
fprintf(stderr, "Error starting Windows Sockets. Error: %d",
WSAGetLastError());
return -1;
}
if (hIoCompPort == INVALID_HANDLE_VALUE) {
hIoCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
0, 1);
if(hIoCompPort == INVALID_HANDLE_VALUE) {
printf("<H2>OS_LibInit Failed CreateIoCompletionPort! ERROR: %d</H2>\r\n\r\n",
GetLastError());
return -1;
}
}
val = getenv(SHUTDOWN_EVENT_NAME);
if (val != NULL)
{
HANDLE shutdownEvent = (HANDLE) atoi(val);
if (_beginthread(ShutdownRequestThread, 0, shutdownEvent) == -1)
{
return -1;
}
}
if (acceptMutex == INVALID_HANDLE_VALUE)
{
val = getenv(MUTEX_VARNAME);
if (val != NULL)
{
acceptMutex = (HANDLE) atoi(val);
}
}
if((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
(GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) &&
(GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) )
{
DWORD pipeMode = PIPE_READMODE_BYTE | PIPE_WAIT;
HANDLE oldStdIn = GetStdHandle(STD_INPUT_HANDLE);
if (! DuplicateHandle(GetCurrentProcess(), oldStdIn,
GetCurrentProcess(), &hListen,
0, TRUE, DUPLICATE_SAME_ACCESS))
{
return -1;
}
if (! SetStdHandle(STD_INPUT_HANDLE, hListen))
{
return -1;
}
CloseHandle(oldStdIn);
if (SetNamedPipeHandleState(hListen, &pipeMode, NULL, NULL))
{
listenType = FD_PIPE_SYNC;
}
else
{
listenType = FD_SOCKET_SYNC;
}
}
if(stdioFds == NULL) {
libInitialized = 1;
return 0;
}
stdioHandles[STDIN_FILENO] = GetStdHandle(STD_INPUT_HANDLE);
if(!SetHandleInformation(stdioHandles[STDIN_FILENO],
HANDLE_FLAG_INHERIT, 0)) {
}
if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
(int)stdioHandles[STDIN_FILENO],
STDIN_FILENO)) == -1) {
return -1;
} else {
stdioFds[STDIN_FILENO] = fakeFd;
}
if (hStdinCompPort == INVALID_HANDLE_VALUE) {
hStdinCompPort = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL,
0, 1);
if(hStdinCompPort == INVALID_HANDLE_VALUE) {
printf("<H2>OS_LibInit Failed CreateIoCompletionPort: STDIN! ERROR: %d</H2>\r\n\r\n",
GetLastError());
return -1;
}
}
if((cLenPtr = getenv("CONTENT_LENGTH")) != NULL &&
atoi(cLenPtr) > 0) {
hStdinThread = (HANDLE) _beginthread(StdinThread, 0, NULL);
if (hStdinThread == (HANDLE) -1) {
printf("<H2>OS_LibInit Failed to create STDIN thread! ERROR: %d</H2>\r\n\r\n",
GetLastError());
return -1;
}
}
stdioHandles[STDOUT_FILENO] = GetStdHandle(STD_OUTPUT_HANDLE);
if(!SetHandleInformation(stdioHandles[STDOUT_FILENO],
HANDLE_FLAG_INHERIT, FALSE)) {
return -1;
}
if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
(int)stdioHandles[STDOUT_FILENO],
STDOUT_FILENO)) == -1) {
return -1;
} else {
stdioFds[STDOUT_FILENO] = fakeFd;
}
stdioHandles[STDERR_FILENO] = GetStdHandle(STD_ERROR_HANDLE);
if(!SetHandleInformation(stdioHandles[STDERR_FILENO],
HANDLE_FLAG_INHERIT, FALSE)) {
return -1;
}
if ((fakeFd = Win32NewDescriptor(FD_PIPE_SYNC,
(int)stdioHandles[STDERR_FILENO],
STDERR_FILENO)) == -1) {
return -1;
} else {
stdioFds[STDERR_FILENO] = fakeFd;
}
return 0;
}
void OS_LibShutdown()
{
if (hIoCompPort != INVALID_HANDLE_VALUE)
{
CloseHandle(hIoCompPort);
hIoCompPort = INVALID_HANDLE_VALUE;
}
if (hStdinCompPort != INVALID_HANDLE_VALUE)
{
CloseHandle(hStdinCompPort);
hStdinCompPort = INVALID_HANDLE_VALUE;
}
if (acceptMutex != INVALID_HANDLE_VALUE)
{
ReleaseMutex(acceptMutex);
}
if (stdioHandles[0] != INVALID_HANDLE_VALUE) {
DisconnectNamedPipe(hListen);
CancelIo(hListen);
OS_StopImpersonation();
}
WSACleanup();
}
static void Win32FreeDescriptor(int fd)
{
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
EnterCriticalSection(&fdTableCritical);
if (fdTable[fd].type != FD_UNUSED)
{
switch (fdTable[fd].type)
{
case FD_FILE_SYNC:
case FD_FILE_ASYNC:
ASSERT(fdTable[fd].path != NULL);
free(fdTable[fd].path);
fdTable[fd].path = NULL;
break;
default:
break;
}
ASSERT(fdTable[fd].path == NULL);
fdTable[fd].type = FD_UNUSED;
fdTable[fd].path = NULL;
fdTable[fd].Errno = NO_ERROR;
fdTable[fd].offsetHighPtr = fdTable[fd].offsetLowPtr = NULL;
if (fdTable[fd].hMapMutex != NULL)
{
CloseHandle(fdTable[fd].hMapMutex);
fdTable[fd].hMapMutex = NULL;
}
}
LeaveCriticalSection(&fdTableCritical);
return;
}
static short getPort(const char * bindPath)
{
short port = 0;
char * p = strchr(bindPath, ':');
if (p && *++p)
{
char buf[6];
strncpy(buf, p, 6);
buf[5] = '\0';
port = (short) atoi(buf);
}
return port;
}
BOOL
BuildNamedPipeAcl(
PACL pAcl,
PDWORD cbAclSize
)
{
DWORD dwAclSize;
SID_IDENTIFIER_AUTHORITY siaWorld = SECURITY_WORLD_SID_AUTHORITY;
SID_IDENTIFIER_AUTHORITY siaCreator = SECURITY_CREATOR_SID_AUTHORITY;
BYTE BufEveryoneSid[32];
BYTE BufOwnerSid[32];
PSID pEveryoneSid = (PSID)BufEveryoneSid;
PSID pOwnerSid = (PSID)BufOwnerSid;
dwAclSize = sizeof(ACL) +
2 * ( sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) ) +
GetSidLengthRequired( 1 ) + GetSidLengthRequired( 1 ) ;
if(*cbAclSize < dwAclSize) {
*cbAclSize = dwAclSize;
return FALSE;
}
*cbAclSize = dwAclSize;
if(!InitializeSid(pEveryoneSid, &siaWorld, 1)) return FALSE;
*GetSidSubAuthority(pEveryoneSid, 0) = SECURITY_WORLD_RID;
if(!InitializeSid(pOwnerSid, &siaCreator, 1)) return FALSE;
*GetSidSubAuthority(pOwnerSid, 0) = SECURITY_CREATOR_OWNER_RID;
if(!InitializeAcl(pAcl, dwAclSize, ACL_REVISION))
return FALSE;
if(!AddAccessAllowedAce(
pAcl,
ACL_REVISION,
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
pEveryoneSid
))
return FALSE;
return AddAccessAllowedAce(
pAcl,
ACL_REVISION,
FILE_ALL_ACCESS,
pOwnerSid
);
}
int OS_CreateLocalIpcFd(const char *bindPath, int backlog)
{
int pseudoFd = -1;
short port = getPort(bindPath);
if (acceptMutex == INVALID_HANDLE_VALUE)
{
acceptMutex = CreateMutex(NULL, FALSE, NULL);
if (acceptMutex == NULL) return -2;
if (! SetHandleInformation(acceptMutex, HANDLE_FLAG_INHERIT, TRUE)) return -3;
}
if (port && *bindPath != ':' && strncmp(bindPath, LOCALHOST, strlen(LOCALHOST)))
{
fprintf(stderr, "To start a service on a TCP port can not "
"specify a host name.\n"
"You should either use \"localhost:<port>\" or "
" just use \":<port>.\"\n");
return -1;
}
listenType = (port) ? FD_SOCKET_SYNC : FD_PIPE_ASYNC;
if (port)
{
SOCKET listenSock;
struct sockaddr_in sockAddr;
int sockLen = sizeof(sockAddr);
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
sockAddr.sin_port = htons(port);
listenSock = socket(AF_INET, SOCK_STREAM, 0);
if (listenSock == INVALID_SOCKET)
{
return -4;
}
if (bind(listenSock, (struct sockaddr *) &sockAddr, sockLen) )
{
return -12;
}
if (listen(listenSock, backlog))
{
return -5;
}
pseudoFd = Win32NewDescriptor(listenType, listenSock, -1);
if (pseudoFd == -1)
{
closesocket(listenSock);
return -6;
}
hListen = (HANDLE) listenSock;
}
else
{
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
BYTE AclBuf[ 64 ];
DWORD cbAclSize = 64;
PACL pAcl = (PACL)AclBuf;
HANDLE hListenPipe = INVALID_HANDLE_VALUE;
char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
if (! pipePath)
{
return -7;
}
strcpy(pipePath, bindPathPrefix);
strcat(pipePath, bindPath);
if (bImpersonate) {
SetErrorMode(SEM_FAILCRITICALERRORS);
if(!BuildNamedPipeAcl(pAcl, &cbAclSize)) {
fprintf(stderr, "BuildNamedPipeAcl");
return -100;
}
if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
fprintf(stderr, "InitializeSecurityDescriptor");
return -100;
}
if(!SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE)) {
fprintf(stderr, "SetSecurityDescriptorDacl");
return -100;
}
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd; sa.bInheritHandle = TRUE;
}
hListenPipe = CreateNamedPipe(pipePath,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_READMODE_BYTE,
PIPE_UNLIMITED_INSTANCES,
4096, 4096, 0, bImpersonate?&sa:NULL);
free(pipePath);
if (hListenPipe == INVALID_HANDLE_VALUE)
{
return -8;
}
if (! SetHandleInformation(hListenPipe, HANDLE_FLAG_INHERIT, TRUE))
{
return -9;
}
pseudoFd = Win32NewDescriptor(listenType, (int) hListenPipe, -1);
if (pseudoFd == -1)
{
CloseHandle(hListenPipe);
return -10;
}
hListen = (HANDLE) hListenPipe;
}
return pseudoFd;
}
int OS_FcgiConnect(char *bindPath)
{
short port = getPort(bindPath);
int pseudoFd = -1;
unsigned int flags = FILE_FLAG_OVERLAPPED;
if (port)
{
struct hostent *hp;
char *host = NULL;
struct sockaddr_in sockAddr;
int sockLen = sizeof(sockAddr);
SOCKET sock;
if (*bindPath != ':')
{
char * p = strchr(bindPath, ':');
if (p) {
int len = p - bindPath + 1;
host = (char *)malloc(len);
if (!host) {
fprintf(stderr, "Unable to allocate memory\n");
return -1;
}
strncpy(host, bindPath, len);
host[len-1] = '\0';
}
}
hp = gethostbyname(host ? host : LOCALHOST);
if (host)
{
free(host);
}
if (hp == NULL)
{
fprintf(stderr, "Unknown host: %s\n", bindPath);
return -1;
}
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
memcpy(&sockAddr.sin_addr, hp->h_addr, hp->h_length);
sockAddr.sin_port = htons(port);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET)
{
return -1;
}
if (connect(sock, (struct sockaddr *) &sockAddr, sockLen) == SOCKET_ERROR)
{
closesocket(sock);
return -1;
}
pseudoFd = Win32NewDescriptor(FD_SOCKET_SYNC, sock, -1);
if (pseudoFd == -1)
{
closesocket(sock);
return -1;
}
}
else
{
char *pipePath = malloc(strlen(bindPathPrefix) + strlen(bindPath) + 1);
HANDLE hPipe;
if (! pipePath)
{
return -1;
}
strcpy(pipePath, bindPathPrefix);
strcat(pipePath, bindPath);
if (bImpersonate) {
flags |= SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION;
}
hPipe = CreateFile(pipePath,
GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
flags,
NULL);
free(pipePath);
if( hPipe == INVALID_HANDLE_VALUE || hPipe == 0)
{
return -1;
}
pseudoFd = Win32NewDescriptor(FD_PIPE_ASYNC, (int) hPipe, -1);
if (pseudoFd == -1)
{
CloseHandle(hPipe);
return -1;
}
if (! CreateIoCompletionPort(hPipe, hIoCompPort, pseudoFd, 1))
{
Win32FreeDescriptor(pseudoFd);
CloseHandle(hPipe);
return -1;
}
}
return pseudoFd;
}
int OS_Read(int fd, char * buf, size_t len)
{
DWORD bytesRead;
int ret = -1;
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
if (shutdownNow) return -1;
switch (fdTable[fd].type)
{
case FD_FILE_SYNC:
case FD_FILE_ASYNC:
case FD_PIPE_SYNC:
case FD_PIPE_ASYNC:
if (ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead, NULL))
{
ret = bytesRead;
}
else
{
fdTable[fd].Errno = GetLastError();
}
break;
case FD_SOCKET_SYNC:
case FD_SOCKET_ASYNC:
ret = recv(fdTable[fd].fid.sock, buf, len, 0);
if (ret == SOCKET_ERROR)
{
fdTable[fd].Errno = WSAGetLastError();
ret = -1;
}
break;
default:
ASSERT(0);
}
return ret;
}
int OS_Write(int fd, char * buf, size_t len)
{
DWORD bytesWritten;
int ret = -1;
ASSERT(fd >= 0 && fd < WIN32_OPEN_MAX);
if (shutdownNow) return -1;
switch (fdTable[fd].type)
{
case FD_FILE_SYNC:
case FD_FILE_ASYNC:
case FD_PIPE_SYNC:
case FD_PIPE_ASYNC:
if (WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten, NULL))
{
ret = bytesWritten;
}
else
{
fdTable[fd].Errno = GetLastError();
}
break;
case FD_SOCKET_SYNC:
case FD_SOCKET_ASYNC:
ret = send(fdTable[fd].fid.sock, buf, len, 0);
if (ret == SOCKET_ERROR)
{
fdTable[fd].Errno = WSAGetLastError();
ret = -1;
}
break;
default:
ASSERT(0);
}
return ret;
}
int OS_SpawnChild(char *execPath, int listenFd, PROCESS_INFORMATION *pInfo, char *env)
{
STARTUPINFO StartupInfo;
BOOL success;
memset((void *)&StartupInfo, 0, sizeof(STARTUPINFO));
StartupInfo.cb = sizeof (STARTUPINFO);
StartupInfo.lpReserved = NULL;
StartupInfo.lpReserved2 = NULL;
StartupInfo.cbReserved2 = 0;
StartupInfo.lpDesktop = NULL;
StartupInfo.dwFlags = STARTF_USESTDHANDLES;
StartupInfo.hStdInput = fdTable[listenFd].fid.fileHandle;
StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
StartupInfo.hStdError = INVALID_HANDLE_VALUE;
success = SetHandleInformation(StartupInfo.hStdInput, HANDLE_FLAG_INHERIT,
TRUE);
if(!success) {
return -1;
}
success = CreateProcess(execPath,
NULL,
NULL,
NULL,
TRUE,
0,
env,
NULL,
&StartupInfo,
pInfo);
if(success) {
return 0;
} else {
return -1;
}
}
int OS_AsyncReadStdin(void *buf, int len, OS_AsyncProc procPtr,
ClientData clientData)
{
POVERLAPPED_REQUEST pOv;
ASSERT(fdTable[STDIN_FILENO].type != FD_UNUSED);
pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
ASSERT(pOv);
memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
pOv->clientData1 = (ClientData)buf;
pOv->instance = fdTable[STDIN_FILENO].instance;
pOv->procPtr = procPtr;
pOv->clientData = clientData;
PostQueuedCompletionStatus(hStdinCompPort, len, STDIN_FILENO,
(LPOVERLAPPED)pOv);
return 0;
}
int OS_AsyncRead(int fd, int offset, void *buf, int len,
OS_AsyncProc procPtr, ClientData clientData)
{
DWORD bytesRead;
POVERLAPPED_REQUEST pOv;
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
ASSERT(fdTable[fd].type != FD_UNUSED);
ASSERT(fdTable[fd].type != FD_FILE_SYNC);
ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
ASSERT(pOv);
memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
if (fdTable[fd].type == FD_FILE_ASYNC)
if (fdTable[fd].offset >= 0)
pOv->overlapped.Offset = fdTable[fd].offset;
else
pOv->overlapped.Offset = offset;
pOv->instance = fdTable[fd].instance;
pOv->procPtr = procPtr;
pOv->clientData = clientData;
bytesRead = fd;
if (!ReadFile(fdTable[fd].fid.fileHandle, buf, len, &bytesRead,
(LPOVERLAPPED)pOv)) {
fdTable[fd].Errno = GetLastError();
if(fdTable[fd].Errno == ERROR_NO_DATA ||
fdTable[fd].Errno == ERROR_PIPE_NOT_CONNECTED) {
PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
return 0;
}
if(fdTable[fd].Errno != ERROR_IO_PENDING) {
PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
return -1;
}
fdTable[fd].Errno = 0;
}
return 0;
}
int OS_AsyncWrite(int fd, int offset, void *buf, int len,
OS_AsyncProc procPtr, ClientData clientData)
{
DWORD bytesWritten;
POVERLAPPED_REQUEST pOv;
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
ASSERT(fdTable[fd].type != FD_UNUSED);
ASSERT(fdTable[fd].type != FD_FILE_SYNC);
ASSERT(fdTable[fd].type != FD_PIPE_SYNC);
ASSERT(fdTable[fd].type != FD_SOCKET_SYNC);
pOv = (POVERLAPPED_REQUEST)malloc(sizeof(struct OVERLAPPED_REQUEST));
ASSERT(pOv);
memset((void *)pOv, 0, sizeof(struct OVERLAPPED_REQUEST));
if (fdTable[fd].type == FD_FILE_ASYNC)
if (fdTable[fd].offset >= 0)
if (fdTable[fd].hMapMutex != NULL) {
WaitForSingleObject(fdTable[fd].hMapMutex, INFINITE);
pOv->overlapped.OffsetHigh = *(fdTable[fd].offsetHighPtr);
pOv->overlapped.Offset = *(fdTable[fd].offsetLowPtr);
*(fdTable[fd].offsetHighPtr) += 0;
*(fdTable[fd].offsetLowPtr) += len;
ReleaseMutex(fdTable[fd].hMapMutex);
} else
pOv->overlapped.Offset = fdTable[fd].offset;
else
pOv->overlapped.Offset = offset;
pOv->instance = fdTable[fd].instance;
pOv->procPtr = procPtr;
pOv->clientData = clientData;
bytesWritten = fd;
if (!WriteFile(fdTable[fd].fid.fileHandle, buf, len, &bytesWritten,
(LPOVERLAPPED)pOv)) {
fdTable[fd].Errno = GetLastError();
if(fdTable[fd].Errno != ERROR_IO_PENDING) {
PostQueuedCompletionStatus(hIoCompPort, 0, fd, (LPOVERLAPPED)pOv);
return -1;
}
fdTable[fd].Errno = 0;
}
if (fdTable[fd].offset >= 0)
fdTable[fd].offset += len;
return 0;
}
int OS_Close(int fd, int shutdown_ok)
{
int ret = 0;
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
ASSERT(fdTable[fd].type != FD_UNUSED);
switch (fdTable[fd].type) {
case FD_PIPE_SYNC:
case FD_PIPE_ASYNC:
case FD_FILE_SYNC:
case FD_FILE_ASYNC:
break;
case FD_SOCKET_SYNC:
case FD_SOCKET_ASYNC:
if (shutdown_ok)
{
if (shutdown(fdTable[fd].fid.sock, SD_SEND) == 0)
{
struct timeval tv;
fd_set rfds;
int sock = fdTable[fd].fid.sock;
int rv;
char trash[1024];
FD_ZERO(&rfds);
do
{
#pragma warning( disable : 4127 )
FD_SET((unsigned) sock, &rfds);
#pragma warning( default : 4127 )
tv.tv_sec = 2;
tv.tv_usec = 0;
rv = select(sock + 1, &rfds, NULL, NULL, &tv);
}
while (rv > 0 && recv(sock, trash, sizeof(trash), 0) > 0);
}
}
closesocket(fdTable[fd].fid.sock);
break;
default:
ret = -1;
}
Win32FreeDescriptor(fd);
return ret;
}
int OS_CloseRead(int fd)
{
int ret = 0;
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
ASSERT(fdTable[fd].type == FD_SOCKET_ASYNC
|| fdTable[fd].type == FD_SOCKET_SYNC);
if (shutdown(fdTable[fd].fid.sock,SD_RECEIVE) == SOCKET_ERROR)
ret = -1;
return ret;
}
int OS_DoIo(struct timeval *tmo)
{
unsigned long fd;
unsigned long bytes;
POVERLAPPED_REQUEST pOv;
struct timeb tb;
int ms;
int ms_last;
int err;
if(tmo)
ms = (tmo->tv_sec*1000 + tmo->tv_usec/1000) / 2;
else
ms = 1000;
ftime(&tb);
ms_last = tb.time*1000 + tb.millitm;
while (ms >= 0) {
if(tmo && (ms = tmo->tv_sec*1000 + tmo->tv_usec/1000)> 100)
ms = 100;
if (!GetQueuedCompletionStatus(hIoCompPort, &bytes, &fd,
(LPOVERLAPPED *)&pOv, ms) && !pOv) {
err = WSAGetLastError();
return 0;
}
ASSERT((fd >= 0) && (fd < WIN32_OPEN_MAX));
ASSERT(pOv);
if(pOv->instance == fdTable[fd].instance)
(*pOv->procPtr)(pOv->clientData, bytes);
free(pOv);
ftime(&tb);
ms -= (tb.time*1000 + tb.millitm - ms_last);
ms_last = tb.time*1000 + tb.millitm;
}
return 0;
}
static int isAddrOK(struct sockaddr_in * inet_sockaddr, const char * okAddrs)
{
static const char *token = " ,;:\t";
char *ipaddr;
char *p;
if (okAddrs == NULL) return TRUE;
ipaddr = inet_ntoa(inet_sockaddr->sin_addr);
p = strstr(okAddrs, ipaddr);
if (p == NULL) return FALSE;
if (p == okAddrs)
{
p += strlen(ipaddr);
return (strchr(token, *p) != NULL);
}
if (strchr(token, *--p) != NULL)
{
p += strlen(ipaddr) + 1;
return (strchr(token, *p) != NULL);
}
return FALSE;
}
#ifndef NO_WSAACEPT
static int CALLBACK isAddrOKCallback(LPWSABUF lpCallerId,
LPWSABUF dc0,
LPQOS dc1,
LPQOS dc2,
LPWSABUF dc3,
LPWSABUF dc4,
GROUP *dc5,
DWORD data)
{
struct sockaddr_in *sockaddr = (struct sockaddr_in *) lpCallerId->buf;
dc0 = NULL; dc1 = NULL; dc2 = NULL; dc3 = NULL; dc4 = NULL; dc5 = NULL;
if ((void *) data == NULL) return CF_ACCEPT;
if (sockaddr->sin_family != AF_INET) return CF_ACCEPT;
return isAddrOK(sockaddr, (const char *) data) ? CF_ACCEPT : CF_REJECT;
}
#endif
static void printLastError(const char * text)
{
LPVOID buf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
0,
(LPTSTR) &buf,
0,
NULL
);
fprintf(stderr, "%s: %s\n", text, (LPCTSTR) buf);
LocalFree(buf);
}
static int acceptNamedPipe()
{
int ipcFd = -1;
if (! ConnectNamedPipe(hListen, NULL))
{
switch (GetLastError())
{
case ERROR_PIPE_CONNECTED:
break;
case ERROR_IO_PENDING:
case ERROR_PIPE_LISTENING:
case ERROR_NO_DATA:
default:
printLastError("unexpected ConnectNamedPipe() error");
}
}
ipcFd = Win32NewDescriptor(FD_PIPE_SYNC, (int) hListen, -1);
if (ipcFd == -1)
{
DisconnectNamedPipe(hListen);
}
return ipcFd;
}
static int acceptSocket(const char *webServerAddrs)
{
SOCKET hSock;
int ipcFd = -1;
for (;;)
{
struct sockaddr sockaddr;
int sockaddrLen = sizeof(sockaddr);
for (;;)
{
const struct timeval timeout = {1, 0};
fd_set readfds;
FD_ZERO(&readfds);
#pragma warning( disable : 4127 )
FD_SET((unsigned int) hListen, &readfds);
#pragma warning( default : 4127 )
if (select(0, &readfds, NULL, NULL, &timeout) == 0)
{
if (shutdownPending)
{
OS_LibShutdown();
return -1;
}
}
else
{
break;
}
}
#if NO_WSAACEPT
hSock = accept((SOCKET) hListen, &sockaddr, &sockaddrLen);
if (hSock == INVALID_SOCKET)
{
break;
}
if (isAddrOK((struct sockaddr_in *) &sockaddr, webServerAddrs))
{
break;
}
closesocket(hSock);
#else
hSock = WSAAccept((unsigned int) hListen,
&sockaddr,
&sockaddrLen,
isAddrOKCallback,
(DWORD) webServerAddrs);
if (hSock != INVALID_SOCKET)
{
break;
}
if (WSAGetLastError() != WSAECONNREFUSED)
{
break;
}
#endif
}
if (hSock == INVALID_SOCKET)
{
fprintf(stderr, "accept()/WSAAccept() failed: %d", WSAGetLastError());
return -1;
}
ipcFd = Win32NewDescriptor(FD_SOCKET_SYNC, hSock, -1);
if (ipcFd == -1)
{
closesocket(hSock);
}
return ipcFd;
}
int OS_Accept(int listen_sock, int fail_on_intr, const char *webServerAddrs)
{
int ipcFd = -1;
listen_sock = 0; fail_on_intr = 0;
if (shutdownPending)
{
OS_LibShutdown();
return -1;
}
if (acceptMutex != INVALID_HANDLE_VALUE)
{
DWORD ret;
#if YOU_WANT_TO_MAKE_THE_PROCESS_HANG_AFTER_FIRST_REQUEST
while ((ret = WaitForSingleObject(acceptMutex, ACCEPT_TIMEOUT)) == WAIT_TIMEOUT)
{
if (shutdownPending) break;
}
if (ret == WAIT_FAILED) {
#else
if (WaitForSingleObject(acceptMutex, INFINITE) == WAIT_FAILED) {
#endif
printLastError("WaitForSingleObject() failed");
return -1;
}
}
if (shutdownPending)
{
OS_LibShutdown();
}
else if (listenType == FD_PIPE_SYNC)
{
ipcFd = acceptNamedPipe();
}
else if (listenType == FD_SOCKET_SYNC)
{
ipcFd = acceptSocket(webServerAddrs);
}
else
{
fprintf(stderr, "unknown listenType (%d)\n", listenType);
}
if (acceptMutex != INVALID_HANDLE_VALUE)
{
ReleaseMutex(acceptMutex);
}
return ipcFd;
}
int OS_IpcClose(int ipcFd, int shutdown)
{
if (ipcFd == -1) return 0;
ASSERT((ipcFd >= 0) && (ipcFd < WIN32_OPEN_MAX));
ASSERT(fdTable[ipcFd].type != FD_UNUSED);
switch (listenType)
{
case FD_PIPE_SYNC:
if (! FlushFileBuffers(fdTable[ipcFd].fid.fileHandle)) return -1;
if (! DisconnectNamedPipe(fdTable[ipcFd].fid.fileHandle)) return -1;
OS_StopImpersonation();
case FD_SOCKET_SYNC:
OS_Close(ipcFd, shutdown);
break;
case FD_UNUSED:
default:
return -1;
break;
}
return 0;
}
int OS_IsFcgi(int sock)
{
sock = 0;
return (listenType != FD_UNUSED);
}
void OS_SetFlags(int fd, int flags)
{
unsigned long pLong = 1L;
if (fdTable[fd].type == FD_SOCKET_SYNC && flags == O_NONBLOCK) {
if (ioctlsocket(fdTable[fd].fid.sock, FIONBIO, &pLong) ==
SOCKET_ERROR) {
SetLastError(WSAGetLastError());
return;
}
if (!CreateIoCompletionPort((HANDLE)fdTable[fd].fid.sock,
hIoCompPort, fd, 1)) {
return;
}
fdTable[fd].type = FD_SOCKET_ASYNC;
}
return;
}