Exemple #1
1
HRESULT NamedPipeChannel::Create(const base::StringPiece16& name, DWORD mode,
                                 DWORD max_instances, DWORD default_timeout) {
  // drop unsupported flags
  mode &= ~(PIPE_NOWAIT | PIPE_REJECT_REMOTE_CLIENTS);

  base::AutoLock guard(lock_);

  if (work_ == nullptr || handle_ != INVALID_HANDLE_VALUE || io_ != nullptr)
    return E_HANDLE;

  auto pipe_name = kPipeNamePrefix + name.as_string();

  handle_ = CreateNamedPipe(pipe_name.c_str(),
                            PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, mode,
                            max_instances, 0, 0, default_timeout, nullptr);
  if (handle_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_WIN32(GetLastError());

  io_ = CreateThreadpoolIo(handle_, OnCompleted, this, nullptr);
  if (io_ == nullptr)
    return HRESULT_FROM_WIN32(GetLastError());

  end_point_ = EndPoint::kServer;

  return S_OK;
}
Exemple #2
0
HRESULT NamedPipe::Create(const wchar_t* name, DWORD max_instances) {
  base::AutoLock guard(lock_);

  if (work_ == nullptr || pipe_ != INVALID_HANDLE_VALUE || io_ != nullptr)
    return E_HANDLE;

  if (name == nullptr || max_instances < 1 ||
      PIPE_UNLIMITED_INSTANCES < max_instances)
    return E_INVALIDARG;

  wchar_t pipe_name[256];
  swprintf_s(pipe_name, L"\\\\.\\pipe\\%s", name);

  pipe_ = CreateNamedPipe(pipe_name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                          PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
                          max_instances, 0, 0, 0, nullptr);
  if (pipe_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_WIN32(GetLastError());

  io_ = CreateThreadpoolIo(pipe_, OnCompleted, this, nullptr);
  if (io_ == nullptr)
    return HRESULT_FROM_WIN32(GetLastError());

  return S_OK;
}
Exemple #3
0
HRESULT NamedPipe::ConnectTo(const wchar_t* name, DWORD timeout) {
  base::AutoLock guard(lock_);

  if (work_ == nullptr || pipe_ != INVALID_HANDLE_VALUE || io_ != nullptr)
    return E_HANDLE;

  if (name == nullptr)
    return E_INVALIDARG;

  wchar_t pipe_name[256];
  swprintf_s(pipe_name, L"\\\\.\\pipe\\%s", name);

  if (!WaitNamedPipe(pipe_name, timeout))
    return HRESULT_FROM_WIN32(GetLastError());

  pipe_ = CreateFile(pipe_name, GENERIC_READ | GENERIC_WRITE,
                     FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
                     FILE_FLAG_OVERLAPPED, NULL);
  if (pipe_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_WIN32(GetLastError());

  io_ = CreateThreadpoolIo(pipe_, OnCompleted, this, nullptr);
  if (io_ == nullptr)
    return HRESULT_FROM_WIN32(GetLastError());

  return S_OK;
}
Exemple #4
0
HRESULT NamedPipeChannel::Open(const base::StringPiece16& name, DWORD timeout) {
  base::AutoLock guard(lock_);

  if (work_ == nullptr || handle_ != INVALID_HANDLE_VALUE || io_ != nullptr)
    return E_HANDLE;

  auto pipe_name = kPipeNamePrefix + name.as_string();

  if (!WaitNamedPipe(pipe_name.c_str(), timeout))
    return HRESULT_FROM_WIN32(GetLastError());

  handle_ = CreateFile(pipe_name.c_str(), GENERIC_READ | GENERIC_WRITE,
                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                       nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  if (handle_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_WIN32(GetLastError());

  io_ = CreateThreadpoolIo(handle_, OnCompleted, this, nullptr);
  if (io_ == nullptr)
    return HRESULT_FROM_WIN32(GetLastError());

  end_point_ = EndPoint::kClient;

  return S_OK;
}
CF_PRIVATE Boolean _CFWriteBytesToFileAsync(CFURLRef url, const void *bytes, CFIndex length) {
    char path[CFMaxPathSize];
    if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)path, CFMaxPathSize)) {
        return false;
    }

    wchar_t wpath[CFMaxPathSize];
    int convertedLength = MultiByteToWideChar(CP_UTF8, 0, path, CFMaxPathSize, wpath, CFMaxPathSize);
    if (0 == convertedLength) {
        unsigned error = GetLastError();
        CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to convert the path (error %u)"), error);
        return false;
    }

    HANDLE fileHandle = NULL;
    CREATEFILE2_EXTENDED_PARAMETERS createExParams;
    createExParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
    createExParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
    createExParams.dwFileFlags = FILE_FLAG_OVERLAPPED;
    createExParams.dwSecurityQosFlags = 0;
    createExParams.lpSecurityAttributes = NULL;
    createExParams.hTemplateFile = NULL;

    OVERLAPPED* overlapped = (OVERLAPPED*)calloc(1, sizeof(OVERLAPPED));

    if ((fileHandle = CreateFile2(wpath, GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, &createExParams)) == INVALID_HANDLE_VALUE) {
        unsigned error = GetLastError();
        CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to open the file (error %u)"), error);
        free(overlapped);
        return false;
    }

    PTP_IO threadPoolIo = CreateThreadpoolIo(fileHandle, _threadpoolCallback, NULL, NULL);
    StartThreadpoolIo(threadPoolIo);

    if (!WriteFile(fileHandle, bytes, length, NULL, overlapped)) {
        unsigned error = GetLastError();
        if (ERROR_IO_PENDING != error) {
            CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to write to the file (error %u)"), error);
            CloseHandle(fileHandle);
            CancelThreadpoolIo(threadPoolIo);
            CloseThreadpoolIo(threadPoolIo);
            free(overlapped);
            return false;
        }
    }

    CloseHandle(fileHandle);

    return true;
}
BOOL InitializeServerIo(
    PSERVER_CONTEXT pServerContext
)
{
    ULONG Result;
    HTTP_BINDING_INFO HttpBindingInfo = {0};

    Result = HttpCreateRequestQueue(
                 g_HttpApiVersion,
                 L"Test_Http_Server_HTTPAPI_V2",
                 NULL,
                 0,
                 &(pServerContext->hRequestQueue));

    if (Result != NO_ERROR)
    {
        fprintf(stderr, "HttpCreateRequestQueue failed\n");
        return FALSE;
    }

    HttpBindingInfo.Flags.Present       = 1;
    HttpBindingInfo.RequestQueueHandle  = pServerContext->hRequestQueue;

    Result = HttpSetUrlGroupProperty(
                 pServerContext->urlGroupId,
                 HttpServerBindingProperty,
                 &HttpBindingInfo,
                 sizeof(HttpBindingInfo));

    if (Result != NO_ERROR)
    {
        fprintf(stderr, "HttpSetUrlGroupProperty(...HttpServerBindingProperty...) failed\n");
        return FALSE;
    }

    pServerContext->Io = CreateThreadpoolIo(
                             pServerContext->hRequestQueue,
                             IoCompletionCallback,
                             NULL,
                             NULL);

    if (pServerContext->Io == NULL)
    {
        fprintf(stderr, "Creating a new I/O completion object failed\n");
        return FALSE;
    }

    return TRUE;
}
bool test_new_thread_pool() {//success is true, failure is false
	int sockErr;

	WSADATA lpWSAData={0};
	sockErr=WSAStartup(0x202, &lpWSAData);
	sListen=WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
	if(INVALID_SOCKET==sListen){
		DebugBreak();
	}
	GUID GuidDisconnectEx = WSAID_DISCONNECTEX;
	DWORD dwBytes;
	WSAIoctl(sListen, SIO_GET_EXTENSION_FUNCTION_POINTER,
             &GuidDisconnectEx, sizeof (GuidDisconnectEx), 
             &DisconnectEx, sizeof (DisconnectEx), 
             &dwBytes, NULL, NULL);
	

	InitializeThreadpoolEnvironment(&tEnvrion);
	pMainPool=CreateThreadpool(NULL);
	pCleanup=CreateThreadpoolCleanupGroup();
	SetThreadpoolCallbackCleanupGroup(&tEnvrion, pCleanup, 0);
	SetThreadpoolCallbackPool(&tEnvrion, pMainPool);

	pListen=CreateThreadpoolIo((HANDLE)sListen, acceptingIoThreadProc, 0, &tEnvrion);

	sockaddr_in service={0};
	service.sin_family=AF_INET;
	service.sin_port=htons(8080);

	sockErr=bind(sListen, (SOCKADDR *) &service, sizeof(service));
	if(SOCKET_ERROR==sockErr){
		DebugBreak();
	}
	sockErr=listen(sListen, SOMAXCONN);
	if(SOCKET_ERROR==sockErr){
		DebugBreak();
	}
	for(int i=0; i<numSockets; i++){
		ntpAddAcceptSocket(sListen);
	}
	OutputDebugString(TEXT("CloseThreadpoolCleanupGroupMembers waiting\n"));
	SleepEx(INFINITE, TRUE);
	CloseThreadpoolCleanupGroupMembers(pCleanup, FALSE, NULL);
	OutputDebugString(TEXT("CloseThreadpoolCleanupGroupMembers done\n"));
	
	return false;
}
Exemple #8
0
void Server::AddClient(Client* client)
{
    assert(client);

    // The socket sAcceptSocket does not inherit the properties of the socket associated with
    // sListenSocket parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket.
    if (setsockopt(client->GetSocket(), SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
                   reinterpret_cast<const char*>(&m_listenSocket),
                   sizeof(m_listenSocket)) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "setsockopt() for AcceptEx() failed.");

        RemoveClient(client);
    }
    else
    {
        client->SetState(Client::ACCEPTED);

        // Connect the socket to IOCP
        TP_IO* pTPIO = CreateThreadpoolIo(reinterpret_cast<HANDLE>(client->GetSocket()),
                                          Server::IoCompletionCallback, NULL, NULL);
        if (pTPIO == NULL)
        {
            ERROR_CODE(GetLastError(), "CreateThreadpoolIo failed for a client.");

            RemoveClient(client);
        }
        else
        {
            std::string ip;
            u_short port = 0;
            Network::GetRemoteAddress(client->GetSocket(), ip, port);
            TRACE("[%d] Accept succeeded. client address : ip[%s], port[%d]", GetCurrentThreadId(),
                  ip.c_str(), port);

            client->SetTPIO(pTPIO);

            EnterCriticalSection(&m_CSForClients);
            m_Clients.push_back(client);
            LeaveCriticalSection(&m_CSForClients);

            PostRecv(client);
        }
    }
}
void ntpAddAcceptSocket(SOCKET sListen) {
	BOOL success;
	SOCKET sAccept=WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
	if(INVALID_SOCKET==sAccept){
		DebugBreak();
	}
	DWORD nBufSize=max(4096, (sizeof(sockaddr_in)+16)*2);
	LPOVERLAPPED_ACCEPT ola=(LPOVERLAPPED_ACCEPT)HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS|HEAP_ZERO_MEMORY, sizeof(OVERLAPPED_ACCEPT)+nBufSize);
	ola->tp=CreateThreadpoolIo((HANDLE)sAccept, workerIoThreadProc, 0, &tEnvrion);
	ola->acceptBuf=(UINT8*)ola+sizeof(OVERLAPPED_ACCEPT);
	ola->s=sAccept;
	ola->bufSize=nBufSize;
	DWORD acceptBufSize=max(0, ola->bufSize-sizeof(sockaddr_in)-16-sizeof(sockaddr_in)-16);
	acceptBufSize=0;
	StartThreadpoolIo(pListen);
	success=AcceptEx(sListen, ola->s, ola->acceptBuf, acceptBufSize, sizeof(sockaddr_in)+16, sizeof(sockaddr_in)+16, 0, &ola->overlapped);
	if(!success && WSAGetLastError()!=ERROR_IO_PENDING){
		DebugBreak();
	}
}
Exemple #10
0
bool Server::Create(short port, int maxPostAccept)
{
    assert(maxPostAccept > 0);

    m_MaxPostAccept = maxPostAccept;

    // Create Client Work Thread Env for using cleaning group. We need this for shutting down
    // properly.
    InitializeThreadpoolEnvironment(&m_ClientTPENV);
    m_ClientTPCLEAN = CreateThreadpoolCleanupGroup();
    if (m_ClientTPCLEAN == NULL)
    {
        ERROR_CODE(GetLastError(), "Could not create client cleaning group.");
        return false;
    }
    SetThreadpoolCallbackCleanupGroup(&m_ClientTPENV, m_ClientTPCLEAN, NULL);

    // Create Listen Socket
    m_listenSocket = Network::CreateSocket(true, port);
    if (m_listenSocket == INVALID_SOCKET)
    {
        return false;
    }

    // Make the address re-usable to re-run the same server instantly.
    bool reuseAddr = true;
    if (setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR,
                   reinterpret_cast<const char*>(&reuseAddr), sizeof(reuseAddr)) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "setsockopt() failed with SO_REUSEADDR.");
        Destroy();
        return false;
    }

    // Create & Start ThreaddPool for socket IO
    m_pTPIO = CreateThreadpoolIo(reinterpret_cast<HANDLE>(m_listenSocket),
                                 Server::IoCompletionCallback, NULL, NULL);
    if (m_pTPIO == NULL)
    {
        ERROR_CODE(WSAGetLastError(), "Could not assign the listen socket to the IOCP handle.");
        Destroy();
        return false;
    }

    // Start listening
    StartThreadpoolIo(m_pTPIO);
    if (listen(m_listenSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "listen() failed.");
        return false;
    }

    // Create critical sections for m_Clients
    InitializeCriticalSection(&m_CSForClients);

    // Create Accept worker
    m_AcceptTPWORK = CreateThreadpoolWork(Server::WorkerPostAccept, this, NULL);
    if (m_AcceptTPWORK == NULL)
    {
        ERROR_CODE(GetLastError(), "Could not create AcceptEx worker TPIO.");
        Destroy();
        return false;
    }

    m_ShuttingDown = false;

    SubmitThreadpoolWork(m_AcceptTPWORK);

    return true;
}
Exemple #11
0
DWORD
CreateHttpListener(
	OUT PHTTP_LISTENER* httpListener
	)
{

	ULONG           result;

	PHTTP_LISTENER _listener = (PHTTP_LISTENER)ALLOC_MEM(sizeof(HTTP_LISTENER)); 
	ZeroMemory(_listener, sizeof(HTTP_LISTENER));
	(*httpListener) = _listener;

	_listener->hRequestQueue = NULL;
	_listener->RequestQueueLength = 5000; // Default request queue length;
	_listener->errorCode = 0;
	_listener->urls = NULL;
	_listener->pthreadPoolIO = NULL;
	_listener->State = HTTP_LISTENER_STATE_FAULTED;	
	_listener->stats = (PLISTENER_STATS)_aligned_malloc(sizeof(LISTENER_STATS),MEMORY_ALLOCATION_ALIGNMENT);
	HTTPAPI_VERSION HttpApiVersion = HTTPAPI_VERSION_2;	

	//
    // Initialize HTTP APIs.
    //
    result = HttpInitialize( 
                HttpApiVersion,
                HTTP_INITIALIZE_SERVER,    // Flags
                NULL                       // Reserved
                );

    if (result != NO_ERROR)
    {
		DEBUG_ASSERT(false);
		LOG_ERROR(L"\nHttpInitialize failed with %lu", result);		
    }
	
	if(result == NO_ERROR)
	{
		result = HttpCreateServerSession(HttpApiVersion,
										&_listener->SessionId, 
										NULL); 
		if(result)
		{		
			LOG_ERROR(L"\nHttpCreateServerSession failed with %lu", result);			
		}
	}

	if(result == NO_ERROR)
	{
		result = HttpCreateRequestQueue(HttpApiVersion, 
										NULL, 
										NULL, 
										0,
										&_listener->hRequestQueue);
		if(result)
		{
			LOG_ERROR(L"\nHttpCreateRequestQueue failed with %lu", result);				
		}
	}

	if(result == NO_ERROR)
	{
		result = HttpSetRequestQueueProperty(_listener->hRequestQueue, 
											HttpServerQueueLengthProperty, 
											&_listener->RequestQueueLength,
											sizeof(_listener->RequestQueueLength),
											NULL,
											NULL);
		if(result)
		{
			LOG_ERROR(L"\nHttpSetRequestQueueProperty failed with %lu", result);				
		}
	}
	
	if(result == NO_ERROR)
	{
		if(SetFileCompletionNotificationModes(_listener->hRequestQueue, 
											FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | 
											FILE_SKIP_SET_EVENT_ON_HANDLE) == FALSE)
		{
			result = GetLastError();			
		}
	}

	if(result == NO_ERROR)
	{	
		result = HttpListenerInitializeThreadPool(_listener);
	}

	if(result == NO_ERROR)
	{
		_listener->pthreadPoolIO =  CreateThreadpoolIo(_listener->hRequestQueue, 
														HttpListenerDemuxer, 
														(void*)_listener, 
														&_listener->tpEnvironment);
	}


	InitializeIOContextCache();
	InitializeHttpInputQueue(_listener);
	_listener->errorCode = result;
	return _listener->errorCode;
}