Beispiel #1
0
int x264_is_pipe( const char *path )
{
    wchar_t path_utf16[MAX_PATH];
    if( utf8_to_utf16( path, path_utf16 ) )
        return WaitNamedPipeW( path_utf16, 0 );
    return 0;
}
Beispiel #2
0
void log_init_thread()
{
	if (!logger_attached)
		return;
	LPCWSTR pipeName = L"\\\\.\\pipe\\flog_server";
	for (;;)
	{
		hLoggerPipe = CreateFileW(pipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
		if (hLoggerPipe == INVALID_HANDLE_VALUE)
		{
			/* Non critical error code, just wait and try connecting again */
			if (GetLastError() != ERROR_PIPE_BUSY || !WaitNamedPipeW(pipeName, NMPWAIT_WAIT_FOREVER))
			{
				logger_attached = 0;
				break;
			}
			continue;
		}
		/* Send initial request */
		struct request request;
		request.magic = PROTOCOL_MAGIC;
		request.version = PROTOCOL_VERSION;
		request.pid = GetProcessId(GetCurrentProcess());
		request.tid = GetThreadId(GetCurrentThread());
		DWORD written;
		if (!WriteFile(hLoggerPipe, &request, sizeof(request), &written, NULL))
		{
			CloseHandle(hLoggerPipe);
			logger_attached = 0;
		}
		break;
	}
}
Beispiel #3
0
	static bool connect_namedpipe(impl_type& impl,const String& name_,DWORD t)
	{
		String name=make_pipename(name_);
		(void)&impl;
		if(t==0) t=1;
		if (WaitNamedPipeW(IConv::to_wide(name).c_str(), t) == FALSE)
		{
			return false;
		}
		return true;
	}
Beispiel #4
0
static DWORD WINAPI pipe_connect_thread_proc(void* parameter) {
  HANDLE pipeHandle = INVALID_HANDLE_VALUE;
  int errno;
  uv_pipe_t* handle;
  uv_connect_t* req;

  req = (uv_connect_t*)parameter;
  assert(req);
  handle = (uv_pipe_t*)req->handle;
  assert(handle);

  /* We're here because CreateFile on a pipe returned ERROR_PIPE_BUSY.  We wait for the pipe to become available with WaitNamedPipe. */
  while (WaitNamedPipeW(handle->name, 30000)) {
    /* The pipe is now available, try to connect. */
    pipeHandle = CreateFileW(handle->name,
                            GENERIC_READ | GENERIC_WRITE,
                            0,
                            NULL,
                            OPEN_EXISTING,
                            FILE_FLAG_OVERLAPPED,
                            NULL);

    if (pipeHandle != INVALID_HANDLE_VALUE) {
      break;
    }
  }

  if (pipeHandle != INVALID_HANDLE_VALUE && !uv_set_pipe_handle(handle, pipeHandle)) {
    handle->handle = pipeHandle;
    req->error = uv_ok_;
  } else {
    req->error = uv_new_sys_error(GetLastError());
  }

  memset(&req->overlapped, 0, sizeof(req->overlapped));

  /* Post completed */
  if (!PostQueuedCompletionStatus(LOOP->iocp,
                                0,
                                0,
                                &req->overlapped)) {
    uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus");
  }

  return 0;
}
Beispiel #5
0
static DWORD WINAPI pipe_connect_thread_proc(void* parameter) {
  HANDLE pipeHandle = INVALID_HANDLE_VALUE;
  int errno;
  uv_loop_t* loop;
  uv_pipe_t* handle;
  uv_connect_t* req;

  req = (uv_connect_t*) parameter;
  assert(req);
  handle = (uv_pipe_t*) req->handle;
  assert(handle);
  loop = handle->loop;
  assert(loop);

  /* We're here because CreateFile on a pipe returned ERROR_PIPE_BUSY. */
  /* We wait for the pipe to become available with WaitNamedPipe. */
  while (WaitNamedPipeW(handle->name, 30000)) {
    /* The pipe is now available, try to connect. */
    pipeHandle = CreateFileW(handle->name,
                            GENERIC_READ | GENERIC_WRITE,
                            0,
                            NULL,
                            OPEN_EXISTING,
                            FILE_FLAG_OVERLAPPED,
                            NULL);

    if (pipeHandle != INVALID_HANDLE_VALUE) {
      break;
    }

    SwitchToThread();
  }

  if (pipeHandle != INVALID_HANDLE_VALUE &&
      !uv_set_pipe_handle(loop, handle, pipeHandle)) {
    handle->handle = pipeHandle;
    SET_REQ_SUCCESS(req);
  } else {
    SET_REQ_ERROR(req, GetLastError());
  }

  /* Post completed */
  POST_COMPLETION_FOR_REQ(loop, req);

  return 0;
}
Beispiel #6
0
void CTextService::_ConnectDic()
{
	DWORD dwMode;

	if(WaitNamedPipeW(mgrpipename, NMPWAIT_USE_DEFAULT_WAIT) == 0)
	{
		return;
	}

	hPipe = CreateFileW(mgrpipename, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
		nullptr, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_EFFECTIVE_ONLY | SECURITY_IDENTIFICATION, nullptr);
	if(hPipe == INVALID_HANDLE_VALUE)
	{
		return;
	}

	dwMode = PIPE_READMODE_MESSAGE | PIPE_WAIT;
	SetNamedPipeHandleState(hPipe, &dwMode, nullptr, nullptr);
}
Beispiel #7
0
/*
 * @implemented
 */
BOOL
WINAPI
WaitNamedPipeA(LPCSTR lpNamedPipeName,
               DWORD nTimeOut)
{
    BOOL r;
    UNICODE_STRING NameU;

    /* Convert the name to Unicode */
    Basep8BitStringToDynamicUnicodeString(&NameU, lpNamedPipeName);

    /* Call the Unicode API */
    r = WaitNamedPipeW(NameU.Buffer, nTimeOut);

    /* Free the Unicode string */
    RtlFreeUnicodeString(&NameU);

    /* Return result */
    return r;
}
Beispiel #8
0
void service_process(BOOL (*start_service)(PCSTR, PCWSTR), int argc, char** argv)
{
    BOOL res;

    StringCbCopyA(service_nameA, sizeof(service_nameA), argv[2]);
    MultiByteToWideChar(CP_ACP, 0, service_nameA, -1, service_nameW, _countof(service_nameW));
    StringCbPrintfW(named_pipe_name, sizeof(named_pipe_name), L"\\\\.\\pipe\\%ls_pipe", service_nameW);

    res = WaitNamedPipeW(named_pipe_name, NMPWAIT_USE_DEFAULT_WAIT);
    if (!res)
        return;

    hClientPipe = CreateFileW(named_pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hClientPipe == INVALID_HANDLE_VALUE)
        return;

    service_trace("Service process starting...\n");
    res = start_service(service_nameA, service_nameW);
    service_trace("Service process stopped.\n");

    CloseHandle(hClientPipe);
}
Beispiel #9
0
static DWORD WINAPI pipe_connect_thread_proc(void* parameter) {
  uv_loop_t* loop;
  uv_pipe_t* handle;
  uv_connect_t* req;
  HANDLE pipeHandle = INVALID_HANDLE_VALUE;
  DWORD duplex_flags;

  req = (uv_connect_t*) parameter;
  assert(req);
  handle = (uv_pipe_t*) req->handle;
  assert(handle);
  loop = handle->loop;
  assert(loop);

  /* We're here because CreateFile on a pipe returned ERROR_PIPE_BUSY. */
  /* We wait for the pipe to become available with WaitNamedPipe. */
  while (WaitNamedPipeW(handle->name, 30000)) {
    /* The pipe is now available, try to connect. */
    pipeHandle = open_named_pipe(handle->name, &duplex_flags);
    if (pipeHandle != INVALID_HANDLE_VALUE) {
      break;
    }

    SwitchToThread();
  }

  if (pipeHandle != INVALID_HANDLE_VALUE &&
      !uv_set_pipe_handle(loop, handle, pipeHandle, duplex_flags)) {
    SET_REQ_SUCCESS(req);
  } else {
    SET_REQ_ERROR(req, GetLastError());
  }

  /* Post completed */
  POST_COMPLETION_FOR_REQ(loop, req);

  return 0;
}
Beispiel #10
0
HRESULT PipeStream::Open(const wchar_t* name, DWORD timeout) {
  if (name == nullptr)
    return E_INVALIDARG;
  if (IsValid())
    return E_HANDLE;

  Reset();

  std::wstring pipe_name(L"\\\\.\\pipe\\");
  pipe_name.append(name);

  if (!WaitNamedPipeW(pipe_name.c_str(), timeout))
    return HRESULT_FROM_LAST_ERROR();

  handle_ = CreateFileW(pipe_name.c_str(), GENERIC_READ | GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
                        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  if (handle_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_LAST_ERROR();

  connected_ = true;

  return S_OK;
}
Beispiel #11
0
BOOL CreateRemoteSessionProcess(
        IN DWORD        dwSessionId,
        IN BOOL         bUseDefaultToken,
        IN HANDLE       hToken,
        IN LPCWSTR      lpApplicationName,
        IN LPSTR       A_lpCommandLine,
        IN LPSECURITY_ATTRIBUTES lpProcessAttributes,
        IN LPSECURITY_ATTRIBUTES lpThreadAttributes,
        IN BOOL bInheritHandles,
        IN DWORD dwCreationFlags,
        IN LPVOID lpEnvironment,
        IN LPCWSTR lpCurrentDirectory,
        IN LPSTARTUPINFO A_lpStartupInfo,
        OUT LPPROCESS_INFORMATION lpProcessInformation)
{

		WCHAR       lpCommandLine[255];
		STARTUPINFOW StartupInfo;
		Char2Wchar(lpCommandLine, A_lpCommandLine, 255);
		ZeroMemory(&StartupInfo,sizeof(STARTUPINFOW));
		StartupInfo.wShowWindow = SW_SHOW;
		StartupInfo.lpDesktop = L"Winsta0\\Winlogon";
		StartupInfo.cb = sizeof(STARTUPINFOW);

        WCHAR           szWinStaPath[MAX_PATH];
        BOOL            bGetNPName=FALSE;
        WCHAR           szNamedPipeName[MAX_PATH]=L"";
        DWORD           dwNameLen;
        HINSTANCE       hInstWinSta;
        HANDLE          hNamedPipe;
        LPVOID          pData=NULL;
        BOOL            bRet = FALSE;
        DWORD           cbReadBytes,cbWriteBytes;
        DWORD           dwEnvLen = 0;
        union{
                CPAU_PARAM      cpauData;
                BYTE            bDump[0x2000];
        };
        CPAU_RET_PARAM  cpauRetData;
        DWORD                   dwUsedBytes = sizeof(cpauData);
        LPBYTE                  pBuffer = (LPBYTE)(&cpauData+1);
        GetSystemDirectoryW(szWinStaPath, MAX_PATH);
        lstrcatW(szWinStaPath,L"\\winsta.dll");
        hInstWinSta = LoadLibraryW(szWinStaPath);

        if(hInstWinSta)
        {
                pWinStationQueryInformationW pfWinStationQueryInformationW=(pWinStationQueryInformationW)GetProcAddress(hInstWinSta,"WinStationQueryInformationW");
                if(pfWinStationQueryInformationW)
                {
                        bGetNPName = pfWinStationQueryInformationW(0, dwSessionId, 0x21,szNamedPipeName, sizeof(szNamedPipeName), &dwNameLen);
                }
                FreeLibrary(hInstWinSta);
        }
        if(!bGetNPName || szNamedPipeName[0] == '\0')
        {
                swprintf(szNamedPipeName,260,L"\\\\.\\Pipe\\TerminalServer\\SystemExecSrvr\\%d", dwSessionId);
        }

        do{
                hNamedPipe = CreateFileW(szNamedPipeName, GENERIC_READ|GENERIC_WRITE,0, NULL, OPEN_EXISTING, 0, 0);
                if(hNamedPipe == INVALID_HANDLE_VALUE)
                {
                        if(GetLastError() == ERROR_PIPE_BUSY)
                        {
                                if(!WaitNamedPipeW(szNamedPipeName, 30000))
                                        return FALSE;
                        }
                        else
                        {
                                return FALSE;
                        }
                }
        }while(hNamedPipe == INVALID_HANDLE_VALUE);

        memset(&cpauData, 0, sizeof(cpauData));
        cpauData.bInheritHandles        = bInheritHandles;
        cpauData.bUseDefaultToken       = bUseDefaultToken;
        cpauData.dwCreationFlags        = dwCreationFlags;
        cpauData.dwProcessId            = GetCurrentProcessId();
        cpauData.hToken                         = hToken;
        cpauData.lpApplicationName      =(LPWSTR)MarshallString(lpApplicationName, &cpauData, sizeof(bDump),&pBuffer, &dwUsedBytes);
        cpauData.lpCommandLine          = (LPWSTR)MarshallString(lpCommandLine,&cpauData, sizeof(bDump), &pBuffer, &dwUsedBytes);
        cpauData.StartupInfo            = StartupInfo;
        cpauData.StartupInfo.lpDesktop  =(LPWSTR)MarshallString(cpauData.StartupInfo.lpDesktop, &cpauData,sizeof(bDump), &pBuffer, &dwUsedBytes);
        cpauData.StartupInfo.lpTitle    =(LPWSTR)MarshallString(cpauData.StartupInfo.lpTitle, &cpauData,sizeof(bDump), &pBuffer, &dwUsedBytes);

        if(lpEnvironment)
        {
                if(dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
                {
                        while((dwEnvLen+dwUsedBytes <= sizeof(bDump)))
                        {
                                if(((LPWSTR)lpEnvironment)[dwEnvLen/2]=='\0' &&((LPWSTR)lpEnvironment)[dwEnvLen/2+1] == '\0')
                                {
                                        dwEnvLen+=2*sizeof(WCHAR);
                                        break;
                                }
                                dwEnvLen+=sizeof(WCHAR);
                        }
                }
                else
                {
                        while(dwEnvLen+dwUsedBytes <= sizeof(bDump))
                        {
                                if(((LPSTR)lpEnvironment)[dwEnvLen]=='\0' && ((LPSTR)lpEnvironment)[dwEnvLen+1]=='\0')
                                {
                                        dwEnvLen+=2;
                                        break;
                                }
                                dwEnvLen++;
                        }
                }
                if(dwEnvLen+dwUsedBytes <= sizeof(bDump))
                {
                        memmove(pBuffer, lpEnvironment, dwEnvLen);
                        cpauData.lpEnvironment = (LPVOID)dwUsedBytes;
                        pBuffer += dwEnvLen;
                        dwUsedBytes += dwEnvLen;
                }
                else
                {
                        cpauData.lpEnvironment = NULL;
                }
        }
        else
        {
                cpauData.lpEnvironment  = NULL;
        }
        cpauData.cbSize  = dwUsedBytes;

		HANDLE hProcess=NULL;
        if(WriteFile(hNamedPipe, &cpauData, cpauData.cbSize, &cbWriteBytes,NULL))
		{
			Sleep(250);
			if (ReadFile(hNamedPipe, & cpauRetData, sizeof(cpauRetData),&cbReadBytes, NULL))
			{
				hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, cpauRetData.ProcInfo.dwProcessId);
	#ifdef _DEBUG
						char			szText[256];
						sprintf(szText," ++++++cpau  %i  %i %i %i %i %i\n",cpauRetData.bRetValue,cpauRetData.ProcInfo.hProcess,cpauRetData.ProcInfo.dwProcessId,cpauRetData.ProcInfo.dwThreadId,cpauRetData.ProcInfo.hThread,hProcess);
						OutputDebugString(szText);						
	#endif
					bRet = cpauRetData.bRetValue;
					if(bRet)
					{
							*lpProcessInformation = cpauRetData.ProcInfo;
					}
					else
							SetLastError(cpauRetData.dwLastErr);
			}
		}
        else
                bRet = FALSE;
		// function sometimes fail, the use processid to get hprocess... bug MS
		if (lpProcessInformation->hProcess==0) lpProcessInformation->hProcess=hProcess;
		//this should never happen, looping connections
		if (lpProcessInformation->hProcess==0) 
			Sleep(5000);
        CloseHandle(hNamedPipe);
        return bRet;

}
Beispiel #12
0
oslPipe SAL_CALL osl_createPipe(rtl_uString *strPipeName, oslPipeOptions Options, 
					   oslSecurity Security)
{
	rtl_uString* name = NULL;
	rtl_uString* path = NULL;
	rtl_uString* temp = NULL;
	oslPipe pPipe;

   	PSECURITY_ATTRIBUTES  pSecAttr = NULL;

	rtl_uString_newFromAscii(&path, PIPESYSTEM);
	rtl_uString_newFromAscii(&name, PIPEPREFIX);

	if ( /*IS_NT &&*/ Security)
	{
		rtl_uString *Ident = NULL;
		rtl_uString *Delim = NULL;

		OSL_VERIFY(osl_getUserIdent(Security, &Ident));
		rtl_uString_newFromAscii(&Delim, "_");

		rtl_uString_newConcat(&temp, name, Ident);
		rtl_uString_newConcat(&name, temp, Delim);

		rtl_uString_release(Ident);
		rtl_uString_release(Delim);
	}
	else
	{
		if (Options & osl_Pipe_CREATE)
		{
	    	PSECURITY_DESCRIPTOR pSecDesc;

	    	pSecDesc = (PSECURITY_DESCRIPTOR) rtl_allocateMemory(SECURITY_DESCRIPTOR_MIN_LENGTH);

	    	/* add a NULL disc. ACL to the security descriptor */
		    OSL_VERIFY(InitializeSecurityDescriptor(pSecDesc, SECURITY_DESCRIPTOR_REVISION));
	    	OSL_VERIFY(SetSecurityDescriptorDacl(pSecDesc, TRUE, (PACL) NULL, FALSE));

			pSecAttr = rtl_allocateMemory(sizeof(SECURITY_ATTRIBUTES));
	    	pSecAttr->nLength = sizeof(SECURITY_ATTRIBUTES);
	    	pSecAttr->lpSecurityDescriptor = pSecDesc;
	    	pSecAttr->bInheritHandle = TRUE;
		}
	}

	rtl_uString_assign(&temp, name);
	rtl_uString_newConcat(&name, temp, strPipeName);

	/* alloc memory */
	pPipe= __osl_createPipeImpl();
	osl_incrementInterlockedCount(&(pPipe->m_Reference));

	/* build system pipe name */
	rtl_uString_assign(&temp, path);
	rtl_uString_newConcat(&path, temp, name);
	rtl_uString_release(temp);
	temp = NULL;

	if (Options & osl_Pipe_CREATE)
	{
		SetLastError( ERROR_SUCCESS );

		if ( IS_NT )
			pPipe->m_NamedObject = CreateMutexW( NULL, FALSE, name->buffer );
		else
		{
			LPSTR	pszTempBuffer = NULL;
			int		nCharsNeeded;

			nCharsNeeded = WideCharToMultiByte( CP_ACP, 0, name->buffer, name->length, NULL, 0, NULL, NULL );
			pszTempBuffer = alloca( nCharsNeeded * sizeof(CHAR) );
			nCharsNeeded = WideCharToMultiByte( CP_ACP, 0, name->buffer, name->length, pszTempBuffer, nCharsNeeded, NULL, NULL );
			pszTempBuffer[nCharsNeeded-1] = 0;

			pPipe->m_NamedObject = CreateMutexA( NULL, FALSE, pszTempBuffer );
		}

		if ( pPipe->m_NamedObject != INVALID_HANDLE_VALUE && pPipe->m_NamedObject != NULL )
		{
			if ( GetLastError() != ERROR_ALREADY_EXISTS )
			{
				pPipe->m_Security = pSecAttr;
				rtl_uString_assign(&pPipe->m_Name, name);

				if (IS_NT)
				{
					/* try to open system pipe */
					pPipe->m_File = CreateNamedPipeW(
						path->buffer, 
						PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
						PIPE_WAIT | PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
						PIPE_UNLIMITED_INSTANCES,
						4096, 4096,
						NMPWAIT_WAIT_FOREVER, 
						pPipe->m_Security);

					if (pPipe->m_File != INVALID_HANDLE_VALUE)
					{
						rtl_uString_release( name );
						rtl_uString_release( path );

						return pPipe;
					}
				}
				else /* Win 9x */
				{
					LPSTR	pszTempBuffer = NULL;
					int		nCharsNeeded;

					nCharsNeeded = WideCharToMultiByte( CP_ACP, 0, path->buffer, path->length, NULL, 0, NULL, NULL );
					pszTempBuffer = alloca( nCharsNeeded * sizeof(CHAR) );
					nCharsNeeded = WideCharToMultiByte( CP_ACP, 0, path->buffer, path->length, pszTempBuffer, nCharsNeeded, NULL, NULL );
					pszTempBuffer[nCharsNeeded-1] = 0;

					pPipe->m_File = CreateSimplePipe( pszTempBuffer );

					if ( IsValidHandle(pPipe->m_File) )
					{
						rtl_uString_release( name );
						rtl_uString_release( path );

						return pPipe;
					}
				}
			}
			else
			{
				CloseHandle( pPipe->m_NamedObject );
				pPipe->m_NamedObject = INVALID_HANDLE_VALUE;
			}
		}
	}
	else
	{
		if (IS_NT)
		{
			BOOL	fPipeAvailable;

			do
			{
				/* free instance should be available first */
				fPipeAvailable = WaitNamedPipeW(path->buffer, NMPWAIT_WAIT_FOREVER);

				/* first try to open system pipe */
				if ( fPipeAvailable )
				{
					pPipe->m_File = CreateFileW(
							path->buffer,
							GENERIC_READ|GENERIC_WRITE, 
							FILE_SHARE_READ | FILE_SHARE_WRITE,
							NULL,
							OPEN_EXISTING, 
							FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 
							NULL);

					if ( pPipe->m_File != INVALID_HANDLE_VALUE )
					{
						// We got it !
						rtl_uString_release( name );
						rtl_uString_release( path );

						return (pPipe);
					}
					else
					{
						// Pipe instance maybe catched by another client -> try again
					}
				}
			} while ( fPipeAvailable );
		}
		else /* Win 9x */
		{
			LPSTR	pszTempBuffer = NULL;
			int		nCharsNeeded;

			nCharsNeeded = WideCharToMultiByte( CP_ACP, 0, path->buffer, path->length, NULL, 0, NULL, NULL );
			pszTempBuffer = alloca( nCharsNeeded * sizeof(CHAR) );
			nCharsNeeded = WideCharToMultiByte( CP_ACP, 0, path->buffer, path->length, pszTempBuffer, nCharsNeeded, NULL, NULL );
			pszTempBuffer[nCharsNeeded-1] = 0;

			pPipe->m_File = OpenSimplePipe( pszTempBuffer );

			if ( IsValidHandle(pPipe->m_File) )
			{
				// We got it !
				rtl_uString_release( name );
				rtl_uString_release( path );

				return (pPipe);
			}
		}
	}

	/* if we reach here something went wrong */
	__osl_destroyPipeImpl(pPipe);

	return NULL;
}
Beispiel #13
0
/*
 * @implemented
 */
BOOL
WINAPI
CallNamedPipeW(LPCWSTR lpNamedPipeName,
               LPVOID lpInBuffer,
               DWORD nInBufferSize,
               LPVOID lpOutBuffer,
               DWORD nOutBufferSize,
               LPDWORD lpBytesRead,
               DWORD nTimeOut)
{
    HANDLE hPipe;
    BOOL bRetry = TRUE;
    BOOL bError;
    DWORD dwPipeMode;

    while (TRUE)
    {
        /* Try creating it */
        hPipe = CreateFileW(lpNamedPipeName,
                            GENERIC_READ | GENERIC_WRITE,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            NULL,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);

        /* Success, break out */
        if (hPipe != INVALID_HANDLE_VALUE)
            break;

        /* Already tried twice, give up */
        if (bRetry == FALSE)
            return FALSE;

        /* Wait on it */
        WaitNamedPipeW(lpNamedPipeName, nTimeOut);

        /* Get ready to try again */
        bRetry = FALSE;
    }

    /* Set the pipe mode */
    dwPipeMode = PIPE_READMODE_MESSAGE | PIPE_WAIT;
    bError = SetNamedPipeHandleState(hPipe, &dwPipeMode, NULL, NULL);
    if (!bError)
    {
        /* Couldn't change state, fail */
        CloseHandle(hPipe);
        return FALSE;
    }

    /* Do the transact */
    bError = TransactNamedPipe(hPipe,
                               lpInBuffer,
                               nInBufferSize,
                               lpOutBuffer,
                               nOutBufferSize,
                               lpBytesRead,
                               NULL);

    /* Close the handle */
    CloseHandle(hPipe);

    return bError;
}
Beispiel #14
0
static DWORD
ScConnectControlPipe(HANDLE *hPipe)
{
    DWORD dwBytesWritten;
    DWORD dwState;
    DWORD dwServiceCurrent = 0;
    NTSTATUS Status;
    WCHAR NtControlPipeName[MAX_PATH + 1];
    RTL_QUERY_REGISTRY_TABLE QueryTable[2];
    DWORD dwProcessId;

    /* Get the service number and create the named pipe */
    RtlZeroMemory(&QueryTable,
                  sizeof(QueryTable));

    QueryTable[0].Name = L"";
    QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_REQUIRED;
    QueryTable[0].EntryContext = &dwServiceCurrent;

    Status = RtlQueryRegistryValues(RTL_REGISTRY_CONTROL,
                                    L"ServiceCurrent",
                                    QueryTable,
                                    NULL,
                                    NULL);

    if (!NT_SUCCESS(Status))
    {
        ERR("RtlQueryRegistryValues() failed (Status %lx)\n", Status);
        return RtlNtStatusToDosError(Status);
    }

    swprintf(NtControlPipeName, L"\\\\.\\pipe\\net\\NtControlPipe%u", dwServiceCurrent);

    if (!WaitNamedPipeW(NtControlPipeName, 30000))
    {
        ERR("WaitNamedPipe(%S) failed (Error %lu)\n", NtControlPipeName, GetLastError());
        return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
    }

    *hPipe = CreateFileW(NtControlPipeName,
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);
    if (*hPipe == INVALID_HANDLE_VALUE)
    {
        ERR("CreateFileW() failed for pipe %S (Error %lu)\n", NtControlPipeName, GetLastError());
        return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
    }

    dwState = PIPE_READMODE_MESSAGE;
    if (!SetNamedPipeHandleState(*hPipe, &dwState, NULL, NULL))
    {
        CloseHandle(*hPipe);
        *hPipe = INVALID_HANDLE_VALUE;
        return ERROR_FAILED_SERVICE_CONTROLLER_CONNECT;
    }

    /* Pass the ProcessId to the SCM */
    dwProcessId = GetCurrentProcessId();
    WriteFile(*hPipe,
              &dwProcessId,
              sizeof(DWORD),
              &dwBytesWritten,
              NULL);

    TRACE("Sent Process ID %lu\n", dwProcessId);

    return ERROR_SUCCESS;
}
Beispiel #15
0
CPipe::CPipe(char *szName, DWORD dWait){
	int	iTemp;
	int	iFlag = 1;
	WCHAR	wbuffer[MAX_PATH+1];
	dTHX;
	
	hPipe = 0;                 
	dBufferSize = BUFFER_SIZE;
	dBytes = 0;
			              	
	char szPipeName[PIPE_NAME_SIZE + 1];				
	dwOpenMode = PIPE_ACCESS_DUPLEX;		
	dwPipeMode = 	PIPE_TYPE_BYTE	 |      
					PIPE_READMODE_BYTE	 |  
					PIPE_WAIT;				
	nMaxInstances =	PIPE_UNLIMITED_INSTANCES;
	nOutBufferSize = dBufferSize;			
	nInBufferSize  = dBufferSize;
	nDefaultTimeOut = PIPE_TIMEOUT;			
	lpSecurityAttributes= NULL; 
	iError = 0;
	strcpy((char *)szError, "");
	
	cBuffer = new char [dBufferSize];
	if (! cBuffer){
		dBufferSize = 0;
	}

	memset((void *)szError, 0, ERROR_TEXT_SIZE);
	memset((void *)szPipeName, 0, PIPE_NAME_SIZE + 1);
	if (strncmp((char *)szName, "\\\\", 2) == 0){
		iPipeType = CLIENT;
		iTemp = 0;
	}else{
		iPipeType = SERVER;
		strcpy(szPipeName, PIPE_NAME_PREFIX);
		iTemp = strlen(PIPE_NAME_PREFIX);
	}
	strncat(szPipeName, szName, PIPE_NAME_SIZE - iTemp);
	if (USING_WIDE()) {
	    A2WHELPER(szPipeName, wbuffer, sizeof(wbuffer));
	}
	if(iPipeType == SERVER){
	    if (USING_WIDE()) {
		hPipe = CreateNamedPipeW(wbuffer,
					dwOpenMode, 
					dwPipeMode, 
					nMaxInstances, 
					nOutBufferSize, 
					nInBufferSize, 
					nDefaultTimeOut,
					lpSecurityAttributes);
	    }
	    else {
		hPipe = CreateNamedPipeA(szPipeName,
					dwOpenMode, 
					dwPipeMode, 
					nMaxInstances, 
					nOutBufferSize, 
					nInBufferSize, 
					nDefaultTimeOut,
					lpSecurityAttributes);
	    }
	}else{
		while(iFlag){
		    if (USING_WIDE()) {
			hPipe = CreateFileW(wbuffer,
					    GENERIC_READ | GENERIC_WRITE, 
					    FILE_SHARE_READ	| FILE_SHARE_WRITE,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
					    NULL);
		    }
		    else {
			hPipe = CreateFileA(szPipeName,
					    GENERIC_READ | GENERIC_WRITE, 
					    FILE_SHARE_READ	| FILE_SHARE_WRITE,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
					    NULL);
		    }

		    if (GetLastError() == ERROR_PIPE_BUSY){
			if (USING_WIDE())
			    iFlag = WaitNamedPipeW(wbuffer, dWait);
			else
			    iFlag = WaitNamedPipeA(szPipeName, dWait);
		    }else{
			    iFlag = 0;
		    }
		}
	}
	if (cBuffer == 0){
		iError = 998;
		strcpy((char *)szError, "Could not allocate a buffer for the pipe connection");
	}
	if (hPipe == INVALID_HANDLE_VALUE){
		iError = 999;
		strcpy((char *)szError, "Could not connect");
		delete this;
	}
}									  
DWORD main(int argc, char *argv[])
{
    HANDLE hPipe;
    SYELOG_MESSAGE Message;
    BOOL fSuccess;
    DWORD cbWritten, dwMode;

    // Try to open a named pipe; wait for it, if necessary.

    TIME_ZONE_INFORMATION tzi;
    GetTimeZoneInformation(&tzi);

    for (;;) {
        hPipe = CreateFileW(SYELOG_PIPE_NAMEW,  // pipe name
                            GENERIC_WRITE,      // write access only
                            0,                  // no sharing
                            NULL,               // no security attributes
                            OPEN_EXISTING,      // opens existing pipe
                            0,                  // default attributes
                            NULL);              // no template file

        // Break if the pipe handle is valid.
         if (hPipe != INVALID_HANDLE_VALUE)
            break;

        // Exit if an error other than ERROR_PIPE_BUSY occurs.

        if (GetLastError() != ERROR_PIPE_BUSY)
            MyErrExit("Could not open pipe");

        // All pipe instances are busy, so wait for 1 seconds.

        if (!WaitNamedPipeW(SYELOG_PIPE_NAMEW, 1000))
            MyErrExit("Could not open pipe");
    }

    // The pipe connected; change to message-read mode.
    dwMode = PIPE_READMODE_MESSAGE;
    fSuccess = SetNamedPipeHandleState(hPipe,    // pipe handle
                                       &dwMode,  // new pipe mode
                                       NULL,     // don't set maximum bytes
                                       NULL);    // don't set maximum time
    if (!fSuccess)
        MyErrExit("SetNamedPipeHandleState");

    // Send a message to the pipe server.

    memset(&Message, 0, sizeof(Message));

    StringCchCopyA(Message.szMessage, ARRAYSIZE(Message.szMessage),
                   (argc > 1) ? argv[1] : "sltestp: hello world!");

    Message.nFacility = SYELOG_FACILITY_APPLICATION;
    Message.nSeverity = SYELOG_SEVERITY_INFORMATION;
    Message.nProcessId = GetCurrentProcessId();
    GetSystemTimeAsFileTime(&Message.ftOccurance);
    PCSTR pszEnd = Message.szMessage;
    for (; *pszEnd; pszEnd++) {
        // no internal contents.
    }
    Message.nBytes = (USHORT)(pszEnd - ((PCSTR)&Message) + 1);

    fSuccess = WriteFile(hPipe,                  // pipe handle
                         &Message,             // message
                         Message.nBytes, // message length
                         &cbWritten,             // bytes written
                         NULL);                  // not overlapped
    if (! fSuccess)
        MyErrExit("WriteFile");

    CloseHandle(hPipe);

    GetTimeZoneInformation(&tzi);

    return 0;
}
Beispiel #17
0
DWORD executeWpkgViaPipe(int called_by, bool debug_flag)
{
	BOOL fSuccess = FALSE;
	int err;

	if (debug_flag) {
		DEBUG = TRUE;
		// Get install path from registry
		HKEY hKey = NULL;
		DWORD dwDataType = REG_SZ;
		DWORD dwSize = 0;
		LPBYTE lpValue   = NULL;
		LONG lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Wpkg-GP", 0, KEY_QUERY_VALUE, &hKey);
		lRet = RegQueryValueExA(hKey, "InstallPath", 0, &dwDataType, lpValue, &dwSize); // dwSize will contain the data size
		if (lRet == ERROR_SUCCESS)
		{
			// Allocate the buffer
			lpValue = (LPBYTE) malloc(dwSize + 1);
			lRet = RegQueryValueExA(hKey, "InstallPath", 0, &dwDataType, lpValue, &dwSize);
			RegCloseKey(hKey);
			// Adding null termination
			lpValue[dwSize] = '\0';
			wchar_t debuglogpath[BUFSIZE];
			swprintf_s(debuglogpath, BUFSIZE, L"%hs\\logs\\wpkg-gp-debug.log", lpValue);
			_wfopen_s(&debugfh, debuglogpath, L"a");
			free(lpValue);
		}
		
	}

	if (called_by == GPE)
		EXECUTE_FROM_GPE = TRUE;
	else if (called_by == EXE)
		EXECUTE_FROM_EXE = TRUE;

	//Making sure the service has started
	SERVICE_STATUS_PROCESS ssStatus;
	DWORD dwBytesNeeded;

	// Get a handle to the SCM database. 
	debug(L"Starting OpenSCManager\n");
	SC_HANDLE schSCManager = OpenSCManager(
		NULL,			// local computer
		NULL,			// servicesActive database
		SC_MANAGER_ALL_ACCESS);	// full access rights 
	if (schSCManager == NULL) {
		err = GetLastError();
		UpdateStatus(LOG_ERROR, L"Error when calling OpenSCManager", err);
		return err;
	}
	debug(L"Started OpenSCManager\n");

	// Get a handle to the service.
	debug(L"Starting OpenService\n");
	SC_HANDLE schService = OpenServiceW( 
		schSCManager,         // SCM database 
		L"WpkgServer",            // name of service 
		SERVICE_ALL_ACCESS);  // full access 
 
	if (schService == NULL) { 
		err = GetLastError();
		CloseServiceHandle(schSCManager);
		UpdateStatus(LOG_ERROR, L"Error when calling OpenService", err);
		return err;
	}
	debug(L"Started OpenService\n");

	// Check the status of the service
	debug(L"Starting QueryServiceStatusEx\n");
	if (!QueryServiceStatusEx( 
			schService,                     // handle to service 
			SC_STATUS_PROCESS_INFO,         // information level
			(LPBYTE) &ssStatus,             // address of structure
			sizeof(SERVICE_STATUS_PROCESS), // size of structure
			&dwBytesNeeded ) )              // size needed if buffer is too small
	{
		err = GetLastError();
		CloseServiceHandle(schService); 
		CloseServiceHandle(schSCManager);
		UpdateStatus(LOG_ERROR, L"Error when calling QueryServiceStatusEx", err);
		return err; 
	}

	debug(L"Finished QueryServiceStatusEx\n");

	debug(L"Checking the status of the service\n");
	for (int i = 0; ssStatus.dwCurrentState != SERVICE_RUNNING; i++) {
		UpdateStatus(LOG_INFO, L"Waiting for the WPKG-GP software installation service to start.", FALSE);
		debug(L"The current status was not SERVICE_RUNNING: %i, but %i, entering wait loop. i is %i (max 120)\n",
		      SERVICE_RUNNING, ssStatus.dwCurrentState, i);
		//Then wait for the service for maximum 120 seconds
		if (i >= 120) {
			UpdateStatus(LOG_ERROR, L"Service did not start for 120 seconds, quitting.", FALSE);
			return 101; //Timeout
		}
		if (EXECUTE_FROM_EXE) {
			UpdateStatus(LOG_INFO, L"Executed from exe file, will not wait for service to start", FALSE);
			break;
		}
		debug(L" Sleeping 1 second\n");
		Sleep(1000);
		if (!QueryServiceStatusEx( 
				schService,                     // handle to service 
				SC_STATUS_PROCESS_INFO,         // information level
				(LPBYTE) &ssStatus,             // address of structure
				sizeof(SERVICE_STATUS_PROCESS), // size of structure
				&dwBytesNeeded ) )              // size needed if buffer is too small
		{
			err = GetLastError();
			CloseServiceHandle(schService); 
			CloseServiceHandle(schSCManager);
			UpdateStatus(LOG_ERROR, L"Error when calling QueryServiceStatusEx in loop", err);
			return err; 
		}

		debug(L"Checking if service is running, comparing CurrentState: %i to SERVICE_RUNNING: %i\n",
			ssStatus.dwCurrentState, SERVICE_RUNNING);
	}

	CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager);

	HANDLE hPipe;
	LPCWSTR lpszPipename = L"\\\\.\\pipe\\WPKG";

	// Try to open a named pipe; wait for it, if necessary.
	while (1) {
		debug(L"Trying to run CreateFile on named pipe\n");
		hPipe = CreateFileW( 
			lpszPipename,   // pipe name 
			GENERIC_READ |  // read and write access 
			GENERIC_WRITE, 
			0,              // no sharing 
			NULL,           // default security attributes
			OPEN_EXISTING,  // opens existing pipe 
			0,              // default attributes 
			NULL);          // no template file

		// Break the loop if the pipe handle is valid. 
		if (hPipe != INVALID_HANDLE_VALUE) {
			debug(L"The pipe handle was valid, continuing\n");
			break;
		}

		// Exit if an error other than ERROR_PIPE_BUSY occurs.
		err = GetLastError();
		if (err != ERROR_PIPE_BUSY) {
			UpdateStatus(LOG_ERROR, L"CreatePipe returned an error.", err);
			return err;
		}
		// All pipe instances are busy, so wait for 20 seconds.
		debug(L"Waiting in 20 seconds for a free pipe instance\n");
		if (!WaitNamedPipeW(lpszPipename, 20000)){
			err = GetLastError();
			UpdateStatus(LOG_ERROR, L"Pipe server had no free instances for 20 seconds, quitting.", err);
			return err;
		}
	}

	// The pipe connected; change to message-read mode. 
	DWORD dwMode = PIPE_READMODE_MESSAGE;
	debug(L"Executing SetNamedPipeHandleState\n");
	fSuccess = SetNamedPipeHandleState(
			hPipe,    // pipe handle 
			&dwMode,  // new pipe mode 
			NULL,     // don't set maximum bytes 
			NULL);    // don't set maximum time
	if (!fSuccess){
		err = GetLastError();
		UpdateStatus(LOG_ERROR, L"CreatePipe returned an error.", err);
		return 206;
	}

	debug(L"Sending message to pipe server\n");

	// Send a message to the pipe server.
	LPCSTR lpvMessage="ExecuteFromGPE";
	DWORD cbWritten;

	fSuccess = WriteFile(
			hPipe,                  // pipe handle 
			lpvMessage,             // message 
			lstrlenA(lpvMessage)+1, // message length 
			&cbWritten,             // bytes written 
			NULL);                  // not overlapped 
	if (!fSuccess) {
		err = GetLastError();
		UpdateStatus(LOG_ERROR, L"WriteFile to named pipe returned an error.", err);
		return err;
	}

	debug(L"Waiting for reply from pipe server\n");
	while (1) { 
		char chBuf[BUFSIZE];
		wchar_t wcBuf[BUFSIZE];
		DWORD cbRead;

		// Read from the pipe. 
		debug(L"Executing ReadFile on pipe\n");
		fSuccess = ReadFile( 
			hPipe,    // pipe handle 
			chBuf,    // buffer to receive reply 
			sizeof(chBuf),  // size of buffer 
			&cbRead,  // number of bytes read 
			NULL);    // not overlapped

		err = GetLastError();
		if (err == ERROR_HANDLE_EOF) {
			debug(L"Got to EOF, continuing");
			break;
		}
		if (err == ERROR_PIPE_NOT_CONNECTED) {
			debug(L"Other end closed the pipe, continuing\n");
			break;
		}
		if (!fSuccess && err != ERROR_MORE_DATA) {
			UpdateStatus(LOG_ERROR, L"ReadFile from named pipe returned an error.", err);
			return err;
		}
		if (cbRead < 4) {
			debug(L"Short message received %d bytes", cbRead);
			continue;
		}

		debug(L"Successfully read from pipe, retrieved Status Code %3.3S\n", chBuf);

		debug(L"Converting string to wchar_t\n");
		cbWritten = MultiByteToWideChar(CP_UTF8, 0, &chBuf[4], cbRead-4, wcBuf, BUFSIZE-1);
		if (cbWritten == 0) {
			err = GetLastError();
			UpdateStatus(LOG_ERROR, L"Conversion of data read from pipe failed.", err);
			return err;
		}
		wcBuf[cbWritten] = 0;

		debug(L"Calling UpdateStatus\n");
		//pStatusCallback(FALSE, wcBuf);
		UpdateStatus(NO_LOG, wcBuf, FALSE);
	}

	CloseHandle(hPipe);
	if (DEBUG)
		if (debugfh != false)
			fclose(debugfh);
	
	return ERROR_SUCCESS;
}