extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/) { lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED); _ASSERTE(SUCCEEDED(hRes)); _Module.Init(ObjectMap, hInstance, &LIBID_ATFDATAPROVIDERLib); _Module.dwThreadID = GetCurrentThreadId(); TCHAR szTokens[] = _T("-/"); int nRet = 0; BOOL bRun = TRUE; LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens); while (lpszToken != NULL) { if (lstrcmpi(lpszToken, _T("UnregServer"))==0) { _Module.UpdateRegistryFromResource(IDR_ATFDataProvider, FALSE); nRet = _Module.UnregisterServer(TRUE); bRun = FALSE; break; } if (lstrcmpi(lpszToken, _T("RegServer"))==0) { _Module.UpdateRegistryFromResource(IDR_ATFDataProvider, TRUE); nRet = _Module.RegisterServer(TRUE); bRun = FALSE; break; } lpszToken = FindOneOf(lpszToken, szTokens); } if (bRun) { SetMiniDumpDefaultCrashHandler(); BEGIN_TRACE() ATLVERIFY(SUCCEEDED(_Module.LoadExchangeCodes())); _Module.StartMonitor(); #if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED) hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED); _ASSERTE(SUCCEEDED(hRes)); hRes = CoResumeClassObjects(); #else hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE); #endif _ASSERTE(SUCCEEDED(hRes)); MSG msg; while (GetMessage(&msg, 0, 0, 0)) DispatchMessage(&msg); _Module.RevokeClassObjects(); Sleep(dwPause); //wait for any threads to finish END_TRACE() } _Module.Term(); CoUninitialize(); return nRet; }
void CModule::UpdateLanguage() { char new_language[MAX_LANGUAGE_LINE_LENGTH]; DWORD res = GetEnvironmentVariable("FARLANG",new_language,sizeof(new_language)); if (!(res && res<sizeof(new_language))) lstrcpy(new_language,"English"); if (!lstrcmp(Language,new_language)) return; lstrcpy(Language,new_language); ClearMsgs(); char path[NM]; lstrcpy(path,ModulePath); lstrcpy(FSF.PointToName(path),"*.lng"); char EnglishFile[NM], LastFile[NM], LastFileLanguage[MAX_LANGUAGE_LINE_LENGTH]; *EnglishFile = 0; *LastFile = 0; WIN32_FIND_DATA fd; HANDLE lfh = INVALID_HANDLE_VALUE; HANDLE fh = FindFirstFile(path,&fd); if (fh!=INVALID_HANDLE_VALUE) { do { if (fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) continue; lfh = CreateFile(fd.cFileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,NULL); if (lfh==INVALID_HANDLE_VALUE) continue; char buf[MAX_LANGUAGE_LINE_LENGTH]; if (!ReadLine(lfh,buf,sizeof(buf))) { CloseHandle(lfh); lfh=INVALID_HANDLE_VALUE; continue; } char *ptr=buf; int res=0; for (int i=0; i<3; i++) { while (*ptr==0x20 || *ptr=='\t') ptr++; switch (i) { case 0: res = lstrlen(ptr)>10; //.Language= res = res && !FSF.LStrnicmp(ptr,".Language",9); ptr += 9; break; case 1: res = lstrlen(ptr)>2; //= res = res && *ptr=='='; ptr++; break; case 2: { char *ptr_s = ptr; while (*ptr && *ptr!=0x20 && *ptr!='\t' && *ptr!=',') { LastFileLanguage[ptr-ptr_s] = *ptr; ptr++; } LastFileLanguage[ptr-ptr_s] = 0; break; } } if (!res) break; } if (res && *LastFileLanguage) { if (!lstrcmpi(LastFileLanguage,Language)) break; if (!lstrcmpi(LastFileLanguage,"English")) lstrcpy(EnglishFile,fd.cFileName); else lstrcpy(LastFile,fd.cFileName); } CloseHandle(lfh); lfh=INVALID_HANDLE_VALUE; } while (FindNextFile(fh,&fd)); FindClose(fh); if (lfh==INVALID_HANDLE_VALUE && (*EnglishFile || *LastFile)) { lfh = CreateFile(*EnglishFile?EnglishFile:LastFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,NULL); } if (fh!=INVALID_HANDLE_VALUE) { char buf[MAX_LANGUAGE_LINE_LENGTH]; while (ReadLine(lfh,buf,sizeof(buf))) { char *ptr = buf; while (*ptr==0x20 || *ptr=='\t') ptr++; if (*ptr!='"') continue; ptr++; char *ptr_e = buf+lstrlen(buf)-1; while (ptr_e>ptr && (*ptr_e==0x20 || *ptr_e=='\t')) ptr_e--; //if (ptr_e==ptr) //continue; *ptr_e = 0; if (!AddMsg(ptr)) break; } CloseHandle(lfh); lfh=OpenLog("G:\\Program Files\\Far\\pm\\PluginManager_lang"); for (int i=0; i<MessagesCount; i++) { WriteLog(lfh,Messages[i]); WriteLog(lfh,"\n"); } CloseLog(&lfh); } } }
void __declspec(dllexport) CreateControl(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra) { char *className; char *text; HWND hwItem; int x, y, width, height; DWORD style, exStyle; size_t id; // get info from stack className = (char *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, g_stringsize * 2); text = (char *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, NSWINDOWS_MAX_STRLEN * 2); // text = &className[g_stringsize]; if (!className) { pushstring("error"); return; } if (popstringn(className, 0)) { pushstring("error"); HeapFree(GetProcessHeap(), 0, className); return; } style = (DWORD) popint_or(); exStyle = (DWORD) popint_or(); PopPlacement(&x, &y, &width, &height); if (popstringn(text, 0)) { pushstring("error"); HeapFree(GetProcessHeap(), 0, className); return; } // create item descriptor id = g_window.controlCount; g_window.controlCount++; g_window.controls = (struct nsControl*) HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, g_window.controls, g_window.controlCount * sizeof(struct nsControl)); if (!lstrcmpi(className, "BUTTON")) g_window.controls[id].type = NSCTL_BUTTON; else if (!lstrcmpi(className, "EDIT")) g_window.controls[id].type = NSCTL_EDIT; else if (!lstrcmpi(className, "COMBOBOX")) g_window.controls[id].type = NSCTL_COMBOBOX; else if (!lstrcmpi(className, "LISTBOX")) g_window.controls[id].type = NSCTL_LISTBOX; else if (!lstrcmpi(className, "RichEdit")) g_window.controls[id].type = NSCTL_RICHEDIT; else if (!lstrcmpi(className, "RICHEDIT_CLASS")) g_window.controls[id].type = NSCTL_RICHEDIT2; else if (!lstrcmpi(className, "STATIC")) g_window.controls[id].type = NSCTL_STATIC; else if (!lstrcmpi(className, "LINK")) g_window.controls[id].type = NSCTL_LINK; else g_window.controls[id].type = NSCTL_UNKNOWN; // apply rtl to style ConvertStyleToRTL(g_window.controls[id].type, &style, &exStyle); // create item's window hwItem = CreateWindowEx( exStyle, lstrcmpi(className, "LINK") ? className : "BUTTON", text, style, x, y, width, height, g_window.hwWindow, (HMENU) (1200 +id), g_hInstance, NULL); g_window.controls[id].window = hwItem; // remember id SetProp(hwItem, NSCONTROL_ID_PROP, (HANDLE) (id + 1)); // set font SendMessage(hwItem, WM_SETFONT, SendMessage(hwndParent, WM_GETFONT, 0, 0), TRUE); // set the WndProc for the link control if(g_window.controls[id].type == NSCTL_LINK) g_window.controls[id].oldWndProc = (WNDPROC) SetWindowLong(hwItem, GWL_WNDPROC, (long) LinkWndProc); // push back result pushint((int) hwItem); // done HeapFree(GetProcessHeap(), 0, className); }
bool ConEmuUpdateSettings::UpdatesAllowed(wchar_t (&szReason)[128]) { szReason[0] = 0; if (!*UpdateVerLocation()) { wcscpy_c(szReason, L"Update.VerLocation is empty"); return false; // Не указано расположение обновления } if (isUpdateUseBuilds != 1 && isUpdateUseBuilds != 2 && isUpdateUseBuilds != 3) { wcscpy_c(szReason, L"Update.UseBuilds is not specified"); return false; // Не указано, какие сборки можно загружать } switch (UpdateDownloadSetup()) { case 1: if (!*UpdateExeCmdLine()) { wcscpy_c(szReason, L"Update.ExeCmdLine is not specified"); return false; // Не указана строка запуска инсталлятора } break; case 2: { LPCWSTR pszCmd = UpdateArcCmdLine(); if (!*pszCmd) { wcscpy_c(szReason, L"Update.ArcCmdLine is not specified"); return false; // Не указана строка запуска архиватора } CmdArg szExe; NextArg(&pszCmd, szExe); pszCmd = PointToName(szExe); if (!pszCmd || !*pszCmd) { wcscpy_c(szReason, L"Update.ArcCmdLine is invalid"); return false; // Ошибка в строке запуска архиватора } if ((lstrcmpi(pszCmd, L"WinRar.exe") == 0) || (lstrcmpi(pszCmd, L"Rar.exe") == 0) || (lstrcmpi(pszCmd, L"UnRar.exe") == 0)) { // Issue 537: AutoUpdate to the version 120509x64 unpacks to the wrong folder HKEY hk; DWORD nSubFolder = 0; if (0 == RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\WinRAR\\Extraction\\Profile", 0, KEY_READ, &hk)) { DWORD nSize = sizeof(nSubFolder); if (0 != RegQueryValueEx(hk, L"UnpToSubfolders", NULL, NULL, (LPBYTE)&nSubFolder, &nSize)) nSubFolder = 0; RegCloseKey(hk); } if (nSubFolder) { wcscpy_c(szReason, L"Update.ArcCmdLine: Unwanted option\n[HKCU\\Software\\WinRAR\\Extraction\\Profile]\n\"UnpToSubfolders\"=1"); return false; // Ошибка в настройке архиватора } } } break; default: wcscpy_c(szReason, L"Update.DownloadSetup is not specified"); return false; // Не указан тип загружаемого пакета (exe/7z) } // Можно return true; }
BOOL CMyApp::InitInstance() { if (!DComOk()) { AfxMessageBox(_T("DCOM OLE Not supported"),MB_SYSTEMMODAL+MB_OK); return FALSE; } // Initialize OLE libraries if (!AfxOleInit2()) { AfxMessageBox(_T("OLE Initialization Failed!"),MB_SYSTEMMODAL+MB_OK); return FALSE; } // Initialize the ATL Module _Module.Init(ObjectMap,m_hInstance); _Module.dwThreadID = GetCurrentThreadId(); #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking // to MFC statically #endif //Reg UnregSever TCHAR szTokens[] = _T("-/"); int nRet = 0; BOOL bRun = TRUE; LPCTSTR lpszToken = FindOneOf(m_lpCmdLine, szTokens); while (lpszToken != NULL) { if (lstrcmpi(lpszToken, _T("UnregServer"))==0) { _Module.UpdateRegistryFromResource(IDR_ModbusServer, FALSE); nRet = _Module.UnregisterServer(); nRet = UnRegisterTypeLib( LIBID_MODBUSSERVERLib, 1, 0, LOCALE_NEUTRAL, SYS_WIN32); bRun = FALSE; break; } if (lstrcmpi(lpszToken, _T("RegServer"))==0) { _Module.UpdateRegistryFromResource(IDR_ModbusServer, TRUE); nRet = _Module.RegisterServer(TRUE); bRun = FALSE; // Update the System Registry COleObjectFactory::UpdateRegistryAll(); // MFC Classes if(!(SUCCEEDED(nRet))){ AfxMessageBox("Register server Failed",MB_SYSTEMMODAL+MB_OK); } bRun=FALSE; break; } lpszToken = FindOneOf(lpszToken, szTokens); } // ATL Classes // Create the dialog box or other stuff here // Register OLE Class Factories // MFC ones are for multiple as specified // by the IMPLEMENT_OLECREATE() macro //COleObjectFactory::RegisterAll(); // ATL ones specifically register with REGCLS_MULTIPLEUSE if (bRun) { if(!(SUCCEEDED(_Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE)))){ AfxMessageBox("RegisterClassObjects Failed",MB_SYSTEMMODAL+MB_OK); } } VERIFY(CTcpServer::StartWinsock()); // Parse the command line to see if launched as OLE server if (RunEmbedded() || RunAutomated()) { // Application was run with /Embedding or /Automation. // Don't show the main window in this case. //Test(); return TRUE; } return FALSE; // Nothing to do, so exit. }
INT_PTR CALLBACK SelectDbDlgProc(HWND hdlg,UINT message,WPARAM wParam,LPARAM lParam) { INT_PTR bReturn; if ( DoMyControlProcessing( hdlg, message, wParam, lParam, &bReturn )) return bReturn; switch ( message ) { case WM_INITDIALOG: { TCHAR szMirandaPath[MAX_PATH]; szMirandaPath[ 0 ] = 0; { HIMAGELIST hIml; hIml=ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), (IsWinVerXPPlus() ? ILC_COLOR32 : ILC_COLOR16) | ILC_MASK, 3, 3); ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_PROFILEGREEN))); ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_PROFILEYELLOW))); ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_PROFILERED))); ImageList_AddIcon(hIml,LoadIcon(hInst,MAKEINTRESOURCE(IDI_BAD))); ListView_SetImageList(GetDlgItem(hdlg,IDC_DBLIST),hIml,LVSIL_SMALL); } ListView_SetExtendedListViewStyleEx(GetDlgItem(hdlg,IDC_DBLIST),LVS_EX_FULLROWSELECT,LVS_EX_FULLROWSELECT); { LV_COLUMN lvc; lvc.mask = LVCF_WIDTH | LVCF_FMT | LVCF_TEXT; lvc.cx = 205; lvc.fmt = LVCFMT_LEFT; lvc.pszText = TranslateT("Database"); ListView_InsertColumn( GetDlgItem(hdlg,IDC_DBLIST), 0, &lvc ); lvc.cx = 68; lvc.fmt = LVCFMT_RIGHT; lvc.pszText = TranslateT("Total size"); ListView_InsertColumn(GetDlgItem(hdlg,IDC_DBLIST), 1, &lvc ); lvc.pszText = TranslateT("Wasted"); ListView_InsertColumn(GetDlgItem(hdlg,IDC_DBLIST), 2, &lvc ); } { TCHAR *str2; GetModuleFileName(NULL,szMirandaPath,SIZEOF(szMirandaPath)); str2 = _tcsrchr(szMirandaPath,'\\'); if( str2 != NULL ) *str2=0; } { int i = 0; HKEY hKey; TCHAR szProfileDir[MAX_PATH]; DWORD cbData = SIZEOF(szMirandaPath); TCHAR szMirandaProfiles[MAX_PATH]; _tcscpy(szMirandaProfiles, szMirandaPath); _tcscat(szMirandaProfiles, _T("\\Profiles")); GetProfileDirectory(szMirandaPath,szProfileDir,SIZEOF(szProfileDir)); // search in profile dir (using ini file) if( lstrcmpi(szProfileDir,szMirandaProfiles) ) FindAdd(hdlg, szProfileDir, _T("[ini]\\")); FindAdd(hdlg, szMirandaProfiles, _T("[prf]\\")); // search in current dir (as DBTOOL) FindAdd(hdlg, szMirandaPath, _T("[ . ]\\")); // search in profile dir (using registry path + ini file) if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\miranda32.exe"),0,KEY_QUERY_VALUE,&hKey) == ERROR_SUCCESS) { if(RegQueryValueEx(hKey,_T("Path"),NULL,NULL,(PBYTE)szMirandaPath,&cbData) == ERROR_SUCCESS) { if( lstrcmp(szProfileDir,szMirandaPath) ) { GetProfileDirectory(szMirandaPath,szProfileDir,SIZEOF(szProfileDir)); FindAdd(hdlg, szProfileDir, _T("[reg]\\")); } } RegCloseKey(hKey); } // select if ( opts.filename[0] ) i = AddDatabaseToList( GetDlgItem( hdlg, IDC_DBLIST ), opts.filename, _T("") ); if ( i == -1 ) i = 0; ListView_SetItemState( GetDlgItem(hdlg,IDC_DBLIST), i, LVIS_SELECTED, LVIS_SELECTED ); } if ( opts.hFile != NULL && opts.hFile != INVALID_HANDLE_VALUE ) { CloseHandle( opts.hFile ); opts.hFile = NULL; } TranslateDialog( hdlg ); return TRUE; } case WZN_PAGECHANGING: GetDlgItemText( hdlg, IDC_FILE, opts.filename, SIZEOF(opts.filename)); break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_FILE: if(HIWORD(wParam)==EN_CHANGE) EnableWindow(GetDlgItem(GetParent(hdlg),IDOK),GetWindowTextLength(GetDlgItem(hdlg,IDC_FILE))); break; case IDC_OTHER: { OPENFILENAME ofn={0}; TCHAR str[MAX_PATH]; // _T("Miranda Databases (*.dat)\0*.DAT\0All Files (*)\0*\0"); TCHAR *filter, *tmp, *tmp1, *tmp2; tmp1 = TranslateT("Miranda Databases (*.dat)"); tmp2 = TranslateT("All Files"); filter = tmp = (TCHAR*)_alloca((_tcslen(tmp1)+_tcslen(tmp2)+11)*sizeof(TCHAR)); tmp = addstring(tmp, tmp1); tmp = addstring(tmp, _T("*.DAT")); tmp = addstring(tmp, tmp2); tmp = addstring(tmp, _T("*")); *tmp = 0; GetDlgItemText( hdlg, IDC_FILE, str, SIZEOF( str )); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hdlg; ofn.hInstance = NULL; ofn.lpstrFilter = filter; ofn.lpstrDefExt = _T("dat"); ofn.lpstrFile = str; ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.nMaxFile = SIZEOF(str); ofn.nMaxFileTitle = MAX_PATH; if ( GetOpenFileName( &ofn )) { int i; i = AddDatabaseToList( GetDlgItem(hdlg,IDC_DBLIST), str, _T("") ); if ( i == -1 ) i=0; ListView_SetItemState( GetDlgItem(hdlg,IDC_DBLIST), i, LVIS_SELECTED, LVIS_SELECTED ); } break; } case IDC_BACK: SendMessage(GetParent(hdlg),WZM_GOTOPAGE,IDD_WELCOME,(LPARAM)WelcomeDlgProc); break; case IDOK: opts.hFile = CreateFile( opts.filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if ( opts.hFile == INVALID_HANDLE_VALUE ) { opts.hFile = NULL; opts.error = GetLastError(); SendMessage( GetParent(hdlg), WZM_GOTOPAGE, IDD_OPENERROR, ( LPARAM )OpenErrorDlgProc ); } else SendMessage( GetParent(hdlg), WZM_GOTOPAGE, IDD_FILEACCESS, (LPARAM)FileAccessDlgProc ); break; } break; case WM_NOTIFY: switch(((LPNMHDR)lParam)->idFrom) { case IDC_DBLIST: switch(((LPNMLISTVIEW)lParam)->hdr.code) { case LVN_ITEMCHANGED: { LV_ITEM lvi; lvi.iItem=ListView_GetNextItem(GetDlgItem(hdlg,IDC_DBLIST),-1,LVNI_SELECTED); if(lvi.iItem==-1) break; lvi.mask=LVIF_PARAM; ListView_GetItem(GetDlgItem(hdlg,IDC_DBLIST),&lvi); SetDlgItemText(hdlg,IDC_FILE,(TCHAR*)lvi.lParam); SendMessage(hdlg,WM_COMMAND,MAKEWPARAM(IDC_FILE,EN_CHANGE),(LPARAM)GetDlgItem(hdlg,IDC_FILE)); break; } } break; } break; case WM_DESTROY: { LV_ITEM lvi; lvi.mask=LVIF_PARAM; for(lvi.iItem=ListView_GetItemCount(GetDlgItem(hdlg,IDC_DBLIST))-1;lvi.iItem>=0;lvi.iItem--) { ListView_GetItem(GetDlgItem(hdlg,IDC_DBLIST),&lvi); free((char*)lvi.lParam); } } break; } return FALSE; }
int __cdecl _tmain(int argc, TCHAR** argv) { TCHAR* lpPath; TCHAR mountPoint[MAX_PATH]; TCHAR volumeName[100]; LPTSTR lpVolumeDevicePath; HANDLE hVolume; if (argc > 1) { if (0 == lstrcmpi(_T("/trace"), argv[1]) || 0 == lstrcmpi(_T("-trace"), argv[1])) { NdasVolSetTrace(0x0000ffff, 0xffffffff, 5); --argc; ++argv; } } lpPath = (argc < 2) ? _T("C:") : argv[1]; lpVolumeDevicePath = lpPath; _tprintf(_T("Device Name: %s\n"), lpVolumeDevicePath); if (NdasIsNdasPath(lpVolumeDevicePath)) { _tprintf(_T("%s is on the NDAS device.\n"), lpVolumeDevicePath ); if (GetVolumePathName(lpVolumeDevicePath, mountPoint, RTL_NUMBER_OF(mountPoint))) { if (GetVolumeNameForVolumeMountPoint( mountPoint, volumeName, RTL_NUMBER_OF(volumeName))) { int len = lstrlen(volumeName); // _tprintf(_T("VolumeName=%s\n"), volumeName); // remove trailing backslash if (len > 0 && _T('\\') == volumeName[len-1]) { volumeName[len-1] = _T('\0'); } // replace \\?\Volume... to \\.\Volume... if (_T('\\') == volumeName[0] && _T('\\') == volumeName[1] && _T('?') == volumeName[2] && _T('\\') == volumeName[3]) { volumeName[2] = _T('.'); } // _tprintf(_T("VolumeName=%s\n"), volumeName); hVolume = CreateFile(volumeName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (INVALID_HANDLE_VALUE != hVolume) { NDAS_SCSI_LOCATION loc; if (NdasGetNdasScsiLocationForVolume(hVolume,&loc)) { _tprintf(_T("NDAS_SCSI_LOCATION=(%d,%d,%d)"), loc.SlotNo, loc.TargetID, loc.LUN); } else { _tprintf(_T("NdasGetNdasScsiLocationForVolume failed.\n")); _tprintf(_T("Error %u(%X)\n"), GetLastError(), GetLastError()); } CloseHandle(hVolume); } else { _tprintf(_T("Opening the volume %s failed.\n"), volumeName); _tprintf(_T("Error %u(%X)\n"), GetLastError(), GetLastError()); } } else { _tprintf(_T("GetVolumeNameForVolumeMountPoint %s failed.\n"), mountPoint); _tprintf(_T("Error %u(%X)\n"), GetLastError(), GetLastError()); } } else { _tprintf(_T("GetVolumePathName %s failed.\n"), lpVolumeDevicePath); _tprintf(_T("Error %u(%X)\n"), GetLastError(), GetLastError()); } } else { _tprintf(_T("Error %u(%X)\n"), GetLastError(), GetLastError()); } return 0; }
bool IsNeedCmd(BOOL bRootCmd, LPCWSTR asCmdLine, CEStr &szExe, LPCWSTR* rsArguments /*= NULL*/, BOOL* rpbNeedCutStartEndQuot /*= NULL*/, BOOL* rpbRootIsCmdExe /*= NULL*/, BOOL* rpbAlwaysConfirmExit /*= NULL*/, BOOL* rpbAutoDisableConfirmExit /*= NULL*/) { bool rbNeedCutStartEndQuot = false; bool rbRootIsCmdExe = true; bool rbAlwaysConfirmExit = false; bool rbAutoDisableConfirmExit = false; wchar_t *pwszEndSpace; if (rsArguments) *rsArguments = NULL; bool lbRc = false; int iRc = 0; BOOL lbFirstWasGot = FALSE; LPCWSTR pwszCopy; int nLastChar; #ifdef _DEBUG CEStr szDbgFirst; #endif if (!asCmdLine || !*asCmdLine) { _ASSERTE(asCmdLine && *asCmdLine); goto wrap; } #ifdef _DEBUG // Это минимальные проверки, собственно к коду - не относятся bool bIsBatch = false; { LPCWSTR psz = asCmdLine; NextArg(&psz, szDbgFirst); psz = PointToExt(szDbgFirst); if (lstrcmpi(psz, L".cmd")==0 || lstrcmpi(psz, L".bat")==0) bIsBatch = true; } #endif if (!szExe.GetBuffer(MAX_PATH)) { _ASSERTE(FALSE && "Failed to allocate MAX_PATH"); lbRc = true; goto wrap; } szExe.Empty(); if (!asCmdLine || *asCmdLine == 0) { _ASSERTE(asCmdLine && *asCmdLine); lbRc = true; goto wrap; } pwszCopy = asCmdLine; // cmd /c ""c:\program files\arc\7z.exe" -?" // да еще и внутри могут быть двойными... // cmd /c "dir c:\" nLastChar = lstrlenW(pwszCopy) - 1; if (pwszCopy[0] == L'"' && pwszCopy[nLastChar] == L'"') { //if (pwszCopy[1] == L'"' && pwszCopy[2]) //{ // pwszCopy ++; // Отбросить первую кавычку в командах типа: ""c:\program files\arc\7z.exe" -?" // if (rbNeedCutStartEndQuot) *rbNeedCutStartEndQuot = TRUE; //} //else // глючила на ""F:\VCProject\FarPlugin\#FAR180\far.exe -new_console"" //if (wcschr(pwszCopy+1, L'"') == (pwszCopy+nLastChar)) { // LPCWSTR pwszTemp = pwszCopy; // // Получим первую команду (исполняемый файл?) // if ((iRc = NextArg(&pwszTemp, szArg)) != 0) { // //Parsing command line failed // lbRc = true; goto wrap; // } // pwszCopy ++; // Отбросить первую кавычку в командах типа: "c:\arc\7z.exe -?" // lbFirstWasGot = TRUE; // if (rbNeedCutStartEndQuot) *rbNeedCutStartEndQuot = TRUE; //} else { // Will be dequoted in 'NextArg' function. Examples // "C:\GCC\msys\bin\make.EXE -f "makefile" COMMON="../../../plugins/common"" // ""F:\VCProject\FarPlugin\#FAR180\far.exe -new_console"" // ""cmd"" // cmd /c ""c:\program files\arc\7z.exe" -?" // да еще и внутри могут быть двойными... // cmd /c "dir c:\" LPCWSTR pwszTemp = pwszCopy; // Получим первую команду (исполняемый файл?) if ((iRc = NextArg(&pwszTemp, szExe)) != 0) { //Parsing command line failed #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif lbRc = true; goto wrap; } if (lstrcmpiW(szExe, L"start") == 0) { // Команду start обрабатывает только процессор #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif lbRc = true; goto wrap; } LPCWSTR pwszQ = pwszCopy + 1 + lstrlen(szExe); wchar_t* pszExpand = NULL; if (*pwszQ != L'"' && IsExecutable(szExe, &pszExpand)) { pwszCopy ++; // отбрасываем lbFirstWasGot = TRUE; if (pszExpand) { szExe.Set(pszExpand); SafeFree(pszExpand); if (rsArguments) *rsArguments = pwszQ; } rbNeedCutStartEndQuot = true; } } } // Получим первую команду (исполняемый файл?) if (!lbFirstWasGot) { szExe.Empty(); // `start` command must be processed by processor itself if ((lstrcmpni(pwszCopy, L"start", 5) == 0) && (!pwszCopy[5] || isSpace(pwszCopy[5]))) { #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif lbRc = true; goto wrap; } // 17.10.2010 - support executable file path without parameters, but with spaces in its path // 22.11.2015 - or some weirdness, like `C:\Program Files\CB/cb_console_runner.exe "C:\sources\app.exe"` LPCWSTR pchEnd = wcschr(pwszCopy, L' '); if (!pchEnd) pchEnd = pwszCopy + lstrlenW(pwszCopy); CEStr szTemp; DWORD nTempSize; while (pchEnd) { szTemp.Set(pwszCopy, (pchEnd - pwszCopy)); _ASSERTE(szTemp[(pchEnd - pwszCopy)] == 0); // If this is a full path without environment variables if (((IsFilePath(szTemp, true) && !wcschr(szTemp, L'%')) // or file/dir may be found via env.var. substitution or searching in %PATH% || FileExistsSearch((LPCWSTR)szTemp, szTemp)) // Than check if it is a FILE (not a directory) && FileExists(szTemp, &nTempSize) && nTempSize) { // OK, it an our executable? if (rsArguments) *rsArguments = pchEnd; szExe.Set(szTemp); break; } _ASSERTE(*pchEnd == 0 || *pchEnd == L' '); if (!*pchEnd) break; // Find next space after nonspace while (*(pchEnd) == L' ') pchEnd++; // If quoted string starts from here - it's supposed to be an argument if (*pchEnd == L'"') { // And we must not get here, because the executable must be already processed above // _ASSERTE(*pchEnd != L'"'); break; } pchEnd = wcschr(pchEnd, L' '); if (!pchEnd) pchEnd = pwszCopy + lstrlenW(pwszCopy); } if (szExe[0] == 0) { if ((iRc = NextArg(&pwszCopy, szExe)) != 0) { //Parsing command line failed #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif lbRc = true; goto wrap; } _ASSERTE(lstrcmpiW(szExe, L"start") != 0); // Обработка переменных окружения и поиск в PATH if (FileExistsSearch((LPCWSTR)szExe, szExe)) { if (rsArguments) *rsArguments = pwszCopy; } } } if (!*szExe) { _ASSERTE(szExe[0] != 0); } else { // Если юзеру нужен редирект - то он должен явно указать ком.процессор // Иначе нереально (или достаточно сложно) определить, является ли символ // редиректом, или это просто один из аргументов команды... // "Левые" символы в имени файла (а вот в "первом аргументе" все однозначно) if (wcspbrk(szExe, L"?*<>|")) { rbRootIsCmdExe = TRUE; // запуск через "процессор" lbRc = true; goto wrap; // добавить "cmd.exe" } // если "путь" не указан if (wcschr(szExe, L'\\') == NULL) { bool bHasExt = (wcschr(szExe, L'.') != NULL); // Проверим, может это команда процессора (типа "DIR")? if (!bHasExt) { bool bIsCommand = false; wchar_t* pszUppr = lstrdup(szExe); if (pszUppr) { // избежать линковки на user32.dll //CharUpperBuff(pszUppr, lstrlen(pszUppr)); for (wchar_t* p = pszUppr; *p; p++) { if (*p >= L'a' && *p <= 'z') *p -= 0x20; } const wchar_t* pszFind = gsInternalCommands; while (*pszFind) { if (lstrcmp(pszUppr, pszFind) == 0) { bIsCommand = true; break; } pszFind += lstrlen(pszFind)+1; } free(pszUppr); } if (bIsCommand) { #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif rbRootIsCmdExe = TRUE; // запуск через "процессор" lbRc = true; goto wrap; // добавить "cmd.exe" } } // Try to find executable in %PATH% { #ifndef CONEMU_MINIMAL MWow64Disable wow; wow.Disable(); // Disable Wow64 file redirector #endif apiSearchPath(NULL, szExe, bHasExt ? NULL : L".exe", szExe); } } // end: if (wcschr(szExe, L'\\') == NULL) } // Если szExe не содержит путь к файлу - запускаем через cmd // "start "" C:\Utils\Files\Hiew32\hiew32.exe C:\00\Far.exe" if (!IsFilePath(szExe)) { #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif rbRootIsCmdExe = TRUE; // запуск через "процессор" lbRc = true; goto wrap; // добавить "cmd.exe" } //pwszCopy = wcsrchr(szArg, L'\\'); if (!pwszCopy) pwszCopy = szArg; else pwszCopy ++; pwszCopy = PointToName(szExe); //2009-08-27 pwszEndSpace = szExe.ms_Val + lstrlenW(szExe) - 1; while ((*pwszEndSpace == L' ') && (pwszEndSpace > szExe)) { *(pwszEndSpace--) = 0; } #ifndef __GNUC__ #pragma warning( push ) #pragma warning(disable : 6400) #endif if (lstrcmpiW(pwszCopy, L"cmd")==0 || lstrcmpiW(pwszCopy, L"cmd.exe")==0 || lstrcmpiW(pwszCopy, L"tcc")==0 || lstrcmpiW(pwszCopy, L"tcc.exe")==0) { rbRootIsCmdExe = TRUE; // уже должен быть выставлен, но проверим rbAlwaysConfirmExit = TRUE; rbAutoDisableConfirmExit = FALSE; _ASSERTE(!bIsBatch); lbRc = false; goto wrap; // уже указан командный процессор, cmd.exe в начало добавлять не нужно } // Issue 1211: Decide not to do weird heuristic. // If user REALLY needs redirection (root command, huh?) // - he must call "cmd /c ..." directly // Если есть одна из команд перенаправления, или слияния - нужен CMD.EXE if (!bRootCmd) { if (wcschr(asCmdLine, L'&') || wcschr(asCmdLine, L'>') || wcschr(asCmdLine, L'<') || wcschr(asCmdLine, L'|') || wcschr(asCmdLine, L'^') // или экранирования ) { #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif lbRc = true; goto wrap; } } //if (lstrcmpiW(pwszCopy, L"far")==0 || lstrcmpiW(pwszCopy, L"far.exe")==0) if (IsFarExe(pwszCopy)) { bool bFound = (wcschr(pwszCopy, L'.') != NULL); // Если указали при запуске просто "far" - это может быть батник, расположенный в %PATH% if (!bFound) { CEStr szSearch; if (apiSearchPath(NULL, pwszCopy, L".exe", szSearch)) { if (lstrcmpi(PointToExt(szSearch), L".exe") == 0) bFound = true; } } if (bFound) { rbAutoDisableConfirmExit = TRUE; rbRootIsCmdExe = FALSE; // FAR! _ASSERTE(!bIsBatch); lbRc = false; goto wrap; // уже указан исполняемый файл, cmd.exe в начало добавлять не нужно } } if (IsExecutable(szExe)) { rbRootIsCmdExe = FALSE; // Для других программ - буфер не включаем _ASSERTE(!bIsBatch); lbRc = false; goto wrap; // Запускается конкретная консольная программа. cmd.exe не требуется } //Можно еще Доделать поиски с: SearchPath, GetFullPathName, добавив расширения .exe & .com //хотя фар сам формирует полные пути к командам, так что можно не заморачиваться #ifdef WARN_NEED_CMD _ASSERTE(FALSE); #endif rbRootIsCmdExe = TRUE; #ifndef __GNUC__ #pragma warning( pop ) #endif lbRc = true; wrap: if (rpbNeedCutStartEndQuot) *rpbNeedCutStartEndQuot = rbNeedCutStartEndQuot; if (rpbRootIsCmdExe) *rpbRootIsCmdExe = rbRootIsCmdExe; if (rpbAlwaysConfirmExit) *rpbAlwaysConfirmExit = rbAlwaysConfirmExit; if (rpbAutoDisableConfirmExit) *rpbAutoDisableConfirmExit = rbAutoDisableConfirmExit; return lbRc; }
void __declspec(dllexport) Init(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra) { HWND hwStartMenuSelect; hwParent = hwndParent; validate_filename = extra->validate_filename; EXDLL_INIT(); extra->RegisterPluginCallback(g_hInstance, PluginCallback); g_done = 0; noicon = 0; rtl = 0; autoadd = 0; text[0] = 0; progname[0] = 0; lastused[0] = 0; checkbox[0] = 0; g_hwStartMenuSelect = NULL; { hwChild = GetDlgItem(hwndParent, 1018); if (!hwChild) { pushstring(_T("error finding childwnd")); return; } popstring(buf); while (buf[0] == _T('/')) { if (!lstrcmpi(buf+1, _T("noicon"))) { noicon = 1; } else if (!lstrcmpi(buf+1, _T("rtl"))) { rtl = 1; } else if (!lstrcmpi(buf+1, _T("text"))) { popstring(text); } else if (!lstrcmpi(buf+1, _T("autoadd"))) { autoadd = 1; } else if (!lstrcmpi(buf+1, _T("lastused"))) { popstring(lastused); } else if (!lstrcmpi(buf+1, _T("checknoshortcuts"))) { popstring(checkbox); } if (popstring(buf)) { *buf = 0; } } if (*buf) { lstrcpy(progname, buf); } else { pushstring(_T("error reading parameters")); return; } hwStartMenuSelect = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_DIALOG), hwndParent, dlgProc); g_hwStartMenuSelect = hwStartMenuSelect; if (!hwStartMenuSelect) { pushstring(_T("error creating dialog")); return; } else { lpWndProcOld = (WNDPROC) SetWindowLongPtr(hwndParent, DWLP_DLGPROC, (LONG_PTR) ParentWndProc); wsprintf(buf, _T("%u"), hwStartMenuSelect); pushstring(buf); } } }
BOOL EnumProfilesForList(TCHAR *fullpath, TCHAR *profile, LPARAM lParam) { ProfileEnumData *ped = (ProfileEnumData*)lParam; HWND hwndList = GetDlgItem(ped->hwnd, IDC_PROFILELIST); TCHAR sizeBuf[64]; bool bFileExists = false, bFileLocked = true; TCHAR *p = _tcsrchr(profile, '.'); _tcscpy(sizeBuf, _T("0 KB")); if (p != NULL) *p = 0; LVITEM item = { 0 }; item.mask = LVIF_TEXT | LVIF_IMAGE; item.pszText = profile; item.iItem = 0; struct _stat statbuf; if (_tstat(fullpath, &statbuf) == 0) { if (statbuf.st_size > 1000000) { mir_sntprintf(sizeBuf, SIZEOF(sizeBuf), _T("%.3lf"), (double)statbuf.st_size / 1048576.0); _tcscpy(sizeBuf + 5, _T(" MB")); } else { mir_sntprintf(sizeBuf, SIZEOF(sizeBuf), _T("%.3lf"), (double)statbuf.st_size / 1024.0); _tcscpy(sizeBuf + 5, _T(" KB")); } bFileExists = TRUE; bFileLocked = !fileExist(fullpath); } item.iImage = bFileLocked; int iItem = SendMessage(hwndList, LVM_INSERTITEM, 0, (LPARAM)&item); if (lstrcmpi(ped->szProfile, fullpath) == 0) ListView_SetItemState(hwndList, iItem, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); item.iItem = iItem; item.iSubItem = 2; item.pszText = sizeBuf; SendMessage(hwndList, LVM_SETITEMTEXT, iItem, (LPARAM)&item); if (bFileExists) { TCHAR szPath[MAX_PATH]; _tcscpy(szPath, fullpath); LVITEM item2; item2.mask = LVIF_TEXT; item2.iItem = iItem; DATABASELINK* dblink = FindDatabasePlugin(szPath); if (dblink != NULL) { if (bFileLocked) { // file locked item2.pszText = TranslateT("<In use>"); item2.iSubItem = 1; SendMessage(hwndList, LVM_SETITEMTEXT, iItem, (LPARAM)&item2); } else { item.pszText = TranslateTS(dblink->szFullName); item.iSubItem = 1; SendMessage(hwndList, LVM_SETITEMTEXT, iItem, (LPARAM)&item); } } } return TRUE; }
// Returns 0 if succeeded, other number on error int NextArg(const wchar_t** asCmdLine, CEStr &rsArg, const wchar_t** rsArgStart/*=NULL*/) { if (!asCmdLine || !*asCmdLine) return CERR_CMDLINEEMPTY; #ifdef _DEBUG if ((rsArg.mn_TokenNo==0) // first token || ((rsArg.mn_TokenNo>0) && (rsArg.ms_LastTokenEnd==*asCmdLine) && (wcsncmp(*asCmdLine,rsArg.ms_LastTokenSave,countof(rsArg.ms_LastTokenSave)-1))==0)) { // OK, параметры корректны } else { _ASSERTE(FALSE && "rsArgs was not resetted before new cycle!"); } #endif LPCWSTR psCmdLine = SkipNonPrintable(*asCmdLine), pch = NULL; if (!*psCmdLine) return CERR_CMDLINEEMPTY; // Remote surrounding quotes, in certain cases // Example: ""7z.exe" /?" // Example: "C:\Windows\system32\cmd.exe" /C ""C:\Python27\python.EXE"" if ((rsArg.mn_TokenNo == 0) || (rsArg.mn_CmdCall == CEStr::cc_CmdCK)) { if (IsNeedDequote(psCmdLine, (rsArg.mn_CmdCall == CEStr::cc_CmdCK), &rsArg.mpsz_Dequoted)) psCmdLine++; if (rsArg.mn_CmdCall == CEStr::cc_CmdCK) rsArg.mn_CmdCall = CEStr::cc_CmdCommand; } size_t nArgLen = 0; bool lbQMode = false; // аргумент начинается с " if (*psCmdLine == L'"') { lbQMode = true; psCmdLine++; // ... /d "\"C:\ConEmu\ConEmuPortable.exe\" /Dir ... bool bQuoteEscaped = (psCmdLine[0] == L'\\' && psCmdLine[1] == L'"'); pch = wcschr(psCmdLine, L'"'); if (pch && (pch > psCmdLine)) { // To be correctly parsed something like this: // reg.exe add "HKCU\MyCo" /ve /t REG_EXPAND_SZ /d "\"C:\ConEmu\ConEmuPortable.exe\" /Dir \"%V\" /cmd \"cmd.exe\" \"-new_console:nC:cmd.exe\" \"-cur_console:d:%V\"" /f // But must not fails with ‘simple’ command like (no escapes in "C:\"): // /dir "C:\" /icon "cmd.exe" /single // Prev version fails while getting strings for -GuiMacro, example: // ConEmu.exe -detached -GuiMacro "print(\" echo abc \"); Context;" pch = wcspbrk(psCmdLine, L"\\\""); while (pch) { // Escaped quotation? if ((*pch == L'\\') && (*(pch+1) == L'"')) { // It's allowed when: // a) at the beginning of the line (handled above, bQuoteEscaped); // b) after space, left bracket or colon (-GuiMacro) // c) when already was forced by bQuoteEscaped if (( ((((pch - 1) >= psCmdLine) && wcschr(L" (,", *(pch-1))) || (*(pch+2) && !isSpace(*(pch+2))) )) || bQuoteEscaped) { bQuoteEscaped = true; pch++; // Point to " } } else if (*pch == L'"') break; // Next entry AFTER pch pch = wcspbrk(pch+1, L"\\\""); } } if (!pch) return CERR_CMDLINE; while (pch[1] == L'"' && (!rsArg.mpsz_Dequoted || ((pch+1) < rsArg.mpsz_Dequoted))) { pch += 2; pch = wcschr(pch, L'"'); if (!pch) return CERR_CMDLINE; } // Теперь в pch ссылка на последнюю " } else { // До конца строки или до первого пробела //pch = wcschr(psCmdLine, L' '); // 09.06.2009 Maks - обломался на: cmd /c" echo Y " pch = psCmdLine; // Ищем обычным образом (до пробела/кавычки) while (*pch && *pch!=L' ' && *pch!=L'"') pch++; //if (!pch) pch = psCmdLine + lstrlenW(psCmdLine); // до конца строки } _ASSERTE(pch >= psCmdLine); nArgLen = pch - psCmdLine; // Set result arugment // Warning: Don't demangle quotes/escapes here, or we'll fail to // concatenate environment or smth, losing quotes and others if (!rsArg.Set(psCmdLine, nArgLen)) return CERR_CMDLINE; rsArg.mb_Quoted = lbQMode; rsArg.mn_TokenNo++; if (rsArgStart) *rsArgStart = psCmdLine; psCmdLine = pch; // Finalize if ((*psCmdLine == L'"') && (lbQMode || (rsArg.mpsz_Dequoted == psCmdLine))) psCmdLine++; // was pointed to closing quotation mark psCmdLine = SkipNonPrintable(psCmdLine); // When whole line was dequoted if ((*psCmdLine == L'"') && (rsArg.mpsz_Dequoted == psCmdLine)) psCmdLine++; #ifdef _DEBUG rsArg.ms_LastTokenEnd = psCmdLine; lstrcpyn(rsArg.ms_LastTokenSave, psCmdLine, countof(rsArg.ms_LastTokenSave)); #endif switch (rsArg.mn_CmdCall) { case CEStr::cc_Undefined: // Если это однозначно "ключ" - то на имя файла не проверяем if (*rsArg.ms_Val == L'/' || *rsArg.ms_Val == L'-') { // Это для парсинга (чтобы ассертов не было) параметров из ShellExecute (там cmd.exe указывается в другом аргументе) if ((rsArg.mn_TokenNo == 1) && (lstrcmpi(rsArg.ms_Val, L"/C") == 0 || lstrcmpi(rsArg.ms_Val, L"/K") == 0)) rsArg.mn_CmdCall = CEStr::cc_CmdCK; } else { pch = PointToName(rsArg.ms_Val); if (pch) { if ((lstrcmpi(pch, L"cmd") == 0 || lstrcmpi(pch, L"cmd.exe") == 0) || (lstrcmpi(pch, L"ConEmuC") == 0 || lstrcmpi(pch, L"ConEmuC.exe") == 0) || (lstrcmpi(pch, L"ConEmuC64") == 0 || lstrcmpi(pch, L"ConEmuC64.exe") == 0)) { rsArg.mn_CmdCall = CEStr::cc_CmdExeFound; } } } break; case CEStr::cc_CmdExeFound: if (lstrcmpi(rsArg.ms_Val, L"/C") == 0 || lstrcmpi(rsArg.ms_Val, L"/K") == 0) rsArg.mn_CmdCall = CEStr::cc_CmdCK; else if ((rsArg.ms_Val[0] != L'/') && (rsArg.ms_Val[0] != L'-')) rsArg.mn_CmdCall = CEStr::cc_Undefined; break; } *asCmdLine = psCmdLine; return 0; }
BOOL CEventHandlerApp::InitATL() { m_bATLInited = TRUE; #if _WIN32_WINNT >= 0x0400 HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED); #else HRESULT hRes = CoInitialize(NULL); #endif if (FAILED(hRes)) { m_bATLInited = FALSE; return FALSE; } _Module.Init(ObjectMap, AfxGetInstanceHandle()); _Module.dwThreadID = GetCurrentThreadId(); LPTSTR lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT TCHAR szTokens[] = _T("-/"); BOOL bRun = TRUE; LPCTSTR lpszToken = _Module.FindOneOf(lpCmdLine, szTokens); while (lpszToken != NULL) { if (lstrcmpi(lpszToken, _T("UnregServer"))==0) { _Module.UpdateRegistryFromResource(IDR_EVENTHANDLER, FALSE); _Module.UnregisterServer(TRUE); //TRUE means typelib is unreg'd bRun = FALSE; break; } if (lstrcmpi(lpszToken, _T("RegServer"))==0) { _Module.UpdateRegistryFromResource(IDR_EVENTHANDLER, TRUE); _Module.RegisterServer(TRUE); bRun = FALSE; break; } lpszToken = _Module.FindOneOf(lpszToken, szTokens); } if (!bRun) { m_bATLInited = FALSE; _Module.Term(); CoUninitialize(); return FALSE; } hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE); if (FAILED(hRes)) { m_bATLInited = FALSE; CoUninitialize(); return FALSE; } return TRUE; }
// called in the first pass to create pluginEntry* structures and validate database plugins static BOOL scanPluginsDir (WIN32_FIND_DATA * fd, TCHAR * path, WPARAM, LPARAM) { int isdb = validguess_db_name(fd->cFileName); BASIC_PLUGIN_INFO bpi; pluginEntry* p = (pluginEntry*)HeapAlloc(hPluginListHeap, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, sizeof(pluginEntry)); _tcsncpy(p->pluginname, fd->cFileName, SIZEOF(p->pluginname)); // plugin name suggests its a db module, load it right now if ( isdb ) { TCHAR buf[MAX_PATH]; mir_sntprintf(buf, SIZEOF(buf), _T("%s\\Plugins\\%s"), path, fd->cFileName); if (checkAPI(buf, &bpi, mirandaVersion, CHECKAPI_DB, NULL)) { // db plugin is valid p->pclass |= (PCLASS_DB | PCLASS_BASICAPI); // copy the dblink stuff p->bpi=bpi; // keep a faster list. if ( pluginListDb != NULL ) p->nextclass = pluginListDb; pluginListDb=p; } else // didn't have basic APIs or DB exports - failed. p->pclass |= PCLASS_FAILED; } else if (validguess_clist_name(fd->cFileName)) { // keep a note of this plugin for later if ( pluginListUI != NULL ) p->nextclass=pluginListUI; pluginListUI=p; p->pclass |= PCLASS_CLIST; } else if (validguess_servicemode_name(fd->cFileName)) { TCHAR buf[MAX_PATH]; mir_sntprintf(buf, SIZEOF(buf), _T("%s\\Plugins\\%s"), path, fd->cFileName); if (checkAPI(buf, &bpi, mirandaVersion, CHECKAPI_NONE, NULL)) { p->pclass |= (PCLASS_OK | PCLASS_BASICAPI); p->bpi = bpi; if (bpi.Interfaces) { int i = 0; MUUID *piface = bpi.Interfaces(); while (!equalUUID(miid_last, piface[i])) { if (!equalUUID(miid_servicemode, piface[i++])) continue; p->pclass |= (PCLASS_SERVICE); if ( pluginListSM != NULL ) p->nextclass = pluginListSM; pluginListSM=p; if (pluginList_crshdmp == NULL && lstrcmpi(fd->cFileName, _T("svc_crshdmp.dll")) == 0) { pluginList_crshdmp = p; p->pclass |= PCLASS_LAST; } break; } } } else // didn't have basic APIs or DB exports - failed. p->pclass |= PCLASS_FAILED; } else if (pluginList_freeimg == NULL && lstrcmpi(fd->cFileName, _T("advaimg.dll")) == 0) pluginList_freeimg = p; // add it to the list pluginList.insert( p ); return TRUE; }
static int checkAPI(TCHAR* plugin, BASIC_PLUGIN_INFO* bpi, DWORD mirandaVersion, int checkTypeAPI, int* exports) { HINSTANCE h = NULL; // this is evil but these plugins are buggy/old and people are blaming Miranda // fontservice plugin is built into the core now { TCHAR * p = _tcsrchr(plugin, '\\'); if ( p != NULL && ++p ) { int i; for ( i = 0; i < SIZEOF(modulesToSkip); i++ ) if ( lstrcmpi( p, modulesToSkip[i] ) == 0 ) return 0; } } h = LoadLibrary(plugin); if ( h == NULL ) return 0; // loaded, check for exports bpi->Load = (Miranda_Plugin_Load) GetProcAddress(h, "Load"); bpi->Unload = (Miranda_Plugin_Unload) GetProcAddress(h, "Unload"); bpi->Info = (Miranda_Plugin_Info) GetProcAddress(h, "MirandaPluginInfo"); bpi->InfoEx = (Miranda_Plugin_InfoEx) GetProcAddress(h, "MirandaPluginInfoEx"); bpi->Interfaces = (Miranda_Plugin_Interfaces) GetProcAddress(h, "MirandaPluginInterfaces"); // if they were present if ( bpi->Load && bpi->Unload && ( bpi->Info || ( bpi->InfoEx && bpi->Interfaces ))) { PLUGININFOEX* pi = 0; if (bpi->InfoEx) pi = bpi->InfoEx(mirandaVersion); else pi = (PLUGININFOEX*)bpi->Info(mirandaVersion); { // similar to the above hack but these plugins are checked for a valid interface first (in case there are updates to the plugin later) TCHAR* p = _tcsrchr(plugin, '\\'); if ( pi != NULL && p != NULL && ++p ) { if ( !bpi->InfoEx || pi->cbSize != sizeof(PLUGININFOEX)) { int i; for ( i = 0; i < SIZEOF(expiredModulesToSkip); i++ ) { if ( lstrcmpi( p, expiredModulesToSkip[i] ) == 0 ) { FreeLibrary(h); return 0; } } } } } if ( checkPI( bpi, pi )) { bpi->pluginInfo = pi; // basic API is present if ( checkTypeAPI == CHECKAPI_NONE ) { bpi->hInst=h; return 1; } // check for DB? if ( checkTypeAPI == CHECKAPI_DB ) { bpi->DbInfo = (Database_Plugin_Info) GetProcAddress(h, "DatabasePluginInfo"); if ( bpi->DbInfo ) { // fetch internal database function pointers bpi->dblink = bpi->DbInfo(NULL); // validate returned link structure if ( bpi->dblink && bpi->dblink->cbSize==sizeof(DATABASELINK) ) { bpi->hInst=h; return 1; } // had DB exports if ( exports != NULL ) *exports=1; } //if } //if // check clist ? if ( checkTypeAPI == CHECKAPI_CLIST ) { bpi->clistlink = (CList_Initialise) GetProcAddress(h, "CListInitialise"); #if defined( _UNICODE ) if ( pi->flags & UNICODE_AWARE ) #endif if ( bpi->clistlink ) { // nothing more can be done here, this export is a load function bpi->hInst=h; if ( exports != NULL ) *exports=1; return 1; } } } // if if ( exports != NULL ) *exports=1; } //if // not found, unload FreeLibrary(h); return 0; }
//------------------------------------------------------------------------ ///| Parsing the command line |/////////////////////////////////////////// //------------------------------------------------------------------------ // Returns: // true - continue normal startup // false - exit process with iResult code bool CConEmuStart::ParseCommandLine(LPCWSTR pszCmdLine, int& iResult) { bool bRc = false; iResult = 100; _ASSERTE(pszCmdLine!=NULL); opt.cmdLine.Set(pszCmdLine ? pszCmdLine : L""); // pszCmdLine *may* or *may not* start with our executable or full path to our executable LPCWSTR pszTemp = opt.cmdLine; LPCWSTR cmdLineRest = SkipNonPrintable(opt.cmdLine); LPCWSTR pszName, pszArgStart; LPCWSTR psUnknown = NULL; CEStr szArg, szNext; CEStr szExeName, szExeNameOnly; // Set %ConEmuArgs% env var // It may be usefull if we need to restart ConEmu // from batch/script with the same arguments (selfupdate etc.) LPCWSTR pszCopyToEnvStart = NULL; // Have to get our exectuable name and name without extension szExeName.Set(PointToName(gpConEmu->ms_ConEmuExe)); szExeNameOnly.Set(szExeName); wchar_t* pszDot = (wchar_t*)PointToExt(szExeNameOnly.ms_Val); _ASSERTE(pszDot); if (pszDot) *pszDot = 0; // Check the first argument in the command line (most probably it will be our executable path/name) if (NextArg(&pszTemp, szArg) != 0) { _ASSERTE(FALSE && "GetCommandLine() is empty"); // Treat as empty command line, allow to start bRc = true; iResult = 0; goto wrap; } pszName = PointToName(szArg); if ((lstrcmpi(pszName, szExeName) == 0) || (lstrcmpi(pszName, szExeNameOnly) == 0)) { // OK, our executable was specified properly in the command line _ASSERTE(*pszTemp != L' '); cmdLineRest = SkipNonPrintable(pszTemp); } // Must be empty at the moment _ASSERTE(opt.runCommand.IsEmpty()); // Does the command line contain our switches? // Or we need to append all switches to starting shell? if (cmdLineRest && *cmdLineRest) { pszTemp = cmdLineRest; if (NextArg(&pszTemp, szArg) == 0) { if ((*szArg.ms_Val != L'/') && (*szArg.ms_Val != L'-') /*&& !wcschr(szArg.ms_Val, L'/')*/ ) { // Save it for further use opt.runCommand.Set(cmdLineRest); // And do not process it (no switches at all) cmdLineRest = NULL; opt.params = -1; } } } // Let parse the reset szArg.Empty(); szNext.Empty(); // Processing loop begin if (cmdLineRest && *cmdLineRest) { pszCopyToEnvStart = cmdLineRest; opt.cfgSwitches.Set(pszCopyToEnvStart); while (NextArg(&cmdLineRest, szArg, &pszArgStart) == 0) { bool lbNotFound = false; // ':' removed from checks because otherwise it will not warn // on invalid usage of "-new_console:a" for example if (szArg.ms_Val[0] == L'-' && szArg.ms_Val[1] && !wcspbrk(szArg.ms_Val+1, L"\\//|.&<>^")) { // Seems this is to be the "switch" too // Use both notations ('-' and '/') *szArg.ms_Val = L'/'; } LPCWSTR curCommand = szArg.ms_Val; #define NeedNextArg() \ if (NextArg(&cmdLineRest, szNext) != 0) { iResult = 101; goto wrap; } \ curCommand = szNext.ms_Val; if (*curCommand != L'/') { continue; // Try next switch? } else { opt.params++; if (!klstricmp(curCommand, _T("/autosetup"))) { BOOL lbTurnOn = TRUE; NeedNextArg(); if (*curCommand == _T('0')) { lbTurnOn = FALSE; } else { NeedNextArg(); DWORD dwAttr = GetFileAttributes(curCommand); if (dwAttr == (DWORD)-1 || (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) { iResult = 102; goto wrap; } } HKEY hk = NULL; DWORD dw; int nSetupRc = 100; if (0 != RegCreateKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Command Processor"), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hk, &dw)) { iResult = 103; goto wrap; } if (lbTurnOn) { size_t cchMax = _tcslen(curCommand); LPCWSTR pszArg1 = NULL; if (*cmdLineRest) { // May be ‘/GHWND=NEW’ or smth else pszArg1 = cmdLineRest; cchMax += _tcslen(pszArg1); } cchMax += 16; // + quotations, spaces and so on wchar_t* pszCmd = (wchar_t*)calloc(cchMax, sizeof(*pszCmd)); _wsprintf(pszCmd, SKIPLEN(cchMax) L"\"%s\"%s%s%s", curCommand, pszArg1 ? L" \"" : L"", pszArg1 ? pszArg1 : L"", pszArg1 ? L"\"" : L""); if (0 == RegSetValueEx(hk, _T("AutoRun"), 0, REG_SZ, (LPBYTE)pszCmd, (DWORD)sizeof(*pszCmd)*(_tcslen(pszCmd)+1))) nSetupRc = 1; free(pszCmd); } else { if (0==RegDeleteValue(hk, _T("AutoRun"))) nSetupRc = 1; } RegCloseKey(hk); // сбросить CreateInNewEnvironment для ConMan ResetConman(); iResult = nSetupRc; goto wrap; } else if (!klstricmp(curCommand, _T("/bypass")) || !klstricmp(curCommand, _T("/apparent")) || !klstricmp(curCommand, _T("/system")) || !klstricmp(curCommand, _T("/interactive")) || !klstricmp(curCommand, _T("/demote"))) { // -bypass // Этот ключик был придуман для прозрачного запуска консоли // в режиме администратора // (т.е. чтобы окно UAC нормально всплывало, но не мелькало консольное окно) // Но не получилось, пока требуются хэндлы процесса, а их не получается // передать в НЕ приподнятый процесс (исходный ConEmu GUI). // -apparent // Same as -bypass, but run the process as SW_SHOWNORMAL // -demote // Запуск процесса (ком.строка после "/demote") в режиме простого юзера, // когда текущий процесс уже запущен "под админом". "Понизить" текущие // привилегии просто так нельзя, поэтому запуск идет через TaskSheduler. // -system // Non-interactive process, started as System account // It's used when starting consoles, our server works fine as non-interactive // -interactive // Used when ConEmu.exe is started under System account, // but we need to give starting process interactive capabilities. _ASSERTE(opt.runCommand.IsEmpty()); pszTemp = cmdLineRest; if ((NextArg(&pszTemp, szNext) == 0) && (szNext.ms_Val[0] == L'-' || szNext.ms_Val[0] == L'/') && (lstrcmpi(szNext.ms_Val+1, L"cmd") == 0)) { opt.runCommand.Set(pszTemp); } else { opt.runCommand.Set(cmdLineRest); } if (opt.runCommand.IsEmpty()) { CEStr lsMsg(L"Invalid cmd line. '", curCommand, L"' exists, command line is empty"); DisplayLastError(lsMsg, -1); goto wrap; } // Information #ifdef _DEBUG STARTUPINFO siOur = {sizeof(siOur)}; GetStartupInfo(&siOur); #endif STARTUPINFO si = {sizeof(si)}; PROCESS_INFORMATION pi = {}; si.dwFlags = STARTF_USESHOWWINDOW; // Only `-demote` and `-apparent` switches were implemented to start application visible // All others are intended to run our server process, without blinking of course if ((0 == klstricmp(curCommand, _T("/demote"))) || (0 == klstricmp(curCommand, _T("/apparent")))) si.wShowWindow = SW_SHOWNORMAL; else si.wShowWindow = SW_HIDE; wchar_t szCurDir[MAX_PATH+1] = L""; GetCurrentDirectory(countof(szCurDir), szCurDir); BOOL b; DWORD nErr = 0; // if we were started from TaskScheduler, it would be nice to wait a little // to let parent (creator of the scheduler task) know we were started successfully bool bFromScheduler = false; // Log the command to be started { CEStr lsLog( L"Starting process", L": ", curCommand, L" `", opt.runCommand.ms_Val, L"`"); LogString(lsLog); } if (!klstricmp(curCommand, _T("/demote"))) { b = CreateProcessDemoted(opt.runCommand.ms_Val, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, szCurDir, &si, &pi, &nErr); } else if (!klstricmp(curCommand, _T("/system"))) { b = CreateProcessSystem(opt.runCommand.ms_Val, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, szCurDir, &si, &pi); } else if (!klstricmp(curCommand, _T("/interactive"))) { b = CreateProcessInteractive((DWORD)-1, NULL, opt.runCommand.ms_Val, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, szCurDir, &si, &pi, &nErr); bFromScheduler = true; } else // -bypass, -apparent { b = CreateProcess(NULL, opt.runCommand.ms_Val, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); nErr = b ? 0 : GetLastError(); bFromScheduler = true; } // Log the result { CEStr lsLog; wchar_t szExtra[32] = L""; if (b) { if (pi.dwProcessId) _wsprintf(szExtra, SKIPCOUNT(szExtra) L", PID=%u", pi.dwProcessId); lsLog = lstrmerge( L"Process was created successfully", szExtra); } else { _wsprintf(szExtra, SKIPCOUNT(szExtra) L", ErrorCode=%u", nErr); lsLog = lstrmerge( L"Failed to start process", szExtra); } LogString(lsLog); } // If the error was not shown yet if (nErr) DisplayLastError(opt.runCommand, nErr); // if we were started from TaskScheduler, it would be nice to wait a little // to let parent (creator of the scheduler task) know we were started successfully if (bFromScheduler) { LogString(L"Sleeping for 5 seconds"); Sleep(5*1000); } // Success? if (b) { iResult = 0; } // Done, close handles, if they were opened SafeCloseHandle(pi.hProcess); SafeCloseHandle(pi.hThread); goto wrap; } else if (!klstricmp(curCommand, _T("/multi"))) { gpConEmu->AppendExtraArgs(curCommand); gpConEmu->opt.MultiConValue = true; } else if (!klstricmp(curCommand, _T("/nomulti"))) { gpConEmu->AppendExtraArgs(curCommand); gpConEmu->opt.MultiConValue = false; } else if (!klstricmp(curCommand, _T("/visible"))) { gpConEmu->opt.VisValue = true; } else if (!klstricmp(curCommand, _T("/ct")) || !klstricmp(curCommand, _T("/cleartype")) || !klstricmp(curCommand, _T("/ct0")) || !klstricmp(curCommand, _T("/ct1")) || !klstricmp(curCommand, _T("/ct2"))) { switch (curCommand[3]) { case L'0': gpConEmu->opt.ClearTypeVal = NONANTIALIASED_QUALITY; break; case L'1': gpConEmu->opt.ClearTypeVal = ANTIALIASED_QUALITY; break; default: gpConEmu->opt.ClearTypeVal = CLEARTYPE_NATURAL_QUALITY; } } // Interface language else if (!klstricmp(curCommand, _T("/lng"))) { NeedNextArg(); if (!gpConEmu->opt.Language.Exists) { gpConEmu->opt.Language = curCommand; gpConEmu->AppendExtraArgs(L"/lng", curCommand); } } // Optional specific "ConEmu.l10n" else if (!klstricmp(curCommand, _T("/lngfile"))) { NeedNextArg(); if (!gpConEmu->opt.LanguageFile.Exists) { gpConEmu->opt.LanguageFile = curCommand; gpConEmu->AppendExtraArgs(L"/lngfile", curCommand); } } // имя шрифта else if (!klstricmp(curCommand, _T("/font"))) { NeedNextArg(); if (!gpConEmu->opt.FontVal.Exists) { gpConEmu->opt.FontVal = curCommand; gpConEmu->AppendExtraArgs(L"/font", curCommand); } } // Высота шрифта else if (!klstricmp(curCommand, _T("/size"))) { NeedNextArg(); if (!gpConEmu->opt.SizeVal.Exists) { gpConEmu->opt.SizeVal.SetInt(curCommand); } } // ADD fontname; by Mors else if (!klstricmp(curCommand, _T("/fontfile"))) { CESwitch szFile(sw_Str); if (!GetCfgParm(cmdLineRest, szFile, MAX_PATH)) { goto wrap; } gpConEmu->AppendExtraArgs(L"/fontfile", szFile.GetStr()); gpFontMgr->RegisterFont(szFile.GetStr(), TRUE); } // Register all fonts from specified directory else if (!klstricmp(curCommand, _T("/fontdir"))) { CESwitch szDir(sw_Str); if (!GetCfgParm(cmdLineRest, szDir, MAX_PATH)) { goto wrap; } gpConEmu->AppendExtraArgs(L"/fontdir", szDir.GetStr()); gpFontMgr->RegisterFontsDir(szDir.GetStr()); } else if (!klstricmp(curCommand, _T("/fs"))) { gpConEmu->opt.WindowModeVal = wmFullScreen; } else if (!klstricmp(curCommand, _T("/max"))) { gpConEmu->opt.WindowModeVal = wmMaximized; } else if (!klstricmp(curCommand, _T("/min")) || !klstricmp(curCommand, _T("/mintsa")) || !klstricmp(curCommand, _T("/starttsa"))) { gpConEmu->WindowStartMinimized = true; if (klstricmp(curCommand, _T("/min")) != 0) { gpConEmu->WindowStartTsa = true; gpConEmu->WindowStartNoClose = (klstricmp(curCommand, _T("/mintsa")) == 0); } } else if (!klstricmp(curCommand, _T("/tsa")) || !klstricmp(curCommand, _T("/tray"))) { gpConEmu->ForceMinimizeToTray = true; } else if (!klstricmp(curCommand, _T("/detached"))) { gpConEmu->m_StartDetached = crb_On; } else if (!klstricmp(curCommand, _T("/here"))) { gpConEmu->mb_ConEmuHere = true; gpConEmu->StoreWorkDir(); } else if (!klstricmp(curCommand, _T("/update"))) { gpConEmu->opt.AutoUpdateOnStart = true; } else if (!klstricmp(curCommand, _T("/noupdate"))) { // This one has more weight than AutoUpdateOnStart gpConEmu->opt.DisableAutoUpdate = true; } else if (!klstricmp(curCommand, _T("/nokeyhook")) || !klstricmp(curCommand, _T("/nokeyhooks")) || !klstricmp(curCommand, _T("/nokeybhook")) || !klstricmp(curCommand, _T("/nokeybhooks"))) { gpConEmu->DisableKeybHooks = true; } else if (!klstricmp(curCommand, _T("/nocloseconfirm"))) { gpConEmu->DisableCloseConfirm = true; } else if (!klstricmp(curCommand, _T("/nomacro"))) { gpConEmu->DisableAllMacro = true; } else if (!klstricmp(curCommand, _T("/nohotkey")) || !klstricmp(curCommand, _T("/nohotkeys"))) { gpConEmu->DisableAllHotkeys = true; } else if (!klstricmp(curCommand, _T("/nodeftrm")) || !klstricmp(curCommand, _T("/nodefterm"))) { gpConEmu->DisableSetDefTerm = true; } else if (!klstricmp(curCommand, _T("/noregfont")) || !klstricmp(curCommand, _T("/noregfonts"))) { gpConEmu->DisableRegisterFonts = true; } else if (!klstricmp(curCommand, _T("/inside")) || !lstrcmpni(curCommand, _T("/inside="), 8)) { bool bRunAsAdmin = isPressed(VK_SHIFT); bool bSyncDir = false; LPCWSTR pszSyncFmt = NULL; gpConEmu->mb_ConEmuHere = true; gpConEmu->StoreWorkDir(); if (curCommand[7] == _T('=')) { bSyncDir = true; pszSyncFmt = curCommand+8; // \eCD /d %1 - \e - ESC, \b - BS, \n - ENTER, %1 - "dir", %2 - "bash dir" } CConEmuInside::InitInside(bRunAsAdmin, bSyncDir, pszSyncFmt, 0, NULL); } else if (!klstricmp(curCommand, _T("/insidepid"))) { NeedNextArg(); bool bRunAsAdmin = isPressed(VK_SHIFT); wchar_t* pszEnd; // Здесь указывается PID, в который нужно внедриться. DWORD nInsideParentPID = wcstol(curCommand, &pszEnd, 10); if (nInsideParentPID) { CConEmuInside::InitInside(bRunAsAdmin, false, NULL, nInsideParentPID, NULL); } } else if (!klstricmp(curCommand, _T("/insidewnd"))) { NeedNextArg(); if (curCommand[0] == L'0' && (curCommand[1] == L'x' || curCommand[1] == L'X')) curCommand += 2; else if (curCommand[0] == L'x' || curCommand[0] == L'X') curCommand ++; bool bRunAsAdmin = isPressed(VK_SHIFT); wchar_t* pszEnd; // Здесь указывается HWND, в котором нужно создаваться. HWND hParent = (HWND)(DWORD_PTR)wcstoul(curCommand, &pszEnd, 16); if (hParent && IsWindow(hParent)) { CConEmuInside::InitInside(bRunAsAdmin, false, NULL, 0, hParent); } } else if (!klstricmp(curCommand, _T("/icon"))) { NeedNextArg(); if (!gpConEmu->opt.IconPrm.Exists && *curCommand) { gpConEmu->opt.IconPrm = true; gpConEmu->mps_IconPath = ExpandEnvStr(curCommand); } } else if (!klstricmp(curCommand, _T("/dir"))) { NeedNextArg(); if (*curCommand) { // Например, "%USERPROFILE%" wchar_t* pszExpand = NULL; if (wcschr(curCommand, L'%') && ((pszExpand = ExpandEnvStr(curCommand)) != NULL)) { gpConEmu->StoreWorkDir(pszExpand); SafeFree(pszExpand); } else { gpConEmu->StoreWorkDir(curCommand); } } } else if (!klstricmp(curCommand, _T("/updatejumplist"))) { // Copy current Task list to Win7 Jump list (Taskbar icon) gpConEmu->mb_UpdateJumpListOnStartup = true; } else if (!klstricmp(curCommand, L"/log") || !klstricmp(curCommand, L"/log0") || !klstricmp(curCommand, L"/log1") || !klstricmp(curCommand, L"/log2") || !klstricmp(curCommand, L"/log3") || !klstricmp(curCommand, L"/log4")) { if (!klstricmp(curCommand, L"/log") || !klstricmp(curCommand, L"/log0")) gpConEmu->opt.AdvLogging.SetInt(1); else gpConEmu->opt.AdvLogging.SetInt((BYTE)(curCommand[4] - L'0')); // 1..4 // Do create logging service DEBUGSTRSTARTUP(L"Creating log file"); gpConEmu->CreateLog(); } else if (!klstricmp(curCommand, _T("/single")) || !klstricmp(curCommand, _T("/reuse"))) { // "/reuse" switch to be remastered gpConEmu->AppendExtraArgs(curCommand); gpSetCls->SingleInstanceArg = sgl_Enabled; } else if (!klstricmp(curCommand, _T("/nosingle"))) { gpConEmu->AppendExtraArgs(curCommand); gpSetCls->SingleInstanceArg = sgl_Disabled; } else if (!klstricmp(curCommand, _T("/DesktopMode"))) { gpConEmu->opt.DesktopMode = true; } else if (!klstricmp(curCommand, _T("/quake")) || !klstricmp(curCommand, _T("/quakeauto")) || !klstricmp(curCommand, _T("/noquake"))) { if (!klstricmp(curCommand, _T("/quake"))) gpConEmu->opt.QuakeMode = 1; else if (!klstricmp(curCommand, _T("/quakeauto"))) gpConEmu->opt.QuakeMode = 2; else { gpConEmu->opt.QuakeMode = 0; if (gpSetCls->SingleInstanceArg == sgl_Default) gpSetCls->SingleInstanceArg = sgl_Disabled; } } else if (!klstricmp(curCommand, _T("/showhide")) || !klstricmp(curCommand, _T("/showhideTSA"))) { gpSetCls->SingleInstanceArg = sgl_Enabled; gpSetCls->SingleInstanceShowHide = !klstricmp(curCommand, _T("/showhide")) ? sih_ShowMinimize : sih_ShowHideTSA; } else if (!klstricmp(curCommand, _T("/reset")) || !klstricmp(curCommand, _T("/resetdefault")) || !klstricmp(curCommand, _T("/basic"))) { gpConEmu->opt.ResetSettings = true; if (!klstricmp(curCommand, _T("/resetdefault"))) { gpSetCls->isFastSetupDisabled = true; } else if (!klstricmp(curCommand, _T("/basic"))) { gpSetCls->isFastSetupDisabled = true; gpSetCls->isResetBasicSettings = true; } } else if (!klstricmp(curCommand, _T("/nocascade")) || !klstricmp(curCommand, _T("/dontcascade"))) { gpConEmu->AppendExtraArgs(curCommand); gpSetCls->isDontCascade = true; } else if (!klstricmp(curCommand, _T("/WndX")) || !klstricmp(curCommand, _T("/WndY")) || !klstricmp(curCommand, _T("/WndW")) || !klstricmp(curCommand, _T("/WndWidth")) || !klstricmp(curCommand, _T("/WndH")) || !klstricmp(curCommand, _T("/WndHeight"))) { TCHAR ch = curCommand[4]; CharUpperBuff(&ch, 1); CESwitch psz(sw_Str); bool bParm = false; if (!GetCfgParm(cmdLineRest, bParm, psz, 32)) { goto wrap; } gpConEmu->opt.SizePosPrm = true; // Direct X/Y implies /nocascade if (ch == _T('X') || ch == _T('Y')) { // TODO: isDontCascade must be in our opt struct !!! gpSetCls->isDontCascade = true; } switch (ch) { case _T('X'): gpConEmu->opt.sWndX.SetStr(psz.Str, sw_Str); break; case _T('Y'): gpConEmu->opt.sWndY.SetStr(psz.Str, sw_Str); break; case _T('W'): gpConEmu->opt.sWndW.SetStr(psz.Str, sw_Str); break; case _T('H'): gpConEmu->opt.sWndH.SetStr(psz.Str, sw_Str); break; } } else if (!klstricmp(curCommand, _T("/Monitor"))) { CESwitch psz(sw_Str); bool bParm = false; if (!GetCfgParm(cmdLineRest, bParm, psz, 64)) { goto wrap; } if ((gpConEmu->opt.Monitor.Mon = MonitorFromParam(psz.Str)) != NULL) { gpConEmu->opt.Monitor.Exists = true; gpConEmu->opt.Monitor.Type = sw_Int; gpStartEnv->hStartMon = gpConEmu->opt.Monitor.Mon; } } else if (!klstricmp(curCommand, _T("/Buffer")) || !klstricmp(curCommand, _T("/BufferHeight"))) { NeedNextArg(); if (!gpConEmu->opt.BufferHeightVal.Exists) { gpConEmu->opt.BufferHeightVal.SetInt(curCommand); if (gpConEmu->opt.BufferHeightVal.GetInt() < 0) { //setParent = true; -- Maximus5 - нефиг, все ручками gpConEmu->opt.BufferHeightVal = -gpConEmu->opt.BufferHeightVal.GetInt(); } if (gpConEmu->opt.BufferHeightVal.GetInt() < LONGOUTPUTHEIGHT_MIN) gpConEmu->opt.BufferHeightVal = LONGOUTPUTHEIGHT_MIN; else if (gpConEmu->opt.BufferHeightVal.GetInt() > LONGOUTPUTHEIGHT_MAX) gpConEmu->opt.BufferHeightVal = LONGOUTPUTHEIGHT_MAX; } } else if (!klstricmp(curCommand, _T("/Config"))) { // -- используем последний из параметров, если их несколько if (!GetCfgParm(cmdLineRest, gpConEmu->opt.ConfigVal, 127)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/Palette"))) { // -- используем последний из параметров, если их несколько if (!GetCfgParm(cmdLineRest, gpConEmu->opt.PaletteVal, MAX_PATH)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/LoadRegistry"))) { gpConEmu->AppendExtraArgs(curCommand); gpConEmu->opt.ForceUseRegistryPrm = true; } else if (!klstricmp(curCommand, _T("/LoadCfgFile")) || !klstricmp(curCommand, _T("/LoadXmlFile"))) { // -- используем последний из параметров, если их несколько if (!GetCfgParm(cmdLineRest, gpConEmu->opt.LoadCfgFile, MAX_PATH, true)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/SaveCfgFile")) || !klstricmp(curCommand, _T("/SaveXmlFile"))) { // -- используем последний из параметров, если их несколько if (!GetCfgParm(cmdLineRest, gpConEmu->opt.SaveCfgFile, MAX_PATH, true)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/GuiMacro"))) { // -- выполняется только последний if (!GetCfgParm(cmdLineRest, gpConEmu->opt.ExecGuiMacro, 0x8000, false)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/UpdateSrcSet"))) { // -- используем последний из параметров, если их несколько if (!GetCfgParm(cmdLineRest, gpConEmu->opt.UpdateSrcSet, MAX_PATH*4, false)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/AnsiLog"))) { // -- используем последний из параметров, если их несколько if (!GetCfgParm(cmdLineRest, gpConEmu->opt.AnsiLogPath, MAX_PATH-40, true)) { goto wrap; } } else if (!klstricmp(curCommand, _T("/SetDefTerm"))) { gpConEmu->opt.SetUpDefaultTerminal = true; } else if (!klstricmp(curCommand, _T("/ZoneId"))) { gpConEmu->opt.FixZoneId = true; } else if (!klstricmp(curCommand, _T("/Exit"))) { gpConEmu->opt.ExitAfterActionPrm = true; } else if (!klstricmp(curCommand, _T("/QuitOnClose"))) { gpConEmu->mb_ForceQuitOnClose = true; } else if (!klstricmp(curCommand, _T("/Title"))) { bool bOk = false; CESwitch pszTitle(sw_Str); if (!GetCfgParm(cmdLineRest, bOk, pszTitle, 127)) { goto wrap; } gpConEmu->SetTitleTemplate(pszTitle.GetStr()); } else if (!klstricmp(curCommand, _T("/FindBugMode"))) { gpConEmu->mb_FindBugMode = true; } else if (!klstricmp(curCommand, _T("/debug")) || !klstricmp(curCommand, _T("/debugw")) || !klstricmp(curCommand, _T("/debugi"))) { // These switches were already processed } else if (!klstricmp(curCommand, _T("/?")) || !klstricmp(curCommand, _T("/h")) || !klstricmp(curCommand, _T("/help"))) { if (gpLng) gpLng->Reload(); ConEmuAbout::OnInfo_About(); iResult = -1; goto wrap; } // Final `-cmd ...` or `-cmdlist ...` else if ( !klstricmp(curCommand, _T("/cmd")) || !klstricmp(curCommand, _T("/cmdlist")) ) { if (opt.cfgSwitches.ms_Val) { _ASSERTE(pszArgStart>pszCopyToEnvStart); _ASSERTE((INT_PTR)(pszArgStart - pszCopyToEnvStart) <= opt.cfgSwitches.GetLen()); opt.cfgSwitches.ms_Val[pszArgStart - pszCopyToEnvStart] = 0; } opt.runCommand.Set(SkipNonPrintable(cmdLineRest)); opt.isScript = (klstricmp(curCommand, L"/cmdlist") == 0); break; } else { // Show error on unknown switch psUnknown = pszArgStart; break; } } // (*curCommand == L'/') // Avoid assertions in NextArg szArg.Empty(); szNext.Empty(); } // while (NextArg(&cmdLineRest, szArg, &pszArgStart) == 0) } // Processing loop end if (psUnknown) { DEBUGSTRSTARTUP(L"Unknown switch, exiting!"); if (gpSet->isLogging()) { // For direct logging we do not use lng resources CEStr lsLog(L"\r\n", L"Unknown switch specified: ", psUnknown, L"\r\n\r\n"); gpConEmu->LogString(lsLog, false, false); } CEStr szNewConWarn; LPCWSTR pszTestSwitch = (psUnknown[0] == L'-' || psUnknown[0] == L'/') ? ((psUnknown[1] == L'-' || psUnknown[1] == L'/') ? (psUnknown+2) : (psUnknown+1)) : psUnknown; if ((lstrcmpni(pszTestSwitch, L"new_console", 11) == 0) || (lstrcmpni(pszTestSwitch, L"cur_console", 11) == 0)) { szNewConWarn = lstrmerge(L"\r\n\r\n", CLngRc::getRsrc(lng_UnknownSwitch4/*"Switch -new_console must be specified *after* /cmd or /cmdlist"*/) ); } CEStr lsMsg( CLngRc::getRsrc(lng_UnknownSwitch1/*"Unknown switch specified:"*/), L"\r\n\r\n", psUnknown, szNewConWarn, L"\r\n\r\n", CLngRc::getRsrc(lng_UnknownSwitch2/*"Visit website to get thorough switches description:"*/), L"\r\n" CEGUIARGSPAGE L"\r\n\r\n", CLngRc::getRsrc(lng_UnknownSwitch3/*"Or run ‘ConEmu.exe -?’ to get the brief."*/) ); MBoxA(lsMsg); goto wrap; } // Set "ConEmuArgs" and "ConEmuArgs2" ProcessConEmuArgsVar(); // Continue normal startup bRc = true; wrap: return bRc; }
int SortAsText(LPCWSTR str1, LPCWSTR str2) { return lstrcmpi(str1, str2); }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst,LPSTR lpszCmdParam, int nCmdShow) { static int ret; static const char *m_Err; #ifdef NSIS_CONFIG_CRC_SUPPORT #ifdef NSIS_CONFIG_VISIBLE_SUPPORT static HWND hwnd; #endif static int crc; static char no_crc; static char do_crc; #endif//NSIS_CONFIG_CRC_SUPPORT #if defined(NSIS_CONFIG_SILENT_SUPPORT) && defined(NSIS_CONFIG_VISIBLE_SUPPORT) static char silent; #endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT int left; #ifdef NSIS_CONFIG_VISIBLE_SUPPORT unsigned int verify_time=GetTickCount()+1000; #endif char *cmdline=state_command_line; char *realcmds; char seekchar=' '; InitCommonControls(); lstrcpyn(state_command_line,GetCommandLine(),NSIS_MAX_STRLEN); if (*cmdline == '\"') seekchar = *cmdline++; while (*cmdline && *cmdline != seekchar) if (*cmdline) cmdline++; if (*cmdline) cmdline++; realcmds=cmdline; do { #ifdef NSIS_CONFIG_CRC_SUPPORT #endif//NSIS_CONFIG_CRC_SUPPORT while (*cmdline == ' ') if (*cmdline) cmdline++; if (cmdline[0] != '/') break; cmdline++; #if defined(NSIS_CONFIG_VISIBLE_SUPPORT) && defined(NSIS_CONFIG_SILENT_SUPPORT) if (cmdline[0] == 'S' && (cmdline[1] == ' ' || !cmdline[1])) { silent++; cmdline+=2; } else #endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_CRC_SUPPORT if (cmdline[0] == 'N' && cmdline[1] == 'C' && cmdline[2] == 'R' && cmdline[3] == 'C' && (cmdline[4] == ' ' || !cmdline[4])) { no_crc++; cmdline+=4; } else #endif//NSIS_CONFIG_CRC_SUPPORT if (cmdline[0] == 'D' && cmdline[1] == '=') { cmdline[-2]=0; // keep this from being passed to uninstaller if necessary lstrcpy(state_install_directory,cmdline+2); cmdline+=lstrlen(cmdline); } else while (*cmdline && *cmdline != ' ') if (*cmdline) cmdline++; } while (*cmdline); lstrcpy(g_caption,_LANG_GENERIC_ERROR); g_hInstance=GetModuleHandle(NULL); GetModuleFileName(g_hInstance,state_exe_directory,NSIS_MAX_STRLEN); g_db_hFile=myOpenFile(state_exe_directory,GENERIC_READ,OPEN_EXISTING); if (g_db_hFile==INVALID_HANDLE_VALUE) { m_Err = _LANG_CANTOPENSELF; goto end; } // make state_exe_directory point to dir, not full exe. trimslashtoend(state_exe_directory); left = m_length = GetFileSize(g_db_hFile,NULL); while (left > 0) { static char temp[512]; DWORD l=left; if (l > 512) l=512; if (!ReadFile(g_db_hFile,temp,l,&l,NULL)) { m_Err=g_crcinvalid; #if defined(NSIS_CONFIG_CRC_SUPPORT) && defined(NSIS_CONFIG_VISIBLE_SUPPORT) if (hwnd) DestroyWindow(hwnd); #endif//NSIS_CONFIG_CRC_SUPPORT goto end; } if (!g_filehdrsize) { int dbl; dbl=isheader((firstheader*)temp); if (dbl) { int a=*(int*)temp; g_filehdrsize=m_pos; if (dbl > left) { m_Err=g_crcinvalid; goto end; } #if defined(NSIS_CONFIG_SILENT_SUPPORT) && defined(NSIS_CONFIG_VISIBLE_SUPPORT) if (a&FH_FLAGS_SILENT) silent++; #endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_CRC_SUPPORT // Changed by Amir Szekely 23rd July 2002 (CRCCheck force) if ((no_crc && !(a&FH_FLAGS_FORCE_CRC)) || !(a&FH_FLAGS_CRC)) break; // if first bit is not set, then no crc checking. do_crc++; #ifndef NSIS_CONFIG_CRC_ANAL left=dbl-4; // end crc checking at crc :) this means you can tack shit on the end and it'll still work. #else //!NSIS_CONFIG_CRC_ANAL left-=4; #endif//NSIS_CONFIG_CRC_ANAL // this is in case the end part is < 512 bytes. if (l > (DWORD)left) l=(DWORD)left; #else//!NSIS_CONFIG_CRC_SUPPORT break; #endif//!NSIS_CONFIG_CRC_SUPPORT } } #ifdef NSIS_CONFIG_CRC_SUPPORT #ifdef NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_SILENT_SUPPORT else if (!silent) #endif//NSIS_CONFIG_SILENT_SUPPORT { if (hwnd) { static MSG msg; while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) DispatchMessage(&msg); } else if (GetTickCount() > verify_time) hwnd=CreateDialog(g_hInstance,MAKEINTRESOURCE(IDD_VERIFY),GetDesktopWindow(),verProc); } #endif//NSIS_CONFIG_VISIBLE_SUPPORT #ifndef NSIS_CONFIG_CRC_ANAL if (left<m_length) #endif//NSIS_CONFIG_CRC_ANAL crc=CRC32(crc, temp, l); #endif//NSIS_CONFIG_CRC_SUPPORT m_pos+=l; left -= l; } #ifdef NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_CRC_SUPPORT if (hwnd) DestroyWindow(hwnd); #endif//NSIS_CONFIG_CRC_SUPPORT #endif//NSIS_CONFIG_VISIBLE_SUPPORT if (!g_filehdrsize) m_Err=g_crcinvalid; else { #ifdef NSIS_CONFIG_CRC_SUPPORT if (do_crc) { DWORD l; int fcrc; SetFilePointer(g_db_hFile,m_pos,NULL,FILE_BEGIN); if (!ReadFile(g_db_hFile,&fcrc,4,&l,NULL) || crc != fcrc) { m_Err=g_crcinvalid; goto end; } } #endif//NSIS_CONFIG_CRC_SUPPORT SetFilePointer(g_db_hFile,g_filehdrsize,NULL,FILE_BEGIN); if (loadHeaders()) m_Err=g_crcinvalid; } if (m_Err) goto end; #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT if (g_is_uninstaller) { if (cmdline[0] == '_' && cmdline[1] == '=' && cmdline[2]) { cmdline[-1]=0; cmdline+=2; if (is_valid_instpath(cmdline)) { lstrcpy(state_install_directory,cmdline); lstrcpy(state_output_directory,cmdline); } else { m_Err = g_errorcopyinginstall; goto end; } } else { int x,done=0; for (x = 0; x < 26; x ++) { static char s[]="A~NSISu_.exe"; static char buf2[NSIS_MAX_STRLEN*2]; static char ibuf[NSIS_MAX_STRLEN]; buf2[0]='\"'; GetTempPath(sizeof(buf2)-1,buf2+1); lstrcat(buf2,s); DeleteFile(buf2+1); // clean up after all the other ones if they are there if (!done) { // get current name int l=GetModuleFileName(g_hInstance,ibuf,sizeof(ibuf)); // check if it is ?~NSISu_.exe - if so, f**k it if (!lstrcmpi(ibuf+l-(sizeof(s)-2),s+1)) break; // copy file if (CopyFile(ibuf,buf2+1,FALSE)) { HANDLE hProc; #ifdef NSIS_SUPPORT_MOVEONREBOOT MoveFileOnReboot(buf2+1,NULL); #endif if (state_install_directory[0]) lstrcpy(ibuf,state_install_directory); else trimslashtoend(ibuf); if (!is_valid_instpath(ibuf)) break; done++; lstrcat(buf2,"\" "); lstrcat(buf2,realcmds); lstrcat(buf2," _="); lstrcat(buf2,ibuf); GetTempPath(sizeof(ibuf),ibuf); hProc=myCreateProcess(buf2,ibuf); if (hProc) CloseHandle(hProc); else m_Err = g_errorcopyinginstall; } } s[0]++; } if (!done) m_Err=g_errorcopyinginstall; goto end; } } #endif//NSIS_CONFIG_UNINSTALL_SUPPORT #ifdef NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_SILENT_SUPPORT if (!g_inst_cmnheader->silent_install) g_inst_cmnheader->silent_install=silent; #endif//NSIS_CONFIG_SILENT_SUPPORT #endif//NSIS_CONFIG_VISIBLE_SUPPORT ret=ui_doinstall(); #ifdef NSIS_CONFIG_LOG log_write(1); #endif//NSIS_CONFIG_LOG end: if (g_db_hFile!=INVALID_HANDLE_VALUE) CloseHandle(g_db_hFile); #ifdef NSIS_COMPRESS_WHOLE if (dbd_hFile!=INVALID_HANDLE_VALUE) CloseHandle(dbd_hFile); #endif if (m_Err) MessageBox(NULL,m_Err,g_caption,MB_OK|MB_ICONSTOP); ExitProcess(ret); }
static int mail_extracthdr(char *headers, char *name, char *buf, int bufsize) { char *p = headers, *q; char hdrname[256]; int i; if (headers == NULL || name == NULL || buf == NULL || bufsize <= 0) return 1; while (*p == '\r' || *p == '\n' || *p == ' ' || *p == '\t') p++; while (*p) { for (i=0; i<(sizeof(hdrname)-1);) { char c = *p++; if (c == 0) break; if (c == ':' || c == '\r' || c == '\n') { p--; break; } if (c == '\t') c=' '; if (i>0 && c==' ') { if(hdrname[i-1]==' ') continue; } if (i==0 && c==' ') continue; hdrname[i++] = c; } hdrname[i] = 0; if (*p == 0) break; if (hdrname[lstrlen(hdrname)-1] == ' ') hdrname[lstrlen(hdrname)-1] = 0; if (hdrname[0] == 0) break; if (*p == ':') { CharLower(hdrname); if (lstrcmpi(hdrname, name) == 0) { p++; goto hdr_found; } } while (*p != '\n' && *p != '\r' && *p) p++; if (*p == 0) break; if (*p == '\n') { p++; if (*p == '\r') p++; } else if (*p == '\r') { p++; if (*p == '\n') p++; } if (*p == '\n' || *p == '\r') break; } return 1; hdr_found: if (*p == ' ' || *p == '\t') p++; for (i=0; i<(bufsize-1);) { char c = *p++; if (c == '\r' || c == '\n') { q = p--; while (*q == '\n' || *q == '\r') q++; if (*q != ' ' && *q != '\t') break; while (*p == '\n' || *p == '\r') p++; continue; } buf[i++] = c; } buf[i] = 0; return 0; }
/* Get uname for Windows */ char *getuname() { int ret_size = OS_SIZE_1024 - 2; char *ret = NULL; char os_v[128 + 1]; typedef void (WINAPI * PGNSI)(LPSYSTEM_INFO); typedef BOOL (WINAPI * PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); /* See http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429%28v=vs.85%29.aspx */ OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; PGPI pGPI; BOOL bOsVersionInfoEx; DWORD dwType; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx((OSVERSIONINFO *)&osvi)) { return (NULL); } } /* Allocate memory */ os_calloc(OS_SIZE_1024 + 1, sizeof(char), ret); ret[OS_SIZE_1024] = '\0'; switch (osvi.dwPlatformId) { /* Test for the Windows NT product family */ case VER_PLATFORM_WIN32_NT: if (osvi.dwMajorVersion == 6) { if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION ) { strncat(ret, "Microsoft Windows Vista ", ret_size - 1); } else { strncat(ret, "Microsoft Windows Server 2008 ", ret_size - 1); } } else if (osvi.dwMinorVersion == 1) { if (osvi.wProductType == VER_NT_WORKSTATION ) { strncat(ret, "Microsoft Windows 7 ", ret_size - 1); } else { strncat(ret, "Microsoft Windows Server 2008 R2 ", ret_size - 1); } } else if (osvi.dwMinorVersion == 2) { if (osvi.wProductType == VER_NT_WORKSTATION ) { strncat(ret, "Microsoft Windows 8 ", ret_size - 1); } else { strncat(ret, "Microsoft Windows Server 2012 ", ret_size - 1); } } else if (osvi.dwMinorVersion == 3) { if (osvi.wProductType == VER_NT_WORKSTATION ) { strncat(ret, "Microsoft Windows 8.1 ", ret_size - 1); } else { strncat(ret, "Microsoft Windows Server 2012 R2 ", ret_size - 1); } } ret_size -= strlen(ret) + 1; /* Get product version */ pGPI = (PGPI) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); pGPI( 6, 0, 0, 0, &dwType); switch (dwType) { case PRODUCT_UNLICENSED: strncat(ret, PRODUCT_UNLICENSED_C, ret_size - 1); break; case PRODUCT_BUSINESS: strncat(ret, PRODUCT_BUSINESS_C, ret_size - 1); break; case PRODUCT_BUSINESS_N: strncat(ret, PRODUCT_BUSINESS_N_C, ret_size - 1); break; case PRODUCT_CLUSTER_SERVER: strncat(ret, PRODUCT_CLUSTER_SERVER_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER: strncat(ret, PRODUCT_DATACENTER_SERVER_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER_CORE: strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER_CORE_V: strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_V_C, ret_size - 1); break; case PRODUCT_DATACENTER_SERVER_V: strncat(ret, PRODUCT_DATACENTER_SERVER_V_C, ret_size - 1); break; case PRODUCT_ENTERPRISE: strncat(ret, PRODUCT_ENTERPRISE_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_N: strncat(ret, PRODUCT_ENTERPRISE_N_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER: strncat(ret, PRODUCT_ENTERPRISE_SERVER_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_CORE: strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_CORE_V: strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_V_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_IA64: strncat(ret, PRODUCT_ENTERPRISE_SERVER_IA64_C, ret_size - 1); break; case PRODUCT_ENTERPRISE_SERVER_V: strncat(ret, PRODUCT_ENTERPRISE_SERVER_V_C, ret_size - 1); break; case PRODUCT_HOME_BASIC: strncat(ret, PRODUCT_HOME_BASIC_C, ret_size - 1); break; case PRODUCT_HOME_BASIC_N: strncat(ret, PRODUCT_HOME_BASIC_N_C, ret_size - 1); break; case PRODUCT_HOME_PREMIUM: strncat(ret, PRODUCT_HOME_PREMIUM_C, ret_size - 1); break; case PRODUCT_HOME_PREMIUM_N: strncat(ret, PRODUCT_HOME_PREMIUM_N_C, ret_size - 1); break; case PRODUCT_HOME_SERVER: strncat(ret, PRODUCT_HOME_SERVER_C, ret_size - 1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT: strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT_C, ret_size - 1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING: strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING_C, ret_size - 1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY: strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY_C, ret_size - 1); break; case PRODUCT_SERVER_FOR_SMALLBUSINESS: strncat(ret, PRODUCT_SERVER_FOR_SMALLBUSINESS_C, ret_size - 1); break; case PRODUCT_SMALLBUSINESS_SERVER: strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_C, ret_size - 1); break; case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER: strncat(ret, PRODUCT_STANDARD_SERVER_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER_CORE: strncat(ret, PRODUCT_STANDARD_SERVER_CORE_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER_CORE_V: strncat(ret, PRODUCT_STANDARD_SERVER_CORE_V_C, ret_size - 1); break; case PRODUCT_STANDARD_SERVER_V: strncat(ret, PRODUCT_STANDARD_SERVER_V_C, ret_size - 1); break; case PRODUCT_STARTER: strncat(ret, PRODUCT_STARTER_C, ret_size - 1); break; case PRODUCT_STORAGE_ENTERPRISE_SERVER: strncat(ret, PRODUCT_STORAGE_ENTERPRISE_SERVER_C, ret_size - 1); break; case PRODUCT_STORAGE_EXPRESS_SERVER: strncat(ret, PRODUCT_STORAGE_EXPRESS_SERVER_C, ret_size - 1); break; case PRODUCT_STORAGE_STANDARD_SERVER: strncat(ret, PRODUCT_STORAGE_STANDARD_SERVER_C, ret_size - 1); break; case PRODUCT_STORAGE_WORKGROUP_SERVER: strncat(ret, PRODUCT_STORAGE_WORKGROUP_SERVER_C, ret_size - 1); break; case PRODUCT_ULTIMATE: strncat(ret, PRODUCT_ULTIMATE_C, ret_size - 1); break; case PRODUCT_ULTIMATE_N: strncat(ret, PRODUCT_ULTIMATE_N_C, ret_size - 1); break; case PRODUCT_WEB_SERVER: strncat(ret, PRODUCT_WEB_SERVER_C, ret_size - 1); break; case PRODUCT_WEB_SERVER_CORE: strncat(ret, PRODUCT_WEB_SERVER_CORE_C, ret_size - 1); break; } ret_size -= strlen(ret) + 1; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { pGNSI = (PGNSI) GetProcAddress( GetModuleHandle("kernel32.dll"), "GetNativeSystemInfo"); if (NULL != pGNSI) { pGNSI(&si); } if ( GetSystemMetrics(89) ) strncat(ret, "Microsoft Windows Server 2003 R2 ", ret_size - 1); else if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { strncat(ret, "Microsoft Windows XP Professional x64 Edition ", ret_size - 1 ); } else { strncat(ret, "Microsoft Windows Server 2003, ", ret_size - 1); } ret_size -= strlen(ret) + 1; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) { strncat(ret, "Microsoft Windows XP ", ret_size - 1); ret_size -= strlen(ret) + 1; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { strncat(ret, "Microsoft Windows 2000 ", ret_size - 1); ret_size -= strlen(ret) + 1; } else if (osvi.dwMajorVersion <= 4) { strncat(ret, "Microsoft Windows NT ", ret_size - 1); ret_size -= strlen(ret) + 1; } else { strncat(ret, "Microsoft Windows Unknown ", ret_size - 1); ret_size -= strlen(ret) + 1; } /* Test for specific product on Windows NT 4.0 SP6 and later */ if (bOsVersionInfoEx) { /* Test for the workstation type */ if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64) { if ( osvi.dwMajorVersion == 4 ) { strncat(ret, "Workstation 4.0 ", ret_size - 1); } else if ( osvi.wSuiteMask & VER_SUITE_PERSONAL ) { strncat(ret, "Home Edition ", ret_size - 1); } else { strncat(ret, "Professional ", ret_size - 1); } /* Fix size */ ret_size -= strlen(ret) + 1; } /* Test for the server type */ else if ( osvi.wProductType == VER_NT_SERVER || osvi.wProductType == VER_NT_DOMAIN_CONTROLLER ) { if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64 ) { if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter Edition for Itanium-based Systems ", ret_size - 1); else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Enterprise Edition for Itanium-based Systems ", ret_size - 1); ret_size -= strlen(ret) + 1; } else if ( si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ) { if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter x64 Edition ", ret_size - 1 ); else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Enterprise x64 Edition ", ret_size - 1 ); else strncat(ret, "Standard x64 Edition ", ret_size - 1 ); ret_size -= strlen(ret) + 1; } else { if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter Edition ", ret_size - 1 ); else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) { strncat(ret, "Enterprise Edition ", ret_size - 1); } else if ( osvi.wSuiteMask == VER_SUITE_BLADE ) { strncat(ret, "Web Edition ", ret_size - 1 ); } else { strncat(ret, "Standard Edition ", ret_size - 1); } ret_size -= strlen(ret) + 1; } } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { if ( osvi.wSuiteMask & VER_SUITE_DATACENTER ) { strncat(ret, "Datacenter Server ", ret_size - 1); } else if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) { strncat(ret, "Advanced Server ", ret_size - 1 ); } else { strncat(ret, "Server ", ret_size - 1); } ret_size -= strlen(ret) + 1; } else if (osvi.dwMajorVersion <= 4) { /* Windows NT 4.0 */ if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Server 4.0, Enterprise Edition ", ret_size - 1 ); else { strncat(ret, "Server 4.0 ", ret_size - 1); } ret_size -= strlen(ret) + 1; } } } /* Test for specific product on Windows NT 4.0 SP5 and earlier */ else { HKEY hKey; char szProductType[81]; DWORD dwBufLen = 80; LONG lRet; lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey ); if (lRet == ERROR_SUCCESS) { char __wv[32]; lRet = RegQueryValueEx( hKey, "ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen); RegCloseKey( hKey ); if ((lRet == ERROR_SUCCESS) && (dwBufLen < 80) ) { if (lstrcmpi( "WINNT", szProductType) == 0 ) { strncat(ret, "Workstation ", ret_size - 1); } else if (lstrcmpi( "LANMANNT", szProductType) == 0 ) { strncat(ret, "Server ", ret_size - 1); } else if (lstrcmpi( "SERVERNT", szProductType) == 0 ) { strncat(ret, "Advanced Server " , ret_size - 1); } ret_size -= strlen(ret) + 1; memset(__wv, '\0', 32); snprintf(__wv, 31, "%d.%d ", (int)osvi.dwMajorVersion, (int)osvi.dwMinorVersion); strncat(ret, __wv, ret_size - 1); ret_size -= strlen(__wv) + 1; } } } /* Display service pack (if any) and build number */ if ( osvi.dwMajorVersion == 4 && lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 ) { HKEY hKey; LONG lRet; char __wp[64]; memset(__wp, '\0', 64); /* Test for SP6 versus SP6a */ lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009", 0, KEY_QUERY_VALUE, &hKey ); if ( lRet == ERROR_SUCCESS ) snprintf(__wp, 63, "Service Pack 6a (Build %d)", (int)osvi.dwBuildNumber & 0xFFFF ); else { /* Windows NT 4.0 prior to SP6a */ snprintf(__wp, 63, "%s (Build %d)", osvi.szCSDVersion, (int)osvi.dwBuildNumber & 0xFFFF); } strncat(ret, __wp, ret_size - 1); ret_size -= strlen(__wp) + 1; RegCloseKey( hKey ); } else { char __wp[64]; memset(__wp, '\0', 64); snprintf(__wp, 63, "%s (Build %d)", osvi.szCSDVersion, (int)osvi.dwBuildNumber & 0xFFFF); strncat(ret, __wp, ret_size - 1); ret_size -= strlen(__wp) + 1; } break; /* Test for Windows Me/98/95 */ case VER_PLATFORM_WIN32_WINDOWS: if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { strncat(ret, "Microsoft Windows 95 ", ret_size - 1); ret_size -= strlen(ret) + 1; } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { strncat(ret, "Microsoft Windows 98 ", ret_size - 1); ret_size -= strlen(ret) + 1; } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { strncat(ret, "Microsoft Windows Millennium Edition", ret_size - 1); ret_size -= strlen(ret) + 1; } break; case VER_PLATFORM_WIN32s: strncat(ret, "Microsoft Win32s", ret_size - 1); ret_size -= strlen(ret) + 1; break; } /* Add OSSEC-HIDS version */ snprintf(os_v, 128, " - %s %s", __ossec_name, __version); strncat(ret, os_v, ret_size - 1); return (ret); }
static int __cdecl GroupSortProc(const struct ClcContact *contact1,const struct ClcContact *contact2) { return lstrcmpi(contact1->szText,contact2->szText); }
void LoadAllPreferences(BOOL fMemOnly) /************************************************************************/ { LPSTR lp; int i, English, Didot; STRING tmp; if (fMemOnly) // memory related info only { // Memory Group Preferences GetDefStr( Control.RamDisk, Control.ProgHome ); FixPath( Lowercase( Control.RamDisk ) ); GetDefInt( Control.MainMemMin, 1024 ); GetDefInt( Control.MainMemFactor, 100 ); if ( Control.MainMemFactor < 10 ) Control.MainMemFactor = 10; if ( Control.MainMemFactor > 100 ) Control.MainMemFactor = 100; GetDefInt( Control.LineArtAsGray, NO ); FrameSettings( Control.RamDisk, Control.MainMemMin, Control.MainMemFactor); // Get Gamma settings GetDefFix( BltSettings.RGamma, 1 ); GetDefFix( BltSettings.GGamma, 1 ); GetDefFix( BltSettings.BGamma, 1 ); return; } AstralCursor( IDC_WAIT ); if ( !szPreferenceFile[0] ) { if ( !AstralStr( IDS_INIFILE, &lp ) ) lp = PRIVATE_INI; lstrcpy( szPreferenceFile, lp ); GetIniPath( szPreferenceFile ); } // Recall List Control.RecallCount = 0; for ( i=0; i<MAX_RECALL; i++ ) { GetDefaultString( itoa(i,tmp,10), "", Control.RecallImage[i], sizeof(Control.RecallImage[i]) ); if ( *Control.RecallImage[i] ) Control.RecallCount++; } // Undo Group Preferences GetDefInt( Control.NoUndo, FALSE ); GetDefInt( Control.UseApply, NO ); GetDefInt( Control.UndoObjects, NO ); GetDefInt( Control.UndoMasks, NO ); // Miscellaneous Group Preferences #ifdef _MAC lstrcpy(Control.PouchPath, ":files:"); #else GetDefStr( Control.PouchPath, Control.ProgHome ); if ( Control.PouchPath[1] != ':' ) { lstrcpy( tmp, Control.ProgHome ); lstrcat( tmp, Control.PouchPath ); lstrcpy( Control.PouchPath, tmp ); } FixPath( Lowercase( Control.PouchPath ) ); #endif // _MAC GetDefInt( Control.UseWacom, 0 ); GetDefInt( Control.MaskTint, 0 ); // Red GetDefInt( Control.IndependentSettings, YES ); GetDefInt( Control.bNoTheme, NO ); #ifdef USEWAVEMIX GetDefInt( Control.bUseWaveMix, YES ); #endif // USEWAVEMIX GetPrivateProfileString( "Drivers", "Wave", "none", tmp, sizeof(STRING), "system.ini"); // if they have no wave driver or the speaker.drv installed, disable // using the wavemix.dll #ifdef USEWAVEMIX if ( (! lstrcmpi( tmp, "none")) || (! lstrcmpi( tmp, "Speaker.drv")) || (! lstrcmpi( tmp, "")) ) Control.bUseWaveMix = NO; #endif // USEWAVEMIX GetDefInt( Control.iAdventBrush, BRUSH_SIZE_MEDIUM ); GetDefInt( Control.iMaxAnimations, 10 ); GetDefInt( Control.iScrnSaverTime, 2 ); IntermissionSetTimeout ((DWORD)Control.iScrnSaverTime * 60000); // Units Group Preferences English = GetProfileInt( "intl", "iMeasure", 1 ); // 1 = English if ( GetDefInt( Didot, -1 ) >= 0 ) // If Didot is overridden... Control.Points = ( !Didot ? 723 : 676 ); else Control.Points = ( English ? 723 : 676 ); GetDefInt( Control.Units, !English ); Control.Units += IDC_PREF_UNITINCHES; GetDefFix( Control.ScreenWidth, 9 ); GetDefInt( View.UseRulers, NO ); GetDefInt( Control.DisplayPixelValue, NO ); // Object Group Preferences GetDefInt( Control.MultipleObjects, YES ); GetDefInt( Control.UseMaskAndObjects, YES ); // New Dialog GetDefInt( Control.NewDepth, 3 ); GetDefInt( Control.NewWidth, 480 ); GetDefInt( Control.NewHeight, 360 ); GetDefInt( Control.NewResolution, 50 ); // Monitor Gamma Dialog GetDefInt( Control.GammaLock, NO ); // Save file options GetDefInt( Save.bSaveMask, NO ); GetDefInt( Save.OKtoSavePath, NO ); GetDefInt( Save.Compressed, YES ); // Clipboard settings GetDefInt( Control.DoPicture, NO ); GetDefInt( Control.DoBitmap, YES ); // Miscellaneous GetDefInt( Control.ScreenColor, NO ); GetDefRGB( Control.rgbBackground, "0,0,0" ); GetDefInt( Control.xImage, 4 ); GetDefInt( Control.yImage, 4 ); GetDefInt( Control.Hints, YES ); GetDefInt( Control.Save24BitWallpaper, FALSE); GetDefInt( Control.UseObjectMarquee, NO ); // Extended Names GetDefStr( Names.ColorMap, "" ); GetDefStr( Names.Special, "" ); GetDefStr( Names.Mask, "" ); GetDefStr( Names.Printer, "" ); GetDefStr( Names.PrintStyle, "" ); GetDefStr( Names.Clipboard, "" ); GetDefStr( Names.CustomBrush, "" ); // Print Style LoadPrintStyle( Names.PrintStyle ); // Print Dialog GetDefInt( Page.Type, 1 ); Page.Type += IDC_PRINTER_IS_MONO; GetDefInt( Page.PrintNumeric, NO ); GetDefInt( Page.OutputType, 0 ); Page.OutputType += IDC_PRINT_GRAY; GetDefInt( Page.ScatterPrint, NO ); GetDefInt( Page.Centered, YES ); GetDefFix( Page.OffsetX, 0 ); GetDefFix( Page.OffsetY, 0 ); GetDefInt( Page.SepFlags, 0 ); GetDefInt( Page.TrimMarks, NO ); GetDefInt( Page.RegMarks, NO ); GetDefInt( Page.Labels, NO ); GetDefInt( Page.StepScale, NO ); GetDefInt( Page.Negative, NO ); GetDefInt( Page.EmulsionDown, NO ); GetDefInt( Page.BinaryPS, NO ); // Binary Postscript GetDefInt( Page.BinaryEPS, NO ); // Binary Encapsulated Postscript GetDefInt( Page.UsePrinterScreening, YES ); // Size Dialog GetDefInt( Edit.SmartSize, NO ); // Convert settings GetDefInt( Convert.MiniType, 0); Convert.MiniType += IDC_MINI256; GetDefInt( Convert.fOptimize, YES ); GetDefInt( Convert.fScatter, NO ); GetDefInt( Convert.fDither, NO ); // Selector Tool // Mask Transformer Tool GetDefInt( Mask.TransformImage, 1 ); Mask.TransformImage = Mask.TransformImage + IDC_COPYIMAGE; // Object Transformer Tool GetDefInt( Mask.iTransformModes, SHAPE_DEFAULT ); GetDefInt( Mask.PasteQuality, NO ); GetDefInt( Mask.TransMode, 0 ); Mask.TransMode += IDC_TRANSMODEFIRST; GetDefInt( Mask.TransformOpacity, 255 ); Mask.TransformOpacity = bound( Mask.TransformOpacity, 0, 255 ); GetDefMergeMode( Mask.TransformMergeMode, (int)MM_NORMAL ); // Paint Tools HandleBrushSettings( IDC_PAINT, NO ); HandleBrushSettings( IDC_CRAYON, NO ); HandleBrushSettings( IDC_MARKER, NO ); HandleBrushSettings( IDC_LINES, NO ); HandleBrushSettings( IDC_SHAPES, NO ); HandleBrushSettings( IDC_ERASER, NO ); // Gradient Tool GetDefInt( Vignette.Gradient, 0 ); Vignette.Gradient += IDC_VIGLINEAR; GetDefInt( Vignette.RepeatCount, 1 ); GetDefInt( Vignette.SoftTransition, YES ); GetDefInt( Vignette.VigColorModel, 0); GetDefInt( Vignette.VigOpacity, 255 ); GetDefMergeMode( Vignette.VigMergeMode, (int)MM_NORMAL ); GetDefInt( Vignette.Midpoint, 128 ); // Texture Fill Tool GetDefStr( Texture.TextureName, "" ); GetDefInt( Texture.fHorzFlip, NO ); GetDefInt( Texture.fVertFlip, NO ); GetDefInt( Texture.TextureOpacity, 255 ); GetDefMergeMode( Texture.TextureMergeMode, (int)MM_NORMAL ); // Tint Fill Tool GetDefInt( Fill.FillOpacity, 255 ); GetDefMergeMode( Fill.FillMergeMode, (int)MM_NORMAL ); // Magic Fill Tool GetDefInt( Fill.FloodRange, 2 ); GetDefInt( Fill.idFillColorModel, 0); GetDefInt( Fill.FloodOpacity, 255 ); GetDefMergeMode( Fill.FloodMergeMode, (int)MM_NORMAL ); // Custom View Tool GetDefInt( View.ZoomOut, NO ); GetDefInt( View.ZoomWindow, NO ); GetDefInt( View.ZoomDefaultSize, 0x6000); GetDefInt( View.FullScreen, NO ); // Text Tool GetDefInt( Text.nFont, 0 ); GetDefInt( Text.Size, 48 ); GetDefInt( Text.Italic, NO ); GetDefInt( Text.Underline, NO ); GetDefInt( Text.Strikeout, NO ); GetDefInt( Text.Weight, NO ); GetDefInt( Text.AntiAlias, NO ); GetDefInt( Text.AutoFill, YES ); GetDefMergeMode( Text.TextMergeMode, (int)MM_NORMAL ); GetDefInt( Text.TextOpacity, 255 ); // Load Common Tool Settings GetDefInt( Common.Opacity, 255 ); GetDefMergeMode( Common.MergeMode, (int)MM_NORMAL ); GetDefInt( Common.BrushSize, 15 ); SetCommonSettings(); Shields( ON ); LoadFileLocations(); AstralCursor( NULL ); }
int WCMD_dir_sort (const void *a, const void *b) { return (lstrcmpi(((const WIN32_FIND_DATA *)a)->cFileName, ((const WIN32_FIND_DATA *)b)->cFileName)); }
void ConEmuUpdateSettings::ResetToDefaults() { // Указатели должны быть освобождены перед вызовом _ASSERTE(szUpdateExeCmdLine==NULL); szUpdateVerLocation = NULL; isUpdateCheckOnStartup = false; isUpdateCheckHourly = false; isUpdateConfirmDownload = true; // true-Show MessageBox, false-notify via TSA only isUpdateUseBuilds = 0; // 0-спросить пользователя при первом запуске, 1-stable only, 2-latest, 3-preview isUpdateUseProxy = false; szUpdateProxy = szUpdateProxyUser = szUpdateProxyPassword = NULL; // "Server:port" // Проверяем, была ли программа установлена через ConEmuSetup.exe? isUpdateDownloadSetup = 0; // 0-Auto, 1-Installer (ConEmuSetup.exe), 2-7z archieve (ConEmu.7z), WinRar or 7z required isSetupDetected = 0; // 0-пока не проверялся, 1-установлено через Installer, пути совпали, 2-Installer не запускался szUpdateExeCmdLineDef = lstrdup(L"\"%1\" /p:%3 /qr"); SafeFree(szUpdateExeCmdLine); bool bWinRar = false; wchar_t* pszArcPath = NULL; BOOL bWin64 = IsWindows64(); for (int i = 0; !(pszArcPath && *pszArcPath) && (i <= 5); i++) { SettingsRegistry regArc; switch (i) { case 0: if (regArc.OpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\7-Zip", KEY_READ|(bWin64?KEY_WOW64_32KEY:0))) { regArc.Load(L"Path", &pszArcPath); } break; case 1: if (bWin64 && regArc.OpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\7-Zip", KEY_READ|KEY_WOW64_64KEY)) { regArc.Load(L"Path", &pszArcPath); } break; case 2: if (regArc.OpenKey(HKEY_CURRENT_USER, L"SOFTWARE\\7-Zip", KEY_READ)) { regArc.Load(L"Path", &pszArcPath); } break; case 3: if (regArc.OpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\WinRAR", KEY_READ|(bWin64?KEY_WOW64_32KEY:0))) { bWinRar = true; regArc.Load(L"exe32", &pszArcPath); } break; case 4: if (bWin64 && regArc.OpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\WinRAR", KEY_READ|KEY_WOW64_64KEY)) { bWinRar = true; regArc.Load(L"exe64", &pszArcPath); } break; case 5: if (regArc.OpenKey(HKEY_CURRENT_USER, L"SOFTWARE\\WinRAR", KEY_READ)) { bWinRar = true; if (!regArc.Load(L"exe32", &pszArcPath) && bWin64) { regArc.Load(L"exe64", &pszArcPath); } } break; } } if (!pszArcPath || !*pszArcPath) { szUpdateArcCmdLineDef = lstrdup(L"\"%ProgramFiles%\\7-Zip\\7zg.exe\" x -y \"%1\""); // "%1"-archive file, "%2"-ConEmu base dir } else { LPCWSTR pszExt = PointToExt(pszArcPath); int cchMax = lstrlen(pszArcPath)+64; szUpdateArcCmdLineDef = (wchar_t*)malloc(cchMax*sizeof(wchar_t)); if (szUpdateArcCmdLineDef) { if (pszExt && lstrcmpi(pszExt, L".exe") == 0) { _ASSERTE(bWinRar==true); //Issue 537: old WinRAR beta's fails //_wsprintf(szUpdateArcCmdLineDef, SKIPLEN(cchMax) L"\"%s\" x -y \"%%1\"%s", pszArcPath, bWinRar ? L" \"%%2\\\"" : L""); _wsprintf(szUpdateArcCmdLineDef, SKIPLEN(cchMax) L"\"%s\" x -y \"%%1\"", pszArcPath); } else { _ASSERTE(bWinRar==false); int nLen = lstrlen(pszArcPath); bool bNeedSlash = (*pszArcPath && (pszArcPath[nLen-1] != L'\\')) ? true : false; _wsprintf(szUpdateArcCmdLineDef, SKIPLEN(cchMax) L"\"%s%s7zg.exe\" x -y \"%%1\"", pszArcPath, bNeedSlash ? L"\\" : L""); } } } SafeFree(pszArcPath); SafeFree(szUpdateArcCmdLine); szUpdateDownloadPath = lstrdup(L"%TEMP%\\ConEmu"); isUpdateLeavePackages = false; szUpdatePostUpdateCmd = lstrdup(L"echo Last successful update>ConEmuUpdate.info && date /t>>ConEmuUpdate.info && time /t>>ConEmuUpdate.info"); // Юзер может чего-то свое делать с распакованными файлами }
bool InitDefTerm() { bool lbRc = true; wchar_t szInfo[MAX_PATH*2]; msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, InitDefaultTerm\n", GetCurrentThreadId()); DebugStr(szInfo); // Don't call DefTermLogString here - gpDefTerm was not initialized yet _ASSERTEX(gpDefTerm==NULL); gpDefTerm = new CDefTermHk(); if (!gpDefTerm) { _ASSERTEX(gpDefTerm!=NULL); return false; } //_ASSERTE(FALSE && "InitDefaultTerm"); // При обновлении ConEmu может обновиться и ConEmuHk.dll // Но в процессы с "DefTerm" грузится копия dll-ки, поэтому // после обновления в уже хукнутый процесс загружается // вторая "ConEmuHk.YYMMDD.dll", а старую при этом нужно // выгрузить. Этим и займемся. HMODULE hPrevHooks = NULL; _ASSERTEX(gnSelfPID!=0 && ghOurModule!=NULL); HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, gnSelfPID); if (hSnap != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; //wchar_t szOurName[MAX_PATH] = L""; //GetModuleFileName(ghOurModule, szOurName, MAX_PATH); wchar_t szMinor[8] = L""; lstrcpyn(szMinor, WSTRING(MVV_4a), countof(szMinor)); wchar_t szAddName[40]; msprintf(szAddName, countof(szAddName), CEDEFTERMDLLFORMAT /*L"ConEmuHk%s.%02u%02u%02u%s.dll"*/, WIN3264TEST(L"",L"64"), MVV_1, MVV_2, MVV_3, szMinor); //LPCWSTR pszOurName = PointToName(szOurName); wchar_t* pszDot = wcschr(szAddName, L'.'); wchar_t szCheckName[MAX_PATH+1]; if (pszDot && Module32First(hSnap, &mi)) { pszDot[1] = 0; // Need to check only name, without version number int nCurLen = lstrlen(szAddName); do { if (mi.hModule == ghOurModule) continue; lstrcpyn(szCheckName, PointToName(mi.szExePath), nCurLen+1); if (lstrcmpi(szCheckName, szAddName) == 0) { msprintf(szInfo, countof(szInfo), L"Prevous ConEmuHk module found at address " WIN3264TEST(L"0x%08X",L"0x%X%08X") L": %s", WIN3264WSPRINT(mi.hModule), mi.szExePath); DefTermLogString(szInfo); hPrevHooks = mi.hModule; break; // Prev (old version) instance found! } } while (Module32Next(hSnap, &mi)); } CloseHandle(hSnap); } // Old library was found, unload it before continue if (hPrevHooks) { DefTermLogString(L"Trying to unload previous ConEmuHk module"); if (!FreeLibrary(hPrevHooks)) { lbRc = false; gpDefTerm->DisplayLastError(L"Unloading failed", GetLastError()); } else { DefTermLogString(L"Unloading succeeded"); } } // For Visual Studio check all spawned processes (children of gnSelfPID), find *.vshost.exe if (gbIsVStudio) { //_ASSERTEX(FALSE && "Continue to find existing *.vshost.exe"); HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap != INVALID_HANDLE_VALUE) { PROCESSENTRY32 pe = {sizeof(pe)}; if (Process32First(hSnap, &pe)) do { if (pe.th32ParentProcessID == gnSelfPID) { if (IsVsNetHostExe(pe.szExeFile)) // *.vshost.exe { // Found! Hook it! DefTermLogString(L"Child VsNetHost found, hooking"); gpDefTerm->StartDefTermHooker(pe.th32ProcessID); break; } } } while (Process32Next(hSnap, &pe)); CloseHandle(hSnap); } } DefTermLogString(L"InitDefaultTerm finished, calling StartDefTerm"); gpDefTerm->StartDefTerm(); return lbRc; }
void CI8DeskSvr::RegDNAService() { m_pLogger->WriteLog(LM_INFO, TEXT("Start Check DNAService.")); TCHAR path[MAX_PATH] = {0}; GetModuleFileName(NULL, path, MAX_PATH); PathRemoveFileSpec(path); PathAddBackslash(path); lstrcat(path, TEXT("DNAService\\DNAService.exe")); stdex::tString szDNAService(path); szDNAService.insert(0, TEXT("\"")); szDNAService += TEXT("\""); std::pair<stdex::tString, bool> cmd[] = { std::make_pair(TEXT("-UnRegServer"), true), std::make_pair(TEXT("-RegServer"), true), std::make_pair(TEXT("-Service"), true), }; if (!IsService()) { cmd[2].second = false; } else { utility::CAutoService schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager.IsValid()) { utility::CAutoService schService = OpenService(schSCManager, TEXT("DNAS"), SERVICE_ALL_ACCESS); if (schService.IsValid()) { char buf[4096] = {0}; LPQUERY_SERVICE_CONFIG lpConfig = reinterpret_cast<LPQUERY_SERVICE_CONFIG>(buf); DWORD dwSize = sizeof(buf); DWORD dwNeedSize = 0; QueryServiceConfig(schService, lpConfig, dwSize, &dwNeedSize); if (lstrcmpi(lpConfig->lpBinaryPathName, szDNAService.c_str()) == 0) { m_pLogger->WriteLog(LM_INFO, TEXT("Registry DNAService Success.")); return ; } } } } for (int idx=0; idx<_countof(cmd);idx++) { if (!cmd[idx].second) continue; TCHAR line[1024] = {0}; _stprintf(line, TEXT("%s %s"), szDNAService.c_str(), cmd[idx].first.c_str()); STARTUPINFO si = {sizeof(si)}; PROCESS_INFORMATION pi = {0}; if (!CreateProcess(NULL, line, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { DWORD dwError = GetLastError(); _com_error Error(dwError); m_pLogger->WriteLog(LM_INFO, TEXT("[%s]:fail:%d:%s"), line, dwError, Error.ErrorMessage()); m_pLogger->WriteLog(LM_INFO, TEXT("Registry DNAService Fail.")); return ; } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } m_pLogger->WriteLog(LM_INFO, TEXT("Registry DNAService Success.")); }
bool CDpiForDialog::SetDialogDPI(const DpiValue& newDpi, LPRECT lprcSuggested /*= NULL*/) { wchar_t szLog[160]; RECT rcClient = {}, rcCurWnd = {}; #ifdef _DEBUG if (gbSkipSetDialogDPI) { GetClientRect(mh_Dlg, &rcClient); GetWindowRect(mh_Dlg, &rcCurWnd); _wsprintf(szLog, SKIPCOUNT(szLog) L"SKIPPED CDpiForDialog::SetDialogDPI x%08X, OldDpi={%i,%i}, NewDpi={%i,%i}, CurSize={%i,%i}, CurClient={%i,%i}", (DWORD)(DWORD_PTR)mh_Dlg, m_CurDpi.Xdpi, m_CurDpi.Ydpi, newDpi.Xdpi, newDpi.Ydpi, (rcCurWnd.right - rcCurWnd.left), (rcCurWnd.bottom - rcCurWnd.top), (rcClient.right - rcClient.left), (rcClient.bottom - rcClient.top)); LogString(szLog); return false; } #endif if (mn_InSet > 0) return false; if (newDpi.Ydpi <= 0 || newDpi.Xdpi <= 0) return false; if (m_CurDpi.Ydpi <= 0 || m_CurDpi.Xdpi <= 0) return false; // When overall DPI is very large but new dpi is small // (example: primary mon is 192 high-dpi, new mon is 96 dpi) // Windows goes crazy... HUGE caption, scrollbars, checkbox marks and so on... // So huge difference makes dialog unattractive, let's try to smooth that DpiValue setDpi(newDpi); if (m_InitDpi.Ydpi > MulDiv(setDpi.Ydpi, 144, 96)) { // Increase DPI one step up setDpi.Ydpi = MulDiv(setDpi.Ydpi, 120, 96); setDpi.Xdpi = MulDiv(setDpi.Xdpi, 120, 96); // Log it _wsprintf(szLog, SKIPCOUNT(szLog) L"CDpiForDialog::SetDialogDPI x%08X forces larger dpi value from {%i,%i} to {%i,%i}", (DWORD)(DWORD_PTR)mh_Dlg, newDpi.Xdpi, newDpi.Ydpi, setDpi.Xdpi, setDpi.Ydpi); LogString(szLog); } if (m_CurDpi.Equals(setDpi)) return false; bool bRc = false; MArray<DlgItem>* p = NULL; DpiValue curDpi(m_CurDpi); HFONT hf = NULL; wchar_t szClass[100]; #ifdef _DEBUG LOGFONT lftest1 = {}, lftest2 = {}; HFONT hftest; int itest1, itest2; #endif // To avoid several nested passes InterlockedIncrement(&mn_InSet); m_CurDpi.SetDpi(setDpi); // Eval mn_CurFontHeight = GetFontSizeForDpi(NULL, m_CurDpi.Ydpi); //(m_CurDpi.Ydpi && m_InitDpi.Ydpi) ? (mn_InitFontHeight * m_CurDpi.Ydpi / m_InitDpi.Ydpi) : -11; mlf_CurFont = mlf_InitFont; mlf_CurFont.lfHeight = mn_CurFontHeight; mlf_CurFont.lfWidth = 0; // Font mapper fault if (mn_CurFontHeight == 0) goto wrap; if (!m_Items.Get(m_CurDpi.Ydpi, &p)) { MArray<DlgItem>* pOrig = NULL; int iOrigDpi = 0; if (!m_Items.GetNext(NULL, &iOrigDpi, &pOrig) || !pOrig || (iOrigDpi <= 0)) goto wrap; int iNewDpi = m_CurDpi.Ydpi; p = new MArray<DlgItem>(); DWORD dwStyle = GetWindowLong(mh_Dlg, GWL_STYLE); DWORD dwStyleEx = GetWindowLong(mh_Dlg, GWL_EXSTYLE); if (!GetClientRect(mh_Dlg, &rcClient) || !GetWindowRect(mh_Dlg, &rcCurWnd)) { delete p; goto wrap; } _ASSERTE(rcClient.left==0 && rcClient.top==0); int calcDlgWidth = rcClient.right * m_CurDpi.Xdpi / curDpi.Xdpi; int calcDlgHeight = rcClient.bottom * m_CurDpi.Ydpi / curDpi.Ydpi; DlgItem i = {mh_Dlg}; // Windows DWM manager do not resize NonClient areas of per-monitor dpi aware applications // So, we can not use AdjustWindowRectEx to determine full window rectangle // Just use current NonClient dimensions i.r.right = calcDlgWidth + ((rcCurWnd.right - rcCurWnd.left) - rcClient.right); i.r.bottom = calcDlgHeight + ((rcCurWnd.bottom - rcCurWnd.top) - rcClient.bottom); // .right and .bottom are width and height of the dialog _ASSERTE(i.r.left==0 && i.r.top==0); p->push_back(i); for (INT_PTR k = 1; k < pOrig->size(); k++) { const DlgItem& iOrig = (*pOrig)[k]; i.h = iOrig.h; i.r.left = iOrig.r.left * iNewDpi / iOrigDpi; i.r.top = iOrig.r.top * iNewDpi / iOrigDpi; i.r.right = iOrig.r.right * iNewDpi / iOrigDpi; i.r.bottom = iOrig.r.bottom * iNewDpi / iOrigDpi; p->push_back(i); } m_Items.Set(iNewDpi, p); } if (p->size() <= 0) { _ASSERTE(FALSE && "No elements"); goto wrap; } else { const DlgItem& di = (*p)[0]; _wsprintf(szLog, SKIPCOUNT(szLog) L"CDpiForDialog::SetDialogDPI x%08X, OldDpi={%i,%i}, NewDpi={%i,%i}, OldSize={%i,%i}, NewSize={%i,%i}, NewFont=%i", (DWORD)(DWORD_PTR)mh_Dlg, curDpi.Xdpi, curDpi.Ydpi, newDpi.Xdpi, newDpi.Ydpi, (rcCurWnd.right - rcCurWnd.left), (rcCurWnd.bottom - rcCurWnd.top), di.r.right, di.r.bottom, mlf_CurFont.lfHeight); LogString(szLog); } hf = CreateFontIndirect(&mlf_CurFont); if (hf == NULL) { goto wrap; } for (INT_PTR k = p->size() - 1; k >= 1; k--) { const DlgItem& di = (*p)[k]; GetClassName(di.h, szClass, countof(szClass)); DWORD nCtrlID = GetWindowLong(di.h, GWL_ID); DWORD nStyles = GetWindowLong(di.h, GWL_STYLE); bool bResizeCombo = (lstrcmpi(szClass, L"ComboBox") == 0); int iComboFieldHeight = 0, iComboWasHeight = 0; LONG_PTR lFieldHeight = 0, lNewHeight = 0; RECT rcCur = {}; HWND hComboEdit = NULL; RECT rcEdit = {}, rcClient = {}; if (bResizeCombo && (nStyles & CBS_OWNERDRAWFIXED)) { GetWindowRect(di.h, &rcCur); hComboEdit = FindWindowEx(di.h, NULL, L"Edit", NULL); GetClientRect(di.h, &rcClient); GetClientRect(hComboEdit, &rcEdit); iComboWasHeight = (rcCur.bottom - rcCur.top); lFieldHeight = SendMessage(di.h, CB_GETITEMHEIGHT, -1, 0); if (lFieldHeight < iComboWasHeight) { iComboFieldHeight = lFieldHeight; } } int newW = di.r.right - di.r.left; int newH = di.r.bottom - di.r.top; MoveWindow(di.h, di.r.left, di.r.top, newW, newH, FALSE); SendMessage(di.h, WM_SETFONT, (WPARAM)hf, FALSE/*immediately*/); if (bResizeCombo) { if ((nStyles & CBS_OWNERDRAWFIXED) && (iComboWasHeight > 0) && (iComboFieldHeight > 0)) { RECT rcEdit2 = {}, rcClient2 = {}; GetClientRect(di.h, &rcClient2); GetClientRect(hComboEdit, &rcEdit2); lNewHeight = newH*iComboFieldHeight/iComboWasHeight; _wsprintf(szLog, SKIPCOUNT(szLog) L"CDpiForDialog::Combo height changed - OldHeight=%i, ItemHeight=%i, NewHeight=%i, NewItemHeight=%i", (rcCur.bottom - rcCur.top), lFieldHeight, newH, lNewHeight); LogString(szLog); SendMessage(di.h, CB_SETITEMHEIGHT, -1, lNewHeight); } SendMessage(di.h, CB_SETEDITSEL, 0, MAKELPARAM(-1,0)); } EditIconHint_ResChanged(di.h); InvalidateRect(di.h, NULL, TRUE); #ifdef _DEBUG itest1 = GetObject(hf, sizeof(lftest1), &lftest1); hftest = (HFONT)SendMessage(di.h, WM_GETFONT, 0, 0); itest2 = GetObject(hftest, sizeof(lftest2), &lftest2); #endif } if (p->size() > 0) { const DlgItem& di = (*p)[0]; SendMessage(mh_Dlg, WM_SETFONT, (WPARAM)hf, FALSE); DWORD nWndFlags = SWP_NOZORDER | (lprcSuggested ? 0 : SWP_NOMOVE); SetWindowPos(mh_Dlg, NULL, lprcSuggested ? lprcSuggested->left : 0, lprcSuggested ? lprcSuggested->top : 0, di.r.right, di.r.bottom, nWndFlags); RECT rc = {}; GetClientRect(mh_Dlg, &rc); InvalidateRect(mh_Dlg, NULL, TRUE); RedrawWindow(mh_Dlg, &rc, NULL, /*RDW_ERASE|*/RDW_ALLCHILDREN/*|RDW_INVALIDATE|RDW_UPDATENOW|RDW_INTERNALPAINT*/); } if (mh_CurFont != hf) DeleteObject(mh_CurFont); mh_CurFont = hf; bRc = true; wrap: InterlockedDecrement(&mn_InSet); return bRc; }
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInst,LPTSTR lpszCmdParam, int nCmdShow) { int ret = 0; const TCHAR *m_Err = _LANG_ERRORWRITINGTEMP; int cl_flags = 0; TCHAR *realcmds; TCHAR seekchar=_T(' '); TCHAR *cmdline; InitCommonControls(); SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); #if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT) { extern HRESULT g_hres; g_hres=OleInitialize(NULL); } #endif // load shfolder.dll before any script code is executed to avoid // weird situations where SetOutPath or even the extraction of // shfolder.dll will cause unexpected behavior. // // this also prevents the following: // // SetOutPath "C:\Program Files\NSIS" # maybe read from reg // File shfolder.dll // Delete $PROGRAMFILES\shfolder.dll # can't be deleted, as the // # new shfolder.dll is used // # to find its own path. g_SHGetFolderPath = myGetProcAddress(MGA_SHGetFolderPath); { // workaround for bug #1008632 // http://sourceforge.net/tracker/index.php?func=detail&aid=1008632&group_id=22049&atid=373085 // // without this, SHGetSpecialFolderLocation doesn't always recognize // some special folders, like the desktop folder for all users, on // Windows 9x. unlike SHGetSpecialFolderPath, which is not available // on all versions of Windows, SHGetSpecialFolderLocation doesn't try // too hard to make sure the caller gets what he asked for. so we give // it a little push in the right direction by doing part of the work // for it. // // part of what SHGetFileInfo does, is to convert a path into an idl. // to do this conversion, it first needs to initialize the list of // special idls, which are exactly the idls we use to get the paths // of special folders (CSIDL_*). SHFILEINFO shfi; SHGetFileInfo(_T(""), 0, &shfi, sizeof(SHFILEINFO), 0); } mystrcpy(g_caption,_LANG_GENERIC_ERROR); mystrcpy(state_command_line, GetCommandLine()); #ifdef NSIS_CONFIG_VISIBLE_SUPPORT g_hInstance = GetModuleHandle(NULL); #endif//NSIS_CONFIG_VISIBLE_SUPPORT cmdline = state_command_line; if (*cmdline == _T('\"')) seekchar = *cmdline++; cmdline=findchar(cmdline, seekchar); cmdline=CharNext(cmdline); realcmds=cmdline; while (*cmdline) { // skip over any spaces while (*cmdline == _T(' ')) cmdline++; // get char we should look for to get the next parm seekchar = _T(' '); if (cmdline[0] == _T('\"')) { cmdline++; seekchar = _T('\"'); } // is it a switch? if (cmdline[0] == _T('/')) { cmdline++; // this only works with spaces because they have just one bit on #define END_OF_ARG(c) (((c)|_T(' '))==_T(' ')) #if defined(NSIS_CONFIG_VISIBLE_SUPPORT) && defined(NSIS_CONFIG_SILENT_SUPPORT) if (cmdline[0] == _T('S') && END_OF_ARG(cmdline[1])) cl_flags |= FH_FLAGS_SILENT; #endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT #ifdef NSIS_CONFIG_CRC_SUPPORT if (*(LPDWORD)cmdline == CHAR4_TO_DWORD(_T('N'),_T('C'),_T('R'),_T('C')) && END_OF_ARG(cmdline[4])) cl_flags |= FH_FLAGS_NO_CRC; #endif//NSIS_CONFIG_CRC_SUPPORT if (*(LPDWORD)(cmdline-2) == CHAR4_TO_DWORD(_T(' '), _T('/'), _T('D'),_T('='))) { *(LPDWORD)(cmdline-2)=0; // keep this from being passed to uninstaller if necessary mystrcpy(state_install_directory,cmdline+2); break; // /D= must always be last } } // skip over our parm cmdline = findchar(cmdline, seekchar); // skip the quote if (*cmdline == _T('\"')) cmdline++; } GetTempPath(NSIS_MAX_STRLEN, state_temp_dir); if (!ValidateTempDir()) { GetWindowsDirectory(state_temp_dir, NSIS_MAX_STRLEN - 5); // leave space for \Temp mystrcat(state_temp_dir, _T("\\Temp")); if (!ValidateTempDir()) { goto end; } } DeleteFile(state_language); m_Err = loadHeaders(cl_flags); if (m_Err) goto end; #ifdef NSIS_CONFIG_UNINSTALL_SUPPORT if (g_is_uninstaller) { TCHAR *p = findchar(state_command_line, 0); // state_command_line has state_install_directory right after it in memory, so reading // a bit over state_command_line won't do any harm while (p >= state_command_line && *(LPDWORD)p != CHAR4_TO_DWORD(_T(' '), _T('_'), _T('?'), _T('='))) p--; m_Err = _LANG_UNINSTINITERROR; if (p >= state_command_line) { *p=0; // terminate before "_?=" p+=4; // skip over " _?=" if (is_valid_instpath(p)) { mystrcpy(state_install_directory, p); mystrcpy(state_output_directory, p); m_Err = 0; } else { goto end; } } else { int x; mystrcat(state_temp_dir,_T("~nsu.tmp")); // check if already running from uninstaller temp dir // this prevents recursive uninstaller calls if (!lstrcmpi(state_temp_dir,state_exe_directory)) goto end; CreateDirectory(state_temp_dir,NULL); SetCurrentDirectory(state_temp_dir); if (!state_install_directory[0]) mystrcpy(state_install_directory,state_exe_directory); mystrcpy(g_usrvars[0], realcmds); *(LPWORD)g_usrvars[1] = CHAR2_TO_WORD(_T('A'),0); for (x = 0; x < 26; x ++) { static TCHAR buf2[NSIS_MAX_STRLEN]; GetNSISString(buf2,g_header->str_uninstchild); // $TEMP\$1u_.exe DeleteFile(buf2); // clean up after all the other ones if they are there if (m_Err) // not done yet { // copy file if (CopyFile(state_exe_path,buf2,TRUE)) { HANDLE hProc; #ifdef NSIS_SUPPORT_MOVEONREBOOT MoveFileOnReboot(buf2,NULL); #endif GetNSISString(buf2,g_header->str_uninstcmd); // '"$TEMP\$1u_.exe" $0 _?=$INSTDIR\' hProc=myCreateProcess(buf2); if (hProc) { CloseHandle(hProc); // success m_Err = 0; } } } g_usrvars[1][0]++; } #ifdef NSIS_SUPPORT_MOVEONREBOOT MoveFileOnReboot(state_temp_dir,NULL); #endif goto end; } } #endif//NSIS_CONFIG_UNINSTALL_SUPPORT g_exec_flags.errlvl = -1; ret = ui_doinstall(); #ifdef NSIS_CONFIG_LOG #if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT) log_write(1); #endif//!NSIS_CONFIG_LOG_ODS && !NSIS_CONFIG_LOG_STDOUT #endif//NSIS_CONFIG_LOG end: CleanUp(); #if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT) OleUninitialize(); #endif if (m_Err) { my_MessageBox(m_Err, MB_OK | MB_ICONSTOP | (IDOK << 21)); ExitProcess(2); return 0; } #ifdef NSIS_SUPPORT_REBOOT if (g_exec_flags.reboot_called) { BOOL (WINAPI *OPT)(HANDLE, DWORD,PHANDLE); BOOL (WINAPI *LPV)(LPCTSTR,LPCTSTR,PLUID); BOOL (WINAPI *ATP)(HANDLE,BOOL,PTOKEN_PRIVILEGES,DWORD,PTOKEN_PRIVILEGES,PDWORD); OPT=myGetProcAddress(MGA_OpenProcessToken); LPV=myGetProcAddress(MGA_LookupPrivilegeValue); ATP=myGetProcAddress(MGA_AdjustTokenPrivileges); if (OPT && LPV && ATP) { HANDLE hToken; TOKEN_PRIVILEGES tkp; if (OPT(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { LPV(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; ATP(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); } } if (!ExitWindowsEx(EWX_REBOOT,0)) ExecuteCallbackFunction(CB_ONREBOOTFAILED); } #endif//NSIS_SUPPORT_REBOOT if (g_exec_flags.errlvl != -1) ret = g_exec_flags.errlvl; ExitProcess(ret); return 0; }
LPCTSTR CConEmuStart::GetCmd(bool *pIsCmdList, bool bNoTask /*= false*/) { LPCWSTR pszCmd = NULL; // true - если передали "скрипт" (как бы содержимое Task вытянутое в строку) // например: "ConEmu.exe -cmdlist cmd ||| powershell ||| far" if (pIsCmdList) *pIsCmdList = false; // User've choosed default task? if (mp_ConEmu->mn_StartupFinished >= CConEmuMain::ss_Started) { if ((pszCmd = GetDefaultTask()) != NULL) return pszCmd; } // Current command line, specified with "/cmd" or "/cmdlist" switches if ((pszCmd = GetCurCmd(pIsCmdList)) != NULL) return pszCmd; switch (gpSet->nStartType) { case 0: if (gpSet->psStartSingleApp && *gpSet->psStartSingleApp) return gpSet->psStartSingleApp; break; case 1: if (bNoTask) return NULL; if (gpSet->psStartTasksFile && *gpSet->psStartTasksFile) return gpSet->psStartTasksFile; break; case 2: if (bNoTask) return NULL; if (gpSet->psStartTasksName && *gpSet->psStartTasksName) return gpSet->psStartTasksName; break; case 3: if (bNoTask) return NULL; return AutoStartTaskName; } // User've choosed default task? if (mp_ConEmu->mn_StartupFinished < CConEmuMain::ss_Started) { if ((pszCmd = GetDefaultTask()) != NULL) return pszCmd; } wchar_t* pszNewCmd = NULL; // Хорошо бы более корректно определить версию фара, но это не всегда просто // Например x64 файл сложно обработать в x86 ConEmu. DWORD nFarSize = 0; if (lstrcmpi(GetDefaultCmd(), L"far") == 0) { // Ищем фар. (1) В папке ConEmu, (2) в текущей директории, (2) на уровень вверх от папки ConEmu wchar_t szFar[MAX_PATH*2], *pszSlash; szFar[0] = L'"'; wcscpy_add(1, szFar, gpConEmu->ms_ConEmuExeDir); // Теперь szFar содержит путь запуска программы pszSlash = szFar + _tcslen(szFar); _ASSERTE(pszSlash > szFar); BOOL lbFound = FALSE; // (1) В папке ConEmu if (!lbFound) { wcscpy_add(pszSlash, szFar, L"\\Far.exe"); if (FileExists(szFar+1, &nFarSize)) lbFound = TRUE; } // (2) в текущей директории if (!lbFound && lstrcmpi(gpConEmu->WorkDir(), gpConEmu->ms_ConEmuExeDir)) { szFar[0] = L'"'; wcscpy_add(1, szFar, gpConEmu->WorkDir()); wcscat_add(1, szFar, L"\\Far.exe"); if (FileExists(szFar+1, &nFarSize)) lbFound = TRUE; } // (3) на уровень вверх if (!lbFound) { szFar[0] = L'"'; wcscpy_add(1, szFar, gpConEmu->ms_ConEmuExeDir); pszSlash = szFar + _tcslen(szFar); *pszSlash = 0; pszSlash = wcsrchr(szFar, L'\\'); if (pszSlash) { wcscpy_add(pszSlash+1, szFar, L"Far.exe"); if (FileExists(szFar+1, &nFarSize)) lbFound = TRUE; } } if (lbFound) { // 110124 - нафиг, если пользователю надо - сам или параметр настроит, или реестр //// far чаще всего будет установлен в "Program Files", поэтому для избежания проблем - окавычиваем //// Пока тупо - если far.exe > 1200K - считаем, что это Far2 //wcscat_c(szFar, (nFarSize>1228800) ? L"\" /w" : L"\""); wcscat_c(szFar, L"\""); // Finally - Result pszNewCmd = lstrdup(szFar); } else { // Если Far.exe не найден рядом с ConEmu - запустить cmd.exe pszNewCmd = GetComspec(&gpSet->ComSpec); //wcscpy_c(szFar, L"cmd"); } } else { // Simple Copy pszNewCmd = lstrdup(GetDefaultCmd()); } SetCurCmd(pszNewCmd, false); return GetCurCmd(pIsCmdList); }
/*++ Routine Description: This routine checks if any device, live or phantom, is using this INF file, and logs if they are. Arguments: InfFullPath - supplies the full path of the INF. Return Value: TRUE if any device is still using this INF, FALSE if no devices are using this INF. --*/ BOOL WINAPI pAnyDeviceUsingInf( IN LPCTSTR szInfFullPath) { // // If we are passed a NULL InfFullPath or an empty string then just // return FALSE since nobody is using this. // if (!szInfFullPath || (szInfFullPath[0] == TEXT('\0'))) { return FALSE; } PTSTR pInfFile; pInfFile = (PTSTR) pGetFilePart(szInfFullPath); XTL::AutoHDevInfo DeviceInfoSet = ::SetupDiGetClassDevs( NULL, NULL, NULL, DIGCF_ALLCLASSES); if (INVALID_HANDLE_VALUE == DeviceInfoSet) { return FALSE; } TCHAR CurrentDeviceInfFile[MAX_PATH]; TCHAR DeviceId[MAX_DEVICE_ID_LEN]; DWORD dwIndex = 0; SP_DEVINFO_DATA DeviceInfoData; DeviceInfoData.cbSize = sizeof(DeviceInfoData); DWORD Err = ERROR_SUCCESS; while (TRUE) { BOOL fSuccess = ::SetupDiEnumDeviceInfo( DeviceInfoSet, dwIndex++, &DeviceInfoData); if (!fSuccess) { break; } // // Open the 'driver' key for this device. // XTL::AutoKeyHandle hKey = ::SetupDiOpenDevRegKey( DeviceInfoSet, &DeviceInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DRV, KEY_READ); if (INVALID_HANDLE_VALUE == hKey) { continue; } DWORD cbSize = sizeof(CurrentDeviceInfFile); DWORD dwType = REG_SZ; LONG lRet = RegQueryValueEx(hKey, INFPATH_VALUE_NAME, NULL, &dwType, (LPBYTE)CurrentDeviceInfFile, &cbSize); if (ERROR_SUCCESS == lRet && 0 == lstrcmpi(CurrentDeviceInfFile, pInfFile)) { // // This key is using this INF file so the INF can't be // deleted. // Err = ERROR_SHARING_VIOLATION; ::SetLastError(Err); } } return (Err != ERROR_SUCCESS); }
void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/) { if (!pOpt) { _ASSERTE(pOpt!=NULL); return; } if (pOpt->isUpdateEnv && (pOpt->csType != cst_EnvVar)) { //if (pOpt->csType == cst_AutoTccCmd) -- always, if isUpdateEnv { LPCWSTR pszNew = NULL; switch (pOpt->csBits) { case csb_SameOS: pszNew = IsWindows64() ? pOpt->Comspec64 : pOpt->Comspec32; break; case csb_SameApp: pszNew = WIN3264TEST(pOpt->Comspec32,pOpt->Comspec64); break; case csb_x32: pszNew = pOpt->Comspec32; break; default: _ASSERTE(pOpt->csBits==csb_SameOS || pOpt->csBits==csb_SameApp || pOpt->csBits==csb_x32); pszNew = NULL; } if (pszNew && *pszNew) { #ifdef SHOW_COMSPEC_CHANGE wchar_t szCurrent[MAX_PATH]; GetEnvironmentVariable(L"ComSpec", szCurrent, countof(szCurrent)); if (lstrcmpi(szCurrent, pszNew)) { wchar_t szMsg[MAX_PATH*4], szProc[MAX_PATH] = {}, szPid[MAX_PATH]; GetModuleFileName(NULL, szProc, countof(szProc)); _wsprintf(szPid, SKIPLEN(countof(szPid)) L"PID=%u, '%s'", GetCurrentProcessId(), PointToName(szProc)); _wsprintf(szMsg, SKIPLEN(countof(szMsg)) L"Changing %%ComSpec%% in %s\nCur=%s\nNew=%s", szPid , szCurrent, pszNew); MessageBox(NULL, szMsg, szPid, MB_SYSTEMMODAL); } #endif _ASSERTE(wcschr(pszNew, L'%')==NULL); SetEnvVarExpanded(L"ComSpec", pszNew); } } } if (pOpt->AddConEmu2Path && !DontModifyPath) { if ((pOpt->ConEmuBaseDir[0] == 0) || (pOpt->ConEmuExeDir[0] == 0)) { _ASSERTE(pOpt->ConEmuBaseDir[0] != 0); _ASSERTE(pOpt->ConEmuExeDir[0] != 0); } else { wchar_t* pszCur = GetEnvVar(L"PATH"); if (!pszCur) pszCur = lstrdup(L""); DWORD n = lstrlen(pszCur); wchar_t* pszUpr = lstrdup(pszCur); wchar_t* pszDirUpr = (wchar_t*)malloc(MAX_PATH*sizeof(*pszCur)); MCHKHEAP; if (!pszUpr || !pszDirUpr) { _ASSERTE(pszUpr && pszDirUpr); } else { bool bChanged = false; wchar_t* pszAdd = NULL; CharUpperBuff(pszUpr, n); for (int i = 0; i <= 1; i++) { // Put '%ConEmuExeDir' on first place switch (i) { case 1: if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuExeDir)) continue; pszAdd = pOpt->ConEmuExeDir; break; case 0: if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuBaseDir)) continue; if (lstrcmp(pOpt->ConEmuExeDir, pOpt->ConEmuBaseDir) == 0) continue; // второй раз ту же директорию не добавляем pszAdd = pOpt->ConEmuBaseDir; break; } int nDirLen = lstrlen(pszAdd); lstrcpyn(pszDirUpr, pszAdd, MAX_PATH); CharUpperBuff(pszDirUpr, nDirLen); MCHKHEAP; // Need to find exact match! bool bFound = false; LPCWSTR pszFind = wcsstr(pszUpr, pszDirUpr); while (pszFind) { if (pszFind[nDirLen] == L';' || pszFind[nDirLen] == 0) { // OK, found bFound = true; break; } // Next try (may be partial match of subdirs...) pszFind = wcsstr(pszFind+nDirLen, pszDirUpr); } if (!bFound) { wchar_t* pszNew = lstrmerge(pszAdd, L";", pszCur); if (!pszNew) { _ASSERTE(pszNew && "Failed to reallocate PATH variable"); break; } MCHKHEAP; SafeFree(pszCur); pszCur = pszNew; bChanged = true; // Set flag, check next dir } } MCHKHEAP; if (bChanged) { SetEnvironmentVariable(L"PATH", pszCur); } } MCHKHEAP; SafeFree(pszUpr); SafeFree(pszDirUpr); MCHKHEAP; SafeFree(pszCur); } } }