void AddFeature(WCHAR* szFeatures, size_t cbDest, WCHAR* Feature, BOOL* bFirst) { if (!*bFirst) StringCbCatW(szFeatures, cbDest, L", "); *bFirst = FALSE; StringCbCatW(szFeatures, cbDest, Feature); }
BOOL FormatFs (int driveNo, int clusterSize, int fsType) { wchar_t dllPath[MAX_PATH] = {0}; WCHAR dir[8] = { (WCHAR) driveNo + L'A', 0 }; PFORMATEX FormatEx; HMODULE hModule; int i; WCHAR szFsFormat[16]; WCHAR szLabel[2] = {0}; switch (fsType) { case FILESYS_NTFS: StringCbCopyW (szFsFormat, sizeof (szFsFormat),L"NTFS"); break; case FILESYS_EXFAT: StringCbCopyW (szFsFormat, sizeof (szFsFormat),L"EXFAT"); break; default: return FALSE; } if (GetSystemDirectory (dllPath, MAX_PATH)) { StringCbCatW(dllPath, sizeof(dllPath), L"\\fmifs.dll"); } else StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32\\fmifs.dll"); hModule = LoadLibrary (dllPath); if (hModule == NULL) return FALSE; if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle (L"fmifs.dll"), "FormatEx"))) { FreeLibrary (hModule); return FALSE; } StringCbCatW (dir, sizeof(dir), L":\\"); FormatExError = TRUE; // Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS. // It often helps to retry several times. for (i = 0; i < 50 && FormatExError; i++) { FormatExError = FALSE; FormatEx (dir, FMIFS_HARDDISK, szFsFormat, szLabel, TRUE, clusterSize * FormatSectorSize, FormatExCallback); } // The device may be referenced for some time after FormatEx() returns Sleep (4000); FreeLibrary (hModule); return FormatExError? FALSE : TRUE; }
HRESULT GetNTObjectSymbolicLinkTarget(LPCWSTR path, LPCWSTR entryName, PUNICODE_STRING LinkTarget) { HANDLE handle; WCHAR buffer[MAX_PATH]; LPWSTR pend = buffer; StringCbCopyExW(buffer, sizeof(buffer), path, &pend, NULL, 0); if (pend[-1] != '\\') { *pend++ = '\\'; *pend = 0; } StringCbCatW(buffer, sizeof(buffer), entryName); DbgPrint("GetNTObjectSymbolicLinkTarget %d\n", buffer); LinkTarget->Length = 0; DWORD err = NtOpenObject(SYMBOLICLINK_OBJECT, &handle, SYMBOLIC_LINK_QUERY, buffer); if (!NT_SUCCESS(err)) return HRESULT_FROM_NT(err); err = NtQuerySymbolicLinkObject(handle, LinkTarget, NULL); if (!NT_SUCCESS(err)) return HRESULT_FROM_NT(err); NtClose(handle); return S_OK; }
//***************************************************************************** // Function: WbemErrorString // Purpose: Turns sc into a text string // Note: The BSTR returned by this method needs to be freed by the caller. // If allocation fails, the method will return NULL //***************************************************************************** BSTR WbemErrorString(SCODE sc) { IWbemStatusCodeTextPtr pStatus; BSTR bstr = NULL; SCODE mysc = CoCreateInstance(CLSID_WbemStatusCodeText, 0, CLSCTX_INPROC_SERVER, IID_IWbemStatusCodeText, (LPVOID *) &pStatus); if (mysc == S_OK) { mysc = pStatus->GetErrorCodeText(sc, 0, 0, &bstr); if (mysc == S_OK) { } else { WCHAR szBuffer2[MAXITOA]; WCHAR szBuffer[sizeof(szBuffer2) + 4]; _ltow_s(sc, szBuffer2, 16); StringCbCopyW(szBuffer, sizeof(szBuffer), L"0x"); StringCbCatW(szBuffer, sizeof(szBuffer), szBuffer2); bstr = SysAllocString(szBuffer); } } return bstr; }
DWORD GetDisplayNameID(IN LPCWSTR lpLogName) { HKEY hKey; WCHAR *KeyPath; DWORD dwMessageID = 0; DWORD cbData; SIZE_T cbKeyPath; cbKeyPath = (wcslen(EVENTLOG_BASE_KEY) + wcslen(lpLogName) + 1) * sizeof(WCHAR); KeyPath = HeapAlloc(GetProcessHeap(), 0, cbKeyPath); if (!KeyPath) { return 0; } StringCbCopyW(KeyPath, cbKeyPath, EVENTLOG_BASE_KEY); StringCbCatW(KeyPath, cbKeyPath, lpLogName); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, KeyPath, 0, KEY_READ, &hKey) != ERROR_SUCCESS) { HeapFree(GetProcessHeap(), 0, KeyPath); return 0; } cbData = sizeof(dwMessageID); RegQueryValueExW(hKey, L"DisplayNameID", NULL, NULL, (LPBYTE)&dwMessageID, &cbData); RegCloseKey(hKey); HeapFree(GetProcessHeap(), 0, KeyPath); return dwMessageID; }
VOID GetDisplayNameFile(IN LPCWSTR lpLogName, OUT PWCHAR lpModuleName) { HKEY hKey; WCHAR *KeyPath; WCHAR szModuleName[MAX_PATH]; DWORD cbData; SIZE_T cbKeyPath; cbKeyPath = (wcslen(EVENTLOG_BASE_KEY) + wcslen(lpLogName) + 1) * sizeof(WCHAR); KeyPath = HeapAlloc(GetProcessHeap(), 0, cbKeyPath); if (!KeyPath) { return; } StringCbCopyW(KeyPath, cbKeyPath, EVENTLOG_BASE_KEY); StringCbCatW(KeyPath, cbKeyPath, lpLogName); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, KeyPath, 0, KEY_READ, &hKey) != ERROR_SUCCESS) { HeapFree(GetProcessHeap(), 0, KeyPath); return; } cbData = sizeof(szModuleName); if (RegQueryValueExW(hKey, L"DisplayNameFile", NULL, NULL, (LPBYTE)szModuleName, &cbData) == ERROR_SUCCESS) { ExpandEnvironmentStringsW(szModuleName, lpModuleName, MAX_PATH); } RegCloseKey(hKey); HeapFree(GetProcessHeap(), 0, KeyPath); }
__inline void TraceW(const wchar_t *format, ...) { if(g_bDebug) { if (format) { va_list arglist; wchar_t str[4096]; va_start(arglist, format); StringCchVPrintfW(str, 4096, format, arglist); StringCbCatW(str, sizeof(str), L"\n"); if (g_fLogFile) { FILE *fout = fopen(g_fLogFile, "a+t"); if (fout) { fwprintf(fout, str); fclose(fout); } } wprintf(str); if (g_bDebugString) { OutputDebugStringW(str); } va_end(arglist); } } }
BOOL GetEventMessageFileDLL(IN LPCWSTR lpLogName, IN LPCWSTR SourceName, IN LPCWSTR EntryName, OUT PWCHAR ExpandedName) { DWORD dwSize; BYTE szModuleName[MAX_PATH]; WCHAR szKeyName[MAX_PATH]; HKEY hAppKey = NULL; HKEY hSourceKey = NULL; BOOL bReturn = FALSE; StringCbCopyW(szKeyName, sizeof(szKeyName), L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\"); StringCbCatW(szKeyName, sizeof(szKeyName), lpLogName); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_READ, &hAppKey) == ERROR_SUCCESS) { if (RegOpenKeyExW(hAppKey, SourceName, 0, KEY_READ, &hSourceKey) == ERROR_SUCCESS) { dwSize = MAX_PATH; if (RegQueryValueExW(hSourceKey, EntryName, NULL, NULL, (LPBYTE)szModuleName, &dwSize) == ERROR_SUCCESS) { /* Returns a string containing the requested substituted environment variable. */ ExpandEnvironmentStringsW((LPCWSTR)szModuleName, ExpandedName, MAX_PATH); /* Successful */ bReturn = TRUE; } } } else { ShowLastWin32Error(); } if (hSourceKey != NULL) RegCloseKey(hSourceKey); if (hAppKey != NULL) RegCloseKey(hAppKey); return bReturn; }
static BOOL DeleteCurrentAppsDB(VOID) { HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATAW FindFileData; WCHAR szCabPath[MAX_PATH]; WCHAR szSearchPath[MAX_PATH]; WCHAR szPath[MAX_PATH]; WCHAR szTmp[MAX_PATH]; HRESULT hr; BOOL result = TRUE; if (!GetStorageDirectory(szPath, _countof(szPath))) return FALSE; hr = StringCbPrintfW(szCabPath, sizeof(szCabPath), L"%ls\\rappmgr.cab", szPath); if (FAILED(hr)) return FALSE; result = result && DeleteFileW(szCabPath); hr = StringCbCatW(szPath, sizeof(szPath), L"\\rapps\\"); if (FAILED(hr)) return FALSE; hr = StringCbPrintfW(szSearchPath, sizeof(szSearchPath), L"%ls*.txt", szPath); if (FAILED(hr)) return FALSE; hFind = FindFirstFileW(szSearchPath, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) return result; do { hr = StringCbPrintfW(szTmp, sizeof(szTmp), L"%ls%ls", szPath, FindFileData.cFileName); if (FAILED(hr)) continue; result = result && DeleteFileW(szTmp); } while (FindNextFileW(hFind, &FindFileData) != 0); FindClose(hFind); return result; }
int mkfulldir_internal (wchar_t *path) { wchar_t *token; struct _stat st; static wchar_t tokpath[_MAX_PATH]; static wchar_t trail[_MAX_PATH]; StringCbCopyW (tokpath, _MAX_PATH, path); trail[0] = L'\0'; token = wcstok (tokpath, L"\\/"); if (tokpath[0] == L'\\' && tokpath[1] == L'\\') { /* unc */ trail[0] = tokpath[0]; trail[1] = tokpath[1]; trail[2] = L'\0'; if (token) { StringCbCatW (trail, _MAX_PATH, token); StringCbCatW (trail, _MAX_PATH, L"\\"); token = wcstok (NULL, L"\\/"); if (token) { /* get share name */ StringCbCatW (trail, _MAX_PATH, token); StringCbCatW (trail, _MAX_PATH, L"\\"); } token = wcstok (NULL, L"\\/"); } } if (tokpath[1] == L':') { /* drive letter */ StringCbCatW (trail, _MAX_PATH, tokpath); StringCbCatW (trail, _MAX_PATH, L"\\"); token = wcstok (NULL, L"\\/"); } while (token != NULL) { int x; StringCbCatW (trail, _MAX_PATH, token); x = _wmkdir (trail); StringCbCatW (trail, _MAX_PATH, L"\\"); token = wcstok (NULL, L"\\/"); } return _wstat (path, &st); }
SC_HANDLE register_service_exW( SC_HANDLE scm_handle, PCWSTR test_name, PCWSTR service_name, // LPCWSTR lpServiceName, PCWSTR extra_args OPTIONAL, DWORD dwDesiredAccess, DWORD dwServiceType, DWORD dwStartType, DWORD dwErrorControl, LPCWSTR lpLoadOrderGroup OPTIONAL, LPDWORD lpdwTagId OPTIONAL, LPCWSTR lpDependencies OPTIONAL, LPCWSTR lpServiceStartName OPTIONAL, LPCWSTR lpPassword OPTIONAL) { SC_HANDLE service; WCHAR service_cmd[MAX_PATH+150]; /* Retrieve our full path */ if (!GetModuleFileNameW(NULL, service_cmd, MAX_PATH)) { skip("GetModuleFileNameW failed with error %lu!\n", GetLastError()); return NULL; } /* * Build up our custom command line. The first parameter is the test name, * the second parameter is the flag used to decide whether we should start * as a service. */ StringCbCatW(service_cmd, sizeof(service_cmd), L" "); StringCbCatW(service_cmd, sizeof(service_cmd), test_name); StringCbCatW(service_cmd, sizeof(service_cmd), L" "); StringCbCatW(service_cmd, sizeof(service_cmd), service_name); if (extra_args) { StringCbCatW(service_cmd, sizeof(service_cmd), L" "); StringCbCatW(service_cmd, sizeof(service_cmd), extra_args); } trace("service_cmd \"%ls\"\n", service_cmd); service = CreateServiceW(scm_handle, service_name, service_name, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, service_cmd, lpLoadOrderGroup, lpdwTagId, lpDependencies, lpServiceStartName, lpPassword); if (!service && GetLastError() == ERROR_ACCESS_DENIED) { skip("Not enough access right to create service.\n"); return NULL; } ok(service != NULL, "CreateService failed: %lu\n", GetLastError()); return service; }
BOOL FormatNtfs (int driveNo, int clusterSize) { char dllPath[MAX_PATH] = {0}; WCHAR dir[8] = { (WCHAR) driveNo + 'A', 0 }; PFORMATEX FormatEx; HMODULE hModule; int i; if (GetSystemDirectory (dllPath, MAX_PATH)) { StringCbCatA(dllPath, sizeof(dllPath), "\\fmifs.dll"); } else StringCbCopyA(dllPath, sizeof(dllPath), "C:\\Windows\\System32\\fmifs.dll"); hModule = LoadLibrary (dllPath); if (hModule == NULL) return FALSE; if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle ("fmifs.dll"), "FormatEx"))) { FreeLibrary (hModule); return FALSE; } StringCbCatW (dir, sizeof(dir), L":\\"); FormatExError = TRUE; // Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS. // It often helps to retry several times. for (i = 0; i < 50 && FormatExError; i++) { FormatExError = FALSE; FormatEx (dir, FMIFS_HARDDISK, L"NTFS", L"", TRUE, clusterSize * FormatSectorSize, FormatExCallback); } // The device may be referenced for some time after FormatEx() returns Sleep (4000); FreeLibrary (hModule); return FormatExError? FALSE : TRUE; }
BOOL GetFilePathName( PCWSTR BasePath, PCWSTR RelativePath, PWCHAR Buffer, ULONG BufferSize ) { if (FAILED(StringCbCopyW(Buffer, BufferSize, BasePath))) return FALSE; if (FAILED(StringCbCatW(Buffer, BufferSize, RelativePath))) return FALSE; return TRUE; }
int main(void){ wchar_t dest[11] = L"test"; wchar_t empty[10] = L""; plan(12); ok(SUCCEEDED(StringCbCatW(dest, 11 * sizeof(wchar_t), L"TEST")), "Concatenate two short strings."); is_wstring(L"testTEST", dest, "Result of concatenating short strings."); dest[4] = '\0'; /* Reset dest to "test". */ ok(SUCCEEDED(StringCbCatW(dest, 11 * sizeof(wchar_t), L"")), "Concatenate with empty source."); is_wstring(L"test", dest, "Result of concatenating with empty source."); ok(SUCCEEDED(StringCbCatW(empty, 10 * sizeof(wchar_t), L"test")), "Concatenate with empty destination."); is_wstring(L"test", empty, "Result of concatenating with empty destination."); ok(StringCbCatW(dest, 11 * sizeof(wchar_t), L"longer string") == STRSAFE_E_INSUFFICIENT_BUFFER, "Concatenate two strings that are too long."); is_wstring(L"testlonger", dest, "Result of concatenating two strings that are too long."); ok(StringCbCatW(dest, 11 * sizeof(wchar_t), L"test") == STRSAFE_E_INSUFFICIENT_BUFFER, "Concatenate to already full destination."); is_wstring(L"testlonger", dest, "Make sure destination was not modified."); ok(StringCbCatW(dest, 0 * sizeof(wchar_t), L"test") == STRSAFE_E_INVALID_PARAMETER, "Make sure error is thrown if cchDest is zero."); is_wstring(L"testlonger", dest, "Make sure destination was not modified."); return 0; }
//***************************************************************************** // Function: ValueToString // Purpose: Takes a variant, returns a string representation of that variant //***************************************************************************** WCHAR *ValueToString(CIMTYPE dwType, VARIANT *pValue, WCHAR **pbuf, WCHAR *fnHandler(VARIANT *pv)) { DWORD iTotBufSize; WCHAR *vbuf = NULL; WCHAR *buf = NULL; WCHAR lbuf[BLOCKSIZE]; switch (pValue->vt) { case VT_EMPTY: { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty>"); } break; } case VT_NULL: { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<null>"); } break; } case VT_BOOL: { VARIANT_BOOL b = pValue->boolVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { if (!b) { StringCbCopyW(buf, BLOCKSIZE, L"FALSE"); } else { StringCbCopyW(buf, BLOCKSIZE, L"TRUE"); } } break; } case VT_I1: { char b = pValue->bVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { if (b >= 32) { StringCbPrintfW(buf, BLOCKSIZE, L"'%c' (%hd, 0x%hX)", b, (signed char)b, b); } else { StringCbPrintfW(buf, BLOCKSIZE, L"%hd (0x%hX)", (signed char)b, b); } } break; } case VT_UI1: { unsigned char b = pValue->bVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { if (b >= 32) { StringCbPrintfW(buf, BLOCKSIZE, L"'%c' (%hu, 0x%hX)", b, (unsigned char)b, b); } else { StringCbPrintfW(buf, BLOCKSIZE, L"%hu (0x%hX)", (unsigned char)b, b); } } break; } case VT_I2: { SHORT i = pValue->iVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%hd (0x%hX)", i, i); } break; } case VT_UI2: { USHORT i = pValue->uiVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%hu (0x%hX)", i, i); } break; } case VT_I4: { LONG l = pValue->lVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%d (0x%X)", l, l); } break; } case VT_UI4: { ULONG l = pValue->ulVal; buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%u (0x%X)", l, l); } break; } case VT_R4: { float f = pValue->fltVal; buf = (WCHAR *)malloc(CVTBUFSIZE * sizeof(WCHAR)); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%10.4f", f); } break; } case VT_R8: { double d = pValue->dblVal; buf = (WCHAR *)malloc(CVTBUFSIZE * sizeof(WCHAR)); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%10.4f", d); } break; } case VT_BSTR: { if (dwType == CIM_SINT64) { // a little redundant, but it makes me feel better LPWSTR pWStr = pValue->bstrVal; __int64 l = _wtoi64(pWStr); buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%I64d", l); } } else if (dwType == CIM_UINT64) { // a little redundant, but it makes me feel better LPWSTR pWStr = pValue->bstrVal; __int64 l = _wtoi64(pWStr); buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"%I64u", l); } } else // string, datetime, reference { LPWSTR pWStr = pValue->bstrVal; buf = (WCHAR *)malloc((wcslen(pWStr) * sizeof(WCHAR)) + sizeof(WCHAR) + (2 * sizeof(WCHAR))); if (buf) { StringCbPrintfW(buf, BLOCKSIZE, L"\"%wS\"", pWStr); } } break; } case VT_BOOL|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, (iUBound - iLBound + 1) * BLOCKSIZE, L","); } else { bFirst = FALSE; } VARIANT_BOOL v; SafeArrayGetElement(pVec, &i, &v); if (v) { StringCbCatW(buf, (iUBound - iLBound + 1) * BLOCKSIZE, L"TRUE"); } else { StringCbCatW(buf, (iUBound - iLBound + 1) * BLOCKSIZE, L"FALSE"); } } } break; } case VT_I1|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } int bufSize = (iUBound - iLBound + 1) * BLOCKSIZE; buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); WCHAR *pos = buf; DWORD len; BYTE *pbstr; SafeArrayAccessData(pVec, (void HUGEP* FAR*)&pbstr); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCopyW(pos, bufSize - (pos - buf) * sizeof(WCHAR), L","); pos += 1; } else { bFirst = FALSE; } char v; // SafeArrayGetElement(pVec, &i, &v); v = pbstr[i]; if (v < 32) { len = StringCbPrintfW(lbuf, sizeof(lbuf), L"%hd (0x%X)", v, v); } else { len = StringCbPrintfW(lbuf, sizeof(lbuf), L"'%c' %hd (0x%X)", v, v, v); } StringCbCopyW(pos, bufSize - (pos - buf)*sizeof(WCHAR), lbuf); pos += len; } } SafeArrayUnaccessData(pVec); break; } case VT_UI1|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } int bufsize = (iUBound - iLBound + 1) * BLOCKSIZE; buf = (WCHAR *)malloc(bufsize); if (buf) { StringCbCopyW(buf, bufsize, L""); WCHAR *pos = buf; DWORD len; BYTE *pbstr; SafeArrayAccessData(pVec, (void HUGEP* FAR*)&pbstr); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCopyW(pos, bufsize - ((pos - buf)*sizeof(WCHAR)), L","); pos += 1; } else { bFirst = FALSE; } unsigned char v; // SafeArrayGetElement(pVec, &i, &v); v = pbstr[i]; if (v < 32) { len = StringCbPrintfW(lbuf, sizeof(lbuf), L"%hu (0x%X)", v, v); } else { len = StringCbPrintfW(lbuf, sizeof(lbuf), L"'%c' %hu (0x%X)", v, v, v); } StringCbCopyW(pos, bufsize - ((pos - buf)*sizeof(WCHAR)), lbuf); pos += len; } } SafeArrayUnaccessData(pVec); break; } case VT_I2|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L","); } else { bFirst = FALSE; } SHORT v; SafeArrayGetElement(pVec, &i, &v); StringCbPrintfW(lbuf, sizeof(lbuf), L"%hd", v); StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), lbuf); } } break; } case VT_UI2|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L","); } else { bFirst = FALSE; } USHORT v; SafeArrayGetElement(pVec, &i, &v); StringCbPrintfW(lbuf, sizeof(lbuf), L"%hu", v); StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), lbuf); } } break; } case VT_I4|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf,((iUBound - iLBound + 1) * BLOCKSIZE), L","); } else { bFirst = FALSE; } LONG v; SafeArrayGetElement(pVec, &i, &v); _ltow_s(v, lbuf, 10); StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), lbuf); } } break; } case VT_UI4|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L","); } else { bFirst = FALSE; } ULONG v; SafeArrayGetElement(pVec, &i, &v); _ultow_s(v, lbuf, 10); StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), lbuf); } } break; } case CIM_REAL32|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } int bufSize = (iUBound - iLBound + 1) * (CVTBUFSIZE * sizeof(WCHAR)); buf = (WCHAR *)malloc(bufSize); if (buf) { StringCbCopyW(buf, bufSize, L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, bufSize, L","); } else { bFirst = FALSE; } FLOAT v; SafeArrayGetElement(pVec, &i, &v); StringCbPrintfW(lbuf, sizeof(lbuf), L"%10.4f", v); StringCbCatW(buf, bufSize, lbuf); } } break; } case CIM_REAL64|VT_ARRAY: { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } int bufSize = (iUBound - iLBound + 1) * (CVTBUFSIZE * sizeof(WCHAR)); buf = (WCHAR *)malloc(bufSize); if (buf) { StringCbCopyW(buf, bufSize, L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, bufSize, L","); } else { bFirst = FALSE; } double v; SafeArrayGetElement(pVec, &i, &v); StringCbPrintfW(lbuf, sizeof(lbuf), L"%10.4f", v); StringCbCatW(buf, bufSize, lbuf); } } break; } case VT_BSTR|VT_ARRAY: { if (dwType == (CIM_UINT64|VT_ARRAY)) { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L","); } else { bFirst = FALSE; } BSTR v = NULL; SafeArrayGetElement(pVec, &i, &v); StringCbPrintfW(lbuf, sizeof(lbuf), L"%I64u", _wtoi64(v)); StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), lbuf); } } } else if (dwType == (CIM_SINT64|VT_ARRAY)) { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; BOOL bFirst = TRUE; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } buf = (WCHAR *)malloc((iUBound - iLBound + 1) * BLOCKSIZE); if (buf) { StringCbCopyW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L""); for (long i = iLBound; i <= iUBound; i++) { if (!bFirst) { StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), L","); } else { bFirst = FALSE; } BSTR v = NULL; SafeArrayGetElement(pVec, &i, &v); StringCbPrintfW(lbuf, sizeof(lbuf), L"%I64d", _wtoi64(v)); StringCbCatW(buf, ((iUBound - iLBound + 1) * BLOCKSIZE), lbuf); } } } else // string, datetime, reference { SAFEARRAY *pVec = pValue->parray; long iLBound, iUBound; DWORD iNeed; size_t iVSize; DWORD iCurBufSize; SafeArrayGetLBound(pVec, 1, &iLBound); SafeArrayGetUBound(pVec, 1, &iUBound); if ((iUBound - iLBound + 1) == 0) { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<empty array>"); } break; } iTotBufSize = (iUBound - iLBound + 1) * BLOCKSIZE; buf = (WCHAR *)malloc(iTotBufSize); if (buf) { buf[0] = L'\0'; iCurBufSize = 0; iVSize = BLOCKSIZE; vbuf = (WCHAR *)malloc(BLOCKSIZE); if (vbuf) { size_t iLen; WCHAR *Buffer; WCHAR *Buff; for (long i = iLBound; i <= iUBound; i++) { BSTR v = NULL; SafeArrayGetElement(pVec, &i, &v); iLen = (SysStringLen(v) + 1) * sizeof(WCHAR); if (iLen > iVSize) { Buffer = vbuf; vbuf = (WCHAR *)realloc(vbuf, iLen + sizeof(WCHAR)); iVSize = iLen; } // String size + (quotes + comma + null) if (vbuf) { iNeed = (StringCbPrintfW(vbuf, iVSize, L"%wS", v) + 4) * sizeof(WCHAR); if (iNeed + iCurBufSize > iTotBufSize) { iTotBufSize += (iNeed * 2); // Room enough for 2 more entries Buff = buf; buf = (WCHAR *)realloc(buf, iTotBufSize); } if (buf) { StringCbCatW(buf, iTotBufSize, L"\""); StringCbCatW(buf, iTotBufSize, vbuf); if (i + 1 <= iUBound) { StringCbCatW(buf, iTotBufSize, L"\","); } else { StringCbCatW(buf, iTotBufSize, L"\""); } iCurBufSize += iNeed; } else { buf = Buff; } } else { vbuf = Buffer; } SysFreeString(v); } free(vbuf); } } } break; } default: { if (fnHandler != NULL) { buf = fnHandler(pValue); } else { buf = (WCHAR *)malloc(BLOCKSIZE); if (buf) { StringCbCopyW(buf, BLOCKSIZE, L"<conversion error>"); } } break; } } if (!buf) { PrintErrorAndExit("ValueToString() out of memory", S_OK, 0); } *pbuf = buf; return buf; }
//------------------------------------------------------------------------------ // Name: PrintAttribute() // Desc: Display the specified attribute. //------------------------------------------------------------------------------ HRESULT PrintAttribute( WORD wIndex, WORD wStream, __in LPWSTR wszName, WMT_ATTR_DATATYPE AttribDataType, WORD wLangID, BYTE * pbValue, DWORD dwValueLen ) { WCHAR pwszValue[256]; WCHAR wszNum[256]; ZeroMemory( pwszValue, sizeof( pwszValue ) ); ZeroMemory( wszNum, sizeof( wszNum ) ); // // Make the data type string // WCHAR * pwszType = L"Unknown"; WCHAR * pTypes[] = { L"DWORD", L"STRING", L"BINARY", L"BOOL", L"QWORD", L"WORD", L"GUID" }; if( ( sizeof( pTypes ) / sizeof( pTypes[0] ) ) > AttribDataType ) { pwszType = pTypes[AttribDataType]; } // // The attribute value. // switch ( AttribDataType ) { // // string // case WMT_TYPE_STRING: if( 0 == dwValueLen ) { StringCbCatW( pwszValue, sizeof( pwszValue ), L"***** NULL *****" ); } else { if( 0xFEFF == *(WCHAR*)pbValue ) { StringCbCatW( pwszValue, sizeof( pwszValue ), L"UTF-16LE BOM+" ); StringCbCatW( pwszValue, sizeof( pwszValue ), L"\"" ); if( 4 <= dwValueLen ) { StringCbCatW( pwszValue, sizeof( pwszValue ), (WCHAR *)pbValue + 1 ); } StringCbCatW( pwszValue, sizeof( pwszValue ), L"\"" ); } else if( 0xFFFE == *(WCHAR*)pbValue ) { StringCbCatW( pwszValue, sizeof( pwszValue ), L"UTF-16BE BOM+" ); StringCbCatW( pwszValue, sizeof( pwszValue ), L"\"" ); if( 4 <= dwValueLen ) { StringCbCatW( pwszValue, sizeof( pwszValue ), (WCHAR *)pbValue + 1 ); } StringCbCatW( pwszValue, sizeof( pwszValue ), L"\"" ); } else { StringCbCatW( pwszValue, sizeof( pwszValue ), L"\"" ); if( 2 <= dwValueLen ) { StringCbCatW( pwszValue, sizeof( pwszValue ), (WCHAR *)pbValue ); } StringCbCatW( pwszValue, sizeof( pwszValue ), L"\"" ); } } break; // // Binary // case WMT_TYPE_BINARY: StringCbCatW( pwszValue, sizeof( pwszValue ), L"[" ); _itow_s( dwValueLen, wszNum, 10 ); StringCbCatW( pwszValue, sizeof( pwszValue ), wszNum ); StringCbCatW( pwszValue, sizeof( pwszValue ), L" bytes]" ); break; // // Boolean // case WMT_TYPE_BOOL: if( *( (BOOL* )pbValue ) == FALSE ) { StringCbCatW( pwszValue, sizeof( pwszValue ), L"False" ); } else { StringCbCatW( pwszValue, sizeof( pwszValue ), L"True" ); } break; // // DWORD // case WMT_TYPE_DWORD: StringCbPrintfW( wszNum, sizeof(wszNum), L"%ld, 0x%08lx", ( (DWORD *)pbValue )[0], ( (DWORD *)pbValue )[0] ); StringCbCatW( pwszValue, sizeof( pwszValue ), wszNum ); break; // // QWORD // case WMT_TYPE_QWORD: _ui64tow_s( *( (QWORD* )pbValue ), wszNum, sizeof(wszNum) / sizeof(wszNum[0]), 10 ); StringCbCatW( pwszValue, sizeof( pwszValue ), wszNum ); StringCbPrintfW( wszNum, sizeof( wszNum ), L", 0x%08lx%08lx", ( (DWORD *)pbValue )[1], ( (DWORD *)pbValue )[0] ); StringCbCatW( pwszValue, sizeof( pwszValue ), wszNum ); break; // // WORD // case WMT_TYPE_WORD: StringCbPrintfW( wszNum, sizeof( wszNum ), L"%d, 0x%04x", ( ( WORD* )pbValue )[0], ( ( WORD* )pbValue )[0] ); StringCbCatW( pwszValue, sizeof( pwszValue ), wszNum ); break; // // GUID // case WMT_TYPE_GUID: if( !StringFromGUID2( *(GUID *)pbValue, pwszValue, 256 ) ) { StringCbCatW( pwszValue, sizeof( pwszValue ), L"ERROR" ); } break; default: StringCbPrintfW( pwszValue, sizeof( pwszValue ), L"Bad data type (%hu): value not displayed", AttribDataType ); break; } // // Dump the string to the screen. // _tprintf( _T( "* %3u %-25ls %3hu %3hu %7ls %ls\n" ), wIndex, wszName, wStream, wLangID, pwszType, pwszValue ); return( S_OK ); }
BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { static EXPAND_VOL_THREAD_PARAMS *pVolExpandParam; WORD lw = LOWORD (wParam); switch (msg) { case WM_INITDIALOG: { wchar_t szTemp[4096]; pVolExpandParam = (EXPAND_VOL_THREAD_PARAMS*)lParam; EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_KB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_MB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_GB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_TB), !pVolExpandParam->bIsDevice); EnableWindow (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE), !(pVolExpandParam->bIsLegacy && pVolExpandParam->bIsDevice)); SendDlgItemMessage (hwndDlg, IDC_INIT_NEWSPACE, BM_SETCHECK, pVolExpandParam->bInitFreeSpace ? BST_CHECKED : BST_UNCHECKED, 0); if (!pVolExpandParam->bIsDevice) SetCurrentVolSize(hwndDlg,pVolExpandParam->oldSize); SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->oldSize,pVolExpandParam->bIsDevice); SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szTemp); SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pVolExpandParam->szVolumeName); SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pVolExpandParam->FileSystem]); if (pVolExpandParam->bIsDevice) { GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->newSize,TRUE); } else { wchar_t szHostFreeStr[256]; SetWindowText (GetDlgItem (hwndDlg, IDT_NEW_SIZE), L""); GetSpaceString(szHostFreeStr,sizeof(szHostFreeStr),pVolExpandParam->hostSizeFree,FALSE); StringCbPrintfW (szTemp,sizeof(szTemp),L"%s available on host drive", szHostFreeStr); } SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szTemp); // set help text if (pVolExpandParam->bIsDevice) { StringCbPrintfW (szTemp,sizeof(szTemp),L"This is a device-based VeraCrypt volume.\n\nThe new volume size will be choosen automatically as the size of the host device."); if (pVolExpandParam->bIsLegacy) StringCbCatW(szTemp,sizeof(szTemp),L" Note: filling the new space with random data is not supported for legacy volumes."); } else { StringCbPrintfW (szTemp, sizeof(szTemp),L"Please specify the new size of the VeraCrypt volume (must be at least %I64u KB larger than the current size).",TC_MINVAL_FS_EXPAND/1024); } SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTemp); } return 0; case WM_COMMAND: if (lw == IDCANCEL) { EndDialog (hwndDlg, lw); return 1; } if (lw == IDOK) { wchar_t szTemp[4096]; pVolExpandParam->bInitFreeSpace = IsButtonChecked (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE)); if (!pVolExpandParam->bIsDevice) // for devices new size is set by calling function { GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp, ARRAYSIZE (szTemp)); pVolExpandParam->newSize = _wtoi64(szTemp) * GetSizeBoxMultiplier(hwndDlg); } EndDialog (hwndDlg, lw); return 1; } return 0; } return 0; }
int getAFSServerW(const cm_unichar_t *service, const cm_unichar_t *protocol, const cm_unichar_t *cellName, unsigned short afsdbPort, /* network byte order */ int *cellHostAddrs, cm_unichar_t cellHostNames[][MAXHOSTCHARS], unsigned short ports[], /* network byte order */ unsigned short ipRanks[], int *numServers, int *ttl) { #ifdef DNSAPI_ENV PDNS_RECORDW pDnsCell, pDnsIter, pDnsVol,pDnsVolIter, pDnsCIter; int i; cm_unichar_t query[1024]; *numServers = 0; *ttl = 0; if (service == NULL || protocol == NULL || cellName == NULL) return -1; #ifdef AFS_FREELANCE_CLIENT if ( cm_stricmp_utf16(cellName, L"Freelance.Local.Root") == 0 ) return -1; #endif /* AFS_FREELANCE_CLIENT */ /* query the SRV _afs3-vlserver._udp records of cell */ StringCbPrintfW(query, sizeof(query), L"_%S._%S.%S", service, protocol, cellName); if (query[wcslen(query)-1] != L'.') { StringCbCatW(query, sizeof(query), L"."); } if (DnsQuery_W(query, DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, (PDNS_RECORD *) &pDnsCell, NULL) == ERROR_SUCCESS) { /* go through the returned records */ for (pDnsIter = pDnsCell; pDnsIter; pDnsIter = pDnsIter->pNext) { /* if we find an SRV record, we found a service instance */ if (pDnsIter->wType == DNS_TYPE_SRV) { StringCbCopyW(cellHostNames[*numServers], sizeof(cellHostNames[*numServers]), pDnsIter->Data.SRV.pNameTarget); ipRanks[*numServers] = pDnsIter->Data.SRV.wPriority; ports[*numServers] = htons(pDnsIter->Data.SRV.wPort); (*numServers)++; if (!*ttl) *ttl = pDnsIter->dwTtl; if (*numServers == AFSMAXCELLHOSTS) break; } } for (i=0;i<*numServers;i++) cellHostAddrs[i] = 0; /* now check if there are any A records in the results */ for (pDnsIter = pDnsCell; pDnsIter; pDnsIter = pDnsIter->pNext) { if(pDnsIter->wType == DNS_TYPE_A) /* check if its for one of the service instances */ for (i=0;i<*numServers;i++) if(cm_stricmp_utf16(pDnsIter->pName, cellHostNames[i]) == 0) cellHostAddrs[i] = pDnsIter->Data.A.IpAddress; } for (i=0;i<*numServers;i++) { /* if we don't have an IP yet, then we should try resolving the service hostname in a separate query. */ if (!cellHostAddrs[i]) { if (DnsQuery_W(cellHostNames[i], DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, (PDNS_RECORD *) &pDnsVol, NULL) == ERROR_SUCCESS) { for (pDnsVolIter = pDnsVol; pDnsVolIter; pDnsVolIter=pDnsVolIter->pNext) { /* if we get an A record, keep it */ if (pDnsVolIter->wType == DNS_TYPE_A && cm_stricmp_utf16(cellHostNames[i], pDnsVolIter->pName)==0) { cellHostAddrs[i] = pDnsVolIter->Data.A.IpAddress; break; } /* if we get a CNAME, look for a corresponding A record */ if (pDnsVolIter->wType == DNS_TYPE_CNAME && cm_stricmp_utf16(cellHostNames[i], pDnsVolIter->pName)==0) { for (pDnsCIter=pDnsVolIter; pDnsCIter; pDnsCIter=pDnsCIter->pNext) { if (pDnsCIter->wType == DNS_TYPE_A && cm_stricmp_utf16(pDnsVolIter->Data.CNAME.pNameHost, pDnsCIter->pName)==0) { cellHostAddrs[i] = pDnsCIter->Data.A.IpAddress; break; } } if (cellHostAddrs[i]) break; /* TODO: if the additional section is missing, then do another lookup for the CNAME */ } } /* we are done with the service lookup */ DnsRecordListFree((PDNS_RECORD) pDnsVol, DnsFreeRecordListDeep); } } } DnsRecordListFree((PDNS_RECORD) pDnsCell, DnsFreeRecordListDeep); } else { /* query the AFSDB records of cell */ StringCbCopyW(query, sizeof(query), cellName); if (query[wcslen(query)-1] != L'.') { StringCbCatW(query, sizeof(query), L"."); } if (DnsQuery_W(query, DNS_TYPE_AFSDB, DNS_QUERY_STANDARD, NULL, (PDNS_RECORD *) &pDnsCell, NULL) == ERROR_SUCCESS) { /* go through the returned records */ for (pDnsIter = pDnsCell;pDnsIter; pDnsIter = pDnsIter->pNext) { /* if we find an AFSDB record with Preference set to 1, we found a service instance */ if (pDnsIter->wType == DNS_TYPE_AFSDB && pDnsIter->Data.Afsdb.wPreference == 1) { StringCbCopyW(cellHostNames[*numServers], sizeof(cellHostNames[*numServers]), pDnsIter->Data.Afsdb.pNameExchange); ipRanks[*numServers] = 0; ports[*numServers] = afsdbPort; (*numServers)++; if (!*ttl) *ttl = pDnsIter->dwTtl; if (*numServers == AFSMAXCELLHOSTS) break; } } for (i=0;i<*numServers;i++) cellHostAddrs[i] = 0; /* now check if there are any A records in the results */ for (pDnsIter = pDnsCell; pDnsIter; pDnsIter = pDnsIter->pNext) { if(pDnsIter->wType == DNS_TYPE_A) /* check if its for one of the service instances */ for (i=0;i<*numServers;i++) if(cm_stricmp_utf16(pDnsIter->pName, cellHostNames[i]) == 0) cellHostAddrs[i] = pDnsIter->Data.A.IpAddress; } for (i=0;i<*numServers;i++) { /* if we don't have an IP yet, then we should try resolving the service hostname in a separate query. */ if (!cellHostAddrs[i]) { if (DnsQuery_W(cellHostNames[i], DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, (PDNS_RECORD *) &pDnsVol, NULL) == ERROR_SUCCESS) { for (pDnsVolIter = pDnsVol; pDnsVolIter; pDnsVolIter=pDnsVolIter->pNext) { /* if we get an A record, keep it */ if (pDnsVolIter->wType == DNS_TYPE_A && cm_stricmp_utf16(cellHostNames[i], pDnsVolIter->pName)==0) { cellHostAddrs[i] = pDnsVolIter->Data.A.IpAddress; break; } /* if we get a CNAME, look for a corresponding A record */ if (pDnsVolIter->wType == DNS_TYPE_CNAME && cm_stricmp_utf16(cellHostNames[i], pDnsVolIter->pName)==0) { for (pDnsCIter=pDnsVolIter; pDnsCIter; pDnsCIter=pDnsCIter->pNext) { if (pDnsCIter->wType == DNS_TYPE_A && cm_stricmp_utf16(pDnsVolIter->Data.CNAME.pNameHost, pDnsCIter->pName)==0) { cellHostAddrs[i] = pDnsCIter->Data.A.IpAddress; break; } } if (cellHostAddrs[i]) break; /* TODO: if the additional section is missing, then do another lookup for the CNAME */ } } /* we are done with the service lookup */ DnsRecordListFree((PDNS_RECORD) pDnsVol, DnsFreeRecordListDeep); } } } DnsRecordListFree((PDNS_RECORD) pDnsCell, DnsFreeRecordListDeep); } } if ( *numServers > 0 ) return 0; else #endif /* DNSAPI_ENV */ return -1; }
UINT ParserGetString(LPCWSTR lpKeyName, LPWSTR lpReturnedString, UINT nSize, LPCWSTR lpFileName) { PWSTR lpFullFileName = GetINIFullPath(lpFileName); DWORD dwResult; /* we don't have cached section strings for the current system language, create them */ if(bCachedSectionStatus == FALSE) { WCHAR szLocale[4 + 1]; DWORD len; /* find out what is the current system lang code (e.g. "0a") and append it to SectionLocale */ GetLocaleInfoW(GetUserDefaultLCID(), LOCALE_ILANGUAGE, szLocale, _countof(szLocale)); StringCbCatW(szCachedINISectionLocale, sizeof(szCachedINISectionLocale), szLocale); /* copy the locale-dependent string into the buffer of the future neutral one */ StringCbCopyW(szCachedINISectionLocaleNeutral, sizeof(szCachedINISectionLocaleNeutral), szCachedINISectionLocale); /* turn "Section.0c0a" into "Section.0a", keeping just the neutral lang part */ len = wcslen(szCachedINISectionLocale); memmove((szCachedINISectionLocaleNeutral + len) - 4, (szCachedINISectionLocaleNeutral + len) - 2, (2 * sizeof(WCHAR)) + sizeof(UNICODE_NULL)); /* finally, mark us as cache-friendly for the next time */ bCachedSectionStatus = TRUE; } /* 1st - find localized strings (e.g. "Section.0c0a") */ dwResult = GetPrivateProfileStringW(szCachedINISectionLocale, lpKeyName, NULL, lpReturnedString, nSize, lpFullFileName); if (dwResult != 0) return TRUE; /* 2nd - if they weren't present check for neutral sub-langs/ generic translations (e.g. "Section.0a") */ dwResult = GetPrivateProfileStringW(szCachedINISectionLocaleNeutral, lpKeyName, NULL, lpReturnedString, nSize, lpFullFileName); if (dwResult != 0) return TRUE; /* 3rd - if they weren't present fallback to standard english strings (just "Section") */ dwResult = GetPrivateProfileStringW(L"Section", lpKeyName, NULL, lpReturnedString, nSize, lpFullFileName); return (dwResult != 0 ? TRUE : FALSE); }
BOOL DXContext::Internal_Init(DXCONTEXT_PARAMS *pParams, BOOL bFirstInit) { memcpy(&m_current_mode, pParams, sizeof(DXCONTEXT_PARAMS)); memset(&myWindowState,0,sizeof(myWindowState)); // various checks if (m_current_mode.screenmode != WINDOWED) m_current_mode.m_skin = 0; // 1. destroy old window if (m_hwnd) { m_ignore_wm_destroy = 1; DestroyWindow(m_hwnd); m_ignore_wm_destroy = 0; m_hwnd = NULL; } // 2. CHECK TO MAKE SURE DIRECTX/DDRAW IS INSTALLED if (bFirstInit) { // Test for DirectX 9 + start it // note: if you don't call LoadLibrary here, and you're on a system // where DX9 is missing, Direct3DCreate8() might crash; so call it. int d3d9_already_loaded = (GetModuleHandle("d3d9.dll") != NULL) ? 1 : 0; if (!d3d9_already_loaded) m_hmod_d3d9 = LoadLibrary("d3d9.dll"); if ((!d3d9_already_loaded && !m_hmod_d3d9) || !(m_lpD3D = Direct3DCreate9(D3D_SDK_VERSION)) ) { MissingDirectX(NULL); m_lastErr = DXC_ERR_CREATE3D; return FALSE; } if (!m_hmod_d3dx9) m_hmod_d3dx9 = FindD3DX9(m_hwnd_winamp); if ((!m_hmod_d3dx9)) { MissingDirectX(NULL); m_lastErr = DXC_ERR_CREATE3D; return FALSE; } } // 3. get the smallest single rectangle that encloses ALL the monitors on the desktop: SetRect(&m_all_monitors_rect, 0, 0, 0, 0); EnumDisplayMonitors(NULL, NULL, MyMonitorEnumProc, (LPARAM)&m_all_monitors_rect); // 4. some DirectX- / DDraw-specific stuff. Also determine hPluginMonitor. HMONITOR hPluginMonitor = NULL; { D3DADAPTER_IDENTIFIER9 temp; // find the ordinal # of the adapter whose GUID matches what the user picked from the config panel, // and whose DeviceName matches as well. // if no match found, use D3DADAPTER_DEFAULT. m_ordinal_adapter = D3DADAPTER_DEFAULT; int nAdapters = m_lpD3D->GetAdapterCount(); { for (int i=0; i<nAdapters; i++) { if ((m_lpD3D->GetAdapterIdentifier(i, /*D3DENUM_NO_WHQL_LEVEL*/ 0, &temp) == D3D_OK) && (memcmp(&temp.DeviceIdentifier, &m_current_mode.adapter_guid, sizeof(GUID))==0) && !strcmp(temp.DeviceName, m_current_mode.adapter_devicename) ) { m_ordinal_adapter = i; break; } } } if (m_lpD3D->GetAdapterIdentifier(m_ordinal_adapter, /*D3DENUM_NO_WHQL_LEVEL*/ 0, &temp) == D3D_OK) { StringCbCopy(m_szDriver, sizeof(m_szDriver), temp.Driver); StringCbCopy(m_szDesc, sizeof(m_szDesc), temp.Description); } int caps_ok = 0; int caps_tries = 0; int changed_fs_disp_mode; // try to get the device caps for the adapter selected from the config panel. // if GetDeviceCaps() fails, it's probably because the adapter has been // removed from the system (or disabled), so we try again with other adapter(s). do { changed_fs_disp_mode = 0; SetRect(&m_monitor_rect, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); // get bounding rect of the monitor attached to the adapter (to assist w/window positioning) // note: in vert/horz span setups (psuedo-multimon), // this will be 2048x768 or 1024x1536 or something like that. hPluginMonitor = m_lpD3D->GetAdapterMonitor(m_ordinal_adapter); /*if (hPluginMonitor) { MONITORINFO mi; mi.cbSize = sizeof(mi); if (GetMonitorInfo(hPluginMonitor, &mi)) { memcpy(&m_monitor_rect, &mi.rcMonitor, sizeof(RECT)); memcpy(&m_monitor_work_rect, &mi.rcWork, sizeof(RECT)); } }*/ if (bFirstInit) { for (int i=0; i<min(nAdapters, MAX_DXC_ADAPTERS); i++) { // if this is the first call to Init, get the display mode's original color format, // before we go changing it: D3DDISPLAYMODE d3ddm; if (FAILED(m_lpD3D->GetAdapterDisplayMode(i, &d3ddm))) { d3ddm.Format = D3DFMT_UNKNOWN; } m_orig_windowed_mode_format[i] = d3ddm.Format; } } // figure out pixel (color) format for back buffer: (m_current_mode.display_mode.Format) if (m_current_mode.screenmode!=FULLSCREEN && m_ordinal_adapter < MAX_DXC_ADAPTERS) m_current_mode.display_mode.Format = m_orig_windowed_mode_format[m_ordinal_adapter]; // else // for fullscreen, use what they gave us if (m_current_mode.display_mode.Format == D3DFMT_UNKNOWN || !TestFormat(m_ordinal_adapter, m_current_mode.display_mode.Format)) { // if they try to run the plugin without ever running the config panel // first (& pressing OK), then the fullscreen pixelformat hasn't been // chosen... so we try all the possilibities until one works: if (TestFormat(m_ordinal_adapter,D3DFMT_A8R8G8B8)) m_current_mode.display_mode.Format = D3DFMT_A8R8G8B8; else if (TestFormat(m_ordinal_adapter,D3DFMT_X8R8G8B8)) m_current_mode.display_mode.Format = D3DFMT_X8R8G8B8; else if (TestFormat(m_ordinal_adapter,D3DFMT_R8G8B8)) m_current_mode.display_mode.Format = D3DFMT_R8G8B8 ; else if (TestFormat(m_ordinal_adapter,D3DFMT_R5G6B5)) m_current_mode.display_mode.Format = D3DFMT_R5G6B5 ; else if (TestFormat(m_ordinal_adapter,D3DFMT_X1R5G5B5)) m_current_mode.display_mode.Format = D3DFMT_X1R5G5B5; else if (TestFormat(m_ordinal_adapter,D3DFMT_A1R5G5B5)) m_current_mode.display_mode.Format = D3DFMT_A1R5G5B5; else if (TestFormat(m_ordinal_adapter,D3DFMT_A4R4G4B4)) m_current_mode.display_mode.Format = D3DFMT_A4R4G4B4; else if (TestFormat(m_ordinal_adapter,D3DFMT_X4R4G4B4)) m_current_mode.display_mode.Format = D3DFMT_X4R4G4B4; } if (m_current_mode.display_mode.Format==D3DFMT_UNKNOWN) { wchar_t title[64]; m_lastErr = DXC_ERR_FORMAT; MessageBoxW(m_hwnd, WASABI_API_LNGSTRINGW(IDS_DIRECTX_INIT_FAILED), WASABI_API_LNGSTRINGW_BUF(IDS_MILKDROP_ERROR, title, 64), MB_OK|MB_SETFOREGROUND|MB_TOPMOST); return FALSE; } if (m_current_mode.screenmode == FULLSCREEN) changed_fs_disp_mode = CheckAndCorrectFullscreenDispMode(m_ordinal_adapter, &m_current_mode.display_mode); // figure out pixel format of the z-buffer: (m_zFormat) m_zFormat = D3DFMT_UNKNOWN; /* if (TestDepth(m_ordinal_adapter,D3DFMT_D32 )) m_zFormat=D3DFMT_D32; else if (TestDepth(m_ordinal_adapter,D3DFMT_D24S8 )) m_zFormat=D3DFMT_D24S8; else if (TestDepth(m_ordinal_adapter,D3DFMT_D24X4S4 )) m_zFormat=D3DFMT_D24X4S4; else if (TestDepth(m_ordinal_adapter,D3DFMT_D24X8 )) m_zFormat=D3DFMT_D24X8; else if (TestDepth(m_ordinal_adapter,D3DFMT_D16 )) m_zFormat=D3DFMT_D16; else if (TestDepth(m_ordinal_adapter,D3DFMT_D15S1 )) m_zFormat=D3DFMT_D15S1; else if (TestDepth(m_ordinal_adapter,D3DFMT_D16_LOCKABLE)) m_zFormat=D3DFMT_D16_LOCKABLE; */ // get device caps: memset(&m_caps, 0, sizeof(m_caps)); if (FAILED(m_lpD3D->GetDeviceCaps(m_ordinal_adapter, D3DDEVTYPE_HAL, &m_caps))) { // that adapter was found in the system, but it might be disabled // (i.e. 'extend my Windows desktop onto this monitor') is unchecked) // so, try other adapters (try all sequentially). if (caps_tries < nAdapters) { // try again, this time using the default adapter: m_ordinal_adapter = caps_tries; caps_tries++; } else { wchar_t title[64]; m_lastErr = DXC_ERR_CAPSFAIL; MessageBoxW(m_hwnd, WASABI_API_LNGSTRINGW(IDS_DXC_ERR_CAPSFAIL), WASABI_API_LNGSTRINGW_BUF(IDS_MILKDROP_ERROR, title, 64), MB_OK|MB_SETFOREGROUND|MB_TOPMOST); return FALSE; } } else { caps_ok = 1; } } while (!caps_ok); if (changed_fs_disp_mode) { wchar_t title[64]; MessageBoxW(m_hwnd, WASABI_API_LNGSTRINGW(IDS_FS_DISPLAY_MODE_SELECTED_IS_INVALID), WASABI_API_LNGSTRINGW_BUF(IDS_MILKDROP_WARNING, title, 64), MB_OK|MB_SETFOREGROUND|MB_TOPMOST); } switch (m_current_mode.display_mode.Format) { case D3DFMT_R8G8B8 : m_bpp = 32; break; case D3DFMT_A8R8G8B8: m_bpp = 32; break; case D3DFMT_X8R8G8B8: m_bpp = 32; break; case D3DFMT_R5G6B5 : m_bpp = 16; break; case D3DFMT_X1R5G5B5: m_bpp = 16; break; case D3DFMT_A1R5G5B5: m_bpp = 16; break; case D3DFMT_A8R3G3B2: m_bpp = 16; break; case D3DFMT_A4R4G4B4: m_bpp = 16; break; case D3DFMT_X4R4G4B4: m_bpp = 16; break; case D3DFMT_R3G3B2 : m_bpp = 8; break; // misleading? implies a palette... } } // 5. set m_monitor_rect and m_monitor_work_rect. if (hPluginMonitor) { MONITORINFO mi; mi.cbSize = sizeof(mi); if (GetMonitorInfo(hPluginMonitor, &mi)) { m_monitor_rect = mi.rcMonitor; m_monitor_rect_orig = mi.rcMonitor; m_monitor_work_rect = mi.rcWork; m_monitor_work_rect_orig = mi.rcWork; } } // 6. embedded window stuff [where the plugin window is integrated w/winamp] if (m_current_mode.m_skin) { // set up the window's position on screen // note that we'd prefer to set the CLIENT size we want, but we can't, so we'll just do // this here, and later, adjust the client rect size to what's left... int size = GetWindowedModeAutoSize(0); // note: requires 'm_monitor_rect' has been set! myWindowState.r.left = GetPrivateProfileIntW(L"settings",L"avs_wx",64,m_szIniFile); myWindowState.r.top = GetPrivateProfileIntW(L"settings",L"avs_wy",64,m_szIniFile); myWindowState.r.right = myWindowState.r.left + GetPrivateProfileIntW(L"settings",L"avs_ww",size+24,m_szIniFile); myWindowState.r.bottom = myWindowState.r.top + GetPrivateProfileIntW(L"settings",L"avs_wh",size+40,m_szIniFile); // only works on winamp 2.90+! int success = 0; if (GetWinampVersion(mod1.hwndParent) >= 0x2900) { SET_EMBED_GUID((&myWindowState), avs_guid); myWindowState.flags |= EMBED_FLAGS_NOTRANSPARENCY; HWND (*e)(embedWindowState *v); *(void**)&e = (void *)SendMessage(mod1.hwndParent,WM_WA_IPC,(LPARAM)0,IPC_GET_EMBEDIF); if (e) { m_current_mode.parent_window = e(&myWindowState); if (m_current_mode.parent_window) { SetWindowText(m_current_mode.parent_window, m_szWindowCaption); success = 1; } } } if (!success) m_current_mode.m_skin = 0; } // remember the client rect that was originally desired... RECT windowed_mode_desired_client_rect; windowed_mode_desired_client_rect.top = GetPrivateProfileIntW(L"settings",L"nMainWndTop",-1,m_szIniFile); windowed_mode_desired_client_rect.left = GetPrivateProfileIntW(L"settings",L"nMainWndLeft",-1,m_szIniFile); windowed_mode_desired_client_rect.right = GetPrivateProfileIntW(L"settings",L"nMainWndRight",-1,m_szIniFile); windowed_mode_desired_client_rect.bottom = GetPrivateProfileIntW(L"settings",L"nMainWndBottom",-1,m_szIniFile); // ...and in case windowed mode init fails severely, // set it up to try next time for a simple 256x256 window. WriteSafeWindowPos(); // 7. create the window, if not already created if (!m_hwnd) { m_hwnd = CreateWindowEx( MY_EXT_WINDOW_STYLE, // extended style MAKEINTATOM(m_classAtom), // class m_szWindowCaption, // caption MY_WINDOW_STYLE, // style 0, // left 0, // top 256, // temporary width 256, // temporary height m_current_mode.parent_window, // parent window NULL, // menu m_hInstance, // instance (LPVOID)m_uWindowLong ); // parms if (!m_hwnd) { wchar_t title[64]; m_lastErr = DXC_ERR_CREATEWIN; MessageBoxW(m_hwnd, WASABI_API_LNGSTRINGW(IDS_CREATEWINDOW_FAILED), WASABI_API_LNGSTRINGW_BUF(IDS_MILKDROP_ERROR, title, 64), MB_OK|MB_SETFOREGROUND|MB_TOPMOST); return FALSE; } SendMessage(m_hwnd_winamp, WM_WA_IPC, (WPARAM)m_hwnd, IPC_SETVISWND); if (m_current_mode.m_skin) { if (GetWinampVersion(mod1.hwndParent) < 0x5051) ShowWindow(m_current_mode.parent_window,SW_SHOWNA); // showing the parent wnd will make it size the child, too else SendMessage(m_current_mode.parent_window, WM_USER+102, 0, 0); // benski> major hack alert. winamp's embedwnd will call ShowWindow in response. SendMessage moves us over to the main thread (we're currently sitting on the viz thread) } } // 8. minimize winamp before creating devices & such, so there aren't // any confusing window-focus issues MinimizeWinamp(hPluginMonitor); // 9. loop to try and create the window. // if in windowed mode and not enough vidmem, it will try again w/smaller window // (repeatedly, until window client size would be < 64) int iteration = 0; int device_ok = 0; do { // set the window position if (m_current_mode.screenmode==DESKTOP || m_current_mode.screenmode==FAKE_FULLSCREEN) { int x = m_monitor_rect.right - m_monitor_rect.left; int y = m_monitor_rect.bottom - m_monitor_rect.top; if (x >= y*2) { // (pseudo-multimon modes like 2048x768) int mid = (m_monitor_rect.left + m_monitor_rect.right)/2; if (m_current_mode.m_dualhead_horz==1) // show on left side m_monitor_rect.right = mid; else if (m_current_mode.m_dualhead_horz==2) // show on right side m_monitor_rect.left = mid; } else if (y > x*4/3) { // (pseudo-multimon modes like 1024x1536) int mid = (m_monitor_rect.top + m_monitor_rect.bottom)/2; if (m_current_mode.m_dualhead_vert==1) // show on top half m_monitor_rect.bottom = mid; else if (m_current_mode.m_dualhead_vert==2) // show on bottom half m_monitor_rect.top = mid; } // recompute width & height (into x,y): x = m_monitor_rect.right - m_monitor_rect.left; y = m_monitor_rect.bottom - m_monitor_rect.top; m_client_width = x; m_client_height = y; m_window_width = x; m_window_height = y; if (m_current_mode.screenmode == DESKTOP) { // note: we initially hide the window, and then // only display it once the desktop is all nice & ready. // see CPluginShell::DrawAndDisplay(). RECT r = m_monitor_rect; // if possible, shrink the desktop window so it doesn't cover the taskbar. HWND hTaskbar = FindWindow("Shell_TrayWnd", ""); if (hTaskbar) { RECT taskbar; GetWindowRect(hTaskbar, &taskbar); int tbw = taskbar.right - taskbar.left; int tbh = taskbar.bottom-taskbar.top; if (taskbar.bottom == m_monitor_rect.bottom && taskbar.left == m_monitor_rect.left && taskbar.right == m_monitor_rect.right) { r.bottom -= tbh; } else if (taskbar.top == m_monitor_rect.top && taskbar.left == m_monitor_rect.left && taskbar.right == m_monitor_rect.right) { r.top += tbh; } else if (taskbar.left == m_monitor_rect.left && taskbar.top == m_monitor_rect.top && taskbar.bottom == m_monitor_rect.bottom) { r.left += tbw; } else if (taskbar.right == m_monitor_rect.right && taskbar.top == m_monitor_rect.top && taskbar.bottom == m_monitor_rect.bottom) { r.right -= tbw; } m_client_width = r.right - r.left; m_client_height = r.bottom - r.top; m_REAL_client_width = m_client_width; m_REAL_client_height = m_client_height; m_window_width = m_client_width; m_window_height = m_client_height; //...ok, but text is squished - some w/h is not right... } SetWindowPos(m_hwnd,HWND_BOTTOM,r.left,r.top,r.right-r.left,r.bottom-r.top,SWP_HIDEWINDOW); } else // FAKE_FULLSCREEN { if (memcmp(&m_all_monitors_rect, &m_monitor_rect, sizeof(RECT))==0) { // there's only one display, and it's entirely covered // by the plugin -> PUT THE PLUGIN ABOVE THE TASKBAR // -> normally, if the user clicked another window, // it would pop the taskbar to the top; but we don't // have to worry about that here, since we're taking // up the whole screen. // -> don't worry about making the text, etc. avoid // the taskbar in this case (see DrawAndDisplay()) // -> DO worry about hiding the mouse cursor in this case // (see WM_SETCURSOR handler) m_fake_fs_covers_all = 1; //SetWindowPos(m_hwnd,HWND_TOPMOST,m_monitor_rect.left,m_monitor_rect.top,m_window_width,m_window_height,SWP_SHOWWINDOW); } else { // there is space to work outside of the plugin window. // -> here we pretty much have to let the taskbar stay on // top, because it really likes to be there; i.e., // if you click any other window, it automatically // pops up again. // -> therefore, TRY TO KEEP THE WINDOW ON BOTTOM // (below the taskbar). (see PushWindowToBack) // -> don't worry about hiding the mouse cursor in this case // (see WM_SETCURSOR handler) // -> DO worry about making the text, etc. avoid // the taskbar in this case (see DrawAndDisplay()) // (note that if taskbar is in the way, they can move it, // since there are other monitors available) m_fake_fs_covers_all = 0; //SetWindowPos(m_hwnd,HWND_TOP,m_monitor_rect.left,m_monitor_rect.top,m_window_width,m_window_height,SWP_SHOWWINDOW); } SetWindowPos(m_hwnd,HWND_TOPMOST,m_monitor_rect.left,m_monitor_rect.top,m_window_width,m_window_height,SWP_SHOWWINDOW); } } else if (m_current_mode.screenmode == FULLSCREEN) { int x = m_current_mode.display_mode.Width ; int y = m_current_mode.display_mode.Height; int cx = m_monitor_rect.right - m_monitor_rect.left; int cy = m_monitor_rect.bottom - m_monitor_rect.top; // test #1 if (x >= y*2 || y > x*4/3) // tackle problem of vert/horz spans { wchar_t title[64]; int ret = MessageBoxW(m_hwnd, WASABI_API_LNGSTRINGW(IDS_TRYING_TO_ENTER_FS_MODE_WITH_MULTIPLE_DISPLAYS), WASABI_API_LNGSTRINGW_BUF(IDS_TIP, title, 64), MB_OKCANCEL|MB_SETFOREGROUND|MB_TOPMOST); if (ret==IDCANCEL) { m_lastErr = DXC_ERR_USER_CANCELED; return FALSE; } } // test #2 if ((cx >= cy*2 && x < y*2) || (cy > cx*4/3 && y <= x*4/3)) { wchar_t title[64]; int ret = MessageBoxW(m_hwnd, WASABI_API_LNGSTRINGW(IDS_TRYING_TO_ENTER_FS_MODE_WITH_MULTIPLE_DISPLAYS_2), WASABI_API_LNGSTRINGW_BUF(IDS_TIP, title, 64), MB_OKCANCEL|MB_SETFOREGROUND|MB_TOPMOST); if (ret==IDCANCEL) { m_lastErr = DXC_ERR_USER_CANCELED; return FALSE; } } m_client_width = x; m_client_height = y; m_window_width = x; m_window_height = y; SetWindowPos(m_hwnd,HWND_TOPMOST,m_monitor_rect.left,m_monitor_rect.top,m_window_width,m_window_height,SWP_SHOWWINDOW); } else // WINDOWED { RECT margin; if (m_current_mode.m_skin) { RECT r1, r2; GetWindowRect(m_current_mode.parent_window, &r1); GetWindowRect(m_hwnd , &r2); margin.left = r2.left - r1.left; margin.right = r1.right - r2.right; margin.top = r2.top - r1.top; margin.bottom= r1.bottom - r2.bottom; } else { RECT r1; SetRect(&r1, 0, 0, 256, 256); AdjustWindowRect(&r1, MY_WINDOW_STYLE, 0); margin.left = 0 - r1.left; margin.right = r1.right - 256; margin.top = 0 - r1.top; margin.bottom= r1.bottom - 256; } int autosize = 1; RECT r = windowed_mode_desired_client_rect; if (iteration==0 && r.top != -1 && r.left != -1 && r.bottom != -1 && r.right != -1) { // use prev. window coordinates: m_REAL_client_width = r.right - r.left; m_REAL_client_height = r.bottom - r.top; GetSnappedClientSize(); if (m_current_mode.m_skin) // check this here in case they got a non-aligned size by resizing when "integrated with winamp" was unchecked, then checked it & ran the plugin... { // STRANGE ALIGNMENTS FOR THE WINDOW FRAME: (required by winamp 2): // the window frame's width must be divisible by 25, and height by 29. if (GetWinampVersion(mod1.hwndParent) < 0x4000) // ... winamp 5 doesn't have this prob. (test vs. 0x4000 because winamp5 betas have version tags like 0x4987) { m_REAL_client_width = ((m_client_width + margin.left + margin.right)/25)*25 - margin.left - margin.right; m_REAL_client_height = ((m_client_height + margin.top + margin.bottom)/29)*29 - margin.top - margin.bottom; GetSnappedClientSize(); } } // transform screen-space CLIENT rect into screen-space WINDOW rect r.top = windowed_mode_desired_client_rect.top - margin.top; r.left = windowed_mode_desired_client_rect.left - margin.left; r.right = r.left + margin.left + m_REAL_client_width + margin.right; r.bottom = r.top + margin.top + m_REAL_client_height + margin.bottom; // make sure the window is entirely visible on the selected monitor; // otherwise, autosize/place it. // (note that this test is only appled 1) at startup, and 2) after a resize/max/restore. // this test is not applied when merely moving the window.) if (r.top >= m_monitor_work_rect.top && r.left >= m_monitor_work_rect.left && r.right <= m_monitor_work_rect.right && r.bottom <= m_monitor_work_rect.bottom) { if (m_current_mode.m_skin) { m_window_width = m_REAL_client_width ; // m_window_width/height are for OUR borderless window, not the embedwnd parent frame. m_window_height = m_REAL_client_height; SetWindowPos(m_current_mode.parent_window,HWND_NOTOPMOST, r.left, r.top, r.right-r.left, r.bottom-r.top, /*SWP_SHOWWINDOW|*//*SWP_ASYNCWINDOWPOS*/0); SetWindowPos(m_hwnd ,HWND_NOTOPMOST, windowed_mode_desired_client_rect.left, windowed_mode_desired_client_rect.top, m_REAL_client_width, m_REAL_client_height, SWP_SHOWWINDOW); } else { m_window_width = r.right - r.left; m_window_height = r.bottom - r.top; SetWindowPos(m_hwnd,HWND_NOTOPMOST,r.left,r.top,m_window_width,m_window_height,SWP_SHOWWINDOW); } autosize = 0; } } if (autosize) { int size = GetWindowedModeAutoSize(iteration); // note: requires 'm_monitor_rect' has been set! m_REAL_client_width = size; m_REAL_client_height = size; GetSnappedClientSize(); if (m_current_mode.m_skin) { // STRANGE ALIGNMENTS FOR THE WINDOW FRAME: (required by winamp 2): // the window frame's width must be divisible by 25, and height by 29. if (GetWinampVersion(mod1.hwndParent) < 0x4000) // ... winamp 5 doesn't have this prob. (test vs. 0x4000 because winamp5 betas have version tags like 0x4987) { m_REAL_client_width = ((m_client_width + margin.left + margin.right)/25)*25 - margin.left - margin.right; m_REAL_client_height = ((m_client_height + margin.top + margin.bottom)/29)*29 - margin.top - margin.bottom; GetSnappedClientSize(); } m_window_width = m_client_width ; // m_window_width/height are for OUR [borderless] window, not the parent window (which is the embedwnd frame). m_window_height = m_client_height; SetWindowPos(m_current_mode.parent_window,HWND_NOTOPMOST, m_monitor_work_rect.left+32, m_monitor_work_rect.top+32, m_client_width + margin.left + margin.right, m_client_height + margin.top + margin.bottom, /*SWP_SHOWWINDOW|*//*SWP_ASYNCWINDOWPOS*/0); SetWindowPos(m_hwnd ,HWND_NOTOPMOST, m_monitor_work_rect.left+32 + margin.left, m_monitor_work_rect.top+32 + margin.top, m_client_width, m_client_height, SWP_SHOWWINDOW); } else { SetRect(&r, 0, 0, size, size); AdjustWindowRect(&r, MY_WINDOW_STYLE, 0); m_window_width = r.right - r.left; m_window_height = r.bottom - r.top; SetWindowPos(m_hwnd,HWND_NOTOPMOST, m_monitor_work_rect.left+32, m_monitor_work_rect.top+32, m_window_width, m_window_height, SWP_SHOWWINDOW); } } } m_frame_delay = 1; // set this to 2 if you use triple buffering! { m_current_mode.display_mode.Width = m_client_width; m_current_mode.display_mode.Height = m_client_height; // set up m_d3dpp (presentation parameters): ZeroMemory(&m_d3dpp,sizeof(m_d3dpp)); m_d3dpp.Windowed = (m_current_mode.screenmode==FULLSCREEN) ? 0 : 1; m_d3dpp.BackBufferFormat = m_current_mode.display_mode.Format; m_d3dpp.BackBufferWidth = m_client_width; m_d3dpp.BackBufferHeight = m_client_height; m_d3dpp.BackBufferCount = m_current_mode.nbackbuf; if (m_current_mode.screenmode==FULLSCREEN) m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;//D3DSWAPEFFECT_FLIP; else // windowed or fake FS m_d3dpp.SwapEffect = (m_current_mode.allow_page_tearing) ? D3DSWAPEFFECT_DISCARD : D3DSWAPEFFECT_COPY;//D3DSWAPEFFECT_DISCARD;//D3DSWAPEFFECT_FLIP; // note: multisampling is only allowed if swapeffect is DISCARD! m_d3dpp.MultiSampleType = (m_d3dpp.SwapEffect==D3DSWAPEFFECT_DISCARD) ? m_current_mode.multisamp : D3DMULTISAMPLE_NONE; //m_d3dpp.hDeviceWindow = m_hwnd; if (m_current_mode.screenmode==FULLSCREEN) { m_d3dpp.FullScreen_RefreshRateInHz = m_current_mode.display_mode.RefreshRate;//D3DPRESENT_RATE_DEFAULT; m_d3dpp.PresentationInterval = m_current_mode.allow_page_tearing ? D3DPRESENT_INTERVAL_IMMEDIATE : D3DPRESENT_INTERVAL_ONE;//D3DPRESENT_INTERVAL_IMMEDIATE;//D3DPRESENT_INTERVAL_ONE; } if (m_zFormat != D3DFMT_UNKNOWN) { m_d3dpp.EnableAutoDepthStencil=TRUE; m_d3dpp.AutoDepthStencilFormat=m_zFormat; } // finally, create the device: HRESULT hRes; if (FAILED(hRes = m_lpD3D->CreateDevice( m_ordinal_adapter, D3DDEVTYPE_HAL, m_hwnd, (m_caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) ? D3DCREATE_MIXED_VERTEXPROCESSING : D3DCREATE_SOFTWARE_VERTEXPROCESSING, &m_d3dpp, &m_lpDevice))) { int code = LOWORD(hRes); wchar_t str[1024]; if (code==2156) //D3DERR_NOTAVAILABLE { m_lastErr = DXC_ERR_CREATEDEV_NOT_AVAIL; wchar_t str[2048]; WASABI_API_LNGSTRINGW_BUF(IDS_UNABLE_TO_CREATE_DIRECTX_DEVICE, str, 2048); if (m_current_mode.screenmode == FULLSCREEN) StringCbCatW(str, sizeof(str), WASABI_API_LNGSTRINGW(IDS_OLDER_DISPLAY_ADAPTER_CATENATION)); else StringCbCatW(str, sizeof(str), WASABI_API_LNGSTRINGW(IDS_OLDER_DISPLAY_ADAPTER_CATENATION_2)); MessageBoxW(m_hwnd,str, WASABI_API_LNGSTRINGW(IDS_MILKDROP_ERROR), MB_OK|MB_SETFOREGROUND|MB_TOPMOST); return FALSE; } else if (m_current_mode.screenmode==WINDOWED && m_client_width>64) { // DO NOTHING; try again w/smaller window } else if (m_current_mode.screenmode != WINDOWED || m_client_width <= 64) { // usually, code==2154 here, which is D3DERR_OUTOFVIDEOMEMORY m_lastErr = DXC_ERR_CREATEDEV_PROBABLY_OUTOFVIDEOMEMORY; StringCbPrintfW(str, sizeof(str), WASABI_API_LNGSTRINGW(IDS_DIRECTX_INIT_FAILED_X), LOWORD(hRes)); // NOTE: *A 'SUGGESTION' SCREEN SHOULD APPEAR NEXT, PROVIDED BY THE CALLER* MessageBoxW(m_hwnd, str, WASABI_API_LNGSTRINGW(IDS_MILKDROP_ERROR), MB_OK|MB_SETFOREGROUND|MB_TOPMOST); return FALSE; } } else { device_ok = 1; } } iteration++; } while (!device_ok); // set initial viewport SetViewport(); // for desktop mode, push window to back again: if (m_current_mode.screenmode==DESKTOP) SetWindowPos(m_hwnd,HWND_BOTTOM,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); if (m_current_mode.m_skin) { if (GetWinampVersion(mod1.hwndParent) < 0x5051) SetFocus(m_current_mode.parent_window); else PostMessage(m_current_mode.parent_window, WM_USER+103, 0, 0); //SetActiveWindow(m_current_mode.parent_window); //SetForegroundWindow(m_current_mode.parent_window); } /*if (m_current_mode.screenmode == WINDOWED) SaveWindow();*/ // return success m_ready = TRUE; // benski> a little hack to get the window size correct. it seems to work if (m_current_mode.screenmode==WINDOWED) PostMessage(m_hwnd, WM_USER+555, 0, 0); return TRUE; }
static void DisplayHotkeyList (HWND hwndDlg) { LVITEMW item; HWND hList = GetDlgItem (hwndDlg, IDC_HOTKEY_LIST); int i; wchar_t ShortcutMod [MAX_KEY_COMB_NAME_LEN]; wchar_t ShortcutFinal [MAX_KEY_COMB_NAME_LEN*2]; wchar_t Shortcut [MAX_KEY_COMB_NAME_LEN]; SendMessage (hList, LVM_DELETEALLITEMS,0, (LPARAM)&item); for (i = 0; i < NBR_HOTKEYS; i++) { memset (&item,0,sizeof(item)); item.mask = LVIF_TEXT; item.iItem = i; item.iSubItem = 0; switch (i) { case HK_AUTOMOUNT_DEVICES: item.pszText = GetString ("HK_AUTOMOUNT_DEVICES"); break; case HK_DISMOUNT_ALL: item.pszText = GetString ("HK_DISMOUNT_ALL"); break; case HK_WIPE_CACHE: item.pszText = GetString ("HK_WIPE_CACHE"); break; case HK_DISMOUNT_ALL_AND_WIPE: item.pszText = GetString ("HK_DISMOUNT_ALL_AND_WIPE"); break; case HK_FORCE_DISMOUNT_ALL_AND_WIPE: item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE"); break; case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT"); break; case HK_MOUNT_FAVORITE_VOLUMES: item.pszText = GetString ("HK_MOUNT_FAVORITE_VOLUMES"); break; case HK_SHOW_HIDE_MAIN_WINDOW: item.pszText = GetString ("HK_SHOW_HIDE_MAIN_WINDOW"); break; case HK_CLOSE_SECURITY_TOKEN_SESSIONS: item.pszText = GetString ("IDM_CLOSE_ALL_TOKEN_SESSIONS"); break; default: item.pszText = L"[?]"; } SendMessageW (hList,LVM_INSERTITEMW,0,(LPARAM)&item); item.iSubItem = 1; Shortcut[0] = 0; ShortcutMod[0] = 0; if (GetKeyName (tmpHotkeys[i].vKeyCode, Shortcut)) { if (tmpHotkeys[i].vKeyModifiers & MOD_CONTROL) { StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_CONTROL")); StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); } if (tmpHotkeys[i].vKeyModifiers & MOD_SHIFT) { StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_SHIFT")); StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); } if (tmpHotkeys[i].vKeyModifiers & MOD_ALT) { StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_ALT")); StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); } if (tmpHotkeys[i].vKeyModifiers & MOD_WIN) { StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_WIN")); StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); } StringCbPrintfW (ShortcutFinal, sizeof(ShortcutFinal), L"%s%s", ShortcutMod, Shortcut); item.pszText = ShortcutFinal; } else item.pszText = L""; SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&item); } }
/* * @implemented */ HKL WINAPI LoadKeyboardLayoutW(LPCWSTR pwszKLID, UINT Flags) { DWORD dwhkl, dwType, dwSize; UNICODE_STRING ustrKbdName; UNICODE_STRING ustrKLID; WCHAR wszRegKey[256] = L"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\"; WCHAR wszLayoutId[10], wszNewKLID[10]; HKEY hKey; /* LOWORD of dwhkl is Locale Identifier */ dwhkl = wcstol(pwszKLID, NULL, 16); if (Flags & KLF_SUBSTITUTE_OK) { /* Check substitutes key */ if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Keyboard Layout\\Substitutes", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { dwSize = sizeof(wszNewKLID); if (RegQueryValueExW(hKey, pwszKLID, NULL, &dwType, (LPBYTE)wszNewKLID, &dwSize) == ERROR_SUCCESS) { /* Use new KLID value */ pwszKLID = wszNewKLID; } /* Close the key now */ RegCloseKey(hKey); } } /* Append KLID at the end of registry key */ StringCbCatW(wszRegKey, sizeof(wszRegKey), pwszKLID); /* Open layout registry key for read */ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRegKey, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { dwSize = sizeof(wszLayoutId); if (RegQueryValueExW(hKey, L"Layout Id", NULL, &dwType, (LPBYTE)wszLayoutId, &dwSize) == ERROR_SUCCESS) { /* If Layout Id is specified, use this value | f000 as HIWORD */ /* FIXME: Microsoft Office expects this value to be something specific * for Japanese and Korean Windows with an IME the value is 0xe001 * We should probably check to see if an IME exists and if so then * set this word properly. */ dwhkl |= (0xf000 | wcstol(wszLayoutId, NULL, 16)) << 16; } /* Close the key now */ RegCloseKey(hKey); } else ERR("RegOpenKeyExW failed!\n"); /* If Layout Id is not given HIWORD == LOWORD (for dwhkl) */ if (!HIWORD(dwhkl)) dwhkl |= dwhkl << 16; ZeroMemory(&ustrKbdName, sizeof(ustrKbdName)); RtlInitUnicodeString(&ustrKLID, pwszKLID); return NtUserLoadKeyboardLayoutEx(NULL, 0, &ustrKbdName, NULL, &ustrKLID, dwhkl, Flags); }
/* Returns TRUE if the key is allowed and its name is resolved. */ BOOL GetKeyName (UINT vKey, wchar_t *keyName) { BOOL result = TRUE; if (vKey >= 0x30 && vKey <= 0x5a) { // ASCII characters StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%hc", (char) vKey); } else if (vKey >= 0xE9 && vKey <= 0xF5) { // OEM-specific StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM-%d", vKey); // mapping taken from: // http://www.hotkeynet.com/ref/keynames.html // https://mojoware.googlecode.com/svn-history/r3/trunk/mojo_engine/cKeyboard.cpp // http://www.screenio.com/gui_screenio/gs_htmlhelp_subweb/download/SIMKEYS.cob // // These values seem to come from Nokia/Ericsson mobile device keys switch (vKey) { case 0xE9: // OEMReset = 0xE9 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMReset)"); break; case 0xEA: // OEMJump = 0xEA StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMJump)"); break; case 0xEB: // OEMPA1 = 0xEB StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA1)"); break; case 0xEC: // OEMPA2 = 0xEC StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA2)"); break; case 0xED: // OEMPA3 = 0xED StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA3)"); break; case 0xEE: // OEMWSCtrl = 0xEE StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMWSCtrl)"); break; case 0xEF: // OEMCUSel = 0xEF StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMCUSel)"); break; case 0xF0: // OEMATTN = 0xF0 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMATTN)"); break; case 0xF1: // OEMFinish = 0xF1 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMFinish)"); break; case 0xF2: // OEMCopy = 0xF2 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMCopy)"); break; case 0xF3: // OEMAuto = 0xF3 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMAuto)"); break; case 0xF4: // OEMENLW = 0xF4 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMENLW)"); break; case 0xF5: // OEMBackTab = 0xF5 StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMBackTab)"); break; } } else if (vKey >= VK_F1 && vKey <= VK_F24) { // F1-F24 StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"F%d", vKey - VK_F1 + 1); } else if (vKey >= VK_NUMPAD0 && vKey <= VK_NUMPAD9) { // Numpad numbers StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0); } else { switch (vKey) { case VK_MULTIPLY: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s *", GetString ("VK_NUMPAD")); break; case VK_ADD: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s +", GetString ("VK_NUMPAD")); break; case VK_SEPARATOR: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s Separator", GetString ("VK_NUMPAD")); break; case VK_SUBTRACT: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s -", GetString ("VK_NUMPAD")); break; case VK_DECIMAL: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s .", GetString ("VK_NUMPAD")); break; case VK_DIVIDE: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s /", GetString ("VK_NUMPAD")); break; case VK_OEM_1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 1 (';')"); break; case VK_OEM_PLUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"+"); break; case VK_OEM_COMMA: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L","); break; case VK_OEM_MINUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"-"); break; case VK_OEM_PERIOD: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"."); break; case VK_OEM_2: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 2 ('/')"); break; case VK_OEM_3: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 3 (`)"); break; case VK_OEM_4: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 4 ('[')"); break; case VK_OEM_5: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 5 ('\\')"); break; case VK_OEM_6: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 6 (']')"); break; case VK_OEM_7: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 7 (')"); break; case VK_OEM_8: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 8"); break; case VK_OEM_AX: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM AX"); break; case VK_OEM_102: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 102"); break; case VK_ICO_HELP: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_HELP"); break; case VK_ICO_00: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_00"); break; case VK_ICO_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_CLEAR"); break; case VK_ATTN: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Attn"); break; case VK_CRSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"CrSel"); break; case VK_EXSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ExSel"); break; case VK_EREOF: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Erase EOF"); break; case VK_PA1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"PA1"); break; case VK_OEM_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM Clear"); break; case 0: case 1: case 0xFF: result = FALSE; break; default: { char key[16]; wchar_t *desc; StringCbPrintfA (key, sizeof(key),"VKEY_%02X", vKey); desc = GetString (key); if (desc == UnknownString) result = FALSE; else StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, desc); } } } return result; }
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hInstance); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); UNREFERENCED_PARAMETER(nCmdShow); const wchar_t *vs = nullptr; const wchar_t *target = nullptr; const wchar_t *flavor = nullptr; bool createInstallPkg = false; bool clearEnv = false; bool useNmake = false; bool buildReleasedRevision = false; bool useStaticCRT = false; bool buildLLDB = false; int channel = kBaseBuilder; int Argc = 0; auto Argv_ = CommandLineToArgvW(GetCommandLineW(), &Argc); wchar_t *const *Argv = Argv_; int ch; const wchar_t *short_opts = L"V:A:F:BEICRSLNH"; // L"V:T:C:BIERSLNH"; const option option_long_opt[] = { /// {L"vs", required_argument, NULL, 'V'}, {L"arch", required_argument, NULL, 'A'}, {L"flavor", required_argument, NULL, 'F'}, {L"bootstrap", no_argument, NULL, 'B'}, {L"env", no_argument, NULL, 'E'}, {L"install", no_argument, NULL, 'I'}, {L"clear", no_argument, NULL, 'C'}, {L"released", no_argument, NULL, 'R'}, {L"static", no_argument, NULL, 'S'}, {L"lldb", no_argument, NULL, 'L'}, {L"nmake", no_argument, NULL, 'N'}, {L"help", no_argument, NULL, 'H'}, {0, 0, 0, 0} /// }; while ((ch = getopt_long(Argc, Argv, short_opts, option_long_opt, NULL)) != -1) { switch (ch) { case 'V': vs = optarg; break; case 'A': target = optarg; break; case 'F': flavor = optarg; break; case 'B': channel = kNinjaBootstrap; break; case 'E': channel = kOpenEnvironment; break; case 'I': createInstallPkg = true; break; case 'C': clearEnv = true; break; case 'R': buildReleasedRevision = true; break; case 'S': useStaticCRT = true; break; case 'L': buildLLDB = true; break; case 'N': useNmake = true; break; case 'H': Usage(); LocalFree(Argv_); return 0; default: break; } } if (vs == nullptr) { Usage(); return 0; } WCHAR szBuffer[UNC_MAX_PATH] = {0}; StringCbPrintfW(szBuffer, UNC_MAX_PATH, L" -VisualStudio %s -Arch %s", vs, target); if (channel != kOpenEnvironment) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Flavor "); StringCbCatW(szBuffer, UNC_MAX_PATH, flavor); if (createInstallPkg) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Install"); } if (buildReleasedRevision) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Released"); } if (useStaticCRT) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Static"); } if (useNmake && channel == kBaseBuilder) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -NMake"); } if (buildLLDB && channel == kBaseBuilder) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -LLDB"); } } if (clearEnv) { StringCbCatW(szBuffer, UNC_MAX_PATH, L" -Clear"); } auto result = LauncherStartup(szBuffer, channel); LocalFree(Argv_); return result; }
BOOL UpdateProgressBarProc (__int64 byteOffset) { wchar_t text[100]; wchar_t speed[100]; HWND hProgressBar = GetDlgItem (hCurPage, nPbar); int time = GetTickCount (); int elapsed = (time - startTime) / 1000; uint64 bytesDone = (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset); uint64 bytesPerSec = (bProgressBarReverse ? (resumedPointBytesDone - byteOffset) : (bytesDone - resumedPointBytesDone)) / (elapsed + 1); if (bPercentMode) { double perc = (double) (100.0 * (bProgressBarReverse ? ((double) (TotalSize - byteOffset)) : ((double) byteOffset)) / (TotalSize == 0 ? 0.0001 : ((double) TotalSize))); if (perc > 99.999999999) StringCbCopyW (text,sizeof(text), GetString ("PROCESSED_PORTION_100_PERCENT")); else StringCbPrintfW (text, sizeof text, GetString ("PROCESSED_PORTION_X_PERCENT"), perc); StringCbCatW (text, sizeof(speed), L" "); } else { GetSizeString (bytesDone, text, sizeof(text)); if (bytesDone < (unsigned __int64) BYTES_PER_MB * 1000000) StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB")); else if (bytesDone < (unsigned __int64) BYTES_PER_GB * 1000000) StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB")); else if (bytesDone < (unsigned __int64) BYTES_PER_TB * 1000000) StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB")); else StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB")); } SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), text); if (!bShowStatus) { GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed, sizeof(speed)); StringCbCatW (speed, sizeof(speed), L" "); SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), speed); } if (byteOffset < TotalSize) { int64 sec = (int64) ((bProgressBarReverse ? byteOffset : (TotalSize - byteOffset)) / (bytesPerSec == 0 ? 0.001 : bytesPerSec)); if (bytesPerSec == 0 || sec > 60 * 60 * 24 * 999) StringCbPrintfW (text, sizeof(text), L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); else if (sec >= 60 * 60 * 24 * 2) StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec / (60 * 24 * 60), days); else if (sec >= 120 * 60) StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec / (60 * 60), hours); else if (sec >= 120) StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec / 60, minutes); else StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec, seconds); SetWindowTextW (GetDlgItem (hCurPage, IDC_TIMEREMAIN), text); } prevTime = time; SendMessage (hProgressBar, PBM_SETPOS, (int) (10000.0 * (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset) / (TotalSize == 0 ? 1 : TotalSize)), 0); return bVolTransformThreadCancel; }
static DWORD WINAPI ThreadFunc(LPVOID Context) { CComPtr<IBindStatusCallback> dl; WCHAR path[MAX_PATH]; PWSTR p, q; HWND Dlg = (HWND) Context; ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus; ULONG dwCurrentBytesRead = 0; ULONG dwStatusLen = sizeof(dwStatus); BOOL bCancelled = FALSE; BOOL bTempfile = FALSE; BOOL bCab = FALSE; HINTERNET hOpen = NULL; HINTERNET hFile = NULL; HANDLE hOut = INVALID_HANDLE_VALUE; unsigned char lpBuffer[4096]; PCWSTR lpszAgent = L"RApps/1.0"; URL_COMPONENTS urlComponents; size_t urlLength, filenameLength; /* build the path for the download */ p = wcsrchr(AppInfo->szUrlDownload, L'/'); q = wcsrchr(AppInfo->szUrlDownload, L'?'); /* do we have a final slash separator? */ if (!p) goto end; /* prepare the tentative length of the filename, maybe we've to remove part of it later on */ filenameLength = wcslen(p) * sizeof(WCHAR); /* do we have query arguments in the target URL after the filename? account for them (e.g. https://example.org/myfile.exe?no_adware_plz) */ if (q && q > p && (q - p) > 0) filenameLength -= wcslen(q - 1) * sizeof(WCHAR); /* is this URL an update package for RAPPS? if so store it in a different place */ if (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) { bCab = TRUE; if (!GetStorageDirectory(path, _countof(path))) goto end; } else { if (FAILED(StringCbCopyW(path, sizeof(path), SettingsInfo.szDownloadDir))) goto end; } /* is the path valid? can we access it? */ if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(path, NULL)) goto end; } /* append a \ to the provided file system path, and the filename portion from the URL after that */ if (FAILED(StringCbCatW(path, sizeof(path), L"\\"))) goto end; if (FAILED(StringCbCatNW(path, sizeof(path), p + 1, filenameLength))) goto end; if (!bCab && AppInfo->szSHA1[0] != 0 && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) { /* only open it in case of total correctness */ if (VerifyInteg(AppInfo->szSHA1, path)) goto run; } /* download it */ bTempfile = TRUE; CDownloadDialog_Constructor(Dlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl)); if (dl == NULL) goto end; /* FIXME: this should just be using the system-wide proxy settings */ switch(SettingsInfo.Proxy) { case 0: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; case 1: /* direct (no proxy) */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); break; case 2: /* use proxy */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0); break; default: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; } if (!hOpen) goto end; hFile = InternetOpenUrlW(hOpen, AppInfo->szUrlDownload, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0); if (!hFile) goto end; if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL)) goto end; if(dwStatus != HTTP_STATUS_OK) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_UNABLE_TO_DOWNLOAD, szMsgText, sizeof(szMsgText) / sizeof(WCHAR))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } dwStatusLen = sizeof(dwStatus); memset(&urlComponents, 0, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); if(FAILED(StringCbLengthW(AppInfo->szUrlDownload, sizeof(AppInfo->szUrlDownload), &urlLength))) goto end; urlLength /= sizeof(WCHAR); urlComponents.dwSchemeLength = urlLength + 1; urlComponents.lpszScheme = (LPWSTR)malloc(urlComponents.dwSchemeLength * sizeof(WCHAR)); urlComponents.dwHostNameLength = urlLength + 1; urlComponents.lpszHostName = (LPWSTR)malloc(urlComponents.dwHostNameLength * sizeof(WCHAR)); if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents)) goto end; if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS) HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0); if(urlComponents.nScheme == INTERNET_SCHEME_FTP) dwContentLen = FtpGetFileSize(hFile, &dwStatus); #ifdef USE_CERT_PINNING /* are we using HTTPS to download the RAPPS update package? check if the certificate is original */ if ((urlComponents.nScheme == INTERNET_SCHEME_HTTPS) && (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) && (!CertIsValid(hOpen, urlComponents.lpszHostName))) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_CERT_DOES_NOT_MATCH, szMsgText, sizeof(szMsgText) / sizeof(WCHAR))) goto end; MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } #endif free(urlComponents.lpszScheme); free(urlComponents.lpszHostName); hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); if (hOut == INVALID_HANDLE_VALUE) goto end; do { if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead)) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_INTERRUPTED_DOWNLOAD, szMsgText, _countof(szMsgText))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL)) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_UNABLE_TO_WRITE, szMsgText, _countof(szMsgText))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } dwCurrentBytesRead += dwBytesRead; dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload); } while (dwBytesRead && !bCancelled); CloseHandle(hOut); hOut = INVALID_HANDLE_VALUE; if (bCancelled) goto end; /* if this thing isn't a RAPPS update and it has a SHA-1 checksum verify its integrity by using the native advapi32.A_SHA1 functions */ if (!bCab && AppInfo->szSHA1[0] != 0) { WCHAR szMsgText[MAX_STR_LEN]; /* change a few strings in the download dialog to reflect the verification process */ LoadStringW(hInst, IDS_INTEG_CHECK_TITLE, szMsgText, _countof(szMsgText)); SetWindowText(Dlg, szMsgText); SendMessageW(GetDlgItem(Dlg, IDC_DOWNLOAD_STATUS), WM_SETTEXT, 0, (LPARAM)path); /* this may take a while, depending on the file size */ if (!VerifyInteg(AppInfo->szSHA1, path)) { if (!LoadStringW(hInst, IDS_INTEG_CHECK_FAIL, szMsgText, _countof(szMsgText))) goto end; MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } } ShowWindow(Dlg, SW_HIDE); run: /* run it */ if (!bCab) ShellExecuteW( NULL, L"open", path, NULL, NULL, SW_SHOWNORMAL ); end: if (hOut != INVALID_HANDLE_VALUE) CloseHandle(hOut); InternetCloseHandle(hFile); InternetCloseHandle(hOpen); if (bTempfile) { if (bCancelled || (SettingsInfo.bDelInstaller && !bCab)) DeleteFileW(path); } EndDialog(Dlg, 0); return 0; }
static DWORD WINAPI ThreadFunc(LPVOID Context) { CComPtr<IBindStatusCallback> dl; WCHAR path[MAX_PATH]; LPWSTR p; HWND Dlg = (HWND) Context; ULONG dwContentLen, dwBytesWritten, dwBytesRead, dwStatus; ULONG dwCurrentBytesRead = 0; ULONG dwStatusLen = sizeof(dwStatus); BOOL bCancelled = FALSE; BOOL bTempfile = FALSE; BOOL bCab = FALSE; HINTERNET hOpen = NULL; HINTERNET hFile = NULL; HANDLE hOut = INVALID_HANDLE_VALUE; unsigned char lpBuffer[4096]; PCWSTR lpszAgent = L"RApps/1.0"; URL_COMPONENTS urlComponents; size_t urlLength; /* built the path for the download */ p = wcsrchr(AppInfo->szUrlDownload, L'/'); if (!p) goto end; if (wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) { bCab = TRUE; if (!GetStorageDirectory(path, sizeof(path) / sizeof(path[0]))) goto end; } else { if (FAILED(StringCbCopyW(path, sizeof(path), SettingsInfo.szDownloadDir))) goto end; } if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryW(path, NULL)) goto end; } if (FAILED(StringCbCatW(path, sizeof(path), L"\\"))) goto end; if (FAILED(StringCbCatW(path, sizeof(path), p + 1))) goto end; /* download it */ bTempfile = TRUE; CDownloadDialog_Constructor(Dlg, &bCancelled, IID_PPV_ARG(IBindStatusCallback, &dl)); if (dl == NULL) goto end; switch(SettingsInfo.Proxy) { case 0: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; case 1: /* direct (no proxy) */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); break; case 2: /* use proxy */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PROXY, SettingsInfo.szProxyServer, SettingsInfo.szNoProxyFor, 0); break; default: /* preconfig */ hOpen = InternetOpenW(lpszAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); break; } if (!hOpen) goto end; hFile = InternetOpenUrlW(hOpen, AppInfo->szUrlDownload, NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0); if (!hFile) goto end; if (!HttpQueryInfoW(hFile, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwStatusLen, NULL)) goto end; if(dwStatus != HTTP_STATUS_OK) { WCHAR szMsgText[MAX_STR_LEN]; if (!LoadStringW(hInst, IDS_UNABLE_TO_DOWNLOAD, szMsgText, sizeof(szMsgText) / sizeof(WCHAR))) goto end; MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR); goto end; } dwStatusLen = sizeof(dwStatus); memset(&urlComponents, 0, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); if(FAILED(StringCbLengthW(AppInfo->szUrlDownload, sizeof(AppInfo->szUrlDownload), &urlLength))) goto end; urlComponents.dwSchemeLength = urlLength*sizeof(WCHAR); urlComponents.lpszScheme = (PWSTR)malloc(urlComponents.dwSchemeLength); if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents)) goto end; if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS) HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0); if(urlComponents.nScheme == INTERNET_SCHEME_FTP) dwContentLen = FtpGetFileSize(hFile, &dwStatus); free(urlComponents.lpszScheme); hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); if (hOut == INVALID_HANDLE_VALUE) goto end; do { if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead)) goto end; if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL)) goto end; dwCurrentBytesRead += dwBytesRead; dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload); } while (dwBytesRead); CloseHandle(hOut); hOut = INVALID_HANDLE_VALUE; if (bCancelled) goto end; ShowWindow(Dlg, SW_HIDE); /* run it */ if (!bCab) ShellExecuteW( NULL, L"open", path, NULL, NULL, SW_SHOWNORMAL ); end: if (hOut != INVALID_HANDLE_VALUE) CloseHandle(hOut); InternetCloseHandle(hFile); InternetCloseHandle(hOpen); if (bTempfile) { if (bCancelled || (SettingsInfo.bDelInstaller && !bCab)) DeleteFileW(path); } EndDialog(Dlg, 0); return 0; }
BOOL EnumAvailableApplications(INT EnumType, AVAILENUMPROC lpEnumProc) { HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATAW FindFileData; WCHAR szPath[MAX_PATH]; WCHAR szAppsPath[MAX_PATH]; WCHAR szCabPath[MAX_PATH]; PAPPLICATION_INFO Info; HRESULT hr; if (!GetStorageDirectory(szPath, _countof(szPath))) return FALSE; hr = StringCbPrintfW(szCabPath, sizeof(szCabPath), L"%ls\\rappmgr.cab", szPath); if (FAILED(hr)) return FALSE; hr = StringCbCatW(szPath, sizeof(szPath), L"\\rapps\\"); if (FAILED(hr)) return FALSE; hr = StringCbCopyW(szAppsPath, sizeof(szAppsPath), szPath); if (FAILED(hr)) return FALSE; if (!CreateDirectory(szPath, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { return FALSE; } hr = StringCbCatW(szPath, sizeof(szPath), L"*.txt"); if (FAILED(hr)) return FALSE; hFind = FindFirstFileW(szPath, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { if (GetFileAttributesW(szCabPath) == INVALID_FILE_ATTRIBUTES) DownloadApplicationsDB(APPLICATION_DATABASE_URL); ExtractFilesFromCab(szCabPath, szAppsPath); hFind = FindFirstFileW(szPath, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) return FALSE; } do { /* loop for all the cached entries */ for (pCachedEntry = CachedEntriesHead.Flink; pCachedEntry != &CachedEntriesHead; pCachedEntry = pCachedEntry->Flink) { Info = CONTAINING_RECORD(pCachedEntry, APPLICATION_INFO, List); /* do we already have this entry in cache? */ if(_wcsicmp(FindFileData.cFileName, Info->cFileName) == 0) { /* is it current enough, or the file has been modified since our last time here? */ if (CompareFileTime(&FindFileData.ftLastWriteTime, &Info->ftCacheStamp) == 1) { /* recreate our cache, this is the slow path */ RemoveEntryList(&Info->List); HeapFree(GetProcessHeap(), 0, Info); } else { /* speedy path, compare directly, we already have the data */ goto skip_if_cached; } break; } } /* create a new entry */ Info = (PAPPLICATION_INFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(APPLICATION_INFO)); if(!Info) break; Info->Category = ParserGetInt(L"Category", FindFileData.cFileName); /* copy the cache-related fields for the next time */ RtlCopyMemory(&Info->cFileName, &FindFileData.cFileName, MAX_PATH); RtlCopyMemory(&Info->ftCacheStamp, &FindFileData.ftLastWriteTime, sizeof(FILETIME)); /* add our cached entry to the cached list */ InsertTailList(&CachedEntriesHead, &Info->List); skip_if_cached: if (Info->Category == FALSE) continue; if (EnumType != Info->Category && EnumType != ENUM_ALL_AVAILABLE) continue; /* if our cache hit was only partial, we need to parse and lazily fill the rest of fields only when needed */ if (Info->szUrlDownload[0] == 0) { GET_STRING1(L"Name", Info->szName); GET_STRING1(L"URLDownload", Info->szUrlDownload); GET_STRING2(L"RegName", Info->szRegName); GET_STRING2(L"Version", Info->szVersion); GET_STRING2(L"License", Info->szLicense); GET_STRING2(L"Description", Info->szDesc); GET_STRING2(L"Size", Info->szSize); GET_STRING2(L"URLSite", Info->szUrlSite); GET_STRING2(L"CDPath", Info->szCDPath); GET_STRING2(L"SHA1", Info->szSHA1); } if (!lpEnumProc(Info)) break; } while (FindNextFileW(hFind, &FindFileData) != 0); FindClose(hFind); return TRUE; }
/* This is the slowpoll function which gathers up network/hard drive performance data for the random pool */ BOOL SlowPoll (void) { static int isWorkstation = -1; static int cbPerfData = 0x10000; HANDLE hDevice; LPBYTE lpBuffer; DWORD dwSize, status; LPWSTR lpszLanW, lpszLanS; int nDrive; /* Find out whether this is an NT server or workstation if necessary */ if (isWorkstation == -1) { HKEY hKey; if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { wchar_t szValue[32]; dwSize = sizeof (szValue); isWorkstation = TRUE; status = RegQueryValueEx (hKey, L"ProductType", 0, NULL, (LPBYTE) szValue, &dwSize); if (status == ERROR_SUCCESS && _wcsicmp (szValue, L"WinNT")) /* Note: There are (at least) three cases for ProductType: WinNT = NT Workstation, ServerNT = NT Server, LanmanNT = NT Server acting as a Domain Controller */ isWorkstation = FALSE; RegCloseKey (hKey); } } /* Initialize the NetAPI32 function pointers if necessary */ if (hNetAPI32 == NULL) { /* Obtain a handle to the module containing the Lan Manager functions */ wchar_t dllPath[MAX_PATH]; if (GetSystemDirectory (dllPath, MAX_PATH)) { StringCbCatW(dllPath, sizeof(dllPath), L"\\NETAPI32.DLL"); } else StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32\\NETAPI32.DLL"); hNetAPI32 = LoadLibrary (dllPath); if (hNetAPI32 != NULL) { /* Now get pointers to the functions */ pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32, "NetStatisticsGet"); pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32, "NetApiBufferSize"); pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32, "NetApiBufferFree"); /* Make sure we got valid pointers for every NetAPI32 function */ if (pNetStatisticsGet == NULL || pNetApiBufferSize == NULL || pNetApiBufferFree == NULL) { /* Free the library reference and reset the static handle */ FreeLibrary (hNetAPI32); hNetAPI32 = NULL; } } } /* Get network statistics. Note: Both NT Workstation and NT Server by default will be running both the workstation and server services. The heuristic below is probably useful though on the assumption that the majority of the network traffic will be via the appropriate service */ lpszLanW = (LPWSTR) WIDE ("LanmanWorkstation"); lpszLanS = (LPWSTR) WIDE ("LanmanServer"); if (hNetAPI32 && pNetStatisticsGet (NULL, isWorkstation ? lpszLanW : lpszLanS, 0, 0, &lpBuffer) == 0) { pNetApiBufferSize (lpBuffer, &dwSize); RandaddBuf ((unsigned char *) lpBuffer, dwSize); pNetApiBufferFree (lpBuffer); } /* Get disk I/O statistics for all the hard drives */ for (nDrive = 0;; nDrive++) { DISK_PERFORMANCE diskPerformance; wchar_t szDevice[24]; /* Check whether we can access this device */ StringCbPrintfW (szDevice, sizeof(szDevice), L"\\\\.\\PhysicalDrive%d", nDrive); hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) break; /* Note: This only works if you have turned on the disk performance counters with 'diskperf -y'. These counters are off by default */ if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &diskPerformance, sizeof (DISK_PERFORMANCE), &dwSize, NULL)) { RandaddBuf ((unsigned char *) &diskPerformance, dwSize); } CloseHandle (hDevice); } // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but // we keep the check for clarity purpose if ( !CryptoAPIAvailable ) return FALSE; if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) { RandaddBuf (buffer, sizeof (buffer)); burn(buffer, sizeof (buffer)); Randmix(); return TRUE; } else { /* return error in case CryptGenRandom fails */ CryptoAPILastError = GetLastError (); return FALSE; } }
int wmain(int iArgCnt, WCHAR ** argv) { if(!ProcessArguments(iArgCnt, argv)) { DisplayOptions(); return 1; } if (wcslen(wServerName) > 0) { //prompt for credentials for a remote connection DWORD dwRes = CredUICmdLinePromptForCredentialsW( (const WCHAR *) wServerName, NULL, 0, wFullUserName, sizeof(wFullUserName)/sizeof(WCHAR), wPassWord, sizeof(wPassWord)/sizeof(WCHAR), FALSE, CREDUI_FLAGS_EXCLUDE_CERTIFICATES | CREDUI_FLAGS_DO_NOT_PERSIST ); if (dwRes != NO_ERROR) { printf("Failed to retrieve credentials: error %d. Using the default credentials.", dwRes); } bUserNameSet = bPassWordSet = (dwRes == NO_ERROR); } else { //no server name passed in, assume local StringCbCopyW(wServerName, sizeof(wPath), L"."); } StringCbCopyW(wPath, sizeof(wPath), L"\\\\"); StringCbCatW(wPath, sizeof(wPath), wServerName); StringCbCatW(wPath, sizeof(wPath), L"\\"); StringCbCatW(wPath, sizeof(wPath), wNameSpace); IWbemLocator *pLocator = NULL; IWbemServices *pNamespace = 0; IWbemClassObject * pClass = NULL; // Initialize COM. HRESULT hr = CoInitialize(0); if (FAILED(hr)) { printf("\nCoInitialize returned 0x%x:", hr); return 1; } // This sets the default impersonation level to "Impersonate" which is what WMI // providers will generally require. // // DLLs cannot call this function. To bump up the impersonation level, they must // call CoSetProxyBlanket which is illustrated later on. // // When using asynchronous WMI API's remotely in an environment where the "Local System" account // has no network identity (such as non-Kerberos domains), the authentication level of // RPC_C_AUTHN_LEVEL_NONE is needed. However, lowering the authentication level to // RPC_C_AUTHN_LEVEL_NONE makes your application less secure. It is wise to // use semi-synchronous API's for accessing WMI data and events instead of the asynchronous ones. hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_SECURE_REFS, //change to EOAC_NONE if you change dwAuthnLevel to RPC_C_AUTHN_LEVEL_NONE 0); if (FAILED(hr)) { printf("\nCoInitializeSecurity returned 0x%x:", hr); return 1; } hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLocator); if (FAILED(hr)) { printf("\nCoCreateInstance for CLSID_WbemLocator returned 0x%x:", hr); return 1; } hr = pLocator->ConnectServer(wPath, (bUserNameSet) ? wFullUserName : NULL, (bPassWordSet) ? wPassWord : NULL, NULL, 0, NULL, NULL, &pNamespace); if(FAILED(hr)) { wprintf(L"\nConnectServer to %s failed, hr = 0x%x", wPath, hr); } else { printf("\nConnection succeeded"); hr = SetProxySecurity(pNamespace); if(SUCCEEDED(hr)) { ListClasses(pNamespace); ReadACL(pNamespace); } pNamespace->Release(); } CoUninitialize(); printf("\nTerminating normally"); return 0; }