bool wchar_str_ci_less::operator()(const wchar_t *string1, const wchar_t *string2) const { return _wcsicmp(string1, string2) < 0; }
bool Browser::IsDocumentNavigating(IHTMLDocument2* doc) { LOG(TRACE) << "Entering Browser::IsDocumentNavigating"; bool is_navigating = true; // Starting WaitForDocumentComplete() is_navigating = this->is_navigation_started_; CComBSTR ready_state; HRESULT hr = doc->get_readyState(&ready_state); if (FAILED(hr) || is_navigating || _wcsicmp(ready_state, L"complete") != 0) { LOG(DEBUG) << "readyState is not complete. "; return true; } else { is_navigating = false; } // document.readyState == complete is_navigating = this->is_navigation_started_; CComPtr<IHTMLFramesCollection2> frames; hr = doc->get_frames(&frames); if (is_navigating || FAILED(hr)) { LOG(DEBUG) << "Could not get frames, navigation has started or call to IHTMLDocument2::get_frames failed"; return true; } if (frames != NULL) { long frame_count = 0; hr = frames->get_length(&frame_count); CComVariant index; index.vt = VT_I4; for (long i = 0; i < frame_count; ++i) { // Waiting on each frame index.lVal = i; CComVariant result; hr = frames->item(&index, &result); if (FAILED(hr)) { LOGHR(DEBUG, hr) << "Could not get frame item for index " << i << ", call to IHTMLFramesCollection2::item failed"; return true; } CComQIPtr<IHTMLWindow2> window(result.pdispVal); if (!window) { // Frame is not an HTML frame. continue; } CComPtr<IHTMLDocument2> frame_document; bool is_valid_frame_document = this->GetDocumentFromWindow(window, &frame_document); is_navigating = this->is_navigation_started_; if (is_navigating) { break; } // Recursively call to wait for the frame document to complete if (is_valid_frame_document) { is_navigating = this->IsDocumentNavigating(frame_document); if (is_navigating) { break; } } } } else { LOG(DEBUG) << "IHTMLDocument2.get_frames() returned empty collection"; } return is_navigating; }
HRESULT get_specific_device(LPCWSTR szLongName, IMMDevice **ppMMDevice) { HRESULT hr = S_OK; *ppMMDevice = NULL; // get an enumerator IMMDeviceEnumerator *pMMDeviceEnumerator; hr = CoCreateInstance( __uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator ); if (FAILED(hr)) { printf("CoCreateInstance(IMMDeviceEnumerator) failed: hr = 0x%08x\n", hr); return hr; } IMMDeviceCollection *pMMDeviceCollection; // get all the active render endpoints hr = pMMDeviceEnumerator->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &pMMDeviceCollection ); pMMDeviceEnumerator->Release(); if (FAILED(hr)) { printf("IMMDeviceEnumerator::EnumAudioEndpoints failed: hr = 0x%08x\n", hr); return hr; } UINT count; hr = pMMDeviceCollection->GetCount(&count); if (FAILED(hr)) { pMMDeviceCollection->Release(); printf("IMMDeviceCollection::GetCount failed: hr = 0x%08x\n", hr); return hr; } for (UINT i = 0; i < count; i++) { IMMDevice *pMMDevice; // get the "n"th device hr = pMMDeviceCollection->Item(i, &pMMDevice); if (FAILED(hr)) { pMMDeviceCollection->Release(); printf("IMMDeviceCollection::Item failed: hr = 0x%08x\n", hr); return hr; } // open the property store on that device IPropertyStore *pPropertyStore; hr = pMMDevice->OpenPropertyStore(STGM_READ, &pPropertyStore); if (FAILED(hr)) { pMMDevice->Release(); pMMDeviceCollection->Release(); printf("IMMDevice::OpenPropertyStore failed: hr = 0x%08x\n", hr); return hr; } // get the long name property PROPVARIANT pv; PropVariantInit(&pv); hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &pv); pPropertyStore->Release(); if (FAILED(hr)) { pMMDevice->Release(); pMMDeviceCollection->Release(); printf("IPropertyStore::GetValue failed: hr = 0x%08x\n", hr); return hr; } if (VT_LPWSTR != pv.vt) { printf("PKEY_Device_FriendlyName variant type is %u - expected VT_LPWSTR", pv.vt); PropVariantClear(&pv); pMMDevice->Release(); pMMDeviceCollection->Release(); return E_UNEXPECTED; } // is it a match? if (0 == _wcsicmp(pv.pwszVal, szLongName)) { // did we already find it? if (NULL == *ppMMDevice) { *ppMMDevice = pMMDevice; pMMDevice->AddRef(); } else { printf("Found (at least) two devices named %ls\n", szLongName); PropVariantClear(&pv); pMMDevice->Release(); pMMDeviceCollection->Release(); return E_UNEXPECTED; } } pMMDevice->Release(); PropVariantClear(&pv); } pMMDeviceCollection->Release(); if (NULL == *ppMMDevice) { printf("Could not find a device named %ls\n", szLongName); return HRESULT_FROM_WIN32(ERROR_NOT_FOUND); } return S_OK; }
// Parse the command line bool CTeslaDecrypterApp::ParseCommandLine(int argc, TCHAR * argv[]) { LPTSTR strOrgFile = NULL; // Original requested file LPTSTR strOrgDir = NULL; // Original requested directoty LPTSTR strKeyFile = NULL; // Specific key file to use LPTSTR strMasterKey = NULL; // The specific master key DWORD dwStrLen = 0; // String size in TCHARs BYTE masterKey[32] = {0}; // Specific master key bool bKeepOriginal = false; // TRUE if the user has specified to keep the original files bool bScanEntirePc = false; // TRUE if I have to scan the entire Pc bool bDeleteDropper = false; // TRUE if I have to automatically search and delete TeslaCrypt dropper bool bRetVal = false; for (int i = 1; i < argc; i++) { LPTSTR arg = argv[i]; LPTSTR param = NULL; param = wcschr(arg, L':'); if (param) { param[0] = 0; param++; } // Check the arg starting chr if (arg[0] == L'/' || arg[0] == L'-') arg++; else return false; if (_wcsicmp(arg, L"help") == 0) { ShowUsage(); return true; } else if (_wcsicmp(arg, L"keeporiginal") == 0) bKeepOriginal = true; else if (_wcsicmp(arg, L"scanentirepc") == 0) bScanEntirePc = true; else if (_wcsicmp(arg, L"deleteteslacrypt") == 0) bDeleteDropper = true; else if (_wcsicmp(arg, L"key") == 0) { if (strMasterKey || strKeyFile) return false; if (!param) return false; strMasterKey = Trim(param); dwStrLen = wcslen(strMasterKey); if (dwStrLen != 64) { cl_wprintf(RED, L"Error! "); wprintf(L"Master key should be 64 characters long."); return true; } LPBYTE lpMasterKey = CTeslaDecrypter::HexToBytes(strMasterKey, dwStrLen); if (lpMasterKey) { RtlCopyMemory(masterKey, lpMasterKey, COUNTOF(masterKey)); delete lpMasterKey; // DO NOT forget to do this } else { cl_wprintf(RED, L"Error! "); wprintf(L"Parsing error! Bad HEX key specified. \r\n"); return true; } } else if (_wcsicmp(arg, L"keyfile") == 0) { if (strKeyFile || strMasterKey) return false; if (!param) return false; strKeyFile = Trim(param, L'\"', L'\"'); dwStrLen = wcslen(strKeyFile); if (!FileExists(strKeyFile)) { cl_wprintf(RED, L"Error! "); wprintf(L"Key file \"%s\" does not exist.", strKeyFile); return true; } } else if (_wcsicmp(arg, L"file") == 0) { if (strOrgFile || strOrgDir) return false; if (!param) return false; strOrgFile = Trim(param, L'\"', L'\"'); if (!FileExists(strOrgFile)) { cl_wprintf(RED, L"Error! "); wprintf(L"File \"%s\" does not exist.\r\n", strOrgFile); return true; } } else if (_wcsicmp(arg, L"dir") == 0) { if (strOrgDir || strOrgFile) return false; if (!param) return false; strOrgDir = Trim(param, L'\"', L'\"'); if (!FileExists(strOrgDir)) { cl_wprintf(RED, L"Error! "); wprintf(L"Directory \"%s\" does not exist.\r\n", strOrgDir); return true; } } else // Unrecognized param return false; } // First import the key file or master key in the decrypter if (strKeyFile) bRetVal = GetDecrypter()->ReadKeyFile(strKeyFile); else if (strMasterKey) bRetVal = GetDecrypter()->SetMasterKey(masterKey); else { // Use the standard research algorithm LPTSTR impKey = SearchAndImportKeyFile(); // The above call modifies the "KeepOriginal" policy, correct this GetDecrypter()->KeepOriginalFiles(bKeepOriginal); // Another non-sense comment: The pen is on the table!!! if (impKey) {delete impKey; bRetVal = true; } } if (!bRetVal) { cl_wprintf(RED, L"\r\nError! "); wprintf(L"Unable to import the TeslaCrypt master key!\r\n"); return true; } if (bDeleteDropper) { // Automatically scan, kill and delete TeslaCrypt dropper SearchAndKillTeslaProc(false, true, true); } if (bScanEntirePc) { // Decrypt all PC files GetDecrypter()->KeepOriginalFiles(bKeepOriginal); GetDecrypter()->DeleteTeslaCryptGarbage(true); bRetVal = GetDecrypter()->DecryptAllPcFiles(); return true; } else if (strOrgDir) { wprintf(L"Decrypting directory \"%s\"... ", strOrgDir); GetDecrypter()->KeepOriginalFiles(bKeepOriginal); bRetVal = GetDecrypter()->DecryptDirectory(strOrgDir); } else if (strOrgFile) { LPTSTR targetFile = NULL; wprintf(L"Decrypting file \"%s\"... ", wcsrchr(strOrgFile, '\\') + 1); targetFile = ComposeDestFileName(strOrgFile); bRetVal = GetDecrypter()->DecryptTeslaFile(strOrgFile, targetFile); if (targetFile) delete targetFile; // Don't forget to do this } else { // Invalid command line return false; } if (bRetVal) { cl_wprintf(GREEN, L"Success!\r\n"); if (strOrgDir) wprintf(L"Encrypted files in the target directory have been decrypted.\r\n" L"See the log file for all the details.\r\n"); } else { cl_wprintf(RED, L"Error!\r\n"); if (strOrgDir) wprintf(L"Errors while decrypting files.\r\n" L"See log file for details.\r\n"); } return true; }
bool DialogInstall::ReadOptions(const WCHAR* file) { WCHAR buffer[MAX_LINE_LENGTH]; const bool newFormat = m_PackageFormat == PackageFormat::New; const WCHAR* section = newFormat ? L"rmskin" : L"Rainstaller"; const HWND window = m_TabInstall.GetWindow(); if (GetPrivateProfileString(section, L"Name", L"", buffer, 64, file) == 0) { return false; } Static_SetText(GetDlgItem(window, IDC_INSTALLTAB_NAME_TEXT), buffer); if (!newFormat) { // Determine if skins need to backed up based on name int s; int scanned = swscanf(buffer, L"Backup-%d.%d.%d-%d.%d.rmskin", &s, &s, &s, &s, &s); m_BackupPackage = scanned == 5; } GetPrivateProfileString(section, L"Author", L"", buffer, 64, file); Static_SetText(GetDlgItem(window, IDC_INSTALLTAB_AUTHOR_TEXT), buffer); GetPrivateProfileString(section, L"Version", L"", buffer, 64, file); Static_SetText(GetDlgItem(window, IDC_INSTALLTAB_VERSION_TEXT), buffer); m_MergeSkins = GetPrivateProfileInt(section, newFormat ? L"MergeSkins" : L"Merge", 0, file) != 0; GetPrivateProfileString(section, newFormat ? L"VariableFiles" : L"KeepVar", L"", buffer, MAX_LINE_LENGTH, file); m_VariablesFiles = Tokenize(buffer, L"|"); if (GetPrivateProfileString(section, newFormat ? L"MinimumRainmeter" : L"MinRainmeterVer", L"", buffer, MAX_LINE_LENGTH, file) > 0) { std::wstring rainmeterDll = g_Data.programPath + L"Rainmeter.dll"; std::wstring rainmeterVersion = GetFileVersionString(rainmeterDll.c_str()); if (CompareVersions(buffer, rainmeterVersion) == 1) { m_ErrorMessage = L"Rainmeter "; m_ErrorMessage += buffer; m_ErrorMessage += L" or higher is required to install this package.\n\n" L"Get the latest version from rainmeter.net and try again."; return false; } } if (GetPrivateProfileString(section, newFormat ? L"LoadType" : L"LaunchType", L"", buffer, MAX_LINE_LENGTH, file) > 0) { bool loadSkin = _wcsicmp(buffer, newFormat ? L"Skin" : L"Load") == 0; GetPrivateProfileString(section, newFormat ? L"Load" : L"LaunchCommand", L"", buffer, MAX_LINE_LENGTH, file); if (loadSkin) { if (newFormat) { m_LoadSkins.push_back(buffer); } else { m_LoadSkins = Tokenize(buffer, L"|"); } } else { m_LoadLayout = buffer; } } if (newFormat) { if (GetPrivateProfileString(section, L"MinimumDotNET", L"", buffer, MAX_LINE_LENGTH, file) > 0 && CompareVersions(buffer, GetDotNetVersionString()) == 1) { m_ErrorMessage = L".NET framework "; m_ErrorMessage += buffer; m_ErrorMessage += L" or higher is required to install this package."; return false; } if (GetPrivateProfileString(section, L"MinimumWindows", L"", buffer, MAX_LINE_LENGTH, file) > 0 && CompareVersions(buffer, GetWindowsVersionString()) == 1) { m_ErrorMessage = L"Your version of Windows is not supported by this package.\n\n" L"Contact the package author for more information."; return false; } } return true; }
CXTPMarkupObject* CXTPMarkupThickness::ConvertFrom(CXTPMarkupBuilder *pBuilder, CXTPMarkupObject* pObject) const { UNREFERENCED_PARAMETER(pBuilder); if (IsStringObject(pObject)) { LPCWSTR lpszValue = *((CXTPMarkupString*)pObject); int nLength = ((CXTPMarkupString*)pObject)->GetLength(); if (wcschr(lpszValue, L',') == NULL) { int nThickness = _wtoi(lpszValue); if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"pt") == 0) { return new CXTPMarkupThickness(MulDiv(nThickness, 96, 72)); } if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"in") == 0) { return new CXTPMarkupThickness(nThickness * 96); } if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"cm") == 0) { return new CXTPMarkupThickness(int((double)nThickness * 37.79528)); } if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"mm") == 0) { return new CXTPMarkupThickness(int((double)nThickness * 3.779528)); } return new CXTPMarkupThickness(nThickness); } else { if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"pt") == 0) { int left = 0, top = 0, right = 0, bottom = 0; if ( WSCANF_S(lpszValue, L"%ipt, %ipt, %ipt, %ipt", &left, &top, &right, &bottom) != 4) return NULL; return new CXTPMarkupThickness(MulDiv(left, 96, 72), MulDiv(top, 96, 72), MulDiv(right, 96, 72), MulDiv(bottom, 96, 72)); } if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"in") == 0) { int left = 0, top = 0, right = 0, bottom = 0; if ( WSCANF_S(lpszValue, L"%iin, %iin, %iin, %iin", &left, &top, &right, &bottom) != 4) return NULL; return new CXTPMarkupThickness(left * 96, top * 96, right * 96, bottom * 96); } if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"cm") == 0) { int left = 0, top = 0, right = 0, bottom = 0; if ( WSCANF_S(lpszValue, L"%icm, %icm, %icm, %icm", &left, &top, &right, &bottom) != 4) return NULL; return new CXTPMarkupThickness(int((double)left * 37.79528), int((double)top * 37.79528), int((double)right * 37.79528), int((double)bottom * 37.79528)); } if ((nLength > 2) && _wcsicmp(lpszValue + nLength - 2, L"mm") == 0) { int left = 0, top = 0, right = 0, bottom = 0; if ( WSCANF_S(lpszValue, L"%imm, %imm, %imm, %imm", &left, &top, &right, &bottom) != 4) return NULL; return new CXTPMarkupThickness(int((double)left * 3.779528), int((double)top * 3.779528), int((double)right * 3.779528), int((double)bottom * 3.779528)); } int left = 0, top = 0, right = 0, bottom = 0; if ( WSCANF_S(lpszValue, L"%i, %i, %i, %i", &left, &top, &right, &bottom) != 4) return NULL; return new CXTPMarkupThickness(left, top, right, bottom); } } return NULL; }
BOOL IsFontExcluded(const LPCWSTR lpszFaceName) { if (lpszFaceName && _wcsicmp(lpszFaceName, L"Myriad Pro Cond") == 0) { return FALSE; } return TRUE; }
static BOOL SetUserEnvironment(PWSTR* Environment, HKEY hKey, LPWSTR lpSubKeyName) { LONG Error; HKEY hEnvKey; DWORD dwValues; DWORD dwMaxValueNameLength; DWORD dwMaxValueDataLength; DWORD dwValueNameLength; DWORD dwValueDataLength; DWORD dwType; DWORD i; LPWSTR lpValueName; LPWSTR lpValueData; Error = RegOpenKeyExW(hKey, lpSubKeyName, 0, KEY_QUERY_VALUE, &hEnvKey); if (Error != ERROR_SUCCESS) { DPRINT1("RegOpenKeyExW() failed (Error %ld)\n", Error); SetLastError((DWORD)Error); return FALSE; } Error = RegQueryInfoKey(hEnvKey, NULL, NULL, NULL, NULL, NULL, NULL, &dwValues, &dwMaxValueNameLength, &dwMaxValueDataLength, NULL, NULL); if (Error != ERROR_SUCCESS) { DPRINT1("RegQueryInforKey() failed (Error %ld)\n", Error); RegCloseKey(hEnvKey); SetLastError((DWORD)Error); return FALSE; } if (dwValues == 0) { RegCloseKey(hEnvKey); return TRUE; } /* Allocate buffers */ dwMaxValueNameLength++; lpValueName = LocalAlloc(LPTR, dwMaxValueNameLength * sizeof(WCHAR)); if (lpValueName == NULL) { RegCloseKey(hEnvKey); return FALSE; } lpValueData = LocalAlloc(LPTR, dwMaxValueDataLength); if (lpValueData == NULL) { LocalFree(lpValueName); RegCloseKey(hEnvKey); return FALSE; } /* Enumerate values */ for (i = 0; i < dwValues; i++) { dwValueNameLength = dwMaxValueNameLength; dwValueDataLength = dwMaxValueDataLength; Error = RegEnumValueW(hEnvKey, i, lpValueName, &dwValueNameLength, NULL, &dwType, (LPBYTE)lpValueData, &dwValueDataLength); if (Error == ERROR_SUCCESS) { if (!_wcsicmp(lpValueName, L"PATH")) { /* Append 'Path' environment variable */ AppendUserEnvironmentVariable(Environment, lpValueName, lpValueData); } else { /* Set environment variable */ SetUserEnvironmentVariable(Environment, lpValueName, lpValueData, (dwType == REG_EXPAND_SZ)); } } else { LocalFree(lpValueData); LocalFree(lpValueName); RegCloseKey(hEnvKey); return FALSE; } } LocalFree(lpValueData); LocalFree(lpValueName); RegCloseKey(hEnvKey); return TRUE; }
static BOOL SetUserEnvironmentVariable(PWSTR* Environment, LPWSTR lpName, LPWSTR lpValue, BOOL bExpand) { NTSTATUS Status; UNICODE_STRING Name; UNICODE_STRING SrcValue, DstValue; ULONG Length; PVOID Buffer = NULL; WCHAR ShortName[MAX_PATH]; if (bExpand) { RtlInitUnicodeString(&SrcValue, lpValue); Length = 2 * MAX_PATH * sizeof(WCHAR); DstValue.Length = 0; DstValue.MaximumLength = Length; DstValue.Buffer = Buffer = LocalAlloc(LPTR, Length); if (DstValue.Buffer == NULL) { DPRINT1("LocalAlloc() failed\n"); return FALSE; } Status = RtlExpandEnvironmentStrings_U(*Environment, &SrcValue, &DstValue, &Length); if (!NT_SUCCESS(Status)) { DPRINT1("RtlExpandEnvironmentStrings_U() failed (Status %lx)\n", Status); DPRINT1("Length %lu\n", Length); if (Buffer) LocalFree(Buffer); return FALSE; } } else { RtlInitUnicodeString(&DstValue, lpValue); } if (!_wcsicmp(lpName, L"TEMP") || !_wcsicmp(lpName, L"TMP")) { if (GetShortPathNameW(DstValue.Buffer, ShortName, ARRAYSIZE(ShortName))) { RtlInitUnicodeString(&DstValue, ShortName); } else { DPRINT("GetShortPathNameW() failed for %S (Error %lu)\n", DstValue.Buffer, GetLastError()); } DPRINT("Buffer: %S\n", ShortName); } RtlInitUnicodeString(&Name, lpName); DPRINT("Value: %wZ\n", &DstValue); Status = RtlSetEnvironmentVariable(Environment, &Name, &DstValue); if (Buffer) LocalFree(Buffer); if (!NT_SUCCESS(Status)) { DPRINT1("RtlSetEnvironmentVariable() failed (Status %lx)\n", Status); return FALSE; } return TRUE; }
void CheckServiceConfig( wchar_t *my_servicename, /* SERVICENAME property in this installation*/ wchar_t *datadir, /* DATADIR property in this installation*/ wchar_t *bindir, /* INSTALLDIR\bin */ wchar_t *other_servicename, /* Service to check against */ QUERY_SERVICE_CONFIGW * config /* Other service's config */ ) { bool same_bindir = false; wchar_t * commandline= config->lpBinaryPathName; int numargs; wchar_t **argv= CommandLineToArgvW(commandline, &numargs); WcaLog(LOGMSG_VERBOSE, "CommandLine= %S", commandline); if(!argv || !argv[0] || ! wcsstr(argv[0], L"mysqld")) { goto end; } WcaLog(LOGMSG_STANDARD, "MySQL service %S found: CommandLine= %S", other_servicename, commandline); if (wcsstr(argv[0], bindir)) { WcaLog(LOGMSG_STANDARD, "executable under bin directory"); same_bindir = true; } bool is_my_service = (_wcsicmp(my_servicename, other_servicename) == 0); if(!is_my_service) { WcaLog(LOGMSG_STANDARD, "service does not match current service"); /* TODO probably the best thing possible would be to add temporary row to MSI ServiceConfig table with remove on uninstall */ } else if (!same_bindir) { WcaLog(LOGMSG_STANDARD, "Service name matches, but not the executable path directory, mine is %S", bindir); WcaSetProperty(L"SERVICENAME", L""); } /* Check if data directory is used */ if(!datadir || numargs <= 1 || wcsncmp(argv[1],L"--defaults-file=",16) != 0) { goto end; } wchar_t current_datadir_buf[MAX_PATH]={0}; wchar_t normalized_current_datadir[MAX_PATH+1]; wchar_t *current_datadir= current_datadir_buf; wchar_t *defaults_file= argv[1]+16; defaults_file= strip_quotes(defaults_file); WcaLog(LOGMSG_STANDARD, "parsed defaults file is %S", defaults_file); if (GetPrivateProfileStringW(L"mysqld", L"datadir", NULL, current_datadir, MAX_PATH, defaults_file) == 0) { WcaLog(LOGMSG_STANDARD, "Cannot find datadir in ini file '%S'", defaults_file); goto end; } WcaLog(LOGMSG_STANDARD, "datadir from defaults-file is %S", current_datadir); strip_quotes(current_datadir); /* Convert to Windows path */ if (GetFullPathNameW(current_datadir, MAX_PATH, normalized_current_datadir, NULL)) { /* Add backslash to be compatible with directory formats in MSI */ wcsncat(normalized_current_datadir, L"\\", MAX_PATH+1); WcaLog(LOGMSG_STANDARD, "normalized current datadir is '%S'", normalized_current_datadir); } if (_wcsicmp(datadir, normalized_current_datadir) == 0 && !same_bindir) { WcaLog(LOGMSG_STANDARD, "database directory from current installation, but different mysqld.exe"); WcaSetProperty(L"CLEANUPDATA", L""); } end: LocalFree((HLOCAL)argv); }
// ============================================================================= // BTDeviceIsNear // ============================================================================= bool BTDeviceIsNear() { //Initialising winsock WSADATA data; int result; result = WSAStartup(MAKEWORD(2, 2), &data); if (result != 0){ MsgBox("An error occured while initialising winsock, closing...."); return false; } //Initialising query for device WSAQUERYSET queryset; memset(&queryset, 0, sizeof(WSAQUERYSET)); queryset.dwSize = sizeof(WSAQUERYSET); queryset.dwNameSpace = NS_BTH; HANDLE hLookup; result = WSALookupServiceBegin(&queryset, LUP_CONTAINERS, &hLookup); if (result != 0){ MsgBox("An error occured while initialising look for devices, closing...."); return false; } //Initialisation succeed, start looking for devices BYTE buffer[4096]; memset(buffer, 0, sizeof(buffer)); DWORD bufferLength = sizeof(buffer); WSAQUERYSET *pResults = (WSAQUERYSET*)&buffer; while (result == 0) { result = WSALookupServiceNext(hLookup, LUP_RETURN_NAME | LUP_CONTAINERS | LUP_RETURN_ADDR | LUP_FLUSHCACHE | LUP_RETURN_TYPE | LUP_RETURN_BLOB | LUP_RES_SERVICE, &bufferLength, pResults); if (result == 0) { // A device found LPTSTR deviceFoundName = pResults->lpszServiceInstanceName; PSOCKADDR_BTH sa = PSOCKADDR_BTH(pResults->lpcsaBuffer->RemoteAddr.lpSockaddr); if (sa->addressFamily != AF_BTH) { // Address family is not AF_BTH for bluetooth device discovered continue; } //the MAC address is available in sa->btAddr printf("[HookExe] Device found\n"); if ((deviceFoundName != NULL) && (0 == _wcsicmp(deviceFoundName, convertCharArrayToLPCWSTR("btdevice")))) { printf("[HookExe] Found the device!\n"); printf("[HookExe] Device name is %S\t Device addr is 0x%0x\n", deviceFoundName, sa->btAddr); if (BluetoothIsConnectable(hLookup)) { //if (pResults->dwOutputFlags == BTHNS_RESULT_DEVICE_CONNECTED) { printf("[HookExe] Device is CONNECTED!!! 0x%0x \n", pResults->dwOutputFlags); } else { printf("[HookExe] Device is NOOOOOOOT CONNECTED!!! - 0x%0x\n", pResults->dwOutputFlags); } return true; } else { printf("[HookExe] Didn't find the device...\n"); printf("[HookExe] Device name is %S\t Device addr is 0x%0x\n", deviceFoundName, sa->btAddr); } } } WSALookupServiceEnd(hLookup); return false; }
//--------------------------------------------------------------------------- // 检测文件关联情况 // strExt: 要检测的扩展名(例如: ".txt") // strAppKey: ExeName扩展名在注册表中的键值(例如: "txtfile") // 返回TRUE: 表示已关联,FALSE: 表示未关联 BOOL CheckFileRelation(const TCHAR *strExt, const TCHAR *strAppKey, TCHAR *strAppName, TCHAR *strDefaultIcon, TCHAR *strDescribe) { int nRet=TRUE; HKEY hExtKey; TCHAR szPath[_MAX_PATH]; DWORD dwSize=sizeof(szPath); TCHAR strTemp[_MAX_PATH]; if(RegOpenKey(HKEY_CLASSES_ROOT,strExt,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strAppKey)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strAppKey,wcslen(strAppKey)+1); //return nRet; } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); if(RegOpenKey(HKEY_CLASSES_ROOT,strAppKey,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strDescribe)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strDescribe,wcslen(strDescribe)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"%s\\DefaultIcon",strAppKey); if(RegOpenKey(HKEY_CLASSES_ROOT,strTemp,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strDefaultIcon)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strDefaultIcon,wcslen(strDefaultIcon)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"%s\\Shell",strAppKey); if(RegOpenKey(HKEY_CLASSES_ROOT,strTemp,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,L"Open")!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,L"Open",wcslen(L"Open")+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"%s\\Shell\\Open\\Command",strAppKey); if(RegOpenKey(HKEY_CLASSES_ROOT,strTemp,&hExtKey)==ERROR_SUCCESS) { wsprintf(strTemp,L"%s \"%%1\"",strAppName); RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strTemp)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strTemp,wcslen(strTemp)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); if(RegOpenKey(HKEY_CURRENT_USER,strExt,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strAppKey)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strAppKey,wcslen(strAppKey)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); if(RegOpenKey(HKEY_CURRENT_USER,strAppKey,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strDescribe)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strDescribe,wcslen(strDescribe)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"%s\\DefaultIcon",strAppKey); if(RegOpenKey(HKEY_CURRENT_USER,strTemp,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strDefaultIcon)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strDefaultIcon,wcslen(strDefaultIcon)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"%s\\Shell",strAppKey); if(RegOpenKey(HKEY_CURRENT_USER,strTemp,&hExtKey)==ERROR_SUCCESS) { RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,L"Open")!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,L"Open",wcslen(L"Open")+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"%s\\Shell\\Open\\Command",strAppKey); if(RegOpenKey(HKEY_CURRENT_USER,strTemp,&hExtKey)==ERROR_SUCCESS) { wsprintf(strTemp,L"%s \"%%1\"",strAppName); RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strTemp)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strTemp,wcslen(strTemp)+1); } RegCloseKey(hExtKey); } dwSize=sizeof(szPath); wsprintf(strTemp,L"Software\\Classes\\%s_auto_file\\Shell\\Open\\Command",strExt+1); if(RegOpenKey(HKEY_CURRENT_USER,strTemp,&hExtKey)==ERROR_SUCCESS) { wsprintf(strTemp,L"%s \"%%1\"",strAppName); RegQueryValueEx(hExtKey,NULL,NULL,NULL,(LPBYTE)szPath,&dwSize); if(_wcsicmp(szPath,strTemp)!=0) { nRet=FALSE; RegSetValue(hExtKey,L"",REG_SZ,strTemp,wcslen(strTemp)+1); } RegCloseKey(hExtKey); } return nRet; }
DBGSTATIC NET_API_STATUS Parse2( IN DWORD argc, IN LPTSTR argv[], IN LPNET_CONFIG_HANDLE ConfigHandle ) /*++ Routine Description : parse command line arguments, range-check them and set global variables. parameter units range/value default --------- ----- ----------- ------- /REPLICATE - import/export/both REPL_ROLE_IMPORT /EXPORTPATH pathname - repl\export /IMPORTPATH pathname - repl\import /EXPORTLIST names 0-32 0 /IMPORTLIST srvnames 0-32 0 /TRYUSER - yes/no YES /LOGON username - - /PASSWORD password - - /INTERVAL minutes 1-60 5 /PULSE integer 1-10 3 /GUARDTIME minutes 0 to (interval/2) 2 /RANDOM seconds 1-120 60 Arguments : argc : argument count argv : argument string array pointer. ConfigHandle : config handle for replicator section. Return Value : return NO_ERROR if successfully parse parameter ERROR_INVALID_PARAMETER, on syntax error and so on... --*/ { NET_API_STATUS ApiStatus; LPWSTR ParmStrValue; // get and check common parameter to master and client. // /REPL switch ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_REPL, &P_repl ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } if(P_repl[0] == L'\0') { ReplConfigReportBadParmValue( rep_REPL, NULL ); return( ERROR_INVALID_PARAMETER ); } if(_wcsicmp(P_repl, BOTH_SW) == 0) { ReplGlobalRole = REPL_ROLE_BOTH; } else if(_wcsicmp(P_repl, EXPORT_SW) == 0) { ReplGlobalRole = REPL_ROLE_EXPORT; } else if(_wcsicmp(P_repl, IMPORT_SW) == 0) { ReplGlobalRole = REPL_ROLE_IMPORT; } else { ReplConfigReportBadParmValue( rep_REPL, NULL ); return( ERROR_INVALID_PARAMETER ); } IF_DEBUG(REPL) { // debug code NetpKdPrint(( "[Repl] Repl parameter \n")); NetpKdPrint((" REPL = %ws \n", P_repl)); } // get and check repl master parameters if (ReplRoleIncludesMaster( ReplGlobalRole )) { IF_DEBUG(REPL) { // debug code NetpKdPrint(( "[Repl] Repl master parameters \n")); } // EXPORTPATH ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_EXPPATH, &P_exppath ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = PathCheck(&P_exppath, ITYPE_PATH_ABSD, rep_EXPPATH); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" EXPORT PATH = %ws \n", P_exppath)); } // EXPORTLIST ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_EXPLIST, &P_explist ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = ListCheck(P_explist, rep_EXPLIST); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" EXPORT LIST = %ws \n", P_explist)); } // INTERVAL ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_SYNC, &ParmStrValue ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = DwordCheck(ParmStrValue, MIN_SYNC, MAX_SYNC, rep_SYNC, &P_sync ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" INTERVAL = 0x%lx \n", P_sync)); } // PULSE ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_PULSE, &ParmStrValue ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = DwordCheck(ParmStrValue, MIN_PULSE, MAX_PULSE, rep_PULSE, &P_pulse ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" PULSE = 0x%lx \n", P_pulse)); } // GUARD ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_GUARD, &ParmStrValue ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = DwordCheck(ParmStrValue, MIN_GUARD, MAX_GUARD, rep_GUARD, &P_guard ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" GUARD = 0x%lx \n", P_guard)); } if(P_guard > (P_sync / 2)) { NetpKdPrint(( "[REPL-MASTER] guard and sync parms conflict.\n")); ReplFinish( SERVICE_UIC_CODE( SERVICE_UIC_CONFLPARM, 0), NULL); return( ERROR_INVALID_PARAMETER ); } } if (ReplRoleIncludesClient( ReplGlobalRole )) { IF_DEBUG(REPL) { // debug code NetpKdPrint(( "[Repl] Repl client parameters \n")); } // IMPORTPATH ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_IMPPATH, &P_imppath ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = PathCheck(&P_imppath, ITYPE_PATH_ABSD, rep_IMPPATH); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" IMPORT PATH = %ws \n", P_imppath)); } // IMPORTLIST ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_IMPLIST, &P_implist ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = ListCheck(P_implist, rep_IMPLIST); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" IMPORT LIST = %ws \n", P_implist)); } // TRY USER ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_TRYUSER, &ParmStrValue ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = YesNoCheck(ParmStrValue, rep_TRYUSER, &P_tryuser ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" TRYUSER = "******"\n", (DWORD) P_tryuser)); } // LOGON ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_LOGON, &P_logon ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = NameCheck(&P_logon, NAMETYPE_USER, rep_LOGON); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" LOGON = %ws \n", P_logon)); } // PASSWORD ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_PASSWD, &P_passwd ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = NameCheck(&P_passwd, NAMETYPE_PASSWORD, rep_PASSWD); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" PASSWORD = %ws \n", P_passwd)); } // RANDOM ApiStatus = GetParameter(argc, argv, ConfigHandle, rep_RANDOM, &ParmStrValue ); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } ApiStatus = DwordCheck(ParmStrValue, MIN_RANDOM, MAX_RANDOM, rep_RANDOM, &P_random); if (ApiStatus != NO_ERROR) { return( ApiStatus ); } IF_DEBUG(REPL) { // debug code NetpKdPrint((" RANDOM = 0x%lx \n", P_random)); } } return( NO_ERROR ); }
///////////////////////////////////////////////////////////////////////////// // // [OnGetContentInformation] // // IWMSCacheProxyServerCallback // ///////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CProxyPlugin::OnGetContentInformation( long lHr, IWMSContext *pContentInfo, VARIANT varContext ) { HRESULT returnHr = (HRESULT) lHr; HRESULT hr = S_OK; COpState *pOpState = NULL; WMS_CACHE_QUERY_MISS_RESPONSE CacheMissPolicy = WMS_CACHE_QUERY_MISS_SKIP; IWMSDataContainerVersion *pContentVersion = NULL; CComBSTR bstrUrl; BOOL fDownload = FALSE; long lContentType = 0; DWORD dwCacheFlags; WCHAR szPort[ 20 ]; if( ( VT_UNKNOWN != V_VT( &varContext ) ) || ( NULL == V_UNKNOWN( &varContext ) ) ) { return( E_INVALIDARG ); } pOpState = ( COpState *) V_UNKNOWN( &varContext ); if( FAILED( returnHr ) ) { if( NS_E_CONNECTION_FAILURE == returnHr ) { // Do protocol rollover pOpState->m_dwProtocolIndex++; if( NULL == g_ProxyProtocols[ pOpState->m_dwProtocolIndex ] ) { // we have tried all the protocols and failed hr = E_NOINTERFACE; goto abort; } bstrUrl = g_ProxyProtocols[ pOpState->m_dwProtocolIndex ]; bstrUrl.Append( L"://" ); bstrUrl.Append( pOpState->m_bstrHost ); // if we we are using the same protocol requested by the client, then we should // also use the port specified by the client (if one was specified) if( ( 0 != pOpState->m_wPort ) && ( 0 == _wcsicmp( g_ProxyProtocols[ pOpState->m_dwProtocolIndex ], pOpState->m_bstrProtocol ) ) ) { bstrUrl.Append( L":" ); _itow_s( pOpState->m_wPort, szPort,sizeof(szPort)/sizeof(WCHAR), 10 ); bstrUrl.Append( szPort ); } bstrUrl.Append( L"/" ); bstrUrl.Append( pOpState->m_bstrPath ); hr = m_pICacheProxyServer->GetContentInformation( bstrUrl, pOpState->m_pPresentationContext, this, NULL, (IWMSCacheProxyServerCallback *) this, varContext ); if( FAILED( hr ) ) { goto abort; } return( S_OK ); } else if( E_ACCESSDENIED == returnHr ) { // the origin server requires authentication to provide information about this content. // since we don't have the credentials, we can either proxy this stream on-demand (in // which case the player will be prompted for the credentials) or simply fail this request. // let's opt for proxying the stream. CacheMissPolicy = WMS_CACHE_QUERY_MISS_PLAY_ON_DEMAND; } else { hr = returnHr; goto abort; } } else { hr = pContentInfo->GetLongValue( WMS_CACHE_CONTENT_INFORMATION_CONTENT_TYPE, WMS_CACHE_CONTENT_INFORMATION_CONTENT_TYPE_ID, (long *) &lContentType, 0 ); if( FAILED( hr ) ) { goto abort; } if( WMS_CACHE_CONTENT_TYPE_BROADCAST & lContentType ) { hr = pContentInfo->GetAndQueryIUnknownValue( WMS_CACHE_CONTENT_INFORMATION_DATA_CONTAINER_VERSION, WMS_CACHE_CONTENT_INFORMATION_DATA_CONTAINER_VERSION_ID, IID_IWMSDataContainerVersion, (IUnknown **) &pContentVersion, 0 ); if( ( FAILED( hr ) ) || ( NULL == pContentVersion ) ) { hr = FAILED( hr ) ? hr : E_UNEXPECTED; goto abort; } hr = pContentVersion->GetCacheFlags( (long *) &dwCacheFlags ); if( FAILED( hr ) ) { goto abort; } if( dwCacheFlags & WMS_DATA_CONTAINER_VERSION_ALLOW_STREAM_SPLITTING ) { CacheMissPolicy = WMS_CACHE_QUERY_MISS_PLAY_BROADCAST; } else { CacheMissPolicy = WMS_CACHE_QUERY_MISS_PLAY_ON_DEMAND; } } else // It is an on-demand publishing point { CacheMissPolicy = WMS_CACHE_QUERY_MISS_PLAY_ON_DEMAND; } } hr = S_OK; bstrUrl = g_ProxyProtocols[ pOpState->m_dwProtocolIndex ]; bstrUrl.Append( L"://" ); bstrUrl.Append( pOpState->m_bstrHost ); // if we we are using the same protocol requested by the client, then we should // also use the port specified by the client (if one was specified) if( ( 0 != pOpState->m_wPort ) && ( 0 == _wcsicmp( g_ProxyProtocols[ pOpState->m_dwProtocolIndex ], pOpState->m_bstrProtocol ) ) ) { bstrUrl.Append( L":" ); _itow_s( pOpState->m_wPort, szPort,sizeof(szPort)/sizeof(WCHAR), 10 ); bstrUrl.Append( szPort ); } bstrUrl.Append( L"/" ); bstrUrl.Append( pOpState->m_bstrPath ); abort: hr = pOpState->m_pCacheProxyCallback->OnQueryCacheMissPolicy( hr, CacheMissPolicy, bstrUrl, NULL, pContentInfo, pOpState->m_varContext ); if( FAILED( hr ) ) { hr = S_OK; } if( NULL != pOpState ) { pOpState->Release(); } if( NULL != pContentVersion ) { pContentVersion->Release(); } return( S_OK ); }
// DLL Entry Point extern "C" BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved ) { if (dwReason==DLL_PROCESS_ATTACH) { wchar_t path[_MAX_PATH]; GetModuleFileName(NULL,path,_countof(path)); const wchar_t *exe=PathFindFileName(path); if (_wcsicmp(exe,L"explorer.exe")==0) return FALSE; bool bIE9=false; if (_wcsicmp(exe,L"iexplore.exe")==0) { DWORD version=GetVersionEx(GetModuleHandle(NULL)); if (version<0x09000000) return FALSE; bIE9=true; } g_Instance=hInstance; InitSettings(); if (bIE9 && !GetSettingBool(L"ShowCaption") && !GetSettingBool(L"ShowProgress") && !GetSettingBool(L"ShowZone")) return FALSE; CString language=GetSettingString(L"Language"); ParseTranslations(NULL,language); GetModuleFileName(hInstance,path,_countof(path)); *PathFindFileName(path)=0; HINSTANCE resInstance=NULL; if (!language.IsEmpty()) { wchar_t fname[_MAX_PATH]; Sprintf(fname,_countof(fname),L"%s" INI_PATH L"%s.dll",path,language); resInstance=LoadLibraryEx(fname,NULL,LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE); } else { wchar_t languages[100]={0}; ULONG size=4; // up to 4 languages ULONG len=_countof(languages); GetThreadPreferredUILanguages(MUI_LANGUAGE_NAME,&size,languages,&len); for (const wchar_t *language=languages;*language;language+=Strlen(language)+1) { wchar_t fname[_MAX_PATH]; Sprintf(fname,_countof(fname),L"%s" INI_PATH L"%s.dll",path,language); resInstance=LoadLibraryEx(fname,NULL,LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE); if (resInstance) break; } } if (resInstance && GetVersionEx(resInstance)!=GetVersionEx(g_Instance)) { FreeLibrary(resInstance); resInstance=NULL; } LoadTranslationResources(g_Instance,resInstance,g_LoadDialogs); if (resInstance) FreeLibrary(resInstance); InitClassicIE9(hInstance); } return _AtlModule.DllMain(dwReason, lpReserved); }
/* * @unimplemented */ NTSTATUS NTAPI LsaApLogonUser(IN PLSA_CLIENT_REQUEST ClientRequest, IN SECURITY_LOGON_TYPE LogonType, IN PVOID AuthenticationInformation, IN PVOID ClientAuthenticationBase, IN ULONG AuthenticationInformationLength, OUT PVOID *ProfileBuffer, OUT PULONG ProfileBufferLength, OUT PLUID LogonId, OUT PNTSTATUS SubStatus, OUT PLSA_TOKEN_INFORMATION_TYPE TokenInformationType, OUT PVOID *TokenInformation, OUT PLSA_UNICODE_STRING *AccountName, OUT PLSA_UNICODE_STRING *AuthenticatingAuthority) { PMSV1_0_INTERACTIVE_LOGON LogonInfo; SAMPR_HANDLE ServerHandle = NULL; SAMPR_HANDLE DomainHandle = NULL; SAMPR_HANDLE UserHandle = NULL; PRPC_SID AccountDomainSid = NULL; RPC_UNICODE_STRING Names[1]; SAMPR_ULONG_ARRAY RelativeIds = {0, NULL}; SAMPR_ULONG_ARRAY Use = {0, NULL}; PSAMPR_USER_INFO_BUFFER UserInfo = NULL; UNICODE_STRING LogonServer; BOOLEAN SessionCreated = FALSE; LARGE_INTEGER LogonTime; // LARGE_INTEGER AccountExpires; LARGE_INTEGER PasswordMustChange; LARGE_INTEGER PasswordLastSet; BOOL SpecialAccount = FALSE; NTSTATUS Status; TRACE("LsaApLogonUser()\n"); TRACE("LogonType: %lu\n", LogonType); TRACE("AuthenticationInformation: %p\n", AuthenticationInformation); TRACE("AuthenticationInformationLength: %lu\n", AuthenticationInformationLength); *ProfileBuffer = NULL; *ProfileBufferLength = 0; *SubStatus = STATUS_SUCCESS; if (LogonType == Interactive || LogonType == Batch || LogonType == Service) { ULONG_PTR PtrOffset; LogonInfo = (PMSV1_0_INTERACTIVE_LOGON)AuthenticationInformation; /* Fix-up pointers in the authentication info */ PtrOffset = (ULONG_PTR)AuthenticationInformation - (ULONG_PTR)ClientAuthenticationBase; LogonInfo->LogonDomainName.Buffer = FIXUP_POINTER(LogonInfo->LogonDomainName.Buffer, PtrOffset); LogonInfo->UserName.Buffer = FIXUP_POINTER(LogonInfo->UserName.Buffer, PtrOffset); LogonInfo->Password.Buffer = FIXUP_POINTER(LogonInfo->Password.Buffer, PtrOffset); TRACE("Domain: %S\n", LogonInfo->LogonDomainName.Buffer); TRACE("User: %S\n", LogonInfo->UserName.Buffer); TRACE("Password: %S\n", LogonInfo->Password.Buffer); RtlInitUnicodeString(&LogonServer, L"Testserver"); } else { FIXME("LogonType %lu is not supported yet!\n", LogonType); return STATUS_NOT_IMPLEMENTED; } /* Get the logon time */ NtQuerySystemTime(&LogonTime); /* Check for special accounts */ if (_wcsicmp(LogonInfo->LogonDomainName.Buffer, L"NT AUTHORITY") == 0) { SpecialAccount = TRUE; /* Get the authority domain SID */ Status = GetNtAuthorityDomainSid(&AccountDomainSid); if (!NT_SUCCESS(Status)) { ERR("GetNtAuthorityDomainSid() failed (Status 0x%08lx)\n", Status); return Status; } if (_wcsicmp(LogonInfo->UserName.Buffer, L"LocalService") == 0) { TRACE("SpecialAccount: LocalService\n"); if (LogonType != Service) return STATUS_LOGON_FAILURE; UserInfo = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SAMPR_USER_ALL_INFORMATION)); if (UserInfo == NULL) { Status = STATUS_INSUFFICIENT_RESOURCES; goto done; } UserInfo->All.UserId = SECURITY_LOCAL_SERVICE_RID; UserInfo->All.PrimaryGroupId = SECURITY_LOCAL_SERVICE_RID; } else if (_wcsicmp(LogonInfo->UserName.Buffer, L"NetworkService") == 0) { TRACE("SpecialAccount: NetworkService\n"); if (LogonType != Service) return STATUS_LOGON_FAILURE; UserInfo = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SAMPR_USER_ALL_INFORMATION)); if (UserInfo == NULL) { Status = STATUS_INSUFFICIENT_RESOURCES; goto done; } UserInfo->All.UserId = SECURITY_NETWORK_SERVICE_RID; UserInfo->All.PrimaryGroupId = SECURITY_NETWORK_SERVICE_RID; } else { Status = STATUS_NO_SUCH_USER; goto done; } } else { TRACE("NormalAccount\n"); /* Get the account domain SID */ Status = GetAccountDomainSid(&AccountDomainSid); if (!NT_SUCCESS(Status)) { ERR("GetAccountDomainSid() failed (Status 0x%08lx)\n", Status); return Status; } /* Connect to the SAM server */ Status = SamIConnect(NULL, &ServerHandle, SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN, TRUE); if (!NT_SUCCESS(Status)) { TRACE("SamIConnect() failed (Status 0x%08lx)\n", Status); goto done; } /* Open the account domain */ Status = SamrOpenDomain(ServerHandle, DOMAIN_LOOKUP, AccountDomainSid, &DomainHandle); if (!NT_SUCCESS(Status)) { ERR("SamrOpenDomain failed (Status %08lx)\n", Status); goto done; } Names[0].Length = LogonInfo->UserName.Length; Names[0].MaximumLength = LogonInfo->UserName.MaximumLength; Names[0].Buffer = LogonInfo->UserName.Buffer; /* Try to get the RID for the user name */ Status = SamrLookupNamesInDomain(DomainHandle, 1, Names, &RelativeIds, &Use); if (!NT_SUCCESS(Status)) { ERR("SamrLookupNamesInDomain failed (Status %08lx)\n", Status); Status = STATUS_NO_SUCH_USER; goto done; } /* Fail, if it is not a user account */ if (Use.Element[0] != SidTypeUser) { ERR("Account is not a user account!\n"); Status = STATUS_NO_SUCH_USER; goto done; } /* Open the user object */ Status = SamrOpenUser(DomainHandle, USER_READ_GENERAL | USER_READ_LOGON | USER_READ_ACCOUNT | USER_READ_PREFERENCES, /* FIXME */ RelativeIds.Element[0], &UserHandle); if (!NT_SUCCESS(Status)) { ERR("SamrOpenUser failed (Status %08lx)\n", Status); goto done; } Status = SamrQueryInformationUser(UserHandle, UserAllInformation, &UserInfo); if (!NT_SUCCESS(Status)) { ERR("SamrQueryInformationUser failed (Status %08lx)\n", Status); goto done; } TRACE("UserName: %S\n", UserInfo->All.UserName.Buffer); /* Check the password */ if ((UserInfo->All.UserAccountControl & USER_PASSWORD_NOT_REQUIRED) == 0) { Status = MsvpCheckPassword(&(LogonInfo->Password), UserInfo); if (!NT_SUCCESS(Status)) { ERR("MsvpCheckPassword failed (Status %08lx)\n", Status); goto done; } } /* Check account restrictions for non-administrator accounts */ if (RelativeIds.Element[0] != DOMAIN_USER_RID_ADMIN) { /* Check if the account has been disabled */ if (UserInfo->All.UserAccountControl & USER_ACCOUNT_DISABLED) { ERR("Account disabled!\n"); *SubStatus = STATUS_ACCOUNT_DISABLED; Status = STATUS_ACCOUNT_RESTRICTION; goto done; } /* Check if the account has been locked */ if (UserInfo->All.UserAccountControl & USER_ACCOUNT_AUTO_LOCKED) { ERR("Account locked!\n"); *SubStatus = STATUS_ACCOUNT_LOCKED_OUT; Status = STATUS_ACCOUNT_RESTRICTION; goto done; } #if 0 /* Check if the account expired */ AccountExpires.LowPart = UserInfo->All.AccountExpires.LowPart; AccountExpires.HighPart = UserInfo->All.AccountExpires.HighPart; if (AccountExpires.QuadPart != 0 && LogonTime.QuadPart >= AccountExpires.QuadPart) { ERR("Account expired!\n"); *SubStatus = STATUS_ACCOUNT_EXPIRED; Status = STATUS_ACCOUNT_RESTRICTION; goto done; } #endif /* Check if the password expired */ PasswordMustChange.LowPart = UserInfo->All.PasswordMustChange.LowPart; PasswordMustChange.HighPart = UserInfo->All.PasswordMustChange.HighPart; PasswordLastSet.LowPart = UserInfo->All.PasswordLastSet.LowPart; PasswordLastSet.HighPart = UserInfo->All.PasswordLastSet.HighPart; if (LogonTime.QuadPart >= PasswordMustChange.QuadPart) { ERR("Password expired!\n"); if (PasswordLastSet.QuadPart == 0) *SubStatus = STATUS_PASSWORD_MUST_CHANGE; else *SubStatus = STATUS_PASSWORD_EXPIRED; Status = STATUS_ACCOUNT_RESTRICTION; goto done; } /* FIXME: more checks */ // STATUS_INVALID_LOGON_HOURS; // STATUS_INVALID_WORKSTATION; } } /* Return logon information */ /* Create and return a new logon id */ Status = NtAllocateLocallyUniqueId(LogonId); if (!NT_SUCCESS(Status)) { TRACE("NtAllocateLocallyUniqueId failed (Status %08lx)\n", Status); goto done; } /* Create the logon session */ Status = DispatchTable.CreateLogonSession(LogonId); if (!NT_SUCCESS(Status)) { TRACE("CreateLogonSession failed (Status %08lx)\n", Status); goto done; } SessionCreated = TRUE; /* Build and fill the interactive profile buffer */ Status = BuildInteractiveProfileBuffer(ClientRequest, UserInfo, &LogonServer, (PMSV1_0_INTERACTIVE_PROFILE*)ProfileBuffer, ProfileBufferLength); if (!NT_SUCCESS(Status)) { TRACE("BuildInteractiveProfileBuffer failed (Status %08lx)\n", Status); goto done; } /* Return the token information type */ *TokenInformationType = LsaTokenInformationV1; /* Build and fill the token information buffer */ Status = BuildTokenInformationBuffer((PLSA_TOKEN_INFORMATION_V1*)TokenInformation, AccountDomainSid, UserInfo, SpecialAccount); if (!NT_SUCCESS(Status)) { TRACE("BuildTokenInformationBuffer failed (Status %08lx)\n", Status); goto done; } done: /* Return the account name */ *AccountName = DispatchTable.AllocateLsaHeap(sizeof(UNICODE_STRING)); if (*AccountName != NULL) { (*AccountName)->Buffer = DispatchTable.AllocateLsaHeap(LogonInfo->UserName.Length + sizeof(UNICODE_NULL)); if ((*AccountName)->Buffer != NULL) { (*AccountName)->MaximumLength = LogonInfo->UserName.Length + sizeof(UNICODE_NULL); RtlCopyUnicodeString(*AccountName, &LogonInfo->UserName); } } if (!NT_SUCCESS(Status)) { if (SessionCreated != FALSE) DispatchTable.DeleteLogonSession(LogonId); if (*ProfileBuffer != NULL) { DispatchTable.FreeClientBuffer(ClientRequest, *ProfileBuffer); *ProfileBuffer = NULL; } } if (UserHandle != NULL) SamrCloseHandle(&UserHandle); SamIFree_SAMPR_USER_INFO_BUFFER(UserInfo, UserAllInformation); SamIFree_SAMPR_ULONG_ARRAY(&RelativeIds); SamIFree_SAMPR_ULONG_ARRAY(&Use); if (DomainHandle != NULL) SamrCloseHandle(&DomainHandle); if (ServerHandle != NULL) SamrCloseHandle(&ServerHandle); if (AccountDomainSid != NULL) RtlFreeHeap(RtlGetProcessHeap(), 0, AccountDomainSid); if (Status == STATUS_NO_SUCH_USER || Status == STATUS_WRONG_PASSWORD) { *SubStatus = Status; Status = STATUS_LOGON_FAILURE; } TRACE("LsaApLogonUser done (Status 0x%08lx SubStatus 0x%08lx)\n", Status, *SubStatus); return Status; }
PLUGIN_EXPORT void ExecuteBang(void* data, LPCWSTR args) { ChildMeasure* child = (ChildMeasure*)data; ParentMeasure* parent = child->parent; // !CommandMeasure can only be used on the Parent measure. if (!parent || parent->ownerChild != child) return; // !CommandMeasure Clear if (_wcsicmp(args, L"Clear") == 0) { std::wstring currentData = parent->clipboard->GetIndex(0); // Clear contents of the Clipboard if (!parent->clipboard->DeleteClipboard()) { RmLog(LOG_ERROR, L"Clipboard.dll: Unable to delete clipboard"); } else { if (!currentData.empty()) { // Clear index 0 of ALL instances (if equal to current index 0) clearIndex(currentData); } } return; } else { // Check for commands with args. LPCWSTR arg = wcschr(args, L' '); if (arg) { // Skip the space ++arg; // !CommandMeasure ClearIndex n (where n represents an index) if (_wcsnicmp(args, L"ClearIndex", 10) == 0) { int index = _wtoi(arg); std::wstring currentData = parent->clipboard->GetIndex(index); if (!currentData.empty()) { // Index 0 represents the Windows Clipboard. If deleting this index, other parent measure need to be modified. if (index == 0) { parent->clipboard->ClearClipboard(); clearIndex(currentData); } else { if (!parent->clipboard->DeleteIndex(index)) { std::wstring error = L"Clipboard.dll: Unable to delete index \""; error += index; error += L'"'; RmLog(LOG_ERROR, error.c_str()); } } } return; } // !CommandMeasure "CopyIndex n" (where n represents an index) else if (_wcsnicmp(args, L"CopyIndex", 9) == 0) { LPCWSTR text = parent->clipboard->GetIndex(_wtoi(arg)); if (!parent->clipboard->SetClipboard(text)) { RmLog(LOG_ERROR, L"Clipboard.dll: Unable to set clipboard"); } return; } else { RmLog(LOG_ERROR, L"Clipboard.dll: Unknown args"); } } } return; }
BOOL CSubtitleWebvttReader::Probe(wchar_t *text) { if (bProbe) return FALSE; bProbe = TRUE; return _wcsicmp(text, L"WEBVTT") == 0; }
/* Lately, dirSpec appears to be (rightfully) unused. */ CF_PRIVATE CFMutableArrayRef _CFCreateContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType) { CFMutableArrayRef files = NULL; Boolean releaseBase = false; CFIndex pathLength = dirPath ? strlen(dirPath) : 0; // MF:!!! Need to use four-letter type codes where appropriate. CFStringRef extension = (matchingAbstractType ? _CFCopyExtensionForAbstractType(matchingAbstractType) : NULL); CFIndex targetExtLen = (extension ? CFStringGetLength(extension) : 0); #if DEPLOYMENT_TARGET_WINDOWS // This is a replacement for 'dirent' below, and also uses wchar_t to support unicode paths wchar_t extBuff[CFMaxPathSize]; int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :( if (targetExtLen > 0) { CFIndex usedBytes = 0; CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), kCFStringEncodingUTF16, 0, false, (uint8_t *)extBuff, CFMaxPathLength, &usedBytes); targetExtLen = usedBytes / sizeof(wchar_t); extBuff[targetExtLen] = '\0'; wchar_t *extBuffStr = (wchar_t *)extBuff; if (extBuffStr[0] == '.') extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example wchar_t *extBuffDotPtr = extBuffStr; while ((extBuffDotPtr = wcschr(extBuffStr, '.'))) { //find the next . in the extension... extBuffInteriorDotCount++; extBuffStr = extBuffDotPtr + 1; } } wchar_t pathBuf[CFMaxPathSize]; if (!dirPath) { if (!_CFURLGetWideFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) { if (extension) CFRelease(extension); return NULL; } pathLength = wcslen(pathBuf); } else { // Convert dirPath to a wide representation and put it into our pathBuf // Get the real length of the string in UTF16 characters CFStringRef dirPathStr = CFStringCreateWithCString(kCFAllocatorSystemDefault, dirPath, kCFStringEncodingUTF8); CFIndex strLen = CFStringGetLength(dirPathStr); // Copy the string into the buffer and terminate CFStringGetCharacters(dirPathStr, CFRangeMake(0, strLen), (UniChar *)pathBuf); pathBuf[strLen] = 0; CFRelease(dirPathStr); } WIN32_FIND_DATAW file; HANDLE handle; if (pathLength + 2 >= CFMaxPathLength) { if (extension) { CFRelease(extension); } return NULL; } pathBuf[pathLength] = '\\'; pathBuf[pathLength + 1] = '*'; pathBuf[pathLength + 2] = '\0'; handle = FindFirstFileW(pathBuf, (LPWIN32_FIND_DATAW)&file); if (INVALID_HANDLE_VALUE == handle) { pathBuf[pathLength] = '\0'; if (extension) { CFRelease(extension); } return NULL; } files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks); do { CFURLRef fileURL; CFIndex namelen = wcslen(file.cFileName); if (file.cFileName[0] == '.' && (namelen == 1 || (namelen == 2 && file.cFileName[1] == '.'))) { continue; } if (targetExtLen > namelen) continue; // if the extension is the same length or longer than the name, it can't possibly match. if (targetExtLen > 0) { if (file.cFileName[namelen - 1] == '.') continue; //filename ends with a dot, no extension wchar_t *fileExt = NULL; if (extBuffInteriorDotCount == 0) { fileExt = wcsrchr(file.cFileName, '.'); } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar" wchar_t *save = file.cFileName; while ((save = wcschr(save, '.')) && !fileExt) { wchar_t *temp = save; int moreDots = 0; while ((temp = wcschr(temp, '.'))) { if (++moreDots == extBuffInteriorDotCount) break; } if (moreDots == extBuffInteriorDotCount) { fileExt = save; } } } if (!fileExt) continue; //no extension if (((const wchar_t *)extBuff)[0] != '.') fileExt++; //omit the dot if the target file extension omits the dot CFIndex fileExtLen = wcslen(fileExt); //if the extensions are different lengths, they can't possibly match if (fileExtLen != targetExtLen) continue; // Check to see if it matches the extension we're looking for. if (_wcsicmp(fileExt, (const wchar_t *)extBuff) != 0) { continue; } } if (dirURL == NULL) { CFStringRef dirURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)pathBuf, pathLength * sizeof(wchar_t), kCFStringEncodingUTF16, NO); dirURL = CFURLCreateWithFileSystemPath(alloc, dirURLStr, kCFURLWindowsPathStyle, true); CFRelease(dirURLStr); releaseBase = true; } // MF:!!! What about the trailing slash? CFStringRef fileURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)file.cFileName, namelen * sizeof(wchar_t), kCFStringEncodingUTF16, NO); fileURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, fileURLStr, kCFURLWindowsPathStyle, (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false, dirURL); CFArrayAppendValue(files, fileURL); CFRelease(fileURL); CFRelease(fileURLStr); } while (FindNextFileW(handle, &file)); FindClose(handle); pathBuf[pathLength] = '\0'; #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD uint8_t extBuff[CFMaxPathSize]; int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :( if (targetExtLen > 0) { CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), CFStringFileSystemEncoding(), 0, false, extBuff, CFMaxPathLength, &targetExtLen); extBuff[targetExtLen] = '\0'; char *extBuffStr = (char *)extBuff; if (extBuffStr[0] == '.') extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example char *extBuffDotPtr = extBuffStr; while ((extBuffDotPtr = strchr(extBuffStr, '.'))) { //find the next . in the extension... extBuffInteriorDotCount++; extBuffStr = extBuffDotPtr + 1; } } uint8_t pathBuf[CFMaxPathSize]; if (!dirPath) { if (!CFURLGetFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) { if (extension) CFRelease(extension); return NULL; } else { dirPath = (char *)pathBuf; pathLength = strlen(dirPath); } } struct dirent buffer; struct dirent *dp; int err; int no_hang_fd = __CFProphylacticAutofsAccess ? open("/dev/autofs_nowait", 0) : -1; DIR *dirp = opendir(dirPath); if (!dirp) { if (extension) { CFRelease(extension); } if (-1 != no_hang_fd) close(no_hang_fd); return NULL; // raiseErrno("opendir", path); } files = CFArrayCreateMutable(alloc, 0, & kCFTypeArrayCallBacks); while((0 == readdir_r(dirp, &buffer, &dp)) && dp) { CFURLRef fileURL; unsigned namelen = strlen(dp->d_name); // skip . & ..; they cause descenders to go berserk if (dp->d_name[0] == '.' && (namelen == 1 || (namelen == 2 && dp->d_name[1] == '.'))) { continue; } if (targetExtLen > namelen) continue; // if the extension is the same length or longer than the name, it can't possibly match. if (targetExtLen > 0) { if (dp->d_name[namelen - 1] == '.') continue; //filename ends with a dot, no extension char *fileExt = NULL; if (extBuffInteriorDotCount == 0) { fileExt = strrchr(dp->d_name, '.'); } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar" char *save = dp->d_name; while ((save = strchr(save, '.')) && !fileExt) { char *temp = save; int moreDots = 0; while ((temp = strchr(temp, '.'))) { if (++moreDots == extBuffInteriorDotCount) break; } if (moreDots == extBuffInteriorDotCount) { fileExt = save; } } } if (!fileExt) continue; //no extension if (((char *)extBuff)[0] != '.') fileExt++; //omit the dot if the target extension omits the dot; safe, because we checked to make sure it isn't the last character just before size_t fileExtLen = strlen(fileExt); //if the extensions are different lengths, they can't possibly match if (fileExtLen != targetExtLen) continue; // Check to see if it matches the extension we're looking for. if (strncmp(fileExt, (char *)extBuff, fileExtLen) != 0) { continue; } } if (dirURL == NULL) { dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (uint8_t *)dirPath, pathLength, true); releaseBase = true; } if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN || dp->d_type == DT_LNK || dp->d_type == DT_WHT) { Boolean isDir = (dp->d_type == DT_DIR); if (!isDir) { // Ugh; must stat. char subdirPath[CFMaxPathLength]; struct statinfo statBuf; strlcpy(subdirPath, dirPath, sizeof(subdirPath)); strlcat(subdirPath, "/", sizeof(subdirPath)); strlcat(subdirPath, dp->d_name, sizeof(subdirPath)); if (stat(subdirPath, &statBuf) == 0) { isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } } #if DEPLOYMENT_TARGET_LINUX fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, namelen, isDir, dirURL); #else fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, dp->d_namlen, isDir, dirURL); #endif } else { #if DEPLOYMENT_TARGET_LINUX fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, namelen, false, dirURL); #else fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, dp->d_namlen, false, dirURL); #endif } CFArrayAppendValue(files, fileURL); CFRelease(fileURL); } err = closedir(dirp); if (-1 != no_hang_fd) close(no_hang_fd); if (err != 0) { CFRelease(files); if (releaseBase) { CFRelease(dirURL); } if (extension) { CFRelease(extension); } return NULL; } #else #error _CFCreateContentsOfDirectory() unknown architecture, not implemented #endif if (extension) { CFRelease(extension); } if (releaseBase) { CFRelease(dirURL); } return files; }
STDMETHODIMP CXMLDOMDocument::createNode(VARIANT TYPE, BSTR name, BSTR namespaceURI, IXMLDOMNode **pVal) { ATLTRACE(_T("CXMLDOMDocument::createNode\n")); HRESULT hr = S_OK; if (NULL == pVal) return E_POINTER; *pVal = NULL; VARIANT type; ::VariantInit(&type); if (V_VT(&TYPE) != VT_I4 && V_VT(&TYPE) != VT_BSTR) hr = ::VariantChangeType(&type,&TYPE,0,VT_I4); else hr = ::VariantCopy(&type,&TYPE); if (S_OK != hr) return hr; DOMNodeType nodeType = NODE_INVALID; if (VT_I4 == V_VT(&type)) nodeType = static_cast<DOMNodeType> (V_I4(&type)); else { OLECHAR* str = V_BSTR(&type); for (int i = 0; i < g_DomNodeNameSize; ++i) { if (0 == _wcsicmp(str,g_DomNodeName[i])) { nodeType = static_cast<DOMNodeType> (i); break; } } } ::VariantClear(&type); if (NODE_INVALID == nodeType || NODE_DOCUMENT == nodeType || NODE_DOCUMENT_TYPE == nodeType || NODE_ENTITY == nodeType || NODE_NOTATION == nodeType) return E_FAIL; try { switch(nodeType) { case NODE_ELEMENT: { DOMElement* node; if (SysStringLen(namespaceURI) > 0) node = m_Document->createElementNS(namespaceURI,name); else node = m_Document->createElement(name); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_ATTRIBUTE: { DOMAttr* node; if (SysStringLen(namespaceURI) > 0) node = m_Document->createAttributeNS(namespaceURI,name); else node = m_Document->createAttribute(name); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_TEXT: { DOMText* node = m_Document->createTextNode(OLESTR("")); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_CDATA_SECTION: { DOMCDATASection* node = m_Document->createCDATASection(OLESTR("")); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_ENTITY_REFERENCE: { DOMEntityReference* node = m_Document->createEntityReference(name); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_PROCESSING_INSTRUCTION: { DOMProcessingInstruction* node = m_Document->createProcessingInstruction(name,OLESTR("")); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_COMMENT: { DOMComment* node = m_Document->createComment(OLESTR("")); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } case NODE_DOCUMENT_FRAGMENT: { DOMDocumentFragment* node = m_Document->createDocumentFragment(); hr = wrapNode(m_pIXMLDOMDocument,node,IID_IXMLDOMNode,reinterpret_cast<LPVOID *> (pVal)); break; } default: hr = E_FAIL; break; } } catch(DOMException& ex) { hr = MakeHRESULT(ex); } catch (...) { hr = E_FAIL; } return hr; }
BOOL CMainFrameDropTarget::IsSupportedDropData(COleDataObject* pDataObject) { BOOL bResult; //************************************************************************ //*** THIS FUNCTION HAS TO BE AS FAST AS POSSIBLE!!! //************************************************************************ if (m_cfHTML && pDataObject->IsDataAvailable(m_cfHTML)) { // If the data is in 'HTML Format', there is no need to check the contents. bResult = TRUE; } else if (m_cfShellURL && pDataObject->IsDataAvailable(m_cfShellURL)) { // If the data is in 'UniformResourceLocator', there is no need to check the contents. bResult = TRUE; } else if (pDataObject->IsDataAvailable(CF_TEXT)) { // // Check text data // bResult = FALSE; HANDLE hMem; if ((hMem = pDataObject->GetGlobalData(CF_TEXT)) != NULL) { LPCSTR lpszUrl; if ((lpszUrl = (LPCSTR)GlobalLock(hMem)) != NULL) { // skip white space while (isspace((unsigned char)*lpszUrl)) lpszUrl++; bResult = IsUrlSchemeSupportedA(lpszUrl); GlobalUnlock(hMem); } GlobalFree(hMem); } } else if (pDataObject->IsDataAvailable(CF_HDROP)) { // // Check HDROP data // bResult = FALSE; HANDLE hMem; if ((hMem = pDataObject->GetGlobalData(CF_HDROP)) != NULL) { LPDROPFILES lpDrop; if ((lpDrop = (LPDROPFILES)GlobalLock(hMem)) != NULL) { // Just check, if there's at least one file we can import if (lpDrop->fWide) { LPCWSTR pszFileW = (LPCWSTR)((LPBYTE)lpDrop + lpDrop->pFiles); while (*pszFileW != L'\0') { int iLen = wcslen(pszFileW); LPCWSTR pszExtW = GetFileExtW(pszFileW, iLen); if (pszExtW != NULL && _wcsicmp(pszExtW, FILEEXTDOT_INETSHRTCUTW) == 0) { bResult = TRUE; break; } pszFileW += iLen + 1; } } else { LPCSTR pszFileA = (LPCSTR)((LPBYTE)lpDrop + lpDrop->pFiles); while (*pszFileA != '\0') { int iLen = strlen(pszFileA); LPCSTR pszExtA = GetFileExtA(pszFileA, iLen); if (pszExtA != NULL && _stricmp(pszExtA, FILEEXTDOT_INETSHRTCUTA) == 0) { bResult = TRUE; break; } pszFileA += iLen + 1; } } GlobalUnlock(hMem); } GlobalFree(hMem); } } else { // Unknown data format bResult = FALSE; } return bResult; }
/* ** Creates the given measure. This is the factory method for the measures. ** If new measures are implemented this method needs to be updated. ** */ CMeasure* CMeasure::Create(const WCHAR* measure, CMeterWindow* meterWindow, const WCHAR* name) { // Comparison is caseinsensitive if (_wcsicmp(L"CPU", measure) == 0) { return new CMeasureCPU(meterWindow, name); } else if (_wcsicmp(L"Memory", measure) == 0) { return new CMeasureMemory(meterWindow, name); } else if (_wcsicmp(L"NetIn", measure) == 0) { return new CMeasureNetIn(meterWindow, name); } else if (_wcsicmp(L"NetOut", measure) == 0) { return new CMeasureNetOut(meterWindow, name); } else if (_wcsicmp(L"NetTotal", measure) == 0) { return new CMeasureNetTotal(meterWindow, name); } else if (_wcsicmp(L"PhysicalMemory", measure) == 0) { return new CMeasurePhysicalMemory(meterWindow, name); } else if (_wcsicmp(L"SwapMemory", measure) == 0) { return new CMeasureVirtualMemory(meterWindow, name); } else if (_wcsicmp(L"FreeDiskSpace", measure) == 0) { return new CMeasureDiskSpace(meterWindow, name); } else if (_wcsicmp(L"Uptime", measure) == 0) { return new CMeasureUptime(meterWindow, name); } else if (_wcsicmp(L"Time", measure) == 0) { return new CMeasureTime(meterWindow, name); } else if (_wcsicmp(L"Plugin", measure) == 0) { return new CMeasurePlugin(meterWindow, name); } else if (_wcsicmp(L"Registry", measure) == 0) { return new CMeasureRegistry(meterWindow, name); } else if (_wcsicmp(L"Calc", measure) == 0) { return new CMeasureCalc(meterWindow, name); } else if (_wcsicmp(L"Script", measure) == 0) { return new CMeasureScript(meterWindow, name); } LogWithArgs(LOG_ERROR, L"Measure=%s is not valid in [%s]", measure, name); return NULL; }
bool DialogInstall::ReadPackage() { const WCHAR* fileName = m_PackageFileName.c_str(); const WCHAR* fileExtension = PathFindExtension(fileName); if (_wcsicmp(fileExtension, L".rmskin") == 0) { // Check if the footer is present (for new .rmskin format) PackageFooter footer = {0}; FILE* file = _wfopen(fileName, L"rb"); __int64 fileSize = 0; if (file) { fseek(file, -(long)sizeof(footer), SEEK_END); fileSize = _ftelli64(file); fread(&footer, sizeof(footer), 1, file); fclose(file); } if (strcmp(footer.key, "RMSKIN") == 0) { m_PackageFormat = PackageFormat::New; if (footer.size != fileSize) { return false; } if (footer.flags) { m_BackupPackage = !(footer.flags & PackageFlag::Backup); } } } else if (_wcsicmp(fileExtension, L".zip") != 0) { return false; } m_PackageUnzFile = unzOpen(ConvertToAscii(fileName).c_str()); if (!m_PackageUnzFile) { return false; } WCHAR buffer[MAX_PATH]; // Get temporary file to extract the options file and header bitmap GetTempPath(MAX_PATH, buffer); GetTempFileName(buffer, L"dat", 0, buffer); std::wstring tempFile = buffer; const WCHAR* tempFileSz = tempFile.c_str(); // Helper to sets buffer with current file name auto getFileInfo = [&]()->bool { char cBuffer[MAX_PATH * 3]; unz_file_info ufi; if (unzGetCurrentFileInfo( m_PackageUnzFile, &ufi, cBuffer, _countof(cBuffer), nullptr, 0, nullptr, 0) == UNZ_OK) { const uLong ZIP_UTF8_FLAG = 1 << 11; const DWORD codePage = (ufi.flag & ZIP_UTF8_FLAG) ? CP_UTF8 : CP_ACP; MultiByteToWideChar(codePage, 0, cBuffer, strlen(cBuffer) + 1, buffer, MAX_PATH); while (WCHAR* pos = wcschr(buffer, L'/')) *pos = L'\\'; return true; } return false; }; // Loop through the contents of the archive until the settings file is found WCHAR* path; bool optionsFound = false; do { if (!getFileInfo()) { return false; } path = wcsrchr(buffer, L'\\'); if (!path) { path = buffer; } else { if (m_PackageFormat == PackageFormat::New) { // New package files must be in root of archive continue; } ++path; // Skip slash } if (_wcsicmp(path, m_PackageFormat == PackageFormat::New ? L"RMSKIN.ini" : L"Rainstaller.cfg") == 0) { if (ExtractCurrentFile(tempFile)) { optionsFound = ReadOptions(tempFileSz); DeleteFile(tempFileSz); } break; } } while (unzGoToNextFile(m_PackageUnzFile) == UNZ_OK); if (!optionsFound) { return false; } // Loop through the archive a second time and find included components unzGoToFirstFile(m_PackageUnzFile); m_PackageRoot.assign(buffer, path - buffer); const WCHAR* root = m_PackageRoot.c_str(); do { if (!getFileInfo()) { return false; } if (wcsncmp(buffer, root, m_PackageRoot.length()) != 0) { // Ignore everything that isn't in the root directory continue; } WCHAR* component = buffer + m_PackageRoot.length(); path = wcschr(component, L'\\'); if (path) { *path = L'\0'; ++path; } else { if (_wcsicmp(component, m_PackageFormat == PackageFormat::New ? L"RMSKIN.bmp" : L"Rainstaller.bmp") == 0) { if (!ExtractCurrentFile(tempFile)) { return false; } m_HeaderBitmap = (HBITMAP)LoadImage(nullptr, tempFileSz, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); DeleteFile(tempFileSz); } continue; } const WCHAR* pos = wcschr(path, L'\\'); const WCHAR* extension = PathFindExtension(pos ? pos : path); if (pos) { // Component with subfolders const std::wstring item(path, pos - path); const WCHAR* itemSz = item.c_str(); if (_wcsicmp(component, L"Skins") == 0 && !IsIgnoredSkin(itemSz)) { m_PackageSkins.insert(item); } else if (_wcsicmp(component, m_PackageFormat == PackageFormat::New ? L"Layouts" : L"Themes") == 0 && _wcsicmp(extension, m_PackageFormat == PackageFormat::New ? L".ini" : L".thm") == 0 && !IsIgnoredLayout(itemSz)) { m_PackageLayouts.insert(item); } else if (_wcsicmp(component, L"Addons") == 0 && m_PackageFormat == PackageFormat::Old && !IsIgnoredAddon(itemSz)) { m_PackageAddons.insert(item); } else if (_wcsicmp(component, L"Plugins") == 0 && _wcsicmp(itemSz, IsWin32Build() ? L"32bit" : L"64bit") == 0 && _wcsicmp(extension, L".dll") == 0 && !wcschr(pos + 1, L'\\')) { const std::wstring plugin(pos + 1); if (!IsIgnoredPlugin(plugin.c_str())) { m_PackagePlugins.insert(plugin); } } } else { // Component with subfiles const std::wstring item = path; const WCHAR* itemSz = item.c_str(); if (_wcsicmp(component, L"Fonts") == 0 && m_PackageFormat == PackageFormat::Old && _wcsicmp(extension, L".ttf") == 0) { m_PackageFonts.insert(item); } } } while (unzGoToNextFile(m_PackageUnzFile) == UNZ_OK); if (m_PackageSkins.empty()) { // Fonts can be installed only with skins m_PackageFonts.clear(); } return !(m_PackageSkins.empty() && m_PackageLayouts.empty() && m_PackageAddons.empty() && m_PackageFonts.empty() && m_PackagePlugins.empty()); }
unsigned int CDepSettings::Load(LPCSTR szSettingsPath) { HRESULT hr = E_FAIL; if (!szSettingsPath) return IDS_UNEXPECTED; // Create the DOM CComPtr<IXMLDOMDocument> spDOMDoc; CComPtr<IXMLDOMNode> spRoot; CComPtr<IXMLDOMNode> spResultNode; hr = spDOMDoc.CoCreateInstance(L"Microsoft.XMLDOM"); if (FAILED(hr)) return IDS_ERR_FAILEDTOCREATEDOM; hr = spDOMDoc->put_async(VARIANT_FALSE); if (FAILED(hr)) return IDS_UNEXPECTED; // Load the document CComVariant varDocPath(szSettingsPath); VARIANT_BOOL vResult = VARIANT_FALSE; hr = spDOMDoc->load(varDocPath, &vResult); if (FAILED(hr) || vResult == VARIANT_FALSE) return IDS_ERR_FAILEDTOLOAD_SETTINGS_XML; // find the root element CComBSTR bstrSearch(L"ATLSINSTSETTINGS"); hr = spDOMDoc->selectSingleNode(bstrSearch, &spRoot); if (FAILED(hr) || !spRoot) return IDS_ERR_BADROOTNODE; CStringW strWebHostNameW; // load the list of web hosts bstrSearch = L"WEBHOSTNAME"; hr = spRoot->selectNodes(bstrSearch, &m_spHostList); if (FAILED(hr) || !m_spHostList) return IDS_ERR_WEBHOSTNAME; else { long len = 0; m_spHostList->get_length(&len); if (len == 0) return IDS_ERR_WEBHOSTNAME; CComPtr<IXMLDOMNode> spFirstWebHost; hr = m_spHostList->get_item(0,&spFirstWebHost); if (SUCCEEDED(hr)) { hr = spFirstWebHost->get_text(&bstrSearch); strWebHostNameW=bstrSearch; } } // load the virtual directory name on the host bstrSearch = L"VIRTDIRNAME"; hr = spRoot->selectSingleNode(bstrSearch, &spResultNode); if (FAILED(hr) || !spResultNode) return IDS_ERR_NOVIRTDIR; hr = spResultNode->get_text(&bstrSearch); if (FAILED(hr) || *bstrSearch == L'\0') return IDS_ERR_BADVIRTDIRNODE; m_strVirtDirName = bstrSearch; // load the virtual directory file system path spResultNode.Release(); bstrSearch = L"VIRTDIRFSPATH"; hr = spRoot->selectSingleNode(bstrSearch, &spResultNode); if (FAILED(hr) || !spResultNode) return IDS_ERR_NOVIRTDIRFSPATH; spResultNode->get_text(&bstrSearch); if (FAILED(hr) || *bstrSearch == L'\0') return IDS_ERR_BADVIRTDIRSFPATHNODE; m_strVirtDirFSPath = bstrSearch; if (!AtlIsFullPathT(m_strVirtDirFSPath.GetString())) { CStringW strPath; hr=GetWWWRootPath(strWebHostNameW,strPath); if (FAILED(hr) || strPath.IsEmpty() ) { return IDS_ERR_BADVIRTDIRSFPATHNODE; } m_strVirtDirFSPath=strPath; m_strVirtDirFSPath+=m_strVirtDirName; } // load the DoNotCreateVirtDir value spResultNode.Release(); bstrSearch = L"DONOTCREATEVIRTDIR"; hr = spRoot->selectSingleNode(bstrSearch, &spResultNode); if (hr == S_OK && spResultNode) { hr = spResultNode->get_text(&bstrSearch); if (FAILED(hr)) PrintWarning(IDS_ERR_BADDONOTCREATEVIRTDIR); else { if (!_wcsicmp(bstrSearch, L"false")) m_bDoNotCreateVirtDir = false; else if (!_wcsicmp(bstrSearch, L"true")) m_bDoNotCreateVirtDir = true; else { PrintWarning(IDS_ERR_INVALIDDONOTCREATEVIRTDIR); } } } // load the registerisapi value spResultNode.Release(); bstrSearch = L"REGISTERISAPI"; hr = spRoot->selectSingleNode(bstrSearch, &spResultNode); if (hr == S_OK && spResultNode) { hr = spResultNode->get_text(&bstrSearch); if (FAILED(hr)) PrintWarning(IDS_ERR_BADREGISTERISAPI); else { if (!_wcsicmp(bstrSearch, L"false")) m_bRegIsapi = false; else if (!_wcsicmp(bstrSearch, L"true")) m_bRegIsapi = true; else { PrintWarning(IDS_ERR_INVALIDREGISTERISAPI); } } } // load the unload before copy value spResultNode.Release(); bstrSearch = L"UNLOADBEFORECOPY"; hr = spRoot->selectSingleNode(bstrSearch, &spResultNode); if (hr == S_OK && spResultNode) { hr = spResultNode->get_text(&bstrSearch); if (FAILED(hr)) PrintWarning(IDS_ERR_BADUNLOADBEFORECOPY); else { if (!_wcsicmp(bstrSearch, L"false")) m_bUnloadBeforeCopy = false; else if (!_wcsicmp(bstrSearch, L"true")) m_bUnloadBeforeCopy = true; else PrintWarning(IDS_ERR_INVALIDUNLOADBEFORECOPY); } } // load the app isolation value spResultNode.Release(); bstrSearch = L"APPISOLATION"; hr = spRoot->selectSingleNode(bstrSearch, &spResultNode); if (hr == S_OK && spResultNode) { hr = spResultNode->get_text(&bstrSearch); if (FAILED(hr)) PrintWarning(IDS_ERR_BADAPPISOLATION); else { wchar_t *szEnd = NULL; short nIso = (short)wcstol(bstrSearch, &szEnd, 10); if (errno == ERANGE || nIso < 0 || nIso > 2) { PrintWarning(IDS_ERR_INVALIDAPPISOLATION); } else { switch(nIso) { case 0: m_nAppIsolation = nIso; break; case 1: m_nAppIsolation = 2; break; case 2: m_nAppIsolation = 1; break; } } } } // load the list of APPMAPPING nodes bstrSearch = L"APPMAPPING"; hr = spRoot->selectNodes(bstrSearch, &m_spAppMappings); // load list of APPFILEGROUP nodes bstrSearch = L"APPFILEGROUP"; hr = spRoot->selectNodes(bstrSearch, &m_spAppFileGroups); // see if there is a node for the extension. There better be only one because // we will only select the first one we run into. CComPtr<IXMLDOMNode> spIsapiNode; hr = spRoot->selectSingleNode(CComBSTR(L"//APPFILENAME[@type=\"extension\"] "), &spIsapiNode); if (hr == S_OK && spIsapiNode) { // select the <DEST> node CComPtr<IXMLDOMNode> spDestNode; hr = spIsapiNode->selectSingleNode(CComBSTR(L"DEST"), &spDestNode); if (hr == S_OK && spDestNode) { CComBSTR bstrPath; hr = spDestNode->get_text(&bstrPath); if (hr == S_OK && bstrPath[0] != L'\0') { m_strExtFileName = bstrPath; } } } GetIISMajorVer(); #ifdef _DEBUG // dump the settings printf("loaded settings:\n"); printf("Virtual directory name: %s\n", m_strVirtDirName); printf("Virtual directory fs path: %s\n", m_strVirtDirFSPath); printf("Virtual directory isapi extension name: %s\n",m_strExtFileName); printf("Do not create virtual directory: %s\n", m_bDoNotCreateVirtDir ? "true" : "false"); printf("Register ISAPI: %s\n", m_bRegIsapi ? "true" : "false"); printf("Unload before copy: %s\n", m_bUnloadBeforeCopy ? "true" : "false"); printf("App Isolation: %d\n", m_nAppIsolation); long lCount = 0; if (m_spHostList) { m_spHostList->get_length(&lCount); printf("Host count: %d\n", lCount); } else { printf("no hosts encountered\n"); } if (m_spAppMappings) { lCount = 0; m_spAppMappings->get_length(&lCount); printf("App Mapping count: %d\n", lCount); } else { printf("no app mappings\n"); } if (m_spAppFileGroups) { lCount = 0; m_spAppFileGroups->get_length(&lCount); printf("App file group count: %d\n", lCount); } #endif return S_OK; }
bool DialogInstall::InstallPackage() { if ((!m_MergeSkins && m_BackupSkins) || m_BackupPackage) { // Move skins into backup folder for (auto iter = m_PackageSkins.cbegin(); iter != m_PackageSkins.cend(); ++iter) { std::wstring from = g_Data.skinsPath + *iter; if (_waccess(from.c_str(), 0) == -1) { continue; } SHFILEOPSTRUCT fo = { nullptr, FO_DELETE, nullptr, nullptr, FOF_NO_UI | FOF_NOCONFIRMATION | FOF_ALLOWUNDO }; if (m_BackupPackage) { // Remove current skin from += L'\0'; fo.pFrom = from.c_str(); SHFileOperation(&fo); } else { std::wstring to = g_Data.skinsPath + L"@Backup\\"; CreateDirectory(to.c_str(), nullptr); // Delete current backup to += *iter; to += L'\0'; fo.pFrom = to.c_str(); SHFileOperation(&fo); if (!CopyFiles(from, to, true)) { m_ErrorMessage = L"Unable to move to:\n"; m_ErrorMessage += to; return false; } } } } WCHAR buffer[MAX_PATH]; // Helper to sets buffer with current file name auto getFileInfo = [&]()->bool { char cBuffer[MAX_PATH * 3]; unz_file_info ufi; if (unzGetCurrentFileInfo( m_PackageUnzFile, &ufi, cBuffer, _countof(cBuffer), nullptr, 0, nullptr, 0) == UNZ_OK) { const uLong ZIP_UTF8_FLAG = 1 << 11; const DWORD codePage = (ufi.flag & ZIP_UTF8_FLAG) ? CP_UTF8 : CP_ACP; MultiByteToWideChar(codePage, 0, cBuffer, strlen(cBuffer) + 1, buffer, MAX_PATH); while (WCHAR* pos = wcschr(buffer, L'/')) *pos = L'\\'; return true; } return false; }; unzGoToFirstFile(m_PackageUnzFile); const WCHAR* root = m_PackageRoot.c_str(); do { if (!getFileInfo()) { m_ErrorMessage = L"Error retrieving file info."; return false; } if (wcsncmp(buffer, root, m_PackageRoot.length()) != 0) { // Ignore everything that isn't in the root directory continue; } WCHAR* component = buffer + m_PackageRoot.length(); WCHAR* path = wcschr(component, L'\\'); if (path) { *path = L'\0'; ++path; } else { continue; } bool error = false; std::wstring targetPath; WCHAR* pos = wcschr(path, L'\\'); WCHAR* extension = PathFindExtension(pos ? pos : path); if (pos) { const std::wstring item(path, pos - path); if (_wcsicmp(component, L"Skins") == 0 && m_PackageSkins.find(item) != m_PackageSkins.end()) { targetPath = g_Data.skinsPath; } else if (_wcsicmp(component, L"Addons") == 0 && m_PackageFormat == PackageFormat::Old && m_PackageAddons.find(item) != m_PackageAddons.end()) { targetPath = g_Data.settingsPath; targetPath += L"Addons\\"; } else if (_wcsicmp(component, L"Plugins") == 0 && _wcsnicmp(path, IsWin32Build() ? L"32bit" : L"64bit", pos - path) == 0 && _wcsicmp(extension, L".dll") == 0 && !wcschr(pos + 1, L'\\')) { const std::wstring plugin(pos + 1); if (m_PackagePlugins.find(plugin) != m_PackagePlugins.end()) { path = pos + 1; targetPath = g_Data.settingsPath; targetPath += L"Plugins\\"; } } if (!targetPath.empty()) { targetPath += path; error = !ExtractCurrentFile(targetPath); } else if (_wcsicmp(component, m_PackageFormat == PackageFormat::New ? L"Layouts" : L"Themes") == 0 && _wcsicmp(extension, m_PackageFormat == PackageFormat::New ? L".ini" : L".thm") == 0 && m_PackageLayouts.find(item) != m_PackageLayouts.end()) { if (m_PackageFormat == PackageFormat::Old) { wcscpy_s(extension, 5, L".ini"); } targetPath = g_Data.settingsPath; targetPath += L"Layouts\\"; targetPath += path; error = !ExtractCurrentFile(targetPath); if (!error) { CleanLayoutFile(targetPath.c_str()); } } } else { if (_wcsicmp(component, L"Fonts") == 0 && m_PackageFormat == PackageFormat::Old && _wcsicmp(extension, L".ttf") == 0) { for (auto iter = m_PackageSkins.cbegin(); iter != m_PackageSkins.cend(); ++iter) { targetPath = g_Data.skinsPath; targetPath += *iter; targetPath += L"\\@Resources\\Fonts\\"; targetPath += path; error = !ExtractCurrentFile(targetPath); if (error) { break; } } } } if (error) { m_ErrorMessage = L"Unable to create file:\n"; m_ErrorMessage += targetPath; m_ErrorMessage += L"\n\nSkin Installer will now quit."; return false; } } while (unzGoToNextFile(m_PackageUnzFile) == UNZ_OK); if (!m_MergeSkins && m_BackupSkins) { KeepVariables(); } return true; }
PLUGIN_EXPORT void Reload(void* data, void* rm, double* maxValue) { MeasureData* measure = (MeasureData*)data; int defaultData = -1; LPCTSTR type = RmReadString(rm, L"SysInfoType", L""); if (_wcsicmp(L"COMPUTER_NAME", type) == 0) { measure->type = MEASURE_COMPUTER_NAME; } else if (_wcsicmp(L"USER_NAME", type) == 0) { measure->type = MEASURE_USER_NAME; } else if (_wcsicmp(L"WORK_AREA", type) == 0) { measure->type = MEASURE_WORK_AREA; } else if (_wcsicmp(L"SCREEN_SIZE", type) == 0) { measure->type = MEASURE_SCREEN_SIZE; } else if (_wcsicmp(L"RAS_STATUS", type) == 0) { measure->type = MEASURE_RAS_STATUS; } else if (_wcsicmp(L"OS_VERSION", type) == 0) { measure->type = MEASURE_OS_VERSION; } else if (_wcsicmp(L"OS_BITS", type) == 0) { measure->type = MEASURE_OS_BITS; } else if (_wcsicmp(L"ADAPTER_DESCRIPTION", type) == 0) { defaultData = 0; measure->type = MEASURE_ADAPTER_DESCRIPTION; } else if (_wcsicmp(L"NET_MASK", type) == 0) { defaultData = 0; measure->type = MEASURE_NET_MASK; } else if (_wcsicmp(L"IP_ADDRESS", type) == 0) { defaultData = 0; measure->type = MEASURE_IP_ADDRESS; } else if (_wcsicmp(L"GATEWAY_ADDRESS", type) == 0) { defaultData = 0; measure->type = MEASURE_GATEWAY_ADDRESS; } else if (_wcsicmp(L"HOST_NAME", type) == 0) { measure->type = MEASURE_HOST_NAME; } else if (_wcsicmp(L"DOMAIN_NAME", type) == 0) { measure->type = MEASURE_DOMAIN_NAME; } else if (_wcsicmp(L"DNS_SERVER", type) == 0) { measure->type = MEASURE_DNS_SERVER; } else if (_wcsicmp(L"INTERNET_CONNECTIVITY", type) == 0) { measure->type = MEASURE_INTERNET_CONNECTIVITY; } else if (_wcsicmp(L"LAN_CONNECTIVITY", type) == 0) { measure->type = MEASURE_LAN_CONNECTIVITY; } else if (_wcsicmp(L"WORK_AREA_TOP", type) == 0) { measure->type = MEASURE_WORK_AREA_TOP; } else if (_wcsicmp(L"WORK_AREA_LEFT", type) == 0) { measure->type = MEASURE_WORK_AREA_LEFT; } else if (_wcsicmp(L"WORK_AREA_WIDTH", type) == 0) { measure->type = MEASURE_WORK_AREA_WIDTH; } else if (_wcsicmp(L"WORK_AREA_HEIGHT", type) == 0) { measure->type = MEASURE_WORK_AREA_HEIGHT; } else if (_wcsicmp(L"SCREEN_WIDTH", type) == 0) { measure->type = MEASURE_SCREEN_WIDTH; } else if (_wcsicmp(L"SCREEN_HEIGHT", type) == 0) { measure->type = MEASURE_SCREEN_HEIGHT; } else if (_wcsicmp(L"NUM_MONITORS", type) == 0) { measure->type = MEASURE_NUM_MONITORS; } else if (_wcsicmp(L"VIRTUAL_SCREEN_TOP", type) == 0) { measure->type = MEASURE_VIRTUAL_SCREEN_TOP; } else if (_wcsicmp(L"VIRTUAL_SCREEN_LEFT", type) == 0) { measure->type = MEASURE_VIRTUAL_SCREEN_LEFT; } else if (_wcsicmp(L"VIRTUAL_SCREEN_WIDTH", type) == 0) { measure->type = MEASURE_VIRTUAL_SCREEN_WIDTH; } else if (_wcsicmp(L"VIRTUAL_SCREEN_HEIGHT", type) == 0) { measure->type = MEASURE_VIRTUAL_SCREEN_HEIGHT; } else { WCHAR buffer[256]; _snwprintf_s(buffer, _TRUNCATE, L"SysInfo.dll: SysInfoType=%s is not valid in [%s]", type, RmGetMeasureName(rm)); RmLog(LOG_ERROR, buffer); } measure->data = RmReadInt(rm, L"SysInfoData", defaultData); }
int CALLBACK ProcessPageCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { int ret = 0; LPPROCESS_PAGE_LIST_ITEM Param1; LPPROCESS_PAGE_LIST_ITEM Param2; ULONG IndexParam1; ULONG IndexParam2; WCHAR text1[260]; WCHAR text2[260]; ULONG l1; ULONG l2; LARGE_INTEGER time1; LARGE_INTEGER time2; IO_COUNTERS iocounters1; IO_COUNTERS iocounters2; ULONGLONG ull1; ULONGLONG ull2; if (TaskManagerSettings.SortAscending) { Param1 = (LPPROCESS_PAGE_LIST_ITEM)lParam1; Param2 = (LPPROCESS_PAGE_LIST_ITEM)lParam2; } else { Param1 = (LPPROCESS_PAGE_LIST_ITEM)lParam2; Param2 = (LPPROCESS_PAGE_LIST_ITEM)lParam1; } IndexParam1 = PerfDataGetProcessIndex(Param1->ProcessId); IndexParam2 = PerfDataGetProcessIndex(Param2->ProcessId); if (TaskManagerSettings.SortColumn == COLUMN_IMAGENAME) { PerfDataGetImageName(IndexParam1, text1, sizeof (text1) / sizeof (*text1)); PerfDataGetImageName(IndexParam2, text2, sizeof (text2) / sizeof (*text2)); ret = _wcsicmp(text1, text2); } else if (TaskManagerSettings.SortColumn == COLUMN_PID) { l1 = Param1->ProcessId; l2 = Param2->ProcessId; ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_USERNAME) { PerfDataGetUserName(IndexParam1, text1, sizeof (text1) / sizeof (*text1)); PerfDataGetUserName(IndexParam2, text2, sizeof (text2) / sizeof (*text2)); ret = _wcsicmp(text1, text2); } else if (TaskManagerSettings.SortColumn == COLUMN_SESSIONID) { l1 = PerfDataGetSessionId(IndexParam1); l2 = PerfDataGetSessionId(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_CPUUSAGE) { l1 = PerfDataGetCPUUsage(IndexParam1); l2 = PerfDataGetCPUUsage(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_CPUTIME) { time1 = PerfDataGetCPUTime(IndexParam1); time2 = PerfDataGetCPUTime(IndexParam2); ret = largeintcmp(time1, time2); } else if (TaskManagerSettings.SortColumn == COLUMN_MEMORYUSAGE) { l1 = PerfDataGetWorkingSetSizeBytes(IndexParam1); l2 = PerfDataGetWorkingSetSizeBytes(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_PEAKMEMORYUSAGE) { l1 = PerfDataGetPeakWorkingSetSizeBytes(IndexParam1); l2 = PerfDataGetPeakWorkingSetSizeBytes(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_MEMORYUSAGEDELTA) { l1 = PerfDataGetWorkingSetSizeDelta(IndexParam1); l2 = PerfDataGetWorkingSetSizeDelta(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_PAGEFAULTS) { l1 = PerfDataGetPageFaultCount(IndexParam1); l2 = PerfDataGetPageFaultCount(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_PAGEFAULTSDELTA) { l1 = PerfDataGetPageFaultCountDelta(IndexParam1); l2 = PerfDataGetPageFaultCountDelta(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_VIRTUALMEMORYSIZE) { l1 = PerfDataGetVirtualMemorySizeBytes(IndexParam1); l2 = PerfDataGetVirtualMemorySizeBytes(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_PAGEDPOOL) { l1 = PerfDataGetPagedPoolUsagePages(IndexParam1); l2 = PerfDataGetPagedPoolUsagePages(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_NONPAGEDPOOL) { l1 = PerfDataGetNonPagedPoolUsagePages(IndexParam1); l2 = PerfDataGetNonPagedPoolUsagePages(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_BASEPRIORITY) { l1 = PerfDataGetBasePriority(IndexParam1); l2 = PerfDataGetBasePriority(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_HANDLECOUNT) { l1 = PerfDataGetHandleCount(IndexParam1); l2 = PerfDataGetHandleCount(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_THREADCOUNT) { l1 = PerfDataGetThreadCount(IndexParam1); l2 = PerfDataGetThreadCount(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_USEROBJECTS) { l1 = PerfDataGetUSERObjectCount(IndexParam1); l2 = PerfDataGetUSERObjectCount(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_GDIOBJECTS) { l1 = PerfDataGetGDIObjectCount(IndexParam1); l2 = PerfDataGetGDIObjectCount(IndexParam2); ret = CMP(l1, l2); } else if (TaskManagerSettings.SortColumn == COLUMN_IOREADS) { PerfDataGetIOCounters(IndexParam1, &iocounters1); PerfDataGetIOCounters(IndexParam2, &iocounters2); ull1 = iocounters1.ReadOperationCount; ull2 = iocounters2.ReadOperationCount; ret = CMP(ull1, ull2); } else if (TaskManagerSettings.SortColumn == COLUMN_IOWRITES) { PerfDataGetIOCounters(IndexParam1, &iocounters1); PerfDataGetIOCounters(IndexParam2, &iocounters2); ull1 = iocounters1.WriteOperationCount; ull2 = iocounters2.WriteOperationCount; ret = CMP(ull1, ull2); } else if (TaskManagerSettings.SortColumn == COLUMN_IOOTHER) { PerfDataGetIOCounters(IndexParam1, &iocounters1); PerfDataGetIOCounters(IndexParam2, &iocounters2); ull1 = iocounters1.OtherOperationCount; ull2 = iocounters2.OtherOperationCount; ret = CMP(ull1, ull2); } else if (TaskManagerSettings.SortColumn == COLUMN_IOREADBYTES) { PerfDataGetIOCounters(IndexParam1, &iocounters1); PerfDataGetIOCounters(IndexParam2, &iocounters2); ull1 = iocounters1.ReadTransferCount; ull2 = iocounters2.ReadTransferCount; ret = CMP(ull1, ull2); } else if (TaskManagerSettings.SortColumn == COLUMN_IOWRITEBYTES) { PerfDataGetIOCounters(IndexParam1, &iocounters1); PerfDataGetIOCounters(IndexParam2, &iocounters2); ull1 = iocounters1.WriteTransferCount; ull2 = iocounters2.WriteTransferCount; ret = CMP(ull1, ull2); } else if (TaskManagerSettings.SortColumn == COLUMN_IOOTHERBYTES) { PerfDataGetIOCounters(IndexParam1, &iocounters1); PerfDataGetIOCounters(IndexParam2, &iocounters2); ull1 = iocounters1.OtherTransferCount; ull2 = iocounters2.OtherTransferCount; ret = CMP(ull1, ull2); } return ret; }
void GetProcessID(LPCTSTR pProcessName, std::vector<DWORD>& SetOfPID) { PPERF_DATA_BLOCK pPerfData = NULL; PPERF_OBJECT_TYPE pPerfObj; PPERF_INSTANCE_DEFINITION pPerfInst; PPERF_COUNTER_DEFINITION pPerfCntr, pCurCntr; PPERF_COUNTER_BLOCK PtrToCntr; DWORD BufferSize = TOTALBYTES; DWORD i, j; LONG k; // Allocate the buffer for the performance data. pPerfData = (PPERF_DATA_BLOCK)malloc(BufferSize); wchar_t szKey[32]; swprintf_s(szKey, L"%d %d", PROCESS_OBJECT_INDEX, PROC_ID_COUNTER); LONG lRes; while ((lRes = RegQueryValueEx(HKEY_PERFORMANCE_DATA, szKey, NULL, NULL, (LPBYTE)pPerfData, &BufferSize)) == ERROR_MORE_DATA) { // Get a buffer that is big enough. BufferSize += BYTEINCREMENT; pPerfData = (PPERF_DATA_BLOCK)realloc(pPerfData, BufferSize); } // Get the first object type. pPerfObj = FirstObject(pPerfData); // Process all objects. for (i = 0; i < pPerfData->NumObjectTypes; i++) { if (pPerfObj->ObjectNameTitleIndex != PROCESS_OBJECT_INDEX) { pPerfObj = NextObject(pPerfObj); continue; } SetOfPID.clear(); // Get the first counter. pPerfCntr = FirstCounter(pPerfObj); // Get the first instance. pPerfInst = FirstInstance(pPerfObj); _bstr_t bstrProcessName, bstrInput; // Retrieve all instances. for (k = 0; k < pPerfObj->NumInstances; k++) { pCurCntr = pPerfCntr; bstrInput = pProcessName; bstrProcessName = (wchar_t *)((PBYTE)pPerfInst + pPerfInst->NameOffset); if (!_wcsicmp((LPCTSTR)bstrProcessName, (LPCTSTR)bstrInput)) { // Retrieve all counters. for (j = 0; j < pPerfObj->NumCounters; j++) { if (pCurCntr->CounterNameTitleIndex == PROC_ID_COUNTER) { PtrToCntr = CounterBlock(pPerfInst); DWORD *pdwValue = (DWORD*)((LPBYTE)PtrToCntr + pCurCntr->CounterOffset); SetOfPID.push_back(*pdwValue); break; } // Get the next counter. pCurCntr = NextCounter(pCurCntr); } } // Get the next instance. pPerfInst = NextInstance(pPerfInst); } } free(pPerfData); RegCloseKey(HKEY_PERFORMANCE_DATA); }
CPrefs::CPrefs(int argc, LPCWSTR argv[], HRESULT &hr) : m_pMMDevice(NULL) , m_bInt16(true) , m_bMono(false) , m_iSampleRateDivisor(1) , m_pwfx(NULL) { switch (argc) { case 2: if (0 == _wcsicmp(argv[1], L"-?") || 0 == _wcsicmp(argv[1], L"/?")) { // print usage but don't actually capture hr = S_FALSE; usage(argv[0]); return; } else if (0 == _wcsicmp(argv[1], L"--list-devices")) { // list the devices but don't actually capture hr = list_devices(); // don't actually play if (S_OK == hr) { hr = S_FALSE; return; } } // intentional fallthrough default: // loop through arguments and parse them for (int i = 1; i < argc; i++) { // --device if (0 == _wcsicmp(argv[i], L"--device")) { if (NULL != m_pMMDevice) { printf("Only one --device switch is allowed\n"); hr = E_INVALIDARG; return; } if (i++ == argc) { printf("--device switch requires an argument\n"); hr = E_INVALIDARG; return; } hr = get_specific_device(argv[i], &m_pMMDevice); if (FAILED(hr)) { return; } continue; } // --int-16 if (0 == _wcsicmp(argv[i], L"--int-16")) { if (m_bInt16) { printf("Only one --int-16 switch is allowed\n"); hr = E_INVALIDARG; return; } m_bInt16 = true; continue; } // --mono if (0 == _wcsicmp(argv[i], L"--mono")) { m_bMono = true; continue; } // --div divisor if (0 == _wcsicmp(argv[i], L"--div")) { if (i++ == argc) { printf("--div switch requires an argument\n"); hr = E_INVALIDARG; return; } m_iSampleRateDivisor = _wtoi(argv[i]); continue; } printf("Invalid argument %ls\n", argv[i]); hr = E_INVALIDARG; return; } // open default device if not specified if (NULL == m_pMMDevice) { hr = get_default_device(&m_pMMDevice); if (FAILED(hr)) { return; } } } }
int _tmain(int argc, _TCHAR* argv[]) { WORD wVersionRequested; WSADATA wsaData; int err; SOCKET client_socket = INVALID_SOCKET; sockaddr_in sock; if(argc < 2) { Usage(); return -1; } wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if (err != 0) { // Check if error = WSAVERNOTSUPPORTED and if is -- // It means ws2_32.dll is too old. This system needs a serious update. wprintf(L"WSAStartup failed with error: %d\n", err); return -1; } // // Create a socket // client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (client_socket == INVALID_SOCKET) { wprintf(L"Create socket failed. Error: %u\n", WSAGetLastError()); WSACleanup(); return -1; } // // Fill in sockaddr_in -- Address family, IP address, port // sock.sin_family = AF_INET; sock.sin_addr.s_addr = inet_addr("127.0.0.1"); //(INADDR_ANY); //("127.0.0.1"); sock.sin_port = htons(6000); // // Connect to server // err = connect(client_socket, (SOCKADDR *) & sock, sizeof (sock)); if(err == SOCKET_ERROR) { wprintf(L"Connect() failed. Error: %ld\n", WSAGetLastError()); closesocket(client_socket); WSACleanup(); return -1; } // // Send Command // if(_wcsicmp(argv[1], L"-heart") == 0) { SendHeartCheck(client_socket); } else if(_wcsicmp(argv[1], L"-execute") == 0) { SendProcessExecute(argv[2], client_socket); } else if(_wcsicmp(argv[1], L"-kill") == 0) { SendTerminateProcess(_wtoi(argv[2]), client_socket); } else if(_wcsicmp(argv[1], L"-ps") == 0) { SendEnumerateProcess(client_socket); } else { wprintf(L"Error: Unkown Command!\n"); Usage(); } // // Cleanup // closesocket(client_socket); WSACleanup(); return 0; }