Esempio n. 1
15
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef UNDER_CE
                     LPWSTR
#else
                     LPSTR
#endif
                     lpCmdLine, int nCmdShow)
#endif
{
    CFileInStream archiveStream;
    CLookToRead lookStream;
    CSzArEx db;
    SRes res = SZ_OK;
    ISzAlloc allocImp;
    ISzAlloc allocTempImp;
    WCHAR sfxPath[MAX_PATH + 2];
    WCHAR path[MAX_PATH * 3 + 2];
    size_t pathLen;
    DWORD winRes;
    const wchar_t *cmdLineParams;
    const char *errorMessage = NULL;
    Bool useShellExecute = True;

#ifdef _CONSOLE
    SetConsoleCtrlHandler(HandlerRoutine, TRUE);
#else
    hInstance = hInstance;
    hPrevInstance = hPrevInstance;
    lpCmdLine = lpCmdLine;
    nCmdShow = nCmdShow;
#endif

    CrcGenerateTable();

    allocImp.Alloc = SzAlloc;
    allocImp.Free = SzFree;

    allocTempImp.Alloc = SzAllocTemp;
    allocTempImp.Free = SzFreeTemp;

    FileInStream_CreateVTable(&archiveStream);
    LookToRead_CreateVTable(&lookStream, False);

    winRes = GetModuleFileNameW(NULL, sfxPath, MAX_PATH);
    if (winRes == 0 || winRes > MAX_PATH)
        return 1;
    {
        cmdLineParams = GetCommandLineW();
#ifndef UNDER_CE
        {
            Bool quoteMode = False;
            for (;; cmdLineParams++)
            {
                wchar_t c = *cmdLineParams;
                if (c == L'\"')
                    quoteMode = !quoteMode;
                else if (c == 0 || (c == L' ' && !quoteMode))
                    break;
            }
        }
#endif
    }

    {
        unsigned i;
        DWORD d;
        winRes = GetTempPathW(MAX_PATH, path);
        if (winRes == 0 || winRes > MAX_PATH)
            return 1;
        pathLen = wcslen(path);
        d = (GetTickCount() << 12) ^ (GetCurrentThreadId() << 14) ^ GetCurrentProcessId();
        for (i = 0;; i++, d += GetTickCount())
        {
            if (i >= 100)
            {
                res = SZ_ERROR_FAIL;
                break;
            }
            wcscpy(path + pathLen, L"7z");

            {
                wchar_t *s = path + wcslen(path);
                UInt32 value = d;
                unsigned k;
                for (k = 0; k < 8; k++)
                {
                    unsigned t = value & 0xF;
                    value >>= 4;
                    s[7 - k] = (char)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
                }
                s[k] = '\0';
            }

            if (DoesFileOrDirExist(path))
                continue;
            if (CreateDirectoryW(path, NULL))
            {
                wcscat(path, L"\\");
                pathLen = wcslen(path);
                break;
            }
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                res = SZ_ERROR_FAIL;
                break;
            }
        }
        if (res != SZ_OK)
            errorMessage = "Can't create temp folder";
    }

    if (res != SZ_OK)
    {
        if (!errorMessage)
            errorMessage = "Error";
        PrintErrorMessage(errorMessage);
        return 1;
    }

    if (InFile_OpenW(&archiveStream.file, sfxPath) != 0)
    {
        errorMessage = "can not open input file";
        res = SZ_ERROR_FAIL;
    }
    else
    {
        UInt64 pos = 0;
        if (!FindSignature(&archiveStream.file, &pos))
            res = SZ_ERROR_FAIL;
        else if (File_Seek(&archiveStream.file, (Int64 *)&pos, SZ_SEEK_SET) != 0)
            res = SZ_ERROR_FAIL;
        if (res != 0)
            errorMessage = "Can't find 7z archive";
    }

    if (res == SZ_OK)
    {
        lookStream.realStream = &archiveStream.s;
        LookToRead_Init(&lookStream);
    }

    SzArEx_Init(&db);
    if (res == SZ_OK)
    {
        res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
    }
    if (res == SZ_OK)
    {
        UInt32 executeFileIndex = (UInt32)(Int32)-1;
        UInt32 minPrice = 1 << 30;
        UInt32 i;
        UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
        Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
        size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */

        for (i = 0; i < db.db.NumFiles; i++)
        {
            size_t offset = 0;
            size_t outSizeProcessed = 0;
            const CSzFileItem *f = db.db.Files + i;
            size_t len;
            WCHAR *temp;
            len = SzArEx_GetFileNameUtf16(&db, i, NULL);

            if (len >= MAX_PATH)
            {
                res = SZ_ERROR_FAIL;
                break;
            }

            temp = path + pathLen;

            SzArEx_GetFileNameUtf16(&db, i, temp);
            {
                res = SzArEx_Extract(&db, &lookStream.s, i,
                                     &blockIndex, &outBuffer, &outBufferSize,
                                     &offset, &outSizeProcessed,
                                     &allocImp, &allocTempImp);
                if (res != SZ_OK)
                    break;
            }
            {
                CSzFile outFile;
                size_t processedSize;
                size_t j;
                size_t nameStartPos = 0;
                for (j = 0; temp[j] != 0; j++)
                {
                    if (temp[j] == '/')
                    {
                        temp[j] = 0;
                        MyCreateDir(path);
                        temp[j] = CHAR_PATH_SEPARATOR;
                        nameStartPos = j + 1;
                    }
                }

                if (f->IsDir)
                {
                    MyCreateDir(path);
                    continue;
                }
                else
                {
                    unsigned extLen;
                    const WCHAR *name = temp + nameStartPos;
                    unsigned len = (unsigned)wcslen(name);
                    unsigned nameLen = FindExt(temp + nameStartPos, &extLen);
                    unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen);
                    unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen);

                    unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12));
                    if (minPrice > price)
                    {
                        minPrice = price;
                        executeFileIndex = i;
                        useShellExecute = (extPrice != k_EXE_ExtIndex);
                    }

                    if (DoesFileOrDirExist(path))
                    {
                        errorMessage = "Duplicate file";
                        res = SZ_ERROR_FAIL;
                        break;
                    }
                    if (OutFile_OpenW(&outFile, path))
                    {
                        errorMessage = "Can't open output file";
                        res = SZ_ERROR_FAIL;
                        break;
                    }
                }
                processedSize = outSizeProcessed;
                if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
                {
                    errorMessage = "Can't write output file";
                    res = SZ_ERROR_FAIL;
                }

#ifdef USE_WINDOWS_FILE
                if (f->MTimeDefined)
                {
                    FILETIME mTime;
                    mTime.dwLowDateTime = f->MTime.Low;
                    mTime.dwHighDateTime = f->MTime.High;
                    SetFileTime(outFile.handle, NULL, NULL, &mTime);
                }
#endif

                {
                    SRes res2 = File_Close(&outFile);
                    if (res != SZ_OK)
                        break;
                    if (res2 != SZ_OK)
                    {
                        res = res2;
                        break;
                    }
                }
#ifdef USE_WINDOWS_FILE
                if (f->AttribDefined)
                    SetFileAttributesW(path, f->Attrib);
#endif
            }
        }

        if (res == SZ_OK)
        {
            if (executeFileIndex == (UInt32)(Int32)-1)
            {
                errorMessage = "There is no file to execute";
                res = SZ_ERROR_FAIL;
            }
            else
            {
                WCHAR *temp = path + pathLen;
                UInt32 j;
                SzArEx_GetFileNameUtf16(&db, executeFileIndex, temp);
                for (j = 0; temp[j] != 0; j++)
                    if (temp[j] == '/')
                        temp[j] = CHAR_PATH_SEPARATOR;
            }
        }
        IAlloc_Free(&allocImp, outBuffer);
    }
    SzArEx_Free(&db, &allocImp);

    File_Close(&archiveStream.file);

    if (res == SZ_OK)
    {
        HANDLE hProcess = 0;
        if (useShellExecute)
        {
            SHELLEXECUTEINFO ei;
            UINT32 executeRes;
            BOOL success;

            memset(&ei, 0, sizeof(ei));
            ei.cbSize = sizeof(ei);
            ei.lpFile = path;
            ei.fMask = SEE_MASK_NOCLOSEPROCESS
#ifndef UNDER_CE
                       | SEE_MASK_FLAG_DDEWAIT
#endif
                       /* | SEE_MASK_NO_CONSOLE */
                       ;
            if (wcslen(cmdLineParams) != 0)
                ei.lpParameters = cmdLineParams;
            ei.nShow = SW_SHOWNORMAL; /* SW_HIDE; */
            success = ShellExecuteEx(&ei);
            executeRes = (UINT32)(UINT_PTR)ei.hInstApp;
            if (!success || (executeRes <= 32 && executeRes != 0))  /* executeRes = 0 in Windows CE */
                res = SZ_ERROR_FAIL;
            else
                hProcess = ei.hProcess;
        }
        else
        {
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
            WCHAR cmdLine[MAX_PATH * 3];

            wcscpy(cmdLine, path);
            wcscat(cmdLine, cmdLineParams);
            memset(&si, 0, sizeof(si));
            si.cb = sizeof(si);
            if (CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) == 0)
                res = SZ_ERROR_FAIL;
            else
            {
                CloseHandle(pi.hThread);
                hProcess = pi.hProcess;
            }
        }
        if (hProcess != 0)
        {
            WaitForSingleObject(hProcess, INFINITE);
            CloseHandle(hProcess);
        }
    }

    path[pathLen] = L'\0';
    RemoveDirWithSubItems(path);

    if (res == SZ_OK)
        return 0;

    {
        if (res == SZ_ERROR_UNSUPPORTED)
            errorMessage = "Decoder doesn't support this archive";
        else if (res == SZ_ERROR_MEM)
            errorMessage = "Can't allocate required memory";
        else if (res == SZ_ERROR_CRC)
            errorMessage = "CRC error";
        else
        {
            if (!errorMessage)
                errorMessage = "ERROR";
        }
        if (errorMessage)
            PrintErrorMessage(errorMessage);
    }
    return 1;
}
Esempio n. 2
0
VOID
SuspendedProcessTest (
    VOID
    )

{

    PERFINFO PerfInfo;
    STARTUPINFO si;
    PROCESS_INFORMATION pi[SPD_PROCESS_ITERATIONS];
    BOOL b;
    int Index;
    CHAR Buffer[256];
    KPRIORITY Base;

    GetModuleFileName(0,Buffer,256);

    RtlZeroMemory(&si,sizeof(si));
    si.cb = sizeof(si);

    Base = 13;
    NtSetInformationProcess(
        NtCurrentProcess(),
        ProcessBasePriority,
        (PVOID) &Base,
        sizeof(Base)
        );
//    SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS);
    StartBenchMark("Suspended Process Creation Benchmark)",
                   SPD_PROCESS_ITERATIONS,
                   &PerfInfo);

    for (Index = 0; Index < SPD_PROCESS_ITERATIONS; Index += 1) {
        b = CreateProcess(
                Buffer,
                "just exit",
                NULL,
                NULL,
                TRUE,
                CREATE_SUSPENDED,
                NULL,
                NULL,
                &si,
                &pi[Index]
                );
        if ( !b ) {
            printf("failed %ld\n",Index);
            }
        }
    //
    // Print out performance statistics.
    //

    FinishBenchMark(&PerfInfo);
//    SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS);

    StartBenchMark("Process Startup/Exit Benchmark)",
                   SPD_PROCESS_ITERATIONS,
                   &PerfInfo);
    for (Index = 0; Index < SPD_PROCESS_ITERATIONS; Index += 1) {
        ResumeThread(pi[Index].hThread);
        CloseHandle(pi[Index].hThread);
        WaitForSingleObject(pi[Index].hProcess,-1);
        CloseHandle(pi[Index].hProcess);
        }
    FinishBenchMark(&PerfInfo);

    //
    // End of event1 context switch test.
    //

    return;
}
Esempio n. 3
0
void CDAudio_WaitForFinish(void)
{
	WaitForSingleObject(cdPlayingFinishedEvent, INFINITE);
}
Esempio n. 4
0
// This routine creates a binding with the server.
HRESULT
JITManager::CreateBinding(
    __in HANDLE serverProcessHandle,
    __in_opt void * serverSecurityDescriptor,
    __in UUID * connectionUuid,
    __out RPC_BINDING_HANDLE * bindingHandle)
{
    Assert(IsOOPJITEnabled());

    RPC_STATUS status;
    DWORD attemptCount = 0;
    DWORD sleepInterval = 100; // in milliseconds
    RPC_BINDING_HANDLE localBindingHandle;
    RPC_BINDING_HANDLE_TEMPLATE_V1 bindingTemplate;
    RPC_BINDING_HANDLE_SECURITY_V1_W bindingSecurity;

#ifndef NTBUILD
    RPC_SECURITY_QOS_V4 securityQOS;
    ZeroMemory(&securityQOS, sizeof(RPC_SECURITY_QOS_V4));
    securityQOS.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
    securityQOS.IdentityTracking = RPC_C_QOS_IDENTITY_DYNAMIC;
    securityQOS.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
    securityQOS.Version = 4;
#else
    RPC_SECURITY_QOS_V5 securityQOS;
    ZeroMemory(&securityQOS, sizeof(RPC_SECURITY_QOS_V5));
    securityQOS.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
    securityQOS.IdentityTracking = RPC_C_QOS_IDENTITY_DYNAMIC;
    securityQOS.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
    securityQOS.Version = 5;
    securityQOS.ServerSecurityDescriptor = serverSecurityDescriptor;
#endif // NTBUILD

    ZeroMemory(&bindingTemplate, sizeof(bindingTemplate));
    bindingTemplate.Version = 1;
    bindingTemplate.ProtocolSequence = RPC_PROTSEQ_LRPC;
    bindingTemplate.StringEndpoint = NULL;
    memcpy_s(&bindingTemplate.ObjectUuid, sizeof(UUID), connectionUuid, sizeof(UUID));
    bindingTemplate.Flags |= RPC_BHT_OBJECT_UUID_VALID;

    ZeroMemory(&bindingSecurity, sizeof(bindingSecurity));
    bindingSecurity.Version = 1;
    bindingSecurity.AuthnLevel = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
    bindingSecurity.AuthnSvc = RPC_C_AUTHN_KERNEL;
    bindingSecurity.SecurityQos = (RPC_SECURITY_QOS*)&securityQOS;

    status = RpcBindingCreate(&bindingTemplate, &bindingSecurity, NULL, &localBindingHandle);
    if (status != RPC_S_OK)
    {
        return HRESULT_FROM_WIN32(status);
    }

    // We keep attempting to connect to the server with increasing wait intervals in between.
    // This will wait close to 5 minutes before it finally gives up.
    do
    {
        DWORD waitStatus;

        status = RpcBindingBind(NULL, localBindingHandle, ClientIChakraJIT_v0_0_c_ifspec);
        if (status == RPC_S_OK)
        {
            break;
        }
        else if (status == EPT_S_NOT_REGISTERED)
        {
            // The Server side has not finished registering the RPC Server yet.
            // We should only breakout if we have reached the max attempt count.
            if (attemptCount > 600)
            {
                break;
            }
        }
        else
        {
            // Some unknown error occurred. We are not going to retry for arbitrary errors.
            break;
        }

        // When we come to this point, it means the server has not finished registration yet.
        // We should wait for a while and then reattempt to bind.
        waitStatus = WaitForSingleObject(serverProcessHandle, sleepInterval);
        if (waitStatus == WAIT_OBJECT_0)
        {
            DWORD exitCode = (DWORD)-1;

            // The server process died for some reason. No need to reattempt.
            // We use -1 as the exit code if GetExitCodeProcess fails.
            Assert(GetExitCodeProcess(serverProcessHandle, &exitCode));
            status = RPC_S_SERVER_UNAVAILABLE;
            break;
        }
        else if (waitStatus == WAIT_TIMEOUT)
        {
            // Not an error. the server is still alive and we should reattempt.
        }
        else
        {
            // wait operation failed for an unknown reason.
            Assert(false);
            status = HRESULT_FROM_WIN32(waitStatus);
            break;
        }

        attemptCount++;
        if (sleepInterval < 500)
        {
            sleepInterval += 100;
        }
    } while (status != RPC_S_OK); // redundant check, but compiler would not allow true here.

    if (status != RPC_S_OK)
    {
        RpcBindingFree(&localBindingHandle);
        return HRESULT_FROM_WIN32(status);
    }

    *bindingHandle = localBindingHandle;
    return S_OK;
}
Esempio n. 5
0
void ThreadObject::WaitForExit()
{
    WaitForSingleObject(m_hThread, INFINITE);
    CloseHandle(m_hThread);
}
Esempio n. 6
0
// Loads a dll in a process (uses ntdll.LdrLoadData)
DWORD LoadDllInProcessEx(DWORD dwPid,char* DllPathName)
{
	HANDLE hProcess,hThread;
	RemoteProcessData rpd;
	PWSTR pwModuleFileName;
	HANDLE hModule=NULL;
	UNICODE_STRING usModule;
	LPVOID lpParameters,lpThread;
	SECURITY_ATTRIBUTES saSecAttr;
	DWORD dwActual,dwResult=0,rc;

	hProcess=OpenProcess(PROCESS_ALL_ACCESS,0,dwPid);
	if (hProcess==NULL)
		goto cleanup;

	rpd.pLdrLoadDll=(LDRLOADDLL)GetProcAddress(GetModuleHandle("ntdll"),"LdrLoadDll");
	if (!rpd.pLdrLoadDll)
		goto cleanup;
		
	rpd.Flags=0;
	rpd.PathToFile=NULL;
	rpd.ModuleHandle=NULL;
	
	pwModuleFileName=(PWSTR)malloc((strlen(DllPathName)*2)+1);
	if (!pwModuleFileName)
		goto cleanup;
		
	MultiByteToWideChar(CP_ACP,0,DllPathName,strlen(DllPathName),pwModuleFileName,(strlen(DllPathName)*2)+1);
	usModule.Buffer=(PWSTR)InjectData(hProcess,pwModuleFileName,(strlen(DllPathName)*2)+1);

	free(pwModuleFileName);

	if (!usModule.Buffer)
		goto cleanup;
	
	usModule.Length=(strlen(DllPathName)*2)+1;
	usModule.MaximumLength=(strlen(DllPathName)*2)+1;

	memcpy(&rpd.ModuleFileName,&usModule,sizeof(UNICODE_STRING));

	lpParameters=InjectData(hProcess,&rpd,sizeof(RemoteProcessData)+4096);
	if (!lpParameters)
		goto cleanup;

	lpThread=InjectData(hProcess,&RemoteThread,(PBYTE)EndRemoteThread-(PBYTE)RemoteThread+4096);
	if (!lpThread)
		goto cleanup;

	// Set security attributes
	saSecAttr.nLength=sizeof(SECURITY_ATTRIBUTES);
	saSecAttr.lpSecurityDescriptor = NULL;
	saSecAttr.bInheritHandle = TRUE;

	hThread=CreateRemoteThread(hProcess,&saSecAttr,0,(LPTHREAD_START_ROUTINE)lpThread,lpParameters,0,&dwActual);
	if (hThread==NULL)
		goto cleanup;
	
	rc=WaitForSingleObject(hThread, INFINITE); 

	switch (rc) 
	{
		case WAIT_TIMEOUT:
			break;
		case WAIT_FAILED:
			break;
		case WAIT_OBJECT_0:
			if (ReadProcessMemory(hProcess,lpParameters,&rpd,sizeof(RemoteProcessData),&dwActual))
				dwResult=(DWORD)rpd.ModuleHandle;
			break;
		default:
			break;
	}

cleanup:
	if (rpd.ModuleFileName.Buffer!=NULL)
		VirtualFreeEx(hProcess,rpd.ModuleFileName.Buffer,0,MEM_RELEASE);

	if (lpParameters!=NULL)
		VirtualFreeEx(hProcess,lpParameters,0,MEM_RELEASE);

	if (lpThread!=NULL)
		VirtualFreeEx(hProcess,lpThread,0,MEM_RELEASE);

	if (hThread) CloseHandle(hThread);
	if (hProcess) CloseHandle(hProcess);

	return dwResult;
}
Esempio n. 7
0
void gcore::Mutex::lock() {
  WaitForSingleObject(MUTEX, INFINITE);
}
Esempio n. 8
0
void CPutFile::CheckExe(wstring installname, wstring name, int type)
{
	if(type == 2)//file
	{
		WCHAR path[MAX_PATH] = {0};
		ExpandEnvironmentStringsW(installname.c_str(), path, MAX_PATH);

		if(::PathFileExistsW(path) == TRUE)
			return;
	}
	else if(type == 1)//reg
	{
		HKEY rootkey;
		size_t nEndKeyName = installname.find_first_of(']', 1);
		std::wstring strKeyName = installname.substr(1, nEndKeyName - 1);

		size_t nEnd = strKeyName.find_first_of('\\');
		std::wstring strRootKey = strKeyName.substr(0, nEnd);

		if(strRootKey == L"HKEY_CURRENT_USER")
			rootkey = HKEY_CURRENT_USER;
		else if (strRootKey == _T("HKEY_LOCAL_MACHINE"))
			rootkey = HKEY_LOCAL_MACHINE;
		else if(strRootKey == _T("HKEY_CLASSES_ROOT"))
			rootkey = HKEY_CLASSES_ROOT;

		std::wstring strKey = strKeyName.substr(nEnd + 1, wstring::npos);

		HKEY hKey = NULL;                               // 操作键句柄

		if (ERROR_SUCCESS == ::RegOpenKeyExW(rootkey, strKey.c_str(), 0, KEY_READ, &hKey))   
		{   
			::RegCloseKey(hKey);
			return;
		} 
	}
	else
		return;

	wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str());

	OSVERSIONINFO os = { sizeof(OSVERSIONINFO) };
	::GetVersionEx(&os);
	if(os.dwMajorVersion >= 6)
	{
		SHELLEXECUTEINFOW shExecInfo;
		shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
		shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;//SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; 
		shExecInfo.hwnd = NULL;
		shExecInfo.lpVerb = L"runas";
		shExecInfo.lpFile = LPWSTR(file.c_str());
		shExecInfo.lpParameters = NULL;
		shExecInfo.lpDirectory = NULL;
		shExecInfo.nShow = SW_SHOWNORMAL;
		shExecInfo.hInstApp = NULL;

		if (!ShellExecuteExW(&shExecInfo))
		{			
			int err = GetLastError();
			CRecordProgram::GetInstance()->FeedbackError(L"PutFile", err,
				CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str()));
		}
		else
			WaitForSingleObject (shExecInfo.hProcess, INFINITE); 
	}
	else
	{
		STARTUPINFOW si;
		memset (&si, 0, sizeof (STARTUPINFOW));
		si.wShowWindow = SW_HIDE;
		si.cb = sizeof (STARTUPINFOW);
		PROCESS_INFORMATION pi;
		memset (&pi, 0, sizeof (PROCESS_INFORMATION));	

		if (!CreateProcess(NULL, LPWSTR(file.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
		{
			CRecordProgram::GetInstance()->FeedbackError(L"PutFile", 1200,
				CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str()));
			return;
		}
		else
			WaitForSingleObject (pi.hProcess, INFINITE); 
		CloseHandle (pi.hThread);
		CloseHandle (pi.hProcess);
	}
	return;
}
Esempio n. 9
0
/*! \internal

    \note Obtains ::cs_kmq_global, kmq_queue::cs, ::cs_kmq_msg_ref, ::cs_kmq_msg, 
*/
KHMEXP khm_int32 KHMAPI kmq_dispatch(kmq_timer timeout) {
    kmq_queue * q;
    kmq_message_ref * r;
    kmq_message *m;
    DWORD hr;

    q = kmqint_get_thread_queue();

    assert(q->wait_o);

    hr = WaitForSingleObject(q->wait_o, timeout);
    if(hr == WAIT_OBJECT_0) {
        /* signalled */
        kmqint_get_queue_message_ref(q, &r);

        m = r->msg;

        if(m->type != KMSG_SYSTEM || m->subtype != KMSG_SYSTEM_EXIT) {
            khm_boolean rv;

            if (m->err_ctx)
                kherr_push_context(m->err_ctx);

            /* TODO: before dispatching the message, the message being
               dispatched for this thread needs to be stored so that
               it can be looked up in kmq_is_call_aborted(). This
               needs to happen in kmq_wm_dispatch() and
               kmq_wm_begin() as well. */

            /* dispatch */
            rv = r->recipient(m->type, m->subtype, m->uparam, m->vparam);

            if (m->err_ctx)
                kherr_pop_context();

            EnterCriticalSection(&cs_kmq_msg);
            EnterCriticalSection(&cs_kmq_msg_ref);
            kmqint_put_message_ref(r);
            LeaveCriticalSection(&cs_kmq_msg_ref);

            if(KHM_SUCCEEDED(rv))
                m->nCompleted++;
            else
                m->nFailed++;

            if(m->nCompleted + m->nFailed == m->nSent) {
                kmqint_put_message(m);
            }
            LeaveCriticalSection(&cs_kmq_msg);

            return KHM_ERROR_SUCCESS;
        } else {
            EnterCriticalSection(&cs_kmq_msg);
            EnterCriticalSection(&cs_kmq_msg_ref);
            kmqint_put_message_ref(r);
            LeaveCriticalSection(&cs_kmq_msg_ref);
            m->nCompleted++;
            if(m->nCompleted + m->nFailed == m->nSent) {
                kmqint_put_message(m);
            }
            LeaveCriticalSection(&cs_kmq_msg);

            return KHM_ERROR_EXIT;
        }
    } else {
        return KHM_ERROR_TIMEOUT;
    }
}
// Thread that gets and sends CPU usage
static DWORD WINAPI mainThread(LPVOID args)
{
	UNREFERENCED_PARAMETER(args);

	bool usbOk = true;
	byte checkCounter = 0;
	byte pokeCounter = 0;

	while(1)
	{
		// If exit event is set then exit thread, otherwise wait for timeout and do the usual CPU stuff
		if(WaitForSingleObject(hThreadExitEvent, SAMPLERATE) != WAIT_TIMEOUT)
			break;

		// Get usage
		byte cpuUsage = getCPUUsage();

		EnterCriticalSection(&cs);

		// Store sample
		sample.samples[sample.idx++] = cpuUsage;
		if(sample.idx >= sample.count)
			sample.idx = 0;

		// Get average
		uint avg = 0;
		for(uint i=0;i<sample.count;i++)
			avg += sample.samples[i];
		avg /= sample.count;

		LeaveCriticalSection(&cs);

		cpuUsage = (byte)avg;

		// Show CPU usage
		actions_showCPULoad(cpuUsage);

		// Constantly searching for USB devices takes up a lot of CPU time,
		// so here we only check for new device every so often.
		if(!usbOk)
		{
			if(++checkCounter < (USB_CHECK_INTERVAL / SAMPLERATE))
				continue;
			checkCounter = 0;
		}

		// Send to USB
		if((usbOk = checkDevice(usbOk)))
		{
			if(device_get()->ledMode == MODE_CPU_USAGE)
			{
				// Workout colour
				s_rgbVal colour;
				getCPUColour(cpuUsage, &colour);

				// Send colour
				usbOk = device_setColour(&colour);
			}
			else
			{
				// Just send pokes if not in CPU usage mode,
				// this sees if the device is still connected
				if(++pokeCounter >= (USB_POKE_INTERVAL / SAMPLERATE))
				{
					pokeCounter = 0;
					usbOk = device_poke();
				}
			}
		}
	}

	return EXIT_SUCCESS;
}
Esempio n. 11
0
bool gcore::Mutex::tryLock() {
  return (WaitForSingleObject(MUTEX, 0) == WAIT_OBJECT_0);
}
Esempio n. 12
0
int
main(void)
{
	struct sockaddr_in sin_s, sin_c;
	struct sockaddr_conn sconn;
#ifdef _WIN32
	SOCKET fd_c, fd_s;
#else
	int fd_c, fd_s;
#endif
	struct socket *s_c, *s_s, *s_l;
#ifdef _WIN32
	HANDLE tid_c, tid_s;
#else
	pthread_t tid_c, tid_s;
#endif
	int cur_buf_size, snd_buf_size, rcv_buf_size;
	socklen_t opt_len;
	struct sctp_sndinfo sndinfo;
	char *line;
#ifdef _WIN32
	WSADATA wsaData;
#endif

#ifdef _WIN32
	if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
		printf("WSAStartup failed\n");
		exit (EXIT_FAILURE);
	}
#endif
	usrsctp_init(0, conn_output, debug_printf);
	/* set up a connected UDP socket */
#ifdef _WIN32
	if ((fd_c = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
		printf("socket() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	if ((fd_s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
		printf("socket() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
#else
	if ((fd_c = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
		exit(EXIT_FAILURE);
	}
	if ((fd_s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
		exit(EXIT_FAILURE);
	}
#endif
	memset(&sin_c, 0, sizeof(struct sockaddr_in));
	sin_c.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
	sin_c.sin_len = sizeof(struct sockaddr_in);
#endif
	sin_c.sin_port = htons(9900);
	sin_c.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	memset(&sin_s, 0, sizeof(struct sockaddr_in));
	sin_s.sin_family = AF_INET;
#ifdef HAVE_SIN_LEN
	sin_s.sin_len = sizeof(struct sockaddr_in);
#endif
	sin_s.sin_port = htons(9899);
	sin_s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
#ifdef _WIN32
	if (bind(fd_c, (struct sockaddr *)&sin_c, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		printf("bind() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	if (bind(fd_s, (struct sockaddr *)&sin_s, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		printf("bind() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
#else
	if (bind(fd_c, (struct sockaddr *)&sin_c, sizeof(struct sockaddr_in)) < 0) {
		perror("bind");
		exit(EXIT_FAILURE);
	}
	if (bind(fd_s, (struct sockaddr *)&sin_s, sizeof(struct sockaddr_in)) < 0) {
		perror("bind");
		exit(EXIT_FAILURE);
	}
#endif
#ifdef _WIN32
	if (connect(fd_c, (struct sockaddr *)&sin_s, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		printf("connect() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	if (connect(fd_s, (struct sockaddr *)&sin_c, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		printf("connect() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
#else
	if (connect(fd_c, (struct sockaddr *)&sin_s, sizeof(struct sockaddr_in)) < 0) {
		perror("connect");
		exit(EXIT_FAILURE);
	}
	if (connect(fd_s, (struct sockaddr *)&sin_c, sizeof(struct sockaddr_in)) < 0) {
		perror("connect");
		exit(EXIT_FAILURE);
	}
#endif
#ifdef _WIN32
	tid_c = CreateThread(NULL, 0, &handle_packets, (void *)&fd_c, 0, NULL);
	tid_s = CreateThread(NULL, 0, &handle_packets, (void *)&fd_s, 0, NULL);
#else
	if (pthread_create(&tid_c, NULL, &handle_packets, (void *)&fd_c)) {
		perror("pthread_create tid_c");
		exit(EXIT_FAILURE);
	}

	if (pthread_create(&tid_s, NULL, &handle_packets, (void *)&fd_s)) {
		perror("pthread_create tid_s");
		exit(EXIT_FAILURE);
	};
#endif
#ifdef SCTP_DEBUG
	usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_NONE);
#endif
	usrsctp_sysctl_set_sctp_ecn_enable(0);
	usrsctp_register_address((void *)&fd_c);
	usrsctp_register_address((void *)&fd_s);
	if ((s_c = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, receive_cb, NULL, 0, &fd_c)) == NULL) {
		perror("usrsctp_socket");
		exit(EXIT_FAILURE);
	}
	opt_len = (socklen_t)sizeof(int);
	cur_buf_size = 0;
	if (usrsctp_getsockopt(s_c, SOL_SOCKET, SO_SNDBUF, &cur_buf_size, &opt_len) < 0) {
		perror("usrsctp_getsockopt");
		exit(EXIT_FAILURE);
	}
	printf("Change send socket buffer size from %d ", cur_buf_size);
	snd_buf_size = 1<<20; /* 1 MB */
	if (usrsctp_setsockopt(s_c, SOL_SOCKET, SO_SNDBUF, &snd_buf_size, sizeof(int)) < 0) {
		perror("usrsctp_setsockopt");
		exit(EXIT_FAILURE);
	}
	opt_len = (socklen_t)sizeof(int);
	cur_buf_size = 0;
	if (usrsctp_getsockopt(s_c, SOL_SOCKET, SO_SNDBUF, &cur_buf_size, &opt_len) < 0) {
		perror("usrsctp_getsockopt");
		exit(EXIT_FAILURE);
	}
	printf("to %d.\n", cur_buf_size);
	if ((s_l = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, receive_cb, NULL, 0, &fd_s)) == NULL) {
		perror("usrsctp_socket");
		exit(EXIT_FAILURE);
	}
	opt_len = (socklen_t)sizeof(int);
	cur_buf_size = 0;
	if (usrsctp_getsockopt(s_l, SOL_SOCKET, SO_RCVBUF, &cur_buf_size, &opt_len) < 0) {
		perror("usrsctp_getsockopt");
		exit(EXIT_FAILURE);
	}
	printf("Change receive socket buffer size from %d ", cur_buf_size);
	rcv_buf_size = 1<<16; /* 64 KB */
	if (usrsctp_setsockopt(s_l, SOL_SOCKET, SO_RCVBUF, &rcv_buf_size, sizeof(int)) < 0) {
		perror("usrsctp_setsockopt");
		exit(EXIT_FAILURE);
	}
	opt_len = (socklen_t)sizeof(int);
	cur_buf_size = 0;
	if (usrsctp_getsockopt(s_l, SOL_SOCKET, SO_RCVBUF, &cur_buf_size, &opt_len) < 0) {
		perror("usrsctp_getsockopt");
		exit(EXIT_FAILURE);
	}
	printf("to %d.\n", cur_buf_size);
	/* Bind the client side. */
	memset(&sconn, 0, sizeof(struct sockaddr_conn));
	sconn.sconn_family = AF_CONN;
#ifdef HAVE_SCONN_LEN
	sconn.sconn_len = sizeof(struct sockaddr_conn);
#endif
	sconn.sconn_port = htons(5001);
	sconn.sconn_addr = &fd_c;
	if (usrsctp_bind(s_c, (struct sockaddr *)&sconn, sizeof(struct sockaddr_conn)) < 0) {
		perror("usrsctp_bind");
		exit(EXIT_FAILURE);
	}
	/* Bind the server side. */
	memset(&sconn, 0, sizeof(struct sockaddr_conn));
	sconn.sconn_family = AF_CONN;
#ifdef HAVE_SCONN_LEN
	sconn.sconn_len = sizeof(struct sockaddr_conn);
#endif
	sconn.sconn_port = htons(5001);
	sconn.sconn_addr = &fd_s;
	if (usrsctp_bind(s_l, (struct sockaddr *)&sconn, sizeof(struct sockaddr_conn)) < 0) {
		perror("usrsctp_bind");
		exit(EXIT_FAILURE);
	}
	/* Make server side passive... */
	if (usrsctp_listen(s_l, 1) < 0) {
		perror("usrsctp_listen");
		exit(EXIT_FAILURE);
	}
	/* Initiate the handshake */
	memset(&sconn, 0, sizeof(struct sockaddr_conn));
	sconn.sconn_family = AF_CONN;
#ifdef HAVE_SCONN_LEN
	sconn.sconn_len = sizeof(struct sockaddr_conn);
#endif
	sconn.sconn_port = htons(5001);
	sconn.sconn_addr = &fd_c;
	if (usrsctp_connect(s_c, (struct sockaddr *)&sconn, sizeof(struct sockaddr_conn)) < 0) {
		perror("usrsctp_connect");
		exit(EXIT_FAILURE);
	}
	if ((s_s = usrsctp_accept(s_l, NULL, NULL)) == NULL) {
		perror("usrsctp_accept");
		exit(EXIT_FAILURE);
	}
	usrsctp_close(s_l);
	if ((line = malloc(LINE_LENGTH)) == NULL) {
		exit(EXIT_FAILURE);
	}
	memset(line, 'A', LINE_LENGTH);
	sndinfo.snd_sid = 1;
	sndinfo.snd_flags = 0;
	sndinfo.snd_ppid = htonl(DISCARD_PPID);
	sndinfo.snd_context = 0;
	sndinfo.snd_assoc_id = 0;
	/* Send a 1 MB message */
	if (usrsctp_sendv(s_c, line, LINE_LENGTH, NULL, 0, (void *)&sndinfo,
	                 (socklen_t)sizeof(struct sctp_sndinfo), SCTP_SENDV_SNDINFO, 0) < 0) {
		perror("usrsctp_sendv");
		exit(EXIT_FAILURE);
	}
	free(line);
	usrsctp_shutdown(s_c, SHUT_WR);

	while (usrsctp_finish() != 0) {
#ifdef _WIN32
		Sleep(1000);
#else
		sleep(1);
#endif
	}
#ifdef _WIN32
	TerminateThread(tid_c, 0);
	WaitForSingleObject(tid_c, INFINITE);
	TerminateThread(tid_s, 0);
	WaitForSingleObject(tid_s, INFINITE);
	if (closesocket(fd_c) == SOCKET_ERROR) {
		printf("closesocket() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	if (closesocket(fd_s) == SOCKET_ERROR) {
		printf("closesocket() failed with error: %ld\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	WSACleanup();
#else
	pthread_cancel(tid_c);
	pthread_join(tid_c, NULL);
	pthread_cancel(tid_s);
	pthread_join(tid_s, NULL);
	if (close(fd_c) < 0) {
		perror("close");
		exit(EXIT_FAILURE);
	}
	if (close(fd_s) < 0) {
		perror("close");
		exit(EXIT_FAILURE);
	}
#endif
	return (0);
}
Esempio n. 13
0
bool gcore::Semaphore::tryDecrement() {
  return (WaitForSingleObject((HANDLE)mData, 0) == WAIT_OBJECT_0);
}
Esempio n. 14
0
int
main()
{
    DWORD dwRead, dwWrite;
    char *cmdLine;
    HANDLE hStdInput, hStdOutput, hStdError;
    HANDLE hFileInput, hFileOutput, hFileError;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    char buf[8192];
    DWORD result;

    hFileInput = INVALID_HANDLE_VALUE;
    hFileOutput = INVALID_HANDLE_VALUE;
    hFileError = INVALID_HANDLE_VALUE;
    result = 1;

    /*
     * Don't get command line from argc, argv, because the command line
     * tokenizer will have stripped off all the escape sequences needed
     * for quotes and backslashes, and then we'd have to put them all
     * back in again.  Get the raw command line and parse off what we
     * want ourselves.  The command line should be of the form:
     *
     * stub16.exe program arg1 arg2 ...
     */

    cmdLine = strchr(GetCommandLine(), ' ');
    if (cmdLine == NULL) {
	return 1;
    }
    cmdLine++;

    hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    hStdError = GetStdHandle(STD_ERROR_HANDLE);

    if (GetFileType(hStdInput) == FILE_TYPE_PIPE) {
	hFileInput = CreateTempFile();
	if (hFileInput == INVALID_HANDLE_VALUE) {
	    goto cleanup;
	}
	while (ReadFile(hStdInput, buf, sizeof(buf), &dwRead, NULL) != FALSE) {
	    if (dwRead == 0) {
		break;
	    }
	    if (WriteFile(hFileInput, buf, dwRead, &dwWrite, NULL) == FALSE) {
		goto cleanup;
	    }
	}
	SetFilePointer(hFileInput, 0, 0, FILE_BEGIN);
	SetStdHandle(STD_INPUT_HANDLE, hFileInput);
    }
    if (GetFileType(hStdOutput) == FILE_TYPE_PIPE) {
	hFileOutput = CreateTempFile();
	if (hFileOutput == INVALID_HANDLE_VALUE) {
	    goto cleanup;
	}
	SetStdHandle(STD_OUTPUT_HANDLE, hFileOutput);
    }
    if (GetFileType(hStdError) == FILE_TYPE_PIPE) {
	hFileError = CreateTempFile();
	if (hFileError == INVALID_HANDLE_VALUE) {
	    goto cleanup;
	}
	SetStdHandle(STD_ERROR_HANDLE, hFileError);
    }

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    if (CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, 
	    &pi) == FALSE) {
	goto cleanup;
    }

    WaitForInputIdle(pi.hProcess, 5000);
    WaitForSingleObject(pi.hProcess, INFINITE);
    GetExitCodeProcess(pi.hProcess, &result);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    if (hFileOutput != INVALID_HANDLE_VALUE) {
	SetFilePointer(hFileOutput, 0, 0, FILE_BEGIN);
	while (ReadFile(hFileOutput, buf, sizeof(buf), &dwRead, NULL) != FALSE) {
	    if (dwRead == 0) {
		break;
	    }
	    if (WriteFile(hStdOutput, buf, dwRead, &dwWrite, NULL) == FALSE) {
		break;
	    }
	}
    }
    if (hFileError != INVALID_HANDLE_VALUE) {
	SetFilePointer(hFileError, 0, 0, FILE_BEGIN);
	while (ReadFile(hFileError, buf, sizeof(buf), &dwRead, NULL) != FALSE) {
	    if (dwRead == 0) {
		break;
	    }
	    if (WriteFile(hStdError, buf, dwRead, &dwWrite, NULL) == FALSE) {
		break;
	    }
	}
    }

cleanup:
    if (hFileInput != INVALID_HANDLE_VALUE) {
	CloseHandle(hFileInput);
    }
    if (hFileOutput != INVALID_HANDLE_VALUE) {
	CloseHandle(hFileOutput);
    }
    if (hFileError != INVALID_HANDLE_VALUE) {
	CloseHandle(hFileError);
    }
    CloseHandle(hStdInput);
    CloseHandle(hStdOutput);
    CloseHandle(hStdError);
    ExitProcess(result);
    return 1;
}
Esempio n. 15
0
void gcore::Semaphore::decrement() {
  WaitForSingleObject((HANDLE)mData,INFINITE);
}
Esempio n. 16
0
bool gcore::Semaphore::timedDecrement(unsigned long ms) {
  return (WaitForSingleObject((HANDLE)mData, ms) == WAIT_OBJECT_0);
}
Esempio n. 17
0
DWORD WINAPI SimpleThreadHandler(PVOID pvParam) {
  
   WaitForSingleObject((HANDLE) pvParam, INFINITE);   

   return(0);
}
            DWORD WINAPI FileWatcherThread::run_thread( void *_watcher ) {

                FileWatcherThread *watcher = (FileWatcherThread*)_watcher;


                while(watcher->running) {

                    ReadDirectoryChangesW(
                        watcher->handle, watcher->buffer, watcher->buffer_size, TRUE,
                        FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
                        NULL, &watcher->overlap, NULL
                    );

                    WaitForSingleObject(watcher->overlap.hEvent, INFINITE);

                        int seek = 0;

                        while(seek < watcher->buffer_size) {

                            PFILE_NOTIFY_INFORMATION notifier = PFILE_NOTIFY_INFORMATION(watcher->buffer + seek);

                            WCHAR szwFileName[MAX_PATH];
                            int ulCount = notifier->FileNameLength/2;
                            wcsncpy(szwFileName, notifier->FileName, ulCount);
                            szwFileName[ulCount] = L'\0';

                            std::wstring widepath(szwFileName);
                            std::string path(widepath.begin(), widepath.end());

                            FilewatchEventType _event_type = fe_unknown;

                                switch( notifier->Action ) {

                                    case FILE_ACTION_ADDED:{
                                        _event_type = fe_create;
                                        break;
                                    }

                                    case FILE_ACTION_REMOVED:{
                                        _event_type = fe_remove;
                                        break;
                                    }

                                    case FILE_ACTION_MODIFIED:{
                                        _event_type = fe_modify;
                                        break;
                                    }

                                    case FILE_ACTION_RENAMED_OLD_NAME:{
                                        _event_type = fe_remove;
                                        break;
                                    }

                                    case FILE_ACTION_RENAMED_NEW_NAME:{
                                        _event_type = fe_create;
                                        break;
                                    }

                                } //switch

                                if(_event_type != fe_unknown) {

                                    // put into queue
                                    snow::io::event_node_t* node = new snow::io::event_node_t;
                                    node->path = std::string(watcher->path+"/"+path);
                                    node->event_type = (int)_event_type;

                                    snow::io::eventqueue_push(&filewatch_queue, node);

                                }

                            seek += notifier->NextEntryOffset;

                            if(notifier->NextEntryOffset == 0) {
                                break;
                            }

                        } //seek < buffer size

                    } //while running

                return 0;

            } //run_thread
Esempio n. 19
0
/*
 * Curl_wait_for_resolv() waits for a resolve to finish. This function should
 * be avoided since using this risk getting the multi interface to "hang".
 *
 * If 'entry' is non-NULL, make it point to the resolved dns entry
 *
 * This is the version for resolves-in-a-thread.
 */
CURLcode Curl_wait_for_resolv(struct connectdata *conn,
                              struct Curl_dns_entry **entry)
{
  struct thread_data   *td = (struct thread_data*) conn->async.os_specific;
  struct SessionHandle *data = conn->data;
  long   timeout;
  DWORD  status, ticks;
  CURLcode rc;

  curlassert (conn && td);

  /* now, see if there's a connect timeout or a regular timeout to
     use instead of the default one */
  timeout =
    conn->data->set.connecttimeout ? conn->data->set.connecttimeout :
    conn->data->set.timeout ? conn->data->set.timeout :
    CURL_TIMEOUT_RESOLVE; /* default name resolve timeout */
  ticks = GetTickCount();

  /* wait for the thread to resolve the name */
  status = WaitForSingleObject(td->event_resolved, 1000UL*timeout);

  /* mark that we are now done waiting */
  ReleaseMutex(td->mutex_waiting);

  /* close our handle to the mutex, no point in hanging on to it */
  CloseHandle(td->mutex_waiting);
  td->mutex_waiting = NULL;

  /* close the event handle, it's useless now */
  CloseHandle(td->event_resolved);
  td->event_resolved = NULL;

  /* has the resolver thread succeeded in resolving our query ? */
  if (status == WAIT_OBJECT_0) {
    /* wait for the thread to exit, it's in the callback sequence */
    if (WaitForSingleObject(td->thread_hnd, 5000) == WAIT_TIMEOUT) {
      TerminateThread(td->thread_hnd, 0);
      conn->async.done = TRUE;
      td->thread_status = (DWORD)-1;
      TRACE(("%s() thread stuck?!, ", THREAD_NAME));
    }
    else {
      /* Thread finished before timeout; propagate Winsock error to this
       * thread.  'conn->async.done = TRUE' is set in
       * Curl_addrinfo4/6_callback().
       */
      WSASetLastError(conn->async.status);
      GetExitCodeThread(td->thread_hnd, &td->thread_status);
      TRACE(("%s() status %lu, thread retval %lu, ",
             THREAD_NAME, status, td->thread_status));
    }
  }
  else {
    conn->async.done = TRUE;
    td->thread_status = (DWORD)-1;
    TRACE(("%s() timeout, ", THREAD_NAME));
  }

  TRACE(("elapsed %lu ms\n", GetTickCount()-ticks));

  CloseHandle(td->thread_hnd);

  if(entry)
    *entry = conn->async.dns;

  rc = CURLE_OK;

  if (!conn->async.dns) {
    /* a name was not resolved */
    if (td->thread_status == CURLE_OUT_OF_MEMORY) {
      rc = CURLE_OUT_OF_MEMORY;
      failf(data, "Could not resolve host: %s", curl_easy_strerror(rc));
    }
    else if (td->thread_status == (DWORD)-1 || conn->async.status == NO_DATA) {
      failf(data, "Resolving host timed out: %s", conn->host.name);
      rc = CURLE_OPERATION_TIMEDOUT;
    }
    else if(conn->async.done) {
      failf(data, "Could not resolve host: %s; %s",
            conn->host.name, Curl_strerror(conn,conn->async.status));
      rc = CURLE_COULDNT_RESOLVE_HOST;
    }
    else
      rc = CURLE_OPERATION_TIMEDOUT;
  }

  Curl_destroy_thread_data(&conn->async);

  if(!conn->async.dns)
    conn->bits.close = TRUE;

  return (rc);
}
Esempio n. 20
0
  LIBRARY_API bool socketNet::create (struct networkStruct& socketData)
  {
    char ac[32];
    char *client_ip_address = NULL;
    HANDLE hTimer = NULL;
    LARGE_INTEGER liDueTime;
    liDueTime.QuadPart=-30000000;  //! 3 second timer for polling

    struct sockaddr_in serverAddr; //! server's socket address
    struct sockaddr_in clientAddr; //! client's socket address 
    int sockAddrSize;              //! size of socket address structure
    SOCKET newFd;                  //! socket descriptor from accept
    int ix = 0;                    //! counter for work task names
    int tcpServer_shutdown = 0;
    unsigned long l = 1;           //! to set sockets to nonblocking

    hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
    if (NULL == hTimer)
    {
      //! Timer error
    }

    //! Set up the local address
    sockAddrSize = sizeof (struct sockaddr_in);

    WSADATA wsaData;
    int wsaret = WSAStartup(0x101, &wsaData);
    if (wsaret != 0)
      return false;
    //! Clear (zero-out) serverAddr
    memset((char *) &serverAddr, 0, sockAddrSize);
    serverAddr.sin_addr.s_addr = htons (INADDR_ANY);

    serverAddr.sin_family = AF_INET; 
    serverAddr.sin_port = htons ((u_short)socketData.sP); 

    gethostname(ac, sizeof(ac));
    struct hostent *phe = gethostbyname(ac);

    socketData.serverAddress = new char[128];//inet_ntoa (serverAddr.sin_addr);
    struct in_addr a1;//, a2, a3, a4;

    int i = 0;
    //while (phe->h_addr_list[i] != 0)
    {
      memcpy (&a1, phe->h_addr_list[i], sizeof(struct in_addr));
      sprintf (socketData.serverAddress, "%s", inet_ntoa(a1));
      ++i;
    }

    //! This allows us to have multiple clients attached to the same port
    if (!socketData.bound)
    {
      //! create a TCP-based socket
      if ((socketData.sFd = socket(AF_INET, SOCK_STREAM, 0)) == ERROR_F)
      {
#ifdef NOISY
        perror ("socket");
#endif
        return false; 
      }

      //! bind socket to local address
      if (bind (socketData.sFd,
                (struct sockaddr *) &serverAddr,
                sockAddrSize) == ERROR_F)
      {
#ifdef NOISY
        perror ("bind");
#endif
        closesocket (socketData.sFd); 
        WSACleanup ();
        return false; 
      }
      socketData.bound = true;
    }

    //ioctlsocket (socketData.sFd, FIONBIO, &l);
    
    //! Create queue for client connection requests
    if (listen (socketData.sFd, SERVER_MAX_CONNECTIONS) == ERROR_F)
    { 
      closesocket (socketData.sFd);
      WSACleanup ();
      socketData.bound = true;
      return false;
    }
    //! Accept new connect requests and spawn tasks to process them
    //! Accept the first connection and use it...
    newFd = 0;
    do
    {
      //! If we stop the connection attempt
      bool okay;
      okay = false;
      do
      {
        if (!settings_->globalRunServer)
        {
          closesocket (socketData.sFd);
          WSACleanup();
          return false;
        }
        if ((newFd = accept (socketData.sFd,
                            (struct sockaddr*)&clientAddr,
                            &sockAddrSize)) == ERROR_F) 
        {
          printf ("%s\n", inet_ntoa (clientAddr.sin_addr));

#ifdef NOISY
          perror ("accept"); 
#endif
          int g = WSAGetLastError();
          //! We expect the error WSAEWOULDBLOCK since the socket is non-blocking
          if (g != WSAEWOULDBLOCK)
          {
            closesocket (socketData.sFd);
            WSACleanup ();
            return false; 
          }
          // Set a timer to wait for 0.1 seconds--Poll @ 10 Hz
          if (!SetWaitableTimer(hTimer, &liDueTime, 1, NULL, NULL, 0))
          {
            //! Timer error
          }

          if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)
          {
            //! Timer error
          }
        }
        else
        {
          okay = true;
        }
      } while (!okay);

      if (newFd > 0)            
      {
        client_ip_address = inet_ntoa (clientAddr.sin_addr);
        //! JAM: A problem encountered with Windows is that it constantly
        //!      thinks a connection from 204.204.204.204:52428 is being
        //!      made
        if (strcmp("204.204.204.204", client_ip_address) != 0)
        {
          //! fill out the struct
          socketData.cFd = newFd;
          socketData.address = client_ip_address;
          socketData.cP = ntohs (clientAddr.sin_port);

          //! Disable nonblocking by default
          //unsigned long l = 0;
          //ioctlsocket (socketData.cFd, FIONBIO, &l);
          tcpServer_shutdown = 1;  //! say we are done
        }
      }
    }while (tcpServer_shutdown != 1);
    socketData.connected = true;
    settings_->connected = true;
    //l=1;
    //ioctlsocket (socketData.cFd, FIONBIO, &l);

    return true;
  } 
Esempio n. 21
0
/*
 * The runtime library's popen() on win32 does not work when being
 * called from a service when running on windows <= 2000, because
 * there is no stdin/stdout/stderr.
 *
 * Executing a command in a pipe and reading the first line from it
 * is all we need.
 */
static char *
pipe_read_line(char *cmd, char *line, int maxsize)
{
#ifndef WIN32
	FILE	   *pgver;

	/* flush output buffers in case popen does not... */
	fflush(stdout);
	fflush(stderr);

	errno = 0;
	if ((pgver = popen(cmd, "r")) == NULL)
	{
		perror("popen failure");
		return NULL;
	}

	errno = 0;
	if (fgets(line, maxsize, pgver) == NULL)
	{
		if (feof(pgver))
			fprintf(stderr, "no data was returned by command \"%s\"\n", cmd);
		else
			perror("fgets failure");
		pclose(pgver);			/* no error checking */
		return NULL;
	}

	if (pclose_check(pgver))
		return NULL;

	return line;
#else							/* WIN32 */

	SECURITY_ATTRIBUTES sattr;
	HANDLE		childstdoutrd,
				childstdoutwr,
				childstdoutrddup;
	PROCESS_INFORMATION pi;
	STARTUPINFO si;
	char	   *retval = NULL;

	sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
	sattr.bInheritHandle = TRUE;
	sattr.lpSecurityDescriptor = NULL;

	if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
		return NULL;

	if (!DuplicateHandle(GetCurrentProcess(),
						 childstdoutrd,
						 GetCurrentProcess(),
						 &childstdoutrddup,
						 0,
						 FALSE,
						 DUPLICATE_SAME_ACCESS))
	{
		CloseHandle(childstdoutrd);
		CloseHandle(childstdoutwr);
		return NULL;
	}

	CloseHandle(childstdoutrd);

	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdError = childstdoutwr;
	si.hStdOutput = childstdoutwr;
	si.hStdInput = INVALID_HANDLE_VALUE;

	if (CreateProcess(NULL,
					  cmd,
					  NULL,
					  NULL,
					  TRUE,
					  0,
					  NULL,
					  NULL,
					  &si,
					  &pi))
	{
		/* Successfully started the process */
		char	   *lineptr;

		ZeroMemory(line, maxsize);

		/* Try to read at least one line from the pipe */
		/* This may require more than one wait/read attempt */
		for (lineptr = line; lineptr < line + maxsize - 1;)
		{
			DWORD		bytesread = 0;

			/* Let's see if we can read */
			if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
				break;			/* Timeout, but perhaps we got a line already */

			if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
						  &bytesread, NULL))
				break;			/* Error, but perhaps we got a line already */

			lineptr += strlen(lineptr);

			if (!bytesread)
				break;			/* EOF */

			if (strchr(line, '\n'))
				break;			/* One or more lines read */
		}

		if (lineptr != line)
		{
			/* OK, we read some data */
			int			len;

			/* If we got more than one line, cut off after the first \n */
			lineptr = strchr(line, '\n');
			if (lineptr)
				*(lineptr + 1) = '\0';

			len = strlen(line);

			/*
			 * If EOL is \r\n, convert to just \n. Because stdout is a
			 * text-mode stream, the \n output by the child process is
			 * received as \r\n, so we convert it to \n.  The server main.c
			 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
			 * disabling \n to \r\n expansion for stdout.
			 */
			if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
			{
				line[len - 2] = '\n';
				line[len - 1] = '\0';
				len--;
			}

			/*
			 * We emulate fgets() behaviour. So if there is no newline at the
			 * end, we add one...
			 */
			if (len == 0 || line[len - 1] != '\n')
				strcat(line, "\n");

			retval = line;
		}

		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
	}

	CloseHandle(childstdoutwr);
	CloseHandle(childstdoutrddup);

	return retval;
#endif   /* WIN32 */
}
Esempio n. 22
0
static VOID MouseGetPacket(PMOUSE_PACKET Packet)
{
    /* Clear the packet */
    RtlZeroMemory(Packet, sizeof(*Packet));

    /* Acquire the mutex */
    WaitForSingleObject(MouseMutex, INFINITE);

    Packet->Flags |= MOUSE_ALWAYS_SET;

    /* Set the sign flags */
    if (HorzCounter < 0)
    {
        Packet->Flags |= MOUSE_X_SIGN;
        HorzCounter = -HorzCounter;
    }

    if (VertCounter < 0)
    {
        Packet->Flags |= MOUSE_Y_SIGN;
        VertCounter = -VertCounter;
    }

    /* Check for horizontal overflows */
    if (HorzCounter > MOUSE_MAX)
    {
        HorzCounter = MOUSE_MAX;
        Packet->Flags |= MOUSE_X_OVERFLOW;
    }

    /* Check for vertical overflows */
    if (VertCounter > MOUSE_MAX)
    {
        VertCounter = MOUSE_MAX;
        Packet->Flags |= MOUSE_Y_OVERFLOW;
    }

    /* Set the button flags */
    if (ButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) Packet->Flags |= MOUSE_LEFT_BUTTON;
    if (ButtonState & FROM_LEFT_2ND_BUTTON_PRESSED) Packet->Flags |= MOUSE_MIDDLE_BUTTON;
    if (ButtonState &     RIGHTMOST_BUTTON_PRESSED) Packet->Flags |= MOUSE_RIGHT_BUTTON;

    if (MouseId == 4)
    {
        if (ButtonState & FROM_LEFT_3RD_BUTTON_PRESSED) Packet->Extra |= MOUSE_4TH_BUTTON;
        if (ButtonState & FROM_LEFT_4TH_BUTTON_PRESSED) Packet->Extra |= MOUSE_5TH_BUTTON;
    }

    if (MouseId >= 3)
    {
        /* Set the scroll counter */
        Packet->Extra |= ((UCHAR)ScrollCounter & 0x0F);
    }

    /* Store the counters in the packet */
    Packet->HorzCounter = LOBYTE(HorzCounter);
    Packet->VertCounter = LOBYTE(VertCounter);

    /* Reset the counters */
    MouseResetCounters();

    /* Release the mutex */
    ReleaseMutex(MouseMutex);
}
Esempio n. 23
0
wait_result_t wait( event_t & e, DWORD timeout )
{
    return wait_result_t( WaitForSingleObject( e.m_handle, timeout ), 1, &e.m_handle );
}
/******************************************************************************
 *           WaitForDebugEvent   (KERNEL32.@)
 *
 *  Waits for a debugging event to occur in a process being debugged before
 *  filling out the debug event structure.
 *
 * PARAMS
 *  event   [O] Address of structure for event information.
 *  timeout [I] Number of milliseconds to wait for event.
 *
 * RETURNS
 *
 *  Returns true if a debug event occurred and false if the call timed out.
 */
BOOL WINAPI WaitForDebugEvent(
    LPDEBUG_EVENT event,
    DWORD         timeout)
{
    BOOL ret;
    DWORD res;
    int i;

    for (;;)
    {
        HANDLE wait = 0;
        debug_event_t data;
        SERVER_START_REQ( wait_debug_event )
        {
            req->get_handle = (timeout != 0);
            wine_server_set_reply( req, &data, sizeof(data) );
            if (!(ret = !wine_server_call_err( req ))) goto done;

            if (!wine_server_reply_size(reply))  /* timeout */
            {
                wait = wine_server_ptr_handle( reply->wait );
                ret = FALSE;
                goto done;
            }
            event->dwDebugEventCode = data.code;
            event->dwProcessId      = (DWORD)reply->pid;
            event->dwThreadId       = (DWORD)reply->tid;
            switch(data.code)
            {
            case EXCEPTION_DEBUG_EVENT:
                if (data.exception.exc_code == DBG_PRINTEXCEPTION_C && data.exception.nb_params >= 2)
                {
                    event->dwDebugEventCode = OUTPUT_DEBUG_STRING_EVENT;
                    event->u.DebugString.lpDebugStringData  = wine_server_get_ptr( data.exception.params[1] );
                    event->u.DebugString.fUnicode           = FALSE;
                    event->u.DebugString.nDebugStringLength = data.exception.params[0];
                    break;
                }
                else if (data.exception.exc_code == DBG_RIPEXCEPTION && data.exception.nb_params >= 2)
                {
                    event->dwDebugEventCode = RIP_EVENT;
                    event->u.RipInfo.dwError = data.exception.params[0];
                    event->u.RipInfo.dwType  = data.exception.params[1];
                    break;
                }
                event->u.Exception.dwFirstChance = data.exception.first;
                event->u.Exception.ExceptionRecord.ExceptionCode    = data.exception.exc_code;
                event->u.Exception.ExceptionRecord.ExceptionFlags   = data.exception.flags;
                event->u.Exception.ExceptionRecord.ExceptionRecord  = wine_server_get_ptr( data.exception.record );
                event->u.Exception.ExceptionRecord.ExceptionAddress = wine_server_get_ptr( data.exception.address );
                event->u.Exception.ExceptionRecord.NumberParameters = data.exception.nb_params;
                for (i = 0; i < data.exception.nb_params; i++)
                    event->u.Exception.ExceptionRecord.ExceptionInformation[i] = data.exception.params[i];
                break;
            case CREATE_THREAD_DEBUG_EVENT:
                event->u.CreateThread.hThread           = wine_server_ptr_handle( data.create_thread.handle );
                event->u.CreateThread.lpThreadLocalBase = wine_server_get_ptr( data.create_thread.teb );
                event->u.CreateThread.lpStartAddress    = wine_server_get_ptr( data.create_thread.start );
                break;
            case CREATE_PROCESS_DEBUG_EVENT:
                event->u.CreateProcessInfo.hFile                 = wine_server_ptr_handle( data.create_process.file );
                event->u.CreateProcessInfo.hProcess              = wine_server_ptr_handle( data.create_process.process );
                event->u.CreateProcessInfo.hThread               = wine_server_ptr_handle( data.create_process.thread );
                event->u.CreateProcessInfo.lpBaseOfImage         = wine_server_get_ptr( data.create_process.base );
                event->u.CreateProcessInfo.dwDebugInfoFileOffset = data.create_process.dbg_offset;
                event->u.CreateProcessInfo.nDebugInfoSize        = data.create_process.dbg_size;
                event->u.CreateProcessInfo.lpThreadLocalBase     = wine_server_get_ptr( data.create_process.teb );
                event->u.CreateProcessInfo.lpStartAddress        = wine_server_get_ptr( data.create_process.start );
                event->u.CreateProcessInfo.lpImageName           = wine_server_get_ptr( data.create_process.name );
                event->u.CreateProcessInfo.fUnicode              = data.create_process.unicode;
                break;
            case EXIT_THREAD_DEBUG_EVENT:
                event->u.ExitThread.dwExitCode = data.exit.exit_code;
                break;
            case EXIT_PROCESS_DEBUG_EVENT:
                event->u.ExitProcess.dwExitCode = data.exit.exit_code;
                break;
            case LOAD_DLL_DEBUG_EVENT:
                event->u.LoadDll.hFile                 = wine_server_ptr_handle( data.load_dll.handle );
                event->u.LoadDll.lpBaseOfDll           = wine_server_get_ptr( data.load_dll.base );
                event->u.LoadDll.dwDebugInfoFileOffset = data.load_dll.dbg_offset;
                event->u.LoadDll.nDebugInfoSize        = data.load_dll.dbg_size;
                event->u.LoadDll.lpImageName           = wine_server_get_ptr( data.load_dll.name );
                event->u.LoadDll.fUnicode              = data.load_dll.unicode;
                break;
            case UNLOAD_DLL_DEBUG_EVENT:
                event->u.UnloadDll.lpBaseOfDll = wine_server_get_ptr( data.unload_dll.base );
                break;
            }
        done:
            /* nothing */ ;
        }
        SERVER_END_REQ;
        if (ret) return TRUE;
        if (!wait) break;
        res = WaitForSingleObject( wait, timeout );
        CloseHandle( wait );
        if (res != STATUS_WAIT_0) break;
    }
    SetLastError( ERROR_SEM_TIMEOUT );
    return FALSE;
}
Esempio n. 25
0
// wait functions
wait_result_t wait( HANDLE h, DWORD timeout )
{
    return wait_result_t( WaitForSingleObject( h, timeout ), 1, &h );
}
Esempio n. 26
0
int nt_execve(const char *prog, const char *const *args, const char *const *envir)
{
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	enum {none, directex, shellex} execmode;
	DWORD exitcode;
	DWORD dwCreationflags;
	int priority;
	char *argv0;
	char *cmdstr, *cmdend;
	unsigned int cmdsize;
	size_t prognamelen, cmdlen;
	int hasext;
	char extension[_MAX_FNAME];
	const char *begin, *end, *extptr;
	static char exts[MAX_PATH];

	UNREFERENCED_PARAMETER(envir);

	/* get default PATHEXT or use empty exts */
	if (!*exts) {
		DWORD rc;
		/* not initialized */
		rc = GetEnvironmentVariable("PATHEXT", exts, sizeof(exts));
		if ((rc == 0) || (rc >= sizeof(exts)))
			/* if error or PATHEXT too big will retry at the next call */
			*exts = 0;
	}

	/* if prog has an extension initialize begin end to skip PATHEXT search */
	prognamelen = strlen(prog);
	extptr = prog + prognamelen - 1;
	hasext = 0;
	while (extptr > prog && !ISPATHSEP(*extptr)) {
		if (*extptr == '.' && *(extptr - 1) != ':' && !ISPATHSEP(*(extptr - 1))) {
			hasext++;
			break;
		}
		extptr--;
	}
	if (hasext) {
		begin = ".";
		end = "";
		strcpy(extension, extptr);
	} else {
		begin = exts;
		end = exts;
		*extension = '\0';
	}

	argv0 = (char *)heap_alloc(MAX_PATH);
	/* (prognamelen + 1) does not really matter, argv0 is '\0' filled */
	memcpy(argv0, prog, prognamelen + 1);

	errno = 0;
	execmode = none;
	/* NOTE: loops over PATHEXT if no extension found */
	while (*begin) {
		size_t extlen;
		if (GetBinaryType(argv0, &exitcode)) {
			/* exists and is executable
			   NOTE: an "xxx.exe" without a correct PE header (i.e. a text file)
			   has type "DOS binary", but execution will generate a WOW error */
			execmode = directex;
			break;
		}
		if (GetLastError() == ERROR_BAD_EXE_FORMAT) {
			/* exists but is not "executable" */
			execmode = shellex;
			break;
		}
		if (hasext)
			break;
		/* get next PATHEXT extension */
		while (*begin && (*begin != '.'))
			begin++;
		while (*end && (*end != ';'))
			end++;
		if (!*begin)
			break;
		extlen = end - begin;
		if (extlen < sizeof(extension)) {
			memcpy(extension, begin, extlen);
			extension[extlen] = '\0';
			/* prognamelen ignores the last '\r' if present */
			memcpy(argv0, prog, prognamelen);
			/* update argv0 adding the extension to prog */
			memcpy(argv0 + prognamelen, extension, extlen + 1);
		}
		begin = end;
		/* skip sequences of ';' */
		while (*end && *end == ';')
			end++;
	};

	cmdstr = (char *)heap_alloc(MAX_PATH << 2);
	cmdsize = MAX_PATH << 2;
	cmdlen = 0;
	cmdend = cmdstr;

	dbgprintf(PR_VERBOSE, "%s(): execute [%s] extension=[%s] mode=%d hasext=%d\n", __FUNCTION__, argv0, extension, execmode, hasext);
	/* skip over program name */
	args++;

	/* the file (after PATHEXT search) exists, but it's not "executable" */
	if (execmode == shellex) {
		/* if prog had no extension or has the extension associated to shell scripts */
		if ((hasext == 0 && *extension == '\0') || is_shell_script(extension)) {
			int res = process_shebang(argv0, (const char *const *)&cmdstr, &cmdlen, &cmdend, &cmdsize);
			if (res < 0) {
				execmode = none;
			} else if (res == 0) {
				char *newargv[2];
				cmdlen = copy_quote_and_fix_slashes(gModuleName, cmdstr);
				cmdend = cmdstr + cmdlen;
				newargv[0] = path_to_slash(argv0);
				newargv[1] = NULL;
				concat_args_and_quote((const char *const *)newargv, &cmdstr, &cmdlen, &cmdend, &cmdsize);
				*cmdend = 0;
				argv0 = gModuleName;
				execmode = directex;
			} else {
				cmdend = cmdstr + cmdlen;
				execmode = directex;
			}
		} else {
			unsigned long shflags = 0L;
			/* if the file extension is in pathext, use the same console
			   and wait for child. StrStrI() is from shlwapi */
			if (StrStrI(exts, extension))
				shflags = SEE_MASK_NO_CONSOLE | SEE_MASK_NOCLOSEPROCESS;
			if (try_shell_ex(argv0, args, shflags, &cmdstr, &cmdsize))
				return (0);
			/* ShellExecute failed, the file has an unknown extension, but it
			    may be a shell script with a shebang */
			if (process_shebang(argv0, (const char *const *)&cmdstr, &cmdlen, &cmdend, &cmdsize) > 0) {
				cmdend = cmdstr + cmdlen;
				execmode = directex;
			} else {
				/* the file extension is NOT known and the file has NO shebang:
				   returns EPERM, see NOTES */
				errno = EPERM;
				return (-1);
			}
		}
	} else if (execmode == directex) {
		cmdlen = copy_quote_and_fix_slashes(prog, cmdstr);
		cmdend = cmdstr + cmdlen;
	}
	if (execmode == none) {
		/* error: prog not found even after trying PATHEXT extensions */
		errno = ENOENT;
		return (-1);
	}

	concat_args_and_quote(args, &cmdstr, &cmdlen, &cmdend, &cmdsize);
	if (*cmdstr == ' ') {
		/* if we left a ' ' for the quote and there is no quote */
		cmdstr++;
		cmdlen--;
	}
	*cmdend = 0;

	init_startupinfo(&si);
	dwCreationflags = GetPriorityClass(GetCurrentProcess());
	priority = GetThreadPriority(GetCurrentThread());

#if defined(W32DEBUG)
	/* DebugView output is very difficult to read with overlong lines */
	if (cmdlen < 128)
		dbgprintf(PR_EXEC, "%s(): CreateProcess(%s, ..) cmdstr=[%s]\n", __FUNCTION__, argv0, cmdstr);
	else {
		char shortbuf[128+4];
		memcpy(shortbuf, cmdstr, 128);
		memcpy(shortbuf + 128, "...", 4);
		dbgprintf(PR_EXEC, "nt_execve(): CreateProcess(%s, ..) cmdstr=[%s]\n", argv0, shortbuf);
	}
#endif
	if (!CreateProcess(argv0, cmdstr, NULL, NULL,
			   TRUE, // need this for redirecting std handles
			   dwCreationflags | CREATE_SUSPENDED,
			   NULL, NULL, &si, &pi)) {
                exitcode = GetLastError();
		if (exitcode == ERROR_BAD_EXE_FORMAT) {
			dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error BAD_EXE_FORMAT in %s\n", argv0, __FUNCTION__);
			errno  = ENOEXEC;
		} else if (exitcode == ERROR_INVALID_PARAMETER) {
			dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error INVALID_PARAMETER in %s, cmdstr len=%u\n", argv0, __FUNCTION__, strlen(cmdstr));
			/* exceeded command line */
			/* return NOT found, ENAMETOOLONG is correct but not understood by
			   the shell that will retry with another path ... */
			errno = ENOENT;
		} else {
			dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error %ld in %s\n", argv0, exitcode, __FUNCTION__);
			errno = ENOENT;
		}
		goto fail_return;
	} else {
		exitcode = 0;
		if (!SetThreadPriority(pi.hThread, priority))
			dbgprintf(PR_ERROR, "!!! SetThreadPriority(0x%p) failed, error %ld\n", pi.hThread, GetLastError());
		ResumeThread(pi.hThread);
		if (!is_gui(argv0)) {
			if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
				dbgprintf(PR_ERROR, "!!! error %ld waiting for process %ld\n", GetLastError(), pi.dwProcessId);
			if (!GetExitCodeProcess(pi.hProcess, &exitcode))
				dbgprintf(PR_ERROR, "!!! GetExitCodeProcess(0x%p, ..) error %ld in %s\n", pi.hProcess, GetLastError(), __FUNCTION__);
		}
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
		close_si_handles();
		/* @@@@ should wait for the clipboard ?
		if (is_dev_clipboard_active) {
			CloseHandle((HANDLE)_get_osfhandle(0));
			CloseHandle((HANDLE)_get_osfhandle(1));
			CloseHandle((HANDLE)_get_osfhandle(2));
			...
			WaitForSingleObject(ghdevclipthread,60*1000);
			}
		*/
		dbgprintf(PR_ALL, "--- %s(): Exec'd process %ld terminated with exitcode %ld\n", __FUNCTION__, pi.dwProcessId, exitcode);
		exec_exit((int)exitcode);
	}

fail_return:
        heap_free(cmdstr);
	close_si_handles();
	exec_exit(-1);
	return (-1);
}
Esempio n. 27
0
static int try_shell_ex(char *argv0, const char *const *argv, unsigned long shellexflags, char **cmdstr, unsigned int *cmdsize)
{
	char *cmdend;
	size_t cmdlen;
	SHELLEXECUTEINFO shinfo;
	BOOL nocmd = 0;

	path_to_backslash(argv0);

	/* @@@@ is this code really needed ? when ? */
	if ((!*argv) && (argv0[0] == '\\') && (argv0[1] == '\\')) {
		shellexflags |= SEE_MASK_CONNECTNETDRV;
		nocmd = 1;
		goto noargs;
	}

	cmdend = *cmdstr;
	cmdlen = 0;
	concat_args_and_quote(argv, cmdstr, &cmdlen, &cmdend, cmdsize);
	*cmdend = '\0';

noargs:
	dbgprintf(PR_EXEC, "ShellExecute(%s, ..) with cmdstr [%s]\n", argv0, *cmdstr);
	memset(&shinfo, 0, sizeof(shinfo));
	shinfo.cbSize = sizeof(shinfo);
	shinfo.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_FLAG_DDEWAIT | shellexflags;
	shinfo.hwnd = NULL;
	shinfo.lpVerb = NULL;
	shinfo.lpFile = argv0;
	shinfo.lpParameters = nocmd ? NULL : *cmdstr;
	shinfo.lpDirectory = 0;
	shinfo.nShow = SW_SHOWDEFAULT;

	if (ShellExecuteEx(&shinfo)) {
		DWORD retval = 255;
		dbgprintf(PR_EXEC, "ShellExecute() created process handle 0x%p\n", shinfo.hProcess);
		/* may happen if "executing" a file associated to a running program, i.e.
		   "execute" a .html file with an already opened browser window */
		if (shinfo.hProcess != (HANDLE)0) {
			if (shellexflags & SEE_MASK_NOCLOSEPROCESS) {
				if ((intptr_t)(shinfo.hInstApp) > 32) {
					if (WaitForSingleObject(shinfo.hProcess, INFINITE) == WAIT_OBJECT_0) {
						/* try to get the return value */
						GetExitCodeProcess(shinfo.hProcess, &retval);
					} else {
						dbgprintf(PR_ERROR, "!!! ShellExecute() [%s] WaitForSingleObject() error %ld\n", argv0, GetLastError());
					}
				} else {
					dbgprintf(PR_ERROR, "!!! ShellExecute() [%s] error %p\n", argv0, shinfo.hInstApp);
				}
			}
			/* try to close, it may fail but .. what else could we do */
			CloseHandle(shinfo.hProcess);
		}
		dbgprintf(PR_ALL, "--- %s(): ShellExecute() OK, exiting with code %ld\n", __FUNCTION__, retval);
		exec_exit((int)retval);
	} else {
		dbgprintf(PR_EXEC, "ShellExecute() failed\n");
	}
       	return (0);
}
Esempio n. 28
0
static void * _workqueue_job_scheduler(void *data)
{
  	struct workqueue_thread *thread = (struct workqueue_thread *) data;
	struct workqueue_ctx *ctx;
	struct TIME_STRUCT_TYPE wait_time;
	int ret;
	long long wait_ms = 1000;

	DEBUG_MSG("starting data=%p\n", data);
	assert(thread);
	ctx = thread->ctx;
	DEBUG_MSG("thread %d starting\n",thread->thread_num);

	if (ctx->ops && ctx->ops->worker_constructor) {
		DEBUG_MSG("thread %d calling constructor\n",thread->thread_num);
		ctx->ops->worker_constructor(ctx->ops->data);
	}
	LOCK_MUTEX(&thread->mutex);

	while (thread->keep_running) {

		DEBUG_MSG("thread %d looking for work \n",thread->thread_num);
		thread->job = _workqueue_get_job(thread, &wait_time, &wait_ms);

		/* is there a job that needs to be run now */
		if (thread->job) {
			/* there is work to do */
			DEBUG_MSG("launching job %d\n",thread->job->job_id);

			/* keep job_mutex locked while running to test if running */
			LOCK_MUTEX(&thread->job_mutex);
			/* mantain unlocked while running so we can check state.
			  in workqueue_job_running() */
			UNLOCK_MUTEX(&thread->mutex);

			/* launch worker job */
			thread->job->func(thread->job->data);

			DEBUG_MSG("job %d finished\n", thread->job->job_id);
			/* done with job free it */
			free(thread->job);
			thread->job = NULL;

			UNLOCK_MUTEX(&thread->job_mutex);
			LOCK_MUTEX(&thread->mutex);

		} else {
			/* wait until we are signaled that there is new work, or until the wait time is up */


			/* we should idle */

			UNLOCK_MUTEX(&thread->mutex);

#ifdef WINDOWS
			DEBUG_MSG("thread %d going idle\n",thread->thread_num);
			ret = WaitForSingleObject(ctx->work_ready_cond, (DWORD) wait_ms);

#else
			DEBUG_MSG("thread %d going idle.  %d sec; %ld nsec\n",
					thread->thread_num, (int) wait_time.tv_sec, wait_time.tv_nsec);
			// note this wait may be a long time, if the system time changes
			LOCK_MUTEX(&ctx->cond_mutex);
			ret = pthread_cond_timedwait(&ctx->work_ready_cond, &ctx->cond_mutex, &wait_time);
			UNLOCK_MUTEX(&ctx->cond_mutex);
#endif

			LOCK_MUTEX(&thread->mutex);

			if (!thread->keep_running) {
			  	DEBUG_MSG("thread %d stopping\n",thread->thread_num);
				break;
			}
#ifdef WINDOWS
			/* check windows error cases*/
			if( !ret && WAIT_TIMEOUT == GetLastError()) {
			  	DEBUG_MSG("thread %d idle timeout\n",thread->thread_num);
			  	continue; /* wait again */
			} if (!ret)  {
				// other error
			}
#else

			if (ret == ETIMEDOUT) {
			  	DEBUG_MSG("thread %d idle timeout lock\n",thread->thread_num);
			  	continue; /* wait again */
			} else if (ret == EINVAL) {
				ERROR_MSG("thread %d pthread_cond_timedwait EINVAL\n", thread->thread_num);
				usleep(wait_ms); // wait 1000th of time wait
			} else if (ret) {
				ERROR_MSG("thread %d pthread_cond_timedwait ret =%d\n", thread->thread_num, ret);
			}

#endif
		}
	}

	UNLOCK_MUTEX(&thread->mutex);

	if (ctx->ops && ctx->ops->worker_destructor) {
		DEBUG_MSG("thread %d calling destructor\n",thread->thread_num);
		ctx->ops->worker_destructor(ctx->ops->data);
	}
	return NULL;
}
Esempio n. 29
-1
int main( int argc, char *argv[] )
{
    extern HANDLE CDECL __wine_make_process_system(void);
    static const WCHAR RunW[] = {'R','u','n',0};
    static const WCHAR RunOnceW[] = {'R','u','n','O','n','c','e',0};
    static const WCHAR RunServicesW[] = {'R','u','n','S','e','r','v','i','c','e','s',0};
    static const WCHAR RunServicesOnceW[] = {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0};
    static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};

    /* First, set the current directory to SystemRoot */
    int optc;
    BOOL end_session, force, init, kill, restart, shutdown, update;
    HANDLE event;
    SECURITY_ATTRIBUTES sa;
    BOOL is_wow64;

    end_session = force = init = kill = restart = shutdown = update = FALSE;
    GetWindowsDirectoryW( windowsdir, MAX_PATH );
    if( !SetCurrentDirectoryW( windowsdir ) )
        WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );

    if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
    {
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
        WCHAR filename[MAX_PATH];
        void *redir;
        DWORD exit_code;

        memset( &si, 0, sizeof(si) );
        si.cb = sizeof(si);
        GetModuleFileNameW( 0, filename, MAX_PATH );

        Wow64DisableWow64FsRedirection( &redir );
        if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
        {
            WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
            WaitForSingleObject( pi.hProcess, INFINITE );
            GetExitCodeProcess( pi.hProcess, &exit_code );
            ExitProcess( exit_code );
        }
        else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
        Wow64RevertWow64FsRedirection( redir );
    }

    while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
    {
        switch(optc)
        {
        case 'e': end_session = TRUE; break;
        case 'f': force = TRUE; break;
        case 'i': init = TRUE; break;
        case 'k': kill = TRUE; break;
        case 'r': restart = TRUE; break;
        case 's': shutdown = TRUE; break;
        case 'u': update = TRUE; break;
        case 'h': usage(); return 0;
        case '?': usage(); return 1;
        }
    }

    if (end_session)
    {
        if (kill)
        {
            if (!shutdown_all_desktops( force )) return 1;
        }
        else if (!shutdown_close_windows( force )) return 1;
    }

    if (kill) kill_processes( shutdown );

    if (shutdown) return 0;

    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;  /* so that services.exe inherits it */
    event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );

    ResetEvent( event );  /* in case this is a restart */

    create_hardware_registry_keys();
    create_dynamic_registry_keys();
    create_environment_registry_keys();
    wininit();
    pendingRename();

    ProcessWindowsFileProtection();
    ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesOnceW, TRUE, FALSE );

    if (init || (kill && !restart))
    {
        ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesW, FALSE, FALSE );
        start_services_process();
    }
    if (init || update) update_wineprefix( update );

    create_volatile_environment_registry_key();

    ProcessRunKeys( HKEY_LOCAL_MACHINE, RunOnceW, TRUE, TRUE );

    if (!init && !restart)
    {
        ProcessRunKeys( HKEY_LOCAL_MACHINE, RunW, FALSE, FALSE );
        ProcessRunKeys( HKEY_CURRENT_USER, RunW, FALSE, FALSE );
        ProcessStartupItems();
    }

    WINE_TRACE("Operation done\n");

    SetEvent( event );
    return 0;
}
Esempio n. 30
-31
bool execute(const char* command, std::string currentDir, DWORD& retCode, std::string& output) {
	HANDLE outWR;

	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	TCHAR lpTempPathBuffer[BUFSIZE];
	TCHAR szTempFileName[MAX_PATH];
	DWORD ret = GetTempPath(BUFSIZE, lpTempPathBuffer);
	if (ret > BUFSIZE || ret == 0) {
		MessageBox(	NULL, "Error GetTempPath", "Error", MB_OK );
		return false;
	}

	ret = GetTempFileName(lpTempPathBuffer, "svn", 0, szTempFileName);
	if (ret == 0) {
		MessageBox(	NULL, "Error GetTempFileName", "Error", MB_OK );
		return false;
	}

	outWR = CreateFile(szTempFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (outWR == INVALID_HANDLE_VALUE) {
		MessageBox(	NULL, "Error create file", "Error", MB_OK );
		return false;
	}

	PROCESS_INFORMATION processInfomation;
	STARTUPINFO startupInfo;
	memset(&processInfomation, 0, sizeof(processInfomation));
	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	startupInfo.hStdError = outWR;
	startupInfo.hStdOutput = outWR;
	startupInfo.dwFlags |= STARTF_USESTDHANDLES;
	startupInfo.wShowWindow = SW_HIDE;

	BOOL result = CreateProcess(
		NULL,
		(char*) command,
		NULL,
		NULL,
		TRUE,
		0,
		NULL,
		currentDir.c_str(),
		&startupInfo,
		&processInfomation);

	if (!result) {
		MessageBox(	NULL, "Can't CreateProcess", "Error", MB_OK );
		CloseHandle(outWR);
		return false;
	} else {
		WaitForSingleObject(processInfomation.hProcess, INFINITE);
		GetExitCodeProcess(processInfomation.hProcess, &retCode);
		CloseHandle(processInfomation.hProcess);
		CloseHandle(processInfomation.hThread);

		// read from stdout
		if (!CloseHandle(outWR)) {
			MessageBox(	NULL, "Can't CloseHandle", "Error", MB_OK );
			return false;
		}

		outWR = CreateFile(szTempFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (outWR == INVALID_HANDLE_VALUE) {
			MessageBox(	NULL, "Error open file", "Error", MB_OK );
			return false;
		}

		CHAR buf[BUFSIZE];
		DWORD dwRead;
		DWORD totalSize = 0;
		std::vector<char*> allBufs;
		std::vector<DWORD> lens;
		while (true) {
			result = ReadFile(outWR, buf, BUFSIZE, &dwRead, NULL);
			if (!result || dwRead == 0) break;
			totalSize += dwRead;
			char* content = new char[dwRead];
			memcpy(content, buf, dwRead);
			allBufs.push_back(content);
			lens.push_back(dwRead);
		}
		char* content = new char[totalSize + 1];
		char* currentPtr = content;
		for (std::size_t i = 0; i < allBufs.size(); i++) {
			memcpy(currentPtr, allBufs[i], lens[i]);
			currentPtr += lens[i];
		}
		content[totalSize] = 0;
		for (std::size_t i = 0; i < allBufs.size(); i++) {
			delete[] allBufs[i];
		}
		output.swap(std::string(content));
		delete[] content;

		CloseHandle(outWR);
		return true;
	}
}