PWSTR GetHelpFileName( HANDLE hPrinter, HANDLE hheap ) /*++ Routine Description: Return a string which contains the driver's help filename Arguments: hPrinter - Handle to the printer hheap - Handle to a heap from which to allocate memory Return Value: Pointer to the driver help filename, NULL if there is an error --*/ { static WCHAR HelpFileName[] = L"\\XLDRV.HLP"; PDRIVER_INFO_3 pDriverInfo3 = NULL; PWSTR pHelpFile = NULL; PWSTR pDriverDirectory; // // Attempt to get help file name using the new DRIVER_INFO_3 // if ((pDriverInfo3 = MyGetPrinterDriver(hPrinter, 3)) && pDriverInfo3->pHelpFile) pHelpFile = DuplicateUnicodeString(pDriverInfo3->pHelpFile, hheap); MemFree(pDriverInfo3); if (pHelpFile) return pHelpFile; // // If DRIVER_INFO_3 isn't supported, generate help file name by // concatenating the driver directory with hardcoded help filename. // if (pDriverDirectory = MyGetPrinterDriverDirectory(NULL, 1)) { INT size = sizeof(HelpFileName) + sizeof(WCHAR) * (wcslen(pDriverDirectory) + 1); if (pHelpFile = HeapAlloc(hheap, 0, size)) { wcscpy(pHelpFile, pDriverDirectory); wcscat(pHelpFile, HelpFileName); } MemFree(pDriverDirectory); } return pHelpFile; }
static void calculate_path(void) { extern wchar_t *Py_GetProgramName(void); static wchar_t delimiter[2] = {DELIM, '\0'}; static wchar_t separator[2] = {SEP, '\0'}; char *_rtpypath = Py_GETENV("PYTHONPATH"); /* XXX use wide version on Windows */ wchar_t *rtpypath = NULL; wchar_t *home = Py_GetPythonHome(); char *_path = getenv("PATH"); wchar_t *path_buffer = NULL; wchar_t *path = NULL; wchar_t *prog = Py_GetProgramName(); wchar_t argv0_path[MAXPATHLEN+1]; wchar_t zip_path[MAXPATHLEN+1]; int pfound, efound; /* 1 if found; -1 if found build directory */ wchar_t *buf; size_t bufsz; size_t prefixsz; wchar_t *defpath; #ifdef WITH_NEXT_FRAMEWORK NSModule pythonModule; const char* modPath; #endif #ifdef __APPLE__ #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 uint32_t nsexeclength = MAXPATHLEN; #else unsigned long nsexeclength = MAXPATHLEN; #endif char execpath[MAXPATHLEN+1]; #endif wchar_t *_pythonpath, *_prefix, *_exec_prefix; _pythonpath = _Py_char2wchar(PYTHONPATH, NULL); _prefix = _Py_char2wchar(PREFIX, NULL); _exec_prefix = _Py_char2wchar(EXEC_PREFIX, NULL); if (!_pythonpath || !_prefix || !_exec_prefix) { Py_FatalError( "Unable to decode path variables in getpath.c: " "memory error"); } if (_path) { path_buffer = _Py_char2wchar(_path, NULL); path = path_buffer; } /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ if (wcschr(prog, SEP)) wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" * as argv[0], which falls through to the $PATH search below. * If /opt/python2.3/bin isn't in your path, or is near the end, * this algorithm may incorrectly find /usr/bin/python. To work * around this, we can use _NSGetExecutablePath to get a better * hint of what the intended interpreter was, although this * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); if (r == (size_t)-1 || r > MAXPATHLEN) { /* Could not convert execpath, or it's too long. */ progpath[0] = '\0'; } } #endif /* __APPLE__ */ else if (path) { while (1) { wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; if (len > MAXPATHLEN) len = MAXPATHLEN; wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else wcsncpy(progpath, path, MAXPATHLEN); joinpath(progpath, prog); if (isxfile(progpath)) break; if (!delim) { progpath[0] = L'\0'; break; } path = delim + 1; } } else progpath[0] = '\0'; PyMem_RawFree(path_buffer); if (progpath[0] != SEP && progpath[0] != '\0') absolutize(progpath); wcsncpy(argv0_path, progpath, MAXPATHLEN); argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK /* On Mac OS X we have a special case if we're running from a framework. ** This is because the python home should be set relative to the library, ** which is in the framework, not relative to the executable, which may ** be outside of the framework. Except when we're in the build directory... */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ modPath = NSLibraryNameForModule(pythonModule); if (modPath != NULL) { /* We're in a framework. */ /* See if we might be in the build directory. The framework in the ** build directory is incomplete, it only has the .dylib and a few ** needed symlinks, it doesn't have the Lib directories and such. ** If we're running with the framework from the build directory we must ** be running the interpreter in the build directory, so we use the ** build-directory-specific logic to find Lib and such. */ wchar_t* wbuf = _Py_char2wchar(modPath, NULL); if (wbuf == NULL) { Py_FatalError("Cannot decode framework location"); } wcsncpy(argv0_path, wbuf, MAXPATHLEN); reduce(argv0_path); joinpath(argv0_path, lib_python); joinpath(argv0_path, LANDMARK); if (!ismodule(argv0_path)) { /* We are in the build directory so use the name of the executable - we know that the absolute path is passed */ wcsncpy(argv0_path, progpath, MAXPATHLEN); } else { /* Use the location of the library as the progpath */ wcsncpy(argv0_path, wbuf, MAXPATHLEN); } PyMem_RawFree(wbuf); } #endif #if HAVE_READLINK { wchar_t tmpbuffer[MAXPATHLEN+1]; int linklen = _Py_wreadlink(progpath, tmpbuffer, MAXPATHLEN); while (linklen != -1) { if (tmpbuffer[0] == SEP) /* tmpbuffer should never be longer than MAXPATHLEN, but extra check does not hurt */ wcsncpy(argv0_path, tmpbuffer, MAXPATHLEN); else { /* Interpret relative to progpath */ reduce(argv0_path); joinpath(argv0_path, tmpbuffer); } linklen = _Py_wreadlink(argv0_path, tmpbuffer, MAXPATHLEN); } } #endif /* HAVE_READLINK */ reduce(argv0_path); /* At this point, argv0_path is guaranteed to be less than MAXPATHLEN bytes long. */ /* Search for an environment configuration file, first in the executable's directory and then in the parent directory. If found, open it for use when searching for prefixes. */ { wchar_t tmpbuffer[MAXPATHLEN+1]; wchar_t *env_cfg = L"pyvenv.cfg"; FILE * env_file = NULL; wcscpy(tmpbuffer, argv0_path); joinpath(tmpbuffer, env_cfg); env_file = _Py_wfopen(tmpbuffer, L"r"); if (env_file == NULL) { errno = 0; reduce(tmpbuffer); reduce(tmpbuffer); joinpath(tmpbuffer, env_cfg); env_file = _Py_wfopen(tmpbuffer, L"r"); if (env_file == NULL) { errno = 0; } } if (env_file != NULL) { /* Look for a 'home' variable and set argv0_path to it, if found */ if (find_env_config_value(env_file, L"home", tmpbuffer)) { wcscpy(argv0_path, tmpbuffer); } fclose(env_file); env_file = NULL; } } if (!(pfound = search_for_prefix(argv0_path, home, _prefix))) { if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform independent libraries <prefix>\n"); wcsncpy(prefix, _prefix, MAXPATHLEN); joinpath(prefix, lib_python); } else reduce(prefix); wcsncpy(zip_path, prefix, MAXPATHLEN); zip_path[MAXPATHLEN] = L'\0'; if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ reduce(zip_path); reduce(zip_path); } else wcsncpy(zip_path, _prefix, MAXPATHLEN); joinpath(zip_path, L"lib/python00.zip"); bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; if (!(efound = search_for_exec_prefix(argv0_path, home, _exec_prefix))) { if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform dependent libraries <exec_prefix>\n"); wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN); joinpath(exec_prefix, L"lib/lib-dynload"); } /* If we found EXEC_PREFIX do *not* reduce it! (Yet.) */ if ((!pfound || !efound) && !Py_FrozenFlag) fprintf(stderr, "Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]\n"); /* Calculate size of return buffer. */ bufsz = 0; if (_rtpypath && _rtpypath[0] != '\0') { size_t rtpypath_len; rtpypath = _Py_char2wchar(_rtpypath, &rtpypath_len); if (rtpypath != NULL) bufsz += rtpypath_len + 1; } defpath = _pythonpath; prefixsz = wcslen(prefix) + 1; while (1) { wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) /* Paths are relative to prefix */ bufsz += prefixsz; if (delim) bufsz += delim - defpath + 1; else { bufsz += wcslen(defpath) + 1; break; } defpath = delim + 1; } bufsz += wcslen(zip_path) + 1; bufsz += wcslen(exec_prefix) + 1; buf = (wchar_t *)PyMem_Malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n"); fprintf(stderr, "Using default static PYTHONPATH.\n"); module_search_path = L"" PYTHONPATH; } else { /* Run-time value of $PYTHONPATH goes first */ if (rtpypath) { wcscpy(buf, rtpypath); wcscat(buf, delimiter); } else buf[0] = '\0'; /* Next is the default zip path */ wcscat(buf, zip_path); wcscat(buf, delimiter); /* Next goes merge of compile-time $PYTHONPATH with * dynamically located prefix. */ defpath = _pythonpath; while (1) { wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) { wcscat(buf, prefix); wcscat(buf, separator); } if (delim) { size_t len = delim - defpath + 1; size_t end = wcslen(buf) + len; wcsncat(buf, defpath, len); *(buf + end) = '\0'; } else { wcscat(buf, defpath); break; } defpath = delim + 1; } wcscat(buf, delimiter); /* Finally, on goes the directory for dynamic-load modules */ wcscat(buf, exec_prefix); /* And publish the results */ module_search_path = buf; module_search_path_malloced = 1; } /* Reduce prefix and exec_prefix to their essence, * e.g. /usr/local/lib/python1.5 is reduced to /usr/local. * If we're loading relative to the build directory, * return the compiled-in defaults instead. */ if (pfound > 0) { reduce(prefix); reduce(prefix); /* The prefix is the root directory, but reduce() chopped * off the "/". */ if (!prefix[0]) wcscpy(prefix, separator); } else wcsncpy(prefix, _prefix, MAXPATHLEN); if (efound > 0) { reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); if (!exec_prefix[0]) wcscpy(exec_prefix, separator); } else wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN); PyMem_RawFree(_pythonpath); PyMem_RawFree(_prefix); PyMem_RawFree(_exec_prefix); PyMem_RawFree(rtpypath); }
NTSTATUS HidClassPDO_HandleQueryDeviceId( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { NTSTATUS Status; LPWSTR Buffer; LPWSTR NewBuffer, Ptr; ULONG Length; // // copy current stack location // IoCopyCurrentIrpStackLocationToNext(Irp); // // call mini-driver // Status = HidClassFDO_DispatchRequestSynchronous(DeviceObject, Irp); if (!NT_SUCCESS(Status)) { // // failed // return Status; } // // get buffer // Buffer = (LPWSTR)Irp->IoStatus.Information; Length = wcslen(Buffer); // // allocate new buffer // NewBuffer = ExAllocatePoolWithTag(NonPagedPool, (Length + 1) * sizeof(WCHAR), HIDCLASS_TAG); if (!NewBuffer) { // // failed to allocate buffer // return STATUS_INSUFFICIENT_RESOURCES; } // // replace bus // wcscpy(NewBuffer, L"HID\\"); // // get offset to first '\\' // Ptr = wcschr(Buffer, L'\\'); if (Ptr) { // // append result // wcscat(NewBuffer, Ptr + 1); } // // free old buffer // ExFreePoolWithTag(Buffer, 0); // // store result // DPRINT("NewBuffer %S\n", NewBuffer); Irp->IoStatus.Information = (ULONG_PTR)NewBuffer; return STATUS_SUCCESS; }
HRESULT FindGroup(IDirectorySearch *pSearchBase, //Container to search LPOLESTR szFindUser, //Name of user to find. IADs **ppUser,LPOLESTR szGroup) //Return a pointer to the user { HRESULT hrObj = E_FAIL; HRESULT hr = E_FAIL; if ((!pSearchBase)||(!szFindUser)) return E_INVALIDARG; //Create search filter LPOLESTR pszSearchFilter = new OLECHAR[MAX_PATH]; LPOLESTR szADsPath = new OLECHAR[MAX_PATH]; wcscpy(pszSearchFilter, L"(&(objectClass=group)(cn="); wcscat(pszSearchFilter,szGroup); wcscat(pszSearchFilter, L"))"); //Search entire subtree from root. ADS_SEARCHPREF_INFO SearchPrefs; SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE; SearchPrefs.vValue.dwType = ADSTYPE_INTEGER; SearchPrefs.vValue.Integer = ADS_SCOPE_SUBTREE; DWORD dwNumPrefs = 1; // COL for iterations ADS_SEARCH_COLUMN col; // Handle used for searching ADS_SEARCH_HANDLE hSearch; // Set the search preference hr = pSearchBase->SetSearchPreference( &SearchPrefs, dwNumPrefs); if (FAILED(hr)) return hr; // Set attributes to return CONST DWORD dwAttrNameSize = 1; LPOLESTR pszAttribute[dwAttrNameSize] = {L"ADsPath"}; // Execute the search hr = pSearchBase->ExecuteSearch(pszSearchFilter, pszAttribute, dwAttrNameSize, &hSearch ); if (SUCCEEDED(hr)) { // Call IDirectorySearch::GetNextRow() to retrieve the next row //of data while( pSearchBase->GetNextRow( hSearch) != S_ADS_NOMORE_ROWS ) { // loop through the array of passed column names, // print the data for each column for (DWORD x = 0; x < dwAttrNameSize; x++) { // Get the data for this column hr = pSearchBase->GetColumn( hSearch, pszAttribute[x], &col ); if ( SUCCEEDED(hr) ) { // Print the data for the column and free the column // Note the attribute we asked for is type CaseIgnoreString. wcscpy(szADsPath, col.pADsValues->CaseIgnoreString); hr = ADsOpenObject(szADsPath, NULL, NULL, ADS_SECURE_AUTHENTICATION, //Use Secure Authentication IID_IADs, (void**)ppUser); if (SUCCEEDED(hr)) { wprintf(L"%s: %s\r\n",pszAttribute[x],col.pADsValues->CaseIgnoreString); hrObj = S_OK; gbsGroup=SysAllocString(col.pADsValues->CaseIgnoreString); } pSearchBase->FreeColumn( &col ); } else hr = E_FAIL; } } // Close the search handle to clean up pSearchBase->CloseSearchHandle(hSearch); } if (FAILED(hrObj)) hr = hrObj; return hr; }
static wchar_t * goodG2BSource(wchar_t * data) { /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); return data; }
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID lpReserved) { static bool bDllInited = false; BOOL IsUnload = false, bEnableDW = true; switch(reason) { case DLL_PROCESS_ATTACH: #ifdef DEBUG //MessageBox(0, L"Load", NULL, MB_OK); #endif if (bDllInited) return true; bDllInited = true; g_dllInstance = instance; { LPWSTR dllPath = new WCHAR[MAX_PATH + 1]; int nSize = GetModuleFileName(g_dllInstance, dllPath, MAX_PATH + 1); WCHAR* p = &dllPath[nSize]; while (*--p != L'\\'); *p = L'\0'; #ifdef _WIN64 wcscat(dllPath, L"\\EasyHk64.dll"); #else wcscat(dllPath, L"\\EasyHk32.dll"); #endif HMODULE hEasyhk = LoadLibrary(dllPath); delete[]dllPath; if (!hEasyhk) return false; } //弶婜壔弴彉 //DLL_PROCESS_DETACH偱偼偙傟偺媡弴偵偡傞 //1. CRT娭悢偺弶婜壔 //2. 僋儕僥傿僇儖僙僋僔儑儞偺弶婜壔 //3. TLS偺弨旛 //4. CGdippSettings偺僀儞僗僞儞僗惗惉丄INI撉傒崬傒 //5. ExcludeModule僠僃僢僋 // 6. FreeType儔僀僽儔儕偺弶婜壔 // 7. FreeTypeFontEngine偺僀儞僗僞儞僗惗惉 // 8. API傪僼僢僋 // 9. Manager偺GetProcAddress傪僼僢僋 //1 _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW); //_CrtSetBreakAlloc(100); //Opera傛巭傑傟乣 //Assert(GetModuleHandleA("opera.exe") == NULL); setlocale(LC_ALL, ""); g_hinstDLL = instance; //APITracer::Start(instance, APITracer::OutputFile); //2, 3 CCriticalSectionLock::Init(); COwnedCriticalSectionLock::Init(); CThreadCounter::Init(); if (!g_TLInfo.ProcessInit()) { return FALSE; } //4 { CGdippSettings* pSettings = CGdippSettings::CreateInstance(); if (!pSettings || !pSettings->LoadSettings(instance)) { CGdippSettings::DestroyInstance(); return FALSE; } IsUnload = IsProcessUnload(); bEnableDW = pSettings->DirectWrite(); } if (!IsUnload) hook_initinternal(); //不加载的模块就不做任何事情 //5 if (!IsProcessExcluded() && !IsUnload) { #ifndef _WIN64 InitWow64ext(); #endif if (!FontLInit()) { return FALSE; } g_pFTEngine = new FreeTypeFontEngine; if (!g_pFTEngine) { return FALSE; } //if (!AddEasyHookEnv()) return FALSE; //fail to load easyhook InterlockedExchange(&g_bHookEnabled, TRUE); if (hook_init()!=NOERROR) return FALSE; //hook d2d if already loaded /* DWORD dwSessionID = 0; if (ProcessIdToSessionIdProc) ProcessIdToSessionIdProc(GetCurrentThreadId(), &dwSessionID); else dwSessionID = 1;*/ if (IsRunAsUser() && bEnableDW && IsWindowsVistaOrGreater()) //vista or later { //ORIG_LdrLoadDll = LdrLoadDll; //MessageBox(0, L"Test", NULL, MB_OK); HookD2DDll(); //hook_demand_LdrLoadDll(); } /*if (IsWindows8OrGreater()) { *(DWORD_PTR*)&(ORIG_MySetProcessMitigationPolicy) = *(DWORD_PTR*)&(MySetProcessMitigationPolicy); //hook_demand_MySetProcessMitigationPolicy(); }*/ // InstallManagerHook(); } //获得当前加载模式 if (IsUnload) { HANDLE mutex_offical = OpenMutex(MUTEX_ALL_ACCESS, false, _T("{46AD3688-30D0-411e-B2AA-CB177818F428}")); HANDLE mutex_gditray2 = OpenMutex(MUTEX_ALL_ACCESS, false, _T("Global\\MacType")); if (!mutex_gditray2) mutex_gditray2 = OpenMutex(MUTEX_ALL_ACCESS, false, _T("MacType")); HANDLE mutex_CompMode = OpenMutex(MUTEX_ALL_ACCESS, false, _T("Global\\MacTypeCompMode")); if (!mutex_CompMode) mutex_CompMode = OpenMutex(MUTEX_ALL_ACCESS, false, _T("MacTypeCompMode")); BOOL HookMode = (mutex_offical || (mutex_gditray2 && mutex_CompMode)) || (!mutex_offical && !mutex_gditray2); //是否在兼容模式下 CloseHandle(mutex_CompMode); CloseHandle(mutex_gditray2); CloseHandle(mutex_offical); if (!HookMode) //非兼容模式下,拒绝加载 return false; } //APITracer::Finish(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: g_TLInfo.ThreadTerm(); break; case DLL_PROCESS_DETACH: // RemoveManagerHook(); if (!bDllInited) return true; bDllInited = false; if (InterlockedExchange(&g_bHookEnabled, FALSE) && lpReserved == NULL) { //如果是进程终止,则不需要释放 hook_term(); //delete AACacheFull; //delete AACache; // for (int i=0;i<CACHE_SIZE;i++) // delete g_AACache2[i]; //清除缓存 //free(g_charmapCache); } #ifndef DEBUG if (lpReserved != NULL) return true; #endif if (g_pFTEngine) { delete g_pFTEngine; } //if (g_alterGUIFont) // DeleteObject(g_alterGUIFont); FontLFree(); /* #ifndef _WIN64 __FUnloadDelayLoadedDLL2("easyhk32.dll"); #else __FUnloadDelayLoadedDLL2("easyhk64.dll"); #endif*/ CGdippSettings::DestroyInstance(); g_TLInfo.ProcessTerm(); CCriticalSectionLock::Term(); COwnedCriticalSectionLock::Term(); break; } return TRUE; }
static VOID RunTestCases(VOID) { /* TODO: don't duplicate this in the other tests */ /* TODO: Drive Relative tests don't work yet if the current drive isn't C: */ struct { PCWSTR FileName; PREFIX_TYPE PrefixType; PCWSTR FullPathName; RTL_PATH_TYPE PathType; PREFIX_TYPE FilePartPrefixType; SIZE_T FilePartSize; } TestCases[] = { { L"C:", PrefixCurrentPath, L"", RtlPathTypeDriveRelative, PrefixCurrentPathWithoutLastPart }, { L"C:\\", PrefixNone, L"C:\\", RtlPathTypeDriveAbsolute }, { L"C:\\test", PrefixNone, L"C:\\test", RtlPathTypeDriveAbsolute, PrefixCurrentDrive }, { L"C:\\test\\", PrefixNone, L"C:\\test\\", RtlPathTypeDriveAbsolute }, { L"C:/test/", PrefixNone, L"C:\\test\\", RtlPathTypeDriveAbsolute }, { L"C:\\\\test", PrefixNone, L"C:\\test", RtlPathTypeDriveAbsolute, PrefixCurrentDrive }, { L"test", PrefixCurrentPath, L"\\test", RtlPathTypeRelative, PrefixCurrentPath, sizeof(WCHAR) }, { L"\\test", PrefixCurrentDrive, L"test", RtlPathTypeRooted, PrefixCurrentDrive }, { L"/test", PrefixCurrentDrive, L"test", RtlPathTypeRooted, PrefixCurrentDrive }, { L".\\test", PrefixCurrentPath, L"\\test", RtlPathTypeRelative, PrefixCurrentPath, sizeof(WCHAR) }, { L"\\.", PrefixCurrentDrive, L"", RtlPathTypeRooted }, { L"\\.\\", PrefixCurrentDrive, L"", RtlPathTypeRooted }, { L"\\\\.", PrefixNone, L"\\\\.\\", RtlPathTypeRootLocalDevice }, { L"\\\\.\\", PrefixNone, L"\\\\.\\", RtlPathTypeLocalDevice }, { L"\\\\.\\Something\\", PrefixNone, L"\\\\.\\Something\\", RtlPathTypeLocalDevice }, { L"\\??\\", PrefixCurrentDrive, L"??\\", RtlPathTypeRooted }, { L"\\??\\C:", PrefixCurrentDrive, L"??\\C:", RtlPathTypeRooted, PrefixCurrentDrive, 3 * sizeof(WCHAR) }, { L"\\??\\C:\\", PrefixCurrentDrive, L"??\\C:\\", RtlPathTypeRooted }, { L"\\??\\C:\\test", PrefixCurrentDrive, L"??\\C:\\test", RtlPathTypeRooted, PrefixCurrentDrive, 6 * sizeof(WCHAR) }, { L"\\??\\C:\\test\\", PrefixCurrentDrive, L"??\\C:\\test\\", RtlPathTypeRooted }, { L"\\\\??\\", PrefixNone, L"\\\\??\\", RtlPathTypeUncAbsolute }, { L"\\\\??\\C:", PrefixNone, L"\\\\??\\C:", RtlPathTypeUncAbsolute }, { L"\\\\??\\C:\\", PrefixNone, L"\\\\??\\C:\\", RtlPathTypeUncAbsolute }, { L"\\\\??\\C:\\test", PrefixNone, L"\\\\??\\C:\\test", RtlPathTypeUncAbsolute, PrefixNone, sizeof(L"\\\\??\\C:\\") }, { L"\\\\??\\C:\\test\\", PrefixNone, L"\\\\??\\C:\\test\\", RtlPathTypeUncAbsolute }, }; ULONG Length; UNICODE_STRING FileName; WCHAR FullPathNameBuffer[MAX_PATH]; UNICODE_STRING TempString; const WCHAR *ShortName; BOOLEAN NameInvalid; PATH_TYPE_AND_UNKNOWN PathType; WCHAR ExpectedPathName[MAX_PATH]; SIZE_T ExpectedFilePartSize; const WCHAR *ExpectedShortName; const INT TestCount = sizeof(TestCases) / sizeof(TestCases[0]); INT i; BOOLEAN Okay; for (i = 0; i < TestCount; i++) { trace("i = %d\n", i); switch (TestCases[i].PrefixType) { case PrefixNone: ExpectedPathName[0] = UNICODE_NULL; break; case PrefixCurrentDrive: GetCurrentDirectoryW(sizeof(ExpectedPathName) / sizeof(WCHAR), ExpectedPathName); ExpectedPathName[3] = UNICODE_NULL; break; case PrefixCurrentPath: { ULONG Length; Length = GetCurrentDirectoryW(sizeof(ExpectedPathName) / sizeof(WCHAR), ExpectedPathName); if (Length == 3 && TestCases[i].FullPathName[0]) ExpectedPathName[2] = UNICODE_NULL; break; } default: skip("Invalid test!\n"); continue; } wcscat(ExpectedPathName, TestCases[i].FullPathName); RtlInitUnicodeString(&FileName, TestCases[i].FileName); RtlFillMemory(FullPathNameBuffer, sizeof(FullPathNameBuffer), 0xAA); TempString = FileName; PathType.Type = RtlPathTypeNotSet; PathType.Unknown = 1234; ShortName = InvalidPointer; NameInvalid = (BOOLEAN)-1; Length = 1234; StartSeh() Length = RtlGetFullPathName_Ustr(&FileName, sizeof(FullPathNameBuffer), FullPathNameBuffer, &ShortName, &NameInvalid, &PathType); EndSeh(STATUS_SUCCESS); ok_eq_ustr(&FileName, &TempString); Okay = CheckStringBuffer(FullPathNameBuffer, Length, sizeof(FullPathNameBuffer), ExpectedPathName); ok(Okay, "Wrong path name '%S', expected '%S'\n", FullPathNameBuffer, ExpectedPathName); switch (TestCases[i].FilePartPrefixType) { case PrefixNone: ExpectedFilePartSize = 0; break; case PrefixCurrentDrive: ExpectedFilePartSize = sizeof(L"C:\\"); break; case PrefixCurrentPath: ExpectedFilePartSize = GetCurrentDirectoryW(0, NULL) * sizeof(WCHAR); if (ExpectedFilePartSize == sizeof(L"C:\\")) ExpectedFilePartSize -= sizeof(WCHAR); break; case PrefixCurrentPathWithoutLastPart: { WCHAR CurrentPath[MAX_PATH]; PCWSTR BackSlash; ExpectedFilePartSize = GetCurrentDirectoryW(sizeof(CurrentPath) / sizeof(WCHAR), CurrentPath) * sizeof(WCHAR) + sizeof(UNICODE_NULL); if (ExpectedFilePartSize == sizeof(L"C:\\")) ExpectedFilePartSize = 0; else { BackSlash = wcsrchr(CurrentPath, L'\\'); if (BackSlash) ExpectedFilePartSize -= wcslen(BackSlash + 1) * sizeof(WCHAR); else ok(0, "GetCurrentDirectory returned %S\n", CurrentPath); } break; } default: skip("Invalid test!\n"); continue; } ExpectedFilePartSize += TestCases[i].FilePartSize; if (ExpectedFilePartSize == 0) { ExpectedShortName = NULL; } else { ExpectedFilePartSize = (ExpectedFilePartSize - sizeof(UNICODE_NULL)) / sizeof(WCHAR); ExpectedShortName = FullPathNameBuffer + ExpectedFilePartSize; } ok(ShortName == ExpectedShortName, "ShortName = %p, expected %p\n", ShortName, ExpectedShortName); ok(NameInvalid == FALSE, "NameInvalid = %u\n", NameInvalid); ok(PathType.Type == TestCases[i].PathType, "PathType = %d, expected %d\n", PathType.Type, TestCases[i].PathType); ok(PathType.Unknown == 1234 || broken(PathType.Unknown == 0) || broken(PathType.Unknown == 32), "Unknown = %lu\n", PathType.Unknown); } }
void CWE90_LDAP_Injection__w32_wchar_t_file_12_bad() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; if(globalReturnsTrueOrFalse()) { { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (256-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(256-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } } else { /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); } { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } }
static wchar_t *makeCmdLine ( bool ask, wchar_t *buffer, const wchar_t *mask, const wchar_t *dir, const wchar_t *fn, const wchar_t *title = nullptr, const wchar_t macro = L'=' ) { static wchar_t tmp[NM]; static wchar_t n1[NM], drv1[NM], dir1[NM], fil1[NM], ext1[NM]; static wchar_t n2[NM], drv2[NM], dir2[NM], fil2[NM], ext2[NM]; wchar_t *i, *j, *e1 = ext1, *e2 = ext2, *smartQuote = nullptr; fExpand (wcscpy (tmp, fn), dir); GetFullPathName (tmp, _countof(n1), n1, &j); fnSplit (n1, drv1, dir1, fil1, ext1); GetShortPathName (tmp, n2, _countof(n2)); fnSplit (n2, drv2, dir2, fil2, ext2); wcscat (wcscat (wcscat (wcscpy (n1, drv1), dir1), fil1), ext1); wcscat (wcscat (wcscat (wcscpy (n2, drv2), dir2), fil2), ext2); if (*e1 == L'.') e1++; if (*e2 == L'.') e2++; i = (wchar_t *) mask; if (ask) { nullUserStrings (); if (!scanUserInput (false, L'=', mask, title)) return (nullptr); } *tmp = 0; *(j = buffer) = 0; while (*i) { int dosName = 0, noDrive = 0, noBackslash = 0, doQuote = 1; wchar_t *m = wcschr (i, macro); if (m) { *m = 0; wcscat (j, i); j = wcschr (j, 0); *m = macro; if (*++m == macro) { j[0] = macro; j[1] = 0; j = wcschr (j, 0); i = m + 1; } else if (ask && wcschr (L"0123456789?", *m)) { if (*m != L'?') wcscpy (j, userString[*m - L'0']); j = wcschr (j, 0); if (*m == L'?') { m++; while (*m) { if ((m[0] == L'\\') && ((m[1] == L'\\') || (m[1] == L'\'') || (m[1] == L'?'))) { m++; m++; } else { if (*m == L'?') break; else m++; } } } i = m + 1; } else { int modifyer = 1; while (modifyer) { switch (*m) { case L'd': dosName = 1; break; case L'm': noDrive = 1; break; case L't': noBackslash = 1; break; case L'o': doQuote = 0; break; default: m--; modifyer = 0; break; } m++; } switch (*m) { case L'M': wcscat (j, drv1); break; case L'N': wcscat (j, quote (doQuote, wcscpy (tmp, dosName ? fil2 : fil1))); break; case L'E': if (*(m + 1) == L's') { EditorGetStringEx egs; EditorGetStr (&egs); wcsncpy (j + wcslen (j), egs.StringText, egs.StringLength + 1); m++; } else if (*(m + 1) == L'p') { TEditorPos pos = EditorGetPos (); FSF.itoa64 (pos.Row + 1, tmp, 10); wcscat (j, tmp); m++; } else if (*(m + 1) == L'c') { TEditorPos pos = EditorGetPos (); FSF.itoa64 (pos.Col + 1, tmp, 10); wcscat (j, tmp); m++; } else wcscat (j, quote (doQuote, wcscpy (tmp, dosName ? e2 : e1))); break; case L'F': wcscpy (tmp, dosName ? fil2 : fil1); if (*(dosName ? e2 : e1)) wcscat (wcscat (tmp, L"."), dosName ? e2 : e1); wcscat (j, quote (doQuote, tmp)); break; case L'D': if (noDrive) *tmp = 0; else wcscpy (tmp, drv1); wcscat (tmp, dosName ? dir2 : dir1); if (noBackslash) delBackslash (tmp); wcscat (j, quote (doQuote, tmp)); break; case L'P': if (noDrive) { wcscpy (tmp, dosName ? dir2 : dir1); wcscat (tmp, dosName ? fil2 : fil1); if (*(dosName ? e2 : e1)) wcscat (wcscat (tmp, L"."), dosName ? e2 : e1); wcscat (j, quote (doQuote, tmp)); } else wcscat (j, quote (doQuote, wcscat (tmp, dosName ? n2 : n1))); break; case L'\'': if (smartQuote) { for (wchar_t *p = smartQuote; *p; p++) if (*p == L'\"') *p = L'\''; quote (1, smartQuote); smartQuote = nullptr; } else smartQuote = wcschr (j, 0); break; } i = m + 1; j = wcschr (j, 0); } } else break; } wcscat (j, i); return (buffer); }
NTSTATUS MuInitializeUserModeHelper ( PMU_GLOBAL_DATA GlobalData ) { NTSTATUS status; HANDLE file, proc, dllsec; SIZE_T imgsize = 0; PVOID secobj, dllbase = NULL; LARGE_INTEGER secofs; UNICODE_STRING fp; IO_STATUS_BLOCK iosb; OBJECT_ATTRIBUTES oa; WCHAR path[MAX_PATH]; wcscpy(path, MU_ROOTDIR_SYSTEM32); wcscat(path, MU_FILENAME_HELPER_DLL); RtlInitUnicodeString(&fp, path); InitializeObjectAttributes(&oa, &fp, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); status = ZwOpenFile(&file, GENERIC_READ, &oa, &iosb, FILE_SHARE_READ, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT); if (NT_SUCCESS(status)) { status = ZwCreateSection(&dllsec, SECTION_ALL_ACCESS, NULL, NULL, PAGE_EXECUTE_READWRITE, SEC_IMAGE, file); ZwClose(file); if (!NT_SUCCESS(status)) return status; status = ObReferenceObjectByHandle(dllsec, SECTION_ALL_ACCESS, *MmSectionObjectType, KernelMode, &secobj, NULL); ZwClose(dllsec); if (NT_SUCCESS(status)) { secofs.QuadPart = 0; status = MmMapViewOfSection(secobj, PsGetCurrentProcess(), &dllbase, 0, 0, &secofs, &imgsize, ViewShare, 0, PAGE_EXECUTE_READWRITE); if (NT_SUCCESS(status)) { status = MuLinkDll(GlobalData, dllbase); MmUnmapViewOfSection(PsGetCurrentProcess(), dllbase); } if (!NT_SUCCESS(status)) { ObDereferenceObject(secobj); secobj = NULL; } GlobalData->DllSection = secobj; GlobalData->DllImageSize = imgsize; GlobalData->DllImageBase = dllbase; } } return status; }
/* goodG2B() - use goodsource and badsink by changing the "if" so that * both branches use the GoodSource */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; if(globalReturnsTrueOrFalse()) { /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); } else { /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); } { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } }
INT_PTR CALLBACK DriveExtraDlg( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { STARTUPINFOW si; PROCESS_INFORMATION pi; WCHAR szPath[MAX_PATH + 10]; WCHAR szArg[MAX_PATH]; WCHAR * szDrive; LPPROPSHEETPAGEW ppsp; DWORD dwSize; FORMAT_DRIVE_CONTEXT Context; switch (uMsg) { case WM_INITDIALOG: ppsp = (LPPROPSHEETPAGEW)lParam; SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)ppsp->lParam); return TRUE; case WM_COMMAND: ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); szDrive = (WCHAR*)GetWindowLongPtr(hwndDlg, DWLP_USER); switch(LOWORD(wParam)) { case 14000: if (InitializeFmifsLibrary(&Context)) { Context.Drive = szDrive[0]; DialogBoxParamW(shell32_hInstance, L"CHKDSK_DLG", hwndDlg, ChkDskDlg, (LPARAM)&Context); FreeLibrary(Context.hLibrary); } break; case 14001: dwSize = sizeof(szPath); if (RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MyComputer\\DefragPath", NULL, RRF_RT_REG_EXPAND_SZ, NULL, (PVOID)szPath, &dwSize) == S_OK) { swprintf(szArg, szPath, szDrive[0]); if (!GetSystemDirectoryW(szPath, MAX_PATH)) break; szDrive = PathAddBackslashW(szPath); if (!szDrive) break; wcscat(szDrive, L"mmc.exe"); if (CreateProcessW(szPath, szArg, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } } break; case 14002: dwSize = sizeof(szPath); if (RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MyComputer\\BackupPath", NULL, RRF_RT_REG_EXPAND_SZ, NULL, (PVOID)szPath, &dwSize) == S_OK) { if (CreateProcessW(szPath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } } } break; } return FALSE; }
INT_PTR CALLBACK DriveGeneralDlg( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { LPPROPSHEETPAGEW ppsp; LPDRAWITEMSTRUCT drawItem; STARTUPINFOW si; PROCESS_INFORMATION pi; WCHAR * lpstr; WCHAR szPath[MAX_PATH]; UINT length; LPPSHNOTIFY lppsn; switch(uMsg) { case WM_INITDIALOG: ppsp = (LPPROPSHEETPAGEW)lParam; if (ppsp == NULL) break; lpstr = (WCHAR *)ppsp->lParam; SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)lpstr); InitializeGeneralDriveDialog(hwndDlg, lpstr); return TRUE; case WM_DRAWITEM: drawItem = (LPDRAWITEMSTRUCT)lParam; if (drawItem->CtlID >= 14013 && drawItem->CtlID <= 14015) { PaintStaticControls(hwndDlg, drawItem); return TRUE; } break; case WM_COMMAND: if (LOWORD(wParam) == 14010) /* Disk Cleanup */ { lpstr = (WCHAR*)GetWindowLongPtr(hwndDlg, DWLP_USER); ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if (!GetSystemDirectoryW(szPath, MAX_PATH)) break; wcscat(szPath, L"\\cleanmgr.exe /D "); length = wcslen(szPath); szPath[length] = lpstr[0]; szPath[length+1] = L'\0'; if (CreateProcessW(NULL, szPath, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } break; } case WM_NOTIFY: lppsn = (LPPSHNOTIFY) lParam; if (LOWORD(wParam) == 14000) { if (HIWORD(wParam) == EN_CHANGE) { PropSheet_Changed(GetParent(hwndDlg), hwndDlg); } break; } if (lppsn->hdr.code == PSN_APPLY) { lpstr = (LPWSTR)GetWindowLongPtr(hwndDlg, DWLP_USER); if (lpstr && SendDlgItemMessageW(hwndDlg, 14000, WM_GETTEXT, sizeof(szPath)/sizeof(WCHAR), (LPARAM)szPath)) { szPath[(sizeof(szPath)/sizeof(WCHAR))-1] = L'\0'; SetVolumeLabelW(lpstr, szPath); } SetWindowLongPtr( hwndDlg, DWL_MSGRESULT, PSNRET_NOERROR ); return TRUE; } break; default: break; } return FALSE; }
DIR *opendir(const char *dir) {/*{{{*/ DIR *dp; wchar_t *filespecw, *resolvedw; HANDLE handle; char resolved_path_buff[MAXPATHLEN]; size_t resolvedw_len, filespecw_len, index; zend_bool might_need_prefix; if (!VCWD_REALPATH(dir, resolved_path_buff)) { return NULL; } resolvedw = php_win32_ioutil_conv_any_to_w(resolved_path_buff, PHP_WIN32_CP_IGNORE_LEN, &resolvedw_len); if (!resolvedw) { return NULL; } might_need_prefix = resolvedw_len >= 3 && PHP_WIN32_IOUTIL_IS_LETTERW(resolvedw[0]) && L':' == resolvedw[1] && PHP_WIN32_IOUTIL_IS_SLASHW(resolvedw[2]); filespecw_len = resolvedw_len + 2; if (filespecw_len >= _MAX_PATH && might_need_prefix) { filespecw_len += PHP_WIN32_IOUTIL_LONG_PATH_PREFIX_LENW; } filespecw = (wchar_t *)malloc((filespecw_len + 1)*sizeof(wchar_t)); if (filespecw == NULL) { free(resolvedw); return NULL; } if (filespecw_len >= _MAX_PATH && might_need_prefix) { wcscpy(filespecw, PHP_WIN32_IOUTIL_LONG_PATH_PREFIXW); wcscpy(filespecw + PHP_WIN32_IOUTIL_LONG_PATH_PREFIX_LENW, resolvedw); index = resolvedw_len + PHP_WIN32_IOUTIL_LONG_PATH_PREFIX_LENW - 1; } else { wcscpy(filespecw, resolvedw); index = resolvedw_len - 1; } if (index >= 0 && filespecw[index] == L'/' || index == 0 && filespecw[index] == L'\\') filespecw[index] = L'\0'; wcscat(filespecw, L"\\*"); dp = (DIR *) calloc(1, sizeof(DIR) + (_MAX_FNAME*5+1)*sizeof(char)); if (dp == NULL) { free(filespecw); free(resolvedw); return NULL; } if ((handle = FindFirstFileExW(filespecw, FindExInfoBasic, &(dp->fileinfo), FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH)) == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); if (err == ERROR_NO_MORE_FILES || err == ERROR_FILE_NOT_FOUND) { dp->finished = 1; } else { free(dp); free(filespecw); free(resolvedw); return NULL; } } dp->dirw = _wcsdup(resolvedw); dp->handle = handle; dp->offset = 0; dp->finished = 0; free(filespecw); free(resolvedw); return dp; }/*}}}*/
SECURITY_STATUS SspGetContextNames( IN PCheaterContext Context ) /*++ Routine Description: This routine obtains the names for a context by opening the token, getting the User ID, and calling LookupAccountNameW on the user id. Arguments: Context - Context to obtain names for Return Value: STATUS_SUCCESS - Call completed successfully SEC_E_INVALID_HANDLE -- Credential/Context Handle is invalid SEC_E_UNSUPPORTED_FUNCTION -- Function code is not supported --*/ { PTOKEN_USER TokenUserInfo = NULL; ULONG TokenUserSize = 0; NTSTATUS Status; WCHAR UserName[UNLEN+1]; ULONG UserNameLength = UNLEN+1; WCHAR DomainName[DNLEN+1]; ULONG DomainNameLength = DNLEN+1; SID_NAME_USE SidUse; LPWSTR ContextNames = NULL; ASSERT(Context->TokenHandle != NULL); // // Get the LogonId from the token. // Status = NtQueryInformationToken( Context->TokenHandle, TokenUser, TokenUserInfo, TokenUserSize, &TokenUserSize ); if ( Status != STATUS_BUFFER_TOO_SMALL ) { goto Cleanup; } TokenUserInfo = LocalAlloc( 0, TokenUserSize ); if ( TokenUserInfo == NULL ) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Cleanup; } Status = NtQueryInformationToken( Context->TokenHandle, TokenUser, TokenUserInfo, TokenUserSize, &TokenUserSize ); if ( !NT_SUCCESS(Status) ) { goto Cleanup; } // // Now that we have the user ID, calling LookupAccountName to translate // it to a SID. // if (!LookupAccountSidW( NULL, // local system TokenUserInfo->User.Sid, UserName, &UserNameLength, DomainName, &DomainNameLength, &SidUse )) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Cleanup; } // // We now have the use & domain name - put them in the context. // ContextNames = LocalAlloc(0, (wcslen(UserName) + wcslen(DomainName) + 2) * sizeof(WCHAR)); if (ContextNames == NULL) { Status = STATUS_INSUFFICIENT_RESOURCES; goto Cleanup; } if (DomainName[0] != L'\0') { wcscpy(ContextNames, DomainName); wcscat(ContextNames, L"\\"); } wcscat(ContextNames, UserName); LocalFree(Context->ContextNames); Context->ContextNames = ContextNames; Status = STATUS_SUCCESS; Cleanup: if (TokenUserInfo != NULL) { LocalFree(TokenUserInfo); } return(Status); }
BOOLEAN InstallDriver( IN HINF hInf, IN HANDLE hServices, IN HANDLE hDeviceKey, IN LPCWSTR DeviceId, IN LPCWSTR HardwareId) { UNICODE_STRING PathPrefix = RTL_CONSTANT_STRING(L"System32\\DRIVERS\\"); UNICODE_STRING ServiceU = RTL_CONSTANT_STRING(L"Service"); UNICODE_STRING ErrorControlU = RTL_CONSTANT_STRING(L"ErrorControl"); UNICODE_STRING ImagePathU = RTL_CONSTANT_STRING(L"ImagePath"); UNICODE_STRING StartU = RTL_CONSTANT_STRING(L"Start"); UNICODE_STRING TypeU = RTL_CONSTANT_STRING(L"Type"); UNICODE_STRING StringU; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE hService; INFCONTEXT Context; LPWSTR Driver, ClassGuid, ImagePath, FullImagePath; ULONG dwValue; ULONG Disposition; NTSTATUS Status; BOOLEAN deviceInstalled = FALSE; UNICODE_STRING UpperFiltersU = RTL_CONSTANT_STRING(L"UpperFilters"); LPWSTR keyboardClass = L"kbdclass\0"; /* Check if we know the hardware */ if (!SetupFindFirstLineW(hInf, L"HardwareIdsDatabase", HardwareId, &Context)) return FALSE; if (!INF_GetDataField(&Context, 1, &Driver)) return FALSE; /* Get associated class GUID (if any) */ if (!INF_GetDataField(&Context, 2, &ClassGuid)) ClassGuid = NULL; /* Find associated driver name */ /* FIXME: check in other sections too! */ if (!SetupFindFirstLineW(hInf, L"BootBusExtenders.Load", Driver, &Context) && !SetupFindFirstLineW(hInf, L"BusExtenders.Load", Driver, &Context) && !SetupFindFirstLineW(hInf, L"SCSI.Load", Driver, &Context) && !SetupFindFirstLineW(hInf, L"InputDevicesSupport.Load", Driver, &Context) && !SetupFindFirstLineW(hInf, L"Keyboard.Load", Driver, &Context)) { return FALSE; } if (!INF_GetDataField(&Context, 1, &ImagePath)) return FALSE; /* Prepare full driver path */ dwValue = PathPrefix.MaximumLength + wcslen(ImagePath) * sizeof(WCHAR); FullImagePath = (LPWSTR)RtlAllocateHeap(ProcessHeap, 0, dwValue); if (!FullImagePath) { DPRINT1("RtlAllocateHeap() failed\n"); return FALSE; } RtlCopyMemory(FullImagePath, PathPrefix.Buffer, PathPrefix.MaximumLength); wcscat(FullImagePath, ImagePath); DPRINT1("Using driver '%S' for device '%S'\n", ImagePath, DeviceId); /* Create service key */ RtlInitUnicodeString(&StringU, Driver); InitializeObjectAttributes(&ObjectAttributes, &StringU, 0, hServices, NULL); Status = NtCreateKey(&hService, KEY_SET_VALUE, &ObjectAttributes, 0, NULL, 0, &Disposition); if (!NT_SUCCESS(Status)) { DPRINT1("NtCreateKey('%wZ') failed with status 0x%08x\n", &StringU, Status); RtlFreeHeap(ProcessHeap, 0, FullImagePath); return FALSE; } /* Fill service key */ if (Disposition == REG_CREATED_NEW_KEY) { dwValue = 0; NtSetValueKey( hService, &ErrorControlU, 0, REG_DWORD, &dwValue, sizeof(dwValue)); dwValue = 0; NtSetValueKey( hService, &StartU, 0, REG_DWORD, &dwValue, sizeof(dwValue)); dwValue = SERVICE_KERNEL_DRIVER; NtSetValueKey( hService, &TypeU, 0, REG_DWORD, &dwValue, sizeof(dwValue)); } /* HACK: don't put any path in registry */ NtSetValueKey( hService, &ImagePathU, 0, REG_SZ, ImagePath, (wcslen(ImagePath) + 1) * sizeof(WCHAR)); if (ClassGuid &&_wcsicmp(ClassGuid, L"{4D36E96B-E325-11CE-BFC1-08002BE10318}") == 0) { DPRINT1("Installing keyboard class driver for '%S'\n", DeviceId); NtSetValueKey(hDeviceKey, &UpperFiltersU, 0, REG_MULTI_SZ, keyboardClass, (wcslen(keyboardClass) + 2) * sizeof(WCHAR)); } /* Associate device with the service we just filled */ Status = NtSetValueKey( hDeviceKey, &ServiceU, 0, REG_SZ, Driver, (wcslen(Driver) + 1) * sizeof(WCHAR)); if (NT_SUCCESS(Status)) { /* Restart the device, so it will use the driver we registered */ deviceInstalled = ResetDevice(DeviceId); } /* HACK: Update driver path */ NtSetValueKey( hService, &ImagePathU, 0, REG_SZ, FullImagePath, (wcslen(FullImagePath) + 1) * sizeof(WCHAR)); RtlFreeHeap(ProcessHeap, 0, FullImagePath); NtClose(hService); return deviceInstalled; }
PIFIMETRICS APIENTRY BmfdQueryFont( IN DHPDEV dhpdev, IN ULONG_PTR iFile, IN ULONG iFace, IN ULONG_PTR *pid) { PBMFD_FILE pfile = (PBMFD_FILE)iFile; PBMFD_FACE pface; PFONTINFO16 pFontInfo; PIFIMETRICS pifi; PBMFD_IFIMETRICS pifiX; PANOSE panose = {0}; DbgPrint("BmfdQueryFont()\n"); // __debugbreak(); /* Validate parameters */ if (iFace > pfile->cNumFaces || !pid) { return NULL; } pface = &pfile->aface[iFace - 1]; pFontInfo = pface->pFontInfo; /* Allocate the structure */ pifiX = EngAllocMem(FL_ZERO_MEMORY, sizeof(BMFD_IFIMETRICS), TAG_IFIMETRICS); if (!pifiX) { return NULL; } /* Return a pointer to free it later */ *pid = (ULONG_PTR)pifiX; /* Fill IFIMETRICS */ pifi = &pifiX->ifim; pifi->cjThis = sizeof(BMFD_IFIMETRICS); pifi->cjIfiExtra = 0; pifi->dpwszFamilyName = FIELD_OFFSET(BMFD_IFIMETRICS, wszFamilyName); pifi->dpwszStyleName = FIELD_OFFSET(BMFD_IFIMETRICS, wszFamilyName); pifi->dpwszFaceName = FIELD_OFFSET(BMFD_IFIMETRICS, wszFaceName); pifi->dpwszUniqueName = FIELD_OFFSET(BMFD_IFIMETRICS, wszFaceName); pifi->dpFontSim = 0; pifi->lEmbedId = 0; pifi->lItalicAngle = 0; pifi->lCharBias = 0; pifi->dpCharSets = 0; pifi->jWinCharSet = pFontInfo->dfCharSet; pifi->jWinPitchAndFamily = pFontInfo->dfPitchAndFamily; pifi->usWinWeight = GETVAL(pFontInfo->dfWeight); pifi->flInfo = pface->flInfo; pifi->fsSelection = 0; pifi->fsType = 0; pifi->fwdUnitsPerEm = GETVAL(pFontInfo->dfPixHeight); pifi->fwdLowestPPEm = 0; pifi->fwdWinAscender = GETVAL(pFontInfo->dfAscent); pifi->fwdWinDescender = pifi->fwdUnitsPerEm - pifi->fwdWinAscender; pifi->fwdMacAscender = pifi->fwdWinAscender; pifi->fwdMacDescender = - pifi->fwdWinDescender; pifi->fwdMacLineGap = 0; pifi->fwdTypoAscender = pifi->fwdWinAscender; pifi->fwdTypoDescender = - pifi->fwdWinDescender; pifi->fwdTypoLineGap = 0; pifi->fwdAveCharWidth = GETVAL(pFontInfo->dfAvgWidth); pifi->fwdMaxCharInc = GETVAL(pFontInfo->dfMaxWidth); pifi->fwdCapHeight = pifi->fwdUnitsPerEm / 2; pifi->fwdXHeight = pifi->fwdUnitsPerEm / 4; pifi->fwdSubscriptXSize = 0; pifi->fwdSubscriptYSize = 0; pifi->fwdSubscriptXOffset = 0; pifi->fwdSubscriptYOffset = 0; pifi->fwdSuperscriptXSize = 0; pifi->fwdSuperscriptYSize = 0; pifi->fwdSuperscriptXOffset = 0; pifi->fwdSuperscriptYOffset = 0; pifi->fwdUnderscoreSize = 01; pifi->fwdUnderscorePosition = -1; pifi->fwdStrikeoutSize = 1; pifi->fwdStrikeoutPosition = pifi->fwdXHeight + 1; pifi->chFirstChar = pFontInfo->dfFirstChar; pifi->chLastChar = pFontInfo->dfLastChar; pifi->chDefaultChar = pFontInfo->dfFirstChar + pFontInfo->dfDefaultChar; pifi->chBreakChar = pFontInfo->dfFirstChar + pFontInfo->dfBreakChar; pifi->wcFirstChar = pface->wcFirstChar; pifi->wcLastChar = pface->wcLastChar; pifi->wcDefaultChar = pface->wcDefaultChar; pifi->wcBreakChar = pface->wcBreakChar; pifi->ptlBaseline.x = 1; pifi->ptlBaseline.y = 0; pifi->ptlAspect.x = pFontInfo->dfVertRes; // CHECKME pifi->ptlAspect.y = pFontInfo->dfHorizRes; pifi->ptlCaret.x = 0; pifi->ptlCaret.y = 1; pifi->rclFontBox.left = 0; pifi->rclFontBox.right = pifi->fwdAveCharWidth; pifi->rclFontBox.top = pifi->fwdWinAscender; pifi->rclFontBox.bottom = - pifi->fwdWinDescender; *(DWORD*)&pifi->achVendId = 0x30303030; // FIXME pifi->cKerningPairs = 0; pifi->ulPanoseCulture = FM_PANOSE_CULTURE_LATIN; pifi->panose = panose; /* Set char sets */ pifiX->ajCharSet[0] = pifi->jWinCharSet; pifiX->ajCharSet[1] = DEFAULT_CHARSET; if (pface->flInfo & FM_INFO_CONSTANT_WIDTH) pifi->jWinPitchAndFamily |= FIXED_PITCH; #if 0 EngMultiByteToUnicodeN(pifiX->wszFaceName, LF_FACESIZE * sizeof(WCHAR), NULL, pFontInfo->, strnlen(pDesc, LF_FACESIZE)); #endif wcscpy(pifiX->wszFaceName, L"Courier-X"); wcscpy(pifiX->wszFamilyName, L"Courier-X"); /* Initialize font weight style flags and string */ if (pifi->usWinWeight == FW_REGULAR) { // pifi->fsSelection |= FM_SEL_REGULAR; } else if (pifi->usWinWeight > FW_SEMIBOLD) { pifi->fsSelection |= FM_SEL_BOLD; wcscat(pifiX->wszStyleName, L"Bold "); } else if (pifi->usWinWeight <= FW_LIGHT) { wcscat(pifiX->wszStyleName, L"Light "); } if (pFontInfo->dfItalic) { pifi->fsSelection |= FM_SEL_ITALIC; wcscat(pifiX->wszStyleName, L"Italic "); } if (pFontInfo->dfUnderline) { pifi->fsSelection |= FM_SEL_UNDERSCORE; wcscat(pifiX->wszStyleName, L"Underscore "); } if (pFontInfo->dfStrikeOut) { pifi->fsSelection |= FM_SEL_STRIKEOUT; wcscat(pifiX->wszStyleName, L"Strikeout "); } return pifi; }
AAFRESULT STDMETHODCALLTYPE ImplAAFTypeDefExtEnum::CreateValueFromName ( /*[in]*/ aafCharacter_constptr Name, /*[out]*/ ImplAAFPropertyValue ** ppPropVal) { if (! ppPropVal ) return AAFRESULT_NULL_PARAM; if (! Name ) return AAFRESULT_NULL_PARAM; if (!IsRegistered()) return AAFRESULT_NOT_INITIALIZED; //Now try to do a Name lookup aafUID_t the_value = {0}; AAFRESULT rc; rc = LookupValByName(&the_value, Name); if (rc == AAFRESULT_INVALID_PARAM) { // Built-In names changed from v1.0 -> v1.1 // to remove kAAF prefix. so we have to deal with both // old and new style names. // The lookup on the originally provided name failed due to // the name not being found (not some other error). // So here we add kAAF if it isn't there or // remove kAAF if it is there. Then look up again. aafCharacter *Name_mod; if ( wcsncmp (Name, L"kAAF", 4) == 0 ) { // Look past kAAF Name_mod = new aafCharacter[wcslen(Name) - 3]; wcscpy(Name_mod, Name + 4); } else { // Prepend kAAF Name_mod = new aafCharacter[wcslen(Name) + 5]; if (!Name_mod) return AAFRESULT_NOMEMORY; wcscpy(Name_mod, L"kAAF"); wcscat(Name_mod, Name); } // Look up again - Return checked later. rc = LookupValByName(&the_value, Name_mod); // Cleanup of allocated memory delete[] Name_mod; } // At this point, we have a successful lookup and the_val is // set, the name was not found (even with variation), or // some other error occurred. Check the result and return // if we are not successful. check_hr( rc ); //else FOUND //Now allocate a New PV based on the local INT size .... ImplAAFTypeDef* ptd; ImplAAFTypeDefRecord* ptdAuid; ptd = NonRefCountedBaseType (); ASSERTU (ptd); ptdAuid = dynamic_cast<ImplAAFTypeDefRecord*> ((ImplAAFTypeDef*) ptd); ASSERTU (ptdAuid); HRESULT hr = ptdAuid->CreateValueFromStruct ((aafMemPtr_t) &the_value, sizeof (aafUID_t), ppPropVal); return hr; }
// Downloads file from the net unsigned __stdcall NetworkDownloadThreadProc(void* pParam) { MeasureData* measure = (MeasureData*)pParam; const bool download = !measure->downloadFile.empty(); bool ready = false; std::wstring url; if (measure->regExp.empty() && measure->resultString.empty()) { if (!measure->url.empty() && measure->url[0] != L'[') { url = measure->url; } } else { EnterCriticalSection(&g_CriticalSection); url = measure->resultString; LeaveCriticalSection(&g_CriticalSection); std::wstring::size_type pos = url.find(L':'); if (pos == std::wstring::npos && !url.empty()) // No protocol { // Add the base url to the string if (url[0] == L'/') { // Absolute path pos = measure->url.find(L'/', 7); // Assume "http://" (=7) if (pos != std::wstring::npos) { std::wstring path(measure->url.substr(0, pos)); url = path + url; } } else { // Relative path pos = measure->url.rfind(L'/'); if (pos != std::wstring::npos) { std::wstring path(measure->url.substr(0, pos + 1)); url = path + url; } } } } if (!url.empty()) { // Create the filename WCHAR buffer[MAX_PATH] = {0}; std::wstring fullpath, directory; if (download) // download mode { PathCanonicalize(buffer, measure->downloadFile.c_str()); std::wstring path = buffer; std::wstring::size_type pos = path.find_first_not_of(L'\\'); if (pos != std::wstring::npos) { path.erase(0, pos); } PathCanonicalize(buffer, measure->downloadFolder.c_str()); CreateDirectory(buffer, nullptr); // Make sure that the folder exists wcscat(buffer, path.c_str()); if (buffer[wcslen(buffer)-1] != L'\\') // path is a file { fullpath = buffer; PathRemoveFileSpec(buffer); } PathAddBackslash(buffer); } else // cache mode { GetTempPath(MAX_PATH, buffer); wcscat(buffer, L"Rainmeter-Cache\\"); // "%TEMP%\Rainmeter-Cache\" } CreateDirectory(buffer, nullptr); // Make sure that the folder exists directory = buffer; if (fullpath.empty()) { fullpath = directory; std::wstring::size_type pos2 = url.find_first_of(L"?#"); std::wstring::size_type pos1 = url.find_last_of(L'/', pos2); pos1 = (pos1 != std::wstring::npos) ? pos1 + 1 : 0; std::wstring name; if (pos2 != std::wstring::npos) { name.assign(url, pos1, pos2 - pos1); } else { name.assign(url, pos1, url.length() - pos1); } if (!name.empty()) { // Replace reserved characters to "_" pos1 = 0; while ((pos1 = name.find_first_of(L"\\/:*?\"<>|", pos1)) != std::wstring::npos) { name[pos1] = L'_'; } fullpath += name; } else { fullpath += L"index"; } } ready = true; if (download) // download mode { if (!PathFileExists(directory.c_str()) || !PathIsDirectory(directory.c_str())) { ready = false; RmLogF( measure->rm, LOG_ERROR, L"WebParser: Directory does not exist: %s", directory.c_str()); } else if (PathIsDirectory(fullpath.c_str())) { ready = false; RmLogF( measure->rm, LOG_ERROR, L"WebParser: Path is a directory, not a file: %s", fullpath.c_str()); } else if (PathFileExists(fullpath.c_str())) { DWORD attr = GetFileAttributes(fullpath.c_str()); if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY)) { ready = false; RmLogF( measure->rm, LOG_ERROR, L"WebParser: File is read-only: %s", fullpath.c_str()); } } } else // cache mode { EnterCriticalSection(&g_CriticalSection); if (PathFileExists(fullpath.c_str())) { std::wstring::size_type pos = fullpath.find_last_of(L'.'); std::wstring path, ext; if (pos != std::wstring::npos) { path.assign(fullpath, 0, pos); ext.assign(fullpath, pos, fullpath.length() - pos); } else { path = fullpath; } // Assign a serial number int i = 1; do { wsprintf(buffer, L"_%i", i++); fullpath = path; fullpath += buffer; if (!ext.empty()) { fullpath += ext; } } while (PathFileExists(fullpath.c_str())); } // Create empty file HANDLE hFile = CreateFile(fullpath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); LeaveCriticalSection(&g_CriticalSection); } if (ready) { // Delete IE cache before download if "SyncMode5" is not 3 (every visit to the page) { // Check "Temporary Internet Files" sync mode (SyncMode5) // Values: // Every visit to the page 3 // Every time you start Internet Explorer 2 // Automatically (default) 4 // Never 0 // http://support.microsoft.com/kb/263070/en HKEY hKey; LONG ret; DWORD mode; ret = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, KEY_QUERY_VALUE, &hKey); if (ret == ERROR_SUCCESS) { DWORD size = sizeof(mode); ret = RegQueryValueEx(hKey, L"SyncMode5", nullptr, nullptr, (LPBYTE)&mode, &size); RegCloseKey(hKey); } if (ret != ERROR_SUCCESS || mode != 3) { std::wstring::size_type pos = url.find_first_of(L'#'); if (pos != std::wstring::npos) { DeleteUrlCacheEntry(url.substr(0, pos).c_str()); } else { DeleteUrlCacheEntry(url.c_str()); } } } RmLogF( measure->rm, LOG_DEBUG, L"WebParser: Downloading url '%s' to: %s", url.c_str(), fullpath.c_str()); HRESULT resultCoInitialize = CoInitialize(nullptr); // requires before calling URLDownloadToFile function // Download the file HRESULT result = URLDownloadToFile(nullptr, url.c_str(), fullpath.c_str(), 0, nullptr); if (result == S_OK) { EnterCriticalSection(&g_CriticalSection); if (!download) // cache mode { if (!measure->downloadedFile.empty()) { // Delete old downloaded file DeleteFile(measure->downloadedFile.c_str()); } } // Convert LFN to 8.3 filename if the path contains blank character if (fullpath.find_first_of(L' ') != std::wstring::npos) { DWORD size = GetShortPathName(fullpath.c_str(), buffer, MAX_PATH); if (size > 0 && size <= MAX_PATH) { fullpath = buffer; } } measure->downloadedFile = fullpath; LeaveCriticalSection(&g_CriticalSection); if (!measure->finishAction.empty()) { RmExecute(measure->skin, measure->finishAction.c_str()); } } else { ready = false; if (!download) // cache mode { // Delete empty file DeleteFile(fullpath.c_str()); } RmLogF( measure->rm, LOG_ERROR, L"WebParser: Download failed (res=0x%08X, COM=0x%08X): %s", result, resultCoInitialize, url.c_str()); if (!measure->onDownloadErrAction.empty()) { RmExecute(measure->skin, measure->onDownloadErrAction.c_str()); } } if (SUCCEEDED(resultCoInitialize)) { CoUninitialize(); } } else { RmLogF(measure->rm, LOG_ERROR, L"WebParser: Download failed: %s", url.c_str()); if (!measure->onDownloadErrAction.empty()) { RmExecute(measure->skin, measure->onDownloadErrAction.c_str()); } } } else { RmLog(measure->rm, LOG_ERROR, L"WebParser: Url is empty"); } if (!ready) // download failed { EnterCriticalSection(&g_CriticalSection); if (!download) // cache mode { if (!measure->downloadedFile.empty()) { // Delete old downloaded file DeleteFile(measure->downloadedFile.c_str()); } } // Clear old downloaded filename measure->downloadedFile.clear(); LeaveCriticalSection(&g_CriticalSection); } EnterCriticalSection(&g_CriticalSection); CloseHandle(measure->dlThreadHandle); measure->dlThreadHandle = 0; LeaveCriticalSection(&g_CriticalSection); return 0; // thread completed successfully }
HRESULT CSDShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO pCmdInfo) { if (HIWORD(pCmdInfo->lpVerb) != 0) { return E_INVALIDARG; } switch (LOWORD(pCmdInfo->lpVerb)) { case 0: { HANDLE mappingHandle = 0; void *view = NULL; try { // // get the application path // wchar_t directory[MAX_PATH + 1]; wchar_t appPath[MAX_PATH + 1]; if(GetExtensionDirectory(directory) == 0) { return E_INVALIDARG; } // // generate application name // wcscpy(appPath, directory); wcscat(appPath, L"\\SDShellManaged.exe"); // // create mapped file // SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; DWORD requiredSize = sizeof(SDHeader) + fileList.number * (sizeof(SDObject) + MAX_PATH + 1) * sizeof(wchar_t); mappingHandle = CreateFileMapping(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0, requiredSize, NULL); if(mappingHandle == 0) { return E_INVALIDARG; } // // map view // view = MapViewOfFile(mappingHandle, FILE_MAP_WRITE, 0, 0, 0); if(view == NULL) { CloseHandle(mappingHandle); return E_INVALIDARG; } int position = 0; // // copy header // dataHeader.size = sizeof(SDHeader); dataHeader.objectCount = fileList.number; memcpy((unsigned char *)view + position, &dataHeader, sizeof(SDHeader)); position += sizeof(SDHeader); for(int i = 0;i < fileList.number;i++) { SDObject *object = (SDObject *)((unsigned char *)view + position); wchar_t *path = fileList[i]; // // get file type (file / folder) // if((GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { // // directory // object->objectType = OBJECT_TYPE_FOLDER; } else { // file object->objectType = OBJECT_TYPE_FILE; } object->pathLength = wcslen(path); object->size = sizeof(SDObject) + (object->pathLength + 1) * sizeof(wchar_t); object->pathOffset = (char *)object->path - (char *)object; wcscpy(object->path, path); // // increment position // position += object->size; } // // launch application // wchar_t command[MAX_PATH + 1]; StringCchPrintf(command, MAX_PATH, L"\"%s\" %I64d", appPath, (INT64)(INT_PTR)mappingHandle); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); CreateProcess(NULL, command, NULL, NULL, TRUE, 0, NULL, directory, &si, &pi); } catch(...) { // // cleanup // if(view != NULL) { UnmapViewOfFile(view); view = NULL; } if(mappingHandle != 0) { CloseHandle(mappingHandle); } } return S_OK; } break; default: return E_INVALIDARG; break; } }
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { // Attempt to mitigate http://textslashplain.com/2015/12/18/dll-hijacking-just-wont-die HMODULE hKernel32 = LoadLibrary(L"kernel32.dll"); ATLASSERT(hKernel32 != NULL); SetDefaultDllDirectoriesFunction pfn = (SetDefaultDllDirectoriesFunction) GetProcAddress(hKernel32, "SetDefaultDllDirectories"); if (pfn) { (*pfn)(LOAD_LIBRARY_SEARCH_SYSTEM32); } int exitCode = -1; CString cmdLine(lpCmdLine); if (cmdLine.Find(L"--checkInstall") >= 0) { // If we're already installed, exit as fast as possible if (!MachineInstaller::ShouldSilentInstall()) { exitCode = 0; goto out; } // Make sure update.exe gets silent wcscat(lpCmdLine, L" --silent"); } HRESULT hr = ::CoInitialize(NULL); ATLASSERT(SUCCEEDED(hr)); AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); _Module = new CAppModule(); hr = _Module->Init(NULL, hInstance); bool isQuiet = (cmdLine.Find(L"-s") >= 0); bool weAreUACElevated = CUpdateRunner::AreWeUACElevated() == S_OK; bool attemptingToRerun = (cmdLine.Find(L"--rerunningWithoutUAC") >= 0); if (weAreUACElevated && attemptingToRerun) { CUpdateRunner::DisplayErrorMessage(CString(L"Please re-run this installer as a normal user instead of \"Run as Administrator\"."), NULL); exitCode = E_FAIL; goto out; } if (!CFxHelper::CanInstallDotNet4_5()) { // Explain this as nicely as possible and give up. MessageBox(0L, L"This program cannot run on Windows XP or before; it requires a later version of Windows.", L"Incompatible Operating System", 0); exitCode = E_FAIL; goto out; } if (!CFxHelper::IsDotNet45OrHigherInstalled()) { hr = CFxHelper::InstallDotNetFramework(isQuiet); if (FAILED(hr)) { exitCode = hr; // #yolo CUpdateRunner::DisplayErrorMessage(CString(L"Failed to install the .NET Framework, try installing .NET 4.5 or higher manually"), NULL); goto out; } // S_FALSE isn't failure, but we still shouldn't try to install if (hr != S_OK) { exitCode = 0; goto out; } } // If we're UAC-elevated, we shouldn't be because it will give us permissions // problems later. Just silently rerun ourselves. if (weAreUACElevated) { wchar_t buf[4096]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileNameW(hMod, buf, 4096); wcscat(lpCmdLine, L" --rerunningWithoutUAC"); CUpdateRunner::ShellExecuteFromExplorer(buf, lpCmdLine); exitCode = 0; goto out; } exitCode = CUpdateRunner::ExtractUpdaterAndRun(lpCmdLine, false); out: _Module->Term(); ::CoUninitialize(); return exitCode; }
DWORD WINAPI PropDialogHandler(IN LPVOID lpThreadParameter) { // NOTE: lpThreadParameter corresponds to the client shared section handle. APPLET_PROC CPLFunc; /* * Do not launch more than once the console property dialog applet, * or (albeit less probable), if we are not initialized. */ if (!ConsoleInitialized || AlreadyDisplayingProps) { /* Close the associated client shared section handle if needed */ if (lpThreadParameter) { CloseHandle((HANDLE)lpThreadParameter); } return STATUS_UNSUCCESSFUL; } AlreadyDisplayingProps = TRUE; /* Load the Control Applet if needed */ if (ConsoleLibrary == NULL) { WCHAR szBuffer[MAX_PATH]; GetWindowsDirectoryW(szBuffer, MAX_PATH); wcscat(szBuffer, L"\\system32\\console.dll"); ConsoleLibrary = LoadLibraryW(szBuffer); if (ConsoleLibrary == NULL) { DPRINT1("Failed to load console.dll"); AlreadyDisplayingProps = FALSE; return STATUS_UNSUCCESSFUL; } } /* Load its main function */ CPLFunc = (APPLET_PROC)GetProcAddress(ConsoleLibrary, "CPlApplet"); if (CPLFunc == NULL) { DPRINT("Error: Console.dll misses CPlApplet export\n"); AlreadyDisplayingProps = FALSE; return STATUS_UNSUCCESSFUL; } if (CPLFunc(NULL, CPL_INIT, 0, 0) == FALSE) { DPRINT("Error: failed to initialize console.dll\n"); AlreadyDisplayingProps = FALSE; return STATUS_UNSUCCESSFUL; } if (CPLFunc(NULL, CPL_GETCOUNT, 0, 0) != 1) { DPRINT("Error: console.dll returned unexpected CPL count\n"); AlreadyDisplayingProps = FALSE; return STATUS_UNSUCCESSFUL; } CPLFunc(NULL, CPL_DBLCLK, (LPARAM)lpThreadParameter, 0); CPLFunc(NULL, CPL_EXIT , 0, 0); AlreadyDisplayingProps = FALSE; return STATUS_SUCCESS; }
LDAPAUTH_API BOOL CUGP(char * userin,char *password,char *machine, char * groupin,int locdom) { OSVERSIONINFO ovi = { sizeof ovi }; GetVersionEx( &ovi ); if (ovi.dwPlatformId == VER_PLATFORM_WIN32_NT && ovi.dwMajorVersion >= 5 ) { //Handle the command line arguments. LPOLESTR pszBuffer = new OLECHAR[MAX_PATH*2]; LPOLESTR pszBuffer2 = new OLECHAR[MAX_PATH*2]; LPOLESTR pszBuffer3 = new OLECHAR[MAX_PATH*2]; LPOLESTR pszBuffer4 = new OLECHAR[MAX_PATH*2]; mbstowcs( (wchar_t *) pszBuffer, userin, MAX_PATH ); mbstowcs( (wchar_t *) pszBuffer2, password, MAX_PATH ); mbstowcs( (wchar_t *) pszBuffer3, machine, MAX_PATH ); mbstowcs( (wchar_t *) pszBuffer4, groupin, MAX_PATH ); HRESULT hr = S_OK; //Get rootDSE and the domain container's DN. IADs *pObject = NULL; IADs *pObjectUser = NULL; IADs *pObjectGroup = NULL; IDirectorySearch *pDS = NULL; LPOLESTR szPath = new OLECHAR[MAX_PATH]; LPOLESTR myPath = new OLECHAR[MAX_PATH]; VARIANT var; wcscpy(szPath,L"LDAP://"); wcscat(szPath,L"rootDSE"); wprintf(szPath); wprintf(L"\n"); hr = ADsOpenObject(szPath, pszBuffer, pszBuffer2, ADS_SECURE_AUTHENTICATION, //Use Secure Authentication IID_IADs, (void**)&pObject); if (FAILED(hr)) { wprintf(L"Bind to domain failed %i\n",hr); if (pObject) pObject->Release(); delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] pszBuffer4; delete [] szPath; delete [] myPath; return false; } hr = pObject->Get(L"defaultNamingContext",&var); if (SUCCEEDED(hr)) { wcscpy(szPath,L"LDAP://"); wcscat(szPath,var.bstrVal); VariantClear(&var); if (pObject) { pObject->Release(); pObject = NULL; } wprintf( szPath); wprintf(L"\n"); //Bind to the root of the current domain. hr = ADsOpenObject(szPath,pszBuffer,pszBuffer2, ADS_SECURE_AUTHENTICATION,IID_IDirectorySearch,(void**)&pDS); if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) { hr = FindUserByName(pDS, pszBuffer, &pObjectUser); if (FAILED(hr)) { wprintf(L"User not found %i\n",hr); delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; if (pDS) pDS->Release(); if (pObjectUser) pObjectUser->Release(); return false; } if (pObjectUser) pObjectUser->Release(); ///////////////////// VNCACCESS hr = FindGroup(pDS, pszBuffer, &pObjectGroup,pszBuffer4); if (pObjectGroup) { pObjectGroup->Release(); pObjectGroup = NULL; } if (FAILED(hr)) wprintf(L"group not found\n"); if (SUCCEEDED(hr)) { wprintf(L"Group found OK\n"); IADsGroup * pIADsG; hr = ADsOpenObject( gbsGroup,pszBuffer, pszBuffer2, ADS_SECURE_AUTHENTICATION,IID_IADsGroup, (void**) &pIADsG); if (SUCCEEDED(hr)) { VARIANT_BOOL bMember = FALSE; hr = pIADsG->IsMember(gbsMember,&bMember); if (SUCCEEDED(hr)) { if (bMember == -1) { wprintf(L"Object \n\n%s\n\n IS a member of the following Group:\n\n%s\n\n",gbsMember,gbsGroup); delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; if (pDS) pDS->Release(); return true; } else { BSTR bsMemberGUID = NULL; IDirectoryObject * pDOMember = NULL; hr = ADsOpenObject( gbsMember,pszBuffer, pszBuffer2, ADS_SECURE_AUTHENTICATION,IID_IDirectoryObject, (void**) &pDOMember); if (SUCCEEDED(hr)) { hr = GetObjectGuid(pDOMember,bsMemberGUID); pDOMember->Release(); pDOMember = NULL; if (RecursiveIsMember(pIADsG,bsMemberGUID,gbsMember,true, pszBuffer, pszBuffer2)) { delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; if (pDS) pDS->Release(); return true; } } }//else bmember }//ismember }//iadsgroup }//Findgroup wprintf(L"USER not found in group\n"); }//user } if (pDS) pDS->Release(); } /*LOGFAILED(pszBuffer3,pszBuffer);*/ delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; return false; } return false; }
BOOL WINAPI InitializeProfiles(VOID) { WCHAR szProfilesPath[MAX_PATH]; WCHAR szProfilePath[MAX_PATH]; WCHAR szCommonFilesDirPath[MAX_PATH]; WCHAR szBuffer[MAX_PATH]; DWORD dwLength; PFOLDERDATA lpFolderData; HKEY hKey; LONG Error; DPRINT("InitializeProfiles()\n"); /* Load profiles directory path */ if (!LoadStringW(hInstance, IDS_PROFILEPATH, szBuffer, MAX_PATH)) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } /* Expand it */ if (!ExpandEnvironmentStringsW(szBuffer, szProfilesPath, MAX_PATH)) { DPRINT1("Error: %lu\n", GetLastError()); RegCloseKey(hKey); return FALSE; } /* Create profiles directory */ if (!CreateDirectoryW(szProfilesPath, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); RegCloseKey(hKey); return FALSE; } } /* Store the profiles directory path in the registry */ dwLength = (wcslen (szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, L"ProfilesDirectory", 0, REG_EXPAND_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } /* Set 'DefaultUserProfile' value */ wcscpy(szBuffer, L"Default User"); /* Create Default User profile directory path */ wcscpy(szProfilePath, szProfilesPath); wcscat(szProfilePath, L"\\"); wcscat(szProfilePath, szBuffer); /* Attempt default user directory creation */ if (!CreateDirectoryW (szProfilePath, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); RegCloseKey(hKey); return FALSE; } /* Directory existed, let's try to append the postfix */ if (!AppendSystemPostfix(szBuffer, MAX_PATH)) { DPRINT1("AppendSystemPostfix() failed\n", GetLastError()); RegCloseKey(hKey); return FALSE; } /* Create Default User profile directory path again */ wcscpy(szProfilePath, szProfilesPath); wcscat(szProfilePath, L"\\"); wcscat(szProfilePath, szBuffer); /* Attempt creation again with appended postfix */ if (!CreateDirectoryW(szProfilePath, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); RegCloseKey(hKey); return FALSE; } } } /* Store the default user profile path in the registry */ dwLength = (wcslen (szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, L"DefaultUserProfile", 0, REG_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } RegCloseKey(hKey); /* Set current user profile */ SetEnvironmentVariableW(L"USERPROFILE", szProfilePath); /* Create 'Default User' subdirectories */ /* FIXME: Get these paths from the registry */ lpFolderData = &UserShellFolders[0]; while (lpFolderData->lpValueName != NULL) { wcscpy(szBuffer, szProfilePath); wcscat(szBuffer, L"\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } if (!CreateDirectoryW(szBuffer, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } } if (lpFolderData->bHidden == TRUE) { SetFileAttributesW(szBuffer, FILE_ATTRIBUTE_HIDDEN); } lpFolderData++; } /* Set default 'Shell Folders' values */ Error = RegOpenKeyExW(HKEY_USERS, L".Default\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } lpFolderData = &UserShellFolders[0]; while (lpFolderData->lpValueName != NULL) { if (lpFolderData->bShellFolder) { wcscpy(szBuffer, szProfilePath); wcscat(szBuffer, L"\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, lpFolderData->lpValueName, 0, REG_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } } lpFolderData++; } /* Set 'Fonts' folder path */ GetWindowsDirectoryW(szBuffer, MAX_PATH); wcscat(szBuffer, L"\\fonts"); dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, L"Fonts", 0, REG_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } RegCloseKey(hKey); /* Set default 'User Shell Folders' values */ Error = RegOpenKeyExW(HKEY_USERS, L".Default\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } lpFolderData = &UserShellFolders[0]; while (lpFolderData->lpValueName != NULL) { if (lpFolderData->bUserShellFolder) { wcscpy(szBuffer, L"%USERPROFILE%\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, lpFolderData->lpValueName, 0, REG_EXPAND_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } } lpFolderData++; } RegCloseKey(hKey); /* Set 'AllUsersProfile' value */ wcscpy(szBuffer, L"All Users"); /* Create 'All Users' profile directory path */ wcscpy(szProfilePath, szProfilesPath); wcscat(szProfilePath, L"\\"); wcscat(szProfilePath, szBuffer); /* Attempt 'All Users' directory creation */ if (!CreateDirectoryW (szProfilePath, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } /* Directory existed, let's try to append the postfix */ if (!AppendSystemPostfix(szBuffer, MAX_PATH)) { DPRINT1("AppendSystemPostfix() failed\n", GetLastError()); return FALSE; } /* Attempt again creation with appended postfix */ wcscpy(szProfilePath, szProfilesPath); wcscat(szProfilePath, L"\\"); wcscat(szProfilePath, szBuffer); if (!CreateDirectoryW(szProfilePath, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } } } Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, L"AllUsersProfile", 0, REG_SZ, (LPBYTE)szBuffer, dwLength); RegCloseKey(hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } /* Set 'All Users' profile */ SetEnvironmentVariableW(L"ALLUSERSPROFILE", szProfilePath); /* Create 'All Users' subdirectories */ /* FIXME: Take these paths from the registry */ lpFolderData = &CommonShellFolders[0]; while (lpFolderData->lpValueName != NULL) { wcscpy(szBuffer, szProfilePath); wcscat(szBuffer, L"\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } if (!CreateDirectoryW(szBuffer, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } } if (lpFolderData->bHidden) { SetFileAttributesW(szBuffer, FILE_ATTRIBUTE_HIDDEN); } lpFolderData++; } /* Set common 'Shell Folders' values */ Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } lpFolderData = &CommonShellFolders[0]; while (lpFolderData->lpValueName != NULL) { if (lpFolderData->bShellFolder) { wcscpy(szBuffer, szProfilePath); wcscat(szBuffer, L"\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, lpFolderData->lpValueName, 0, REG_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } } lpFolderData++; } RegCloseKey(hKey); /* Set common 'User Shell Folders' values */ Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } lpFolderData = &CommonShellFolders[0]; while (lpFolderData->lpValueName != NULL) { if (lpFolderData->bUserShellFolder) { wcscpy(szBuffer, L"%ALLUSERSPROFILE%\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, lpFolderData->lpValueName, 0, REG_EXPAND_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } } lpFolderData++; } RegCloseKey(hKey); /* Load 'Program Files' location */ if (!LoadStringW(hInstance, IDS_PROGRAMFILES, szBuffer, MAX_PATH)) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } if (!LoadStringW(hInstance, IDS_COMMONFILES, szCommonFilesDirPath, MAX_PATH)) { DPRINT1("Warning: %lu\n", GetLastError()); } /* Expand it */ if (!ExpandEnvironmentStringsW(szBuffer, szProfilesPath, MAX_PATH)) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } wcscpy(szBuffer, szProfilesPath); wcscat(szBuffer, L"\\"); wcscat(szBuffer, szCommonFilesDirPath); if (!ExpandEnvironmentStringsW(szBuffer, szCommonFilesDirPath, MAX_PATH)) { DPRINT1("Warning: %lu\n", GetLastError()); } /* Store it */ Error = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, KEY_SET_VALUE, &hKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } dwLength = (wcslen (szProfilesPath) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, L"ProgramFilesDir", 0, REG_SZ, (LPBYTE)szProfilesPath, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hKey); SetLastError((DWORD)Error); return FALSE; } dwLength = (wcslen(szCommonFilesDirPath) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hKey, L"CommonFilesDir", 0, REG_SZ, (LPBYTE)szCommonFilesDirPath, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Warning: %lu\n", Error); } RegCloseKey (hKey); /* Create directory */ if (!CreateDirectoryW(szProfilesPath, NULL)) { if (GetLastError () != ERROR_ALREADY_EXISTS) { DPRINT1("Error: %lu\n", GetLastError()); return FALSE; } } /* Create directory */ if (!CreateDirectoryW(szCommonFilesDirPath, NULL)) { if (GetLastError () != ERROR_ALREADY_EXISTS) { DPRINT1("Warning: %lu\n", GetLastError()); } } DPRINT("Success\n"); return TRUE; }
int wmain(int argc, WCHAR *argv[]) { _NtQuerySystemInformation NtQuerySystemInformation = (_NtQuerySystemInformation)GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation"); _NtDuplicateObject NtDuplicateObject = (_NtDuplicateObject)GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject"); _NtQueryObject NtQueryObject = (_NtQueryObject)GetLibraryProcAddress("ntdll.dll", "NtQueryObject"); NTSTATUS status; PSYSTEM_HANDLE_INFORMATION handleInfo; ULONG handleInfoSize = 0x10000; ULONG pid = 0; HANDLE processHandle; ULONG i; if (argc < 2) { printf("Usage: handles filepath [pid]\n"); return 1; } if (argc > 2) { pid = _wtoi(argv[2]); } // convert C:\Windows\System32 to \Device\HarddiskVolume1\Windows\System32 const WCHAR* filePath = argv[1]; if (wcslen(filePath) < 2 || filePath[1] != L':') { printf("Can't process input path which is tool short or not contain local driver!\n"); return 1; } PWSTR pDosDriveName = new TCHAR[MAX_PATH]; TCHAR szDrive[3] = TEXT(" :"); szDrive[0] = filePath[0]; DWORD uiLen = QueryDosDeviceW(szDrive, pDosDriveName, MAX_PATH); if (0 == uiLen) { if (ERROR_INSUFFICIENT_BUFFER != GetLastError()) { printf("QueryDosDeviceW failed: %d\n", GetLastError()); return 1; } delete[]pDosDriveName; pDosDriveName = new TCHAR[uiLen + 1]; uiLen = QueryDosDevice(szDrive, pDosDriveName, uiLen + 1); if (0 == uiLen) { printf("QueryDosDeviceW failed: %d\n", GetLastError()); return 1; } } wcscat(pDosDriveName, &filePath[2]); handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize); /* NtQuerySystemInformation won't give us the correct buffer size, so we guess by doubling the buffer size. */ while ((status = NtQuerySystemInformation( SystemHandleInformation, handleInfo, handleInfoSize, NULL )) == STATUS_INFO_LENGTH_MISMATCH) handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2); /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */ if (!NT_SUCCESS(status)) { printf("NtQuerySystemInformation failed!\n"); return 1; } for (i = 0; i < handleInfo->HandleCount; i++) { SYSTEM_HANDLE handle = handleInfo->Handles[i]; HANDLE dupHandle = NULL; POBJECT_TYPE_INFORMATION objectTypeInfo; PVOID objectNameInfo; UNICODE_STRING objectName; ULONG returnLength; // Jump of no file /*if (handle.ObjectTypeNumber != 31) { continue; }*/ /* Check if this handle belongs to the PID the user specified. */ if (pid != 0 && handle.ProcessId != pid) continue; if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, handle.ProcessId))) { //printf("Could not open PID %d! (Don't try to open a system process.)\n", handle.ProcessId); continue; } /* Duplicate the handle so we can query it. */ DWORD re = NtDuplicateObject( processHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &dupHandle, 0, 0, 0 ); if (ERROR_SUCCESS != re) { printf("[%#x] Error!\n", handle.Handle); continue; } /* Query the object type. */ objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000); if (!NT_SUCCESS(NtQueryObject( dupHandle, ObjectTypeInformation, objectTypeInfo, 0x1000, NULL ))) { printf("[%#x] Error!\n", handle.Handle); CloseHandle(dupHandle); continue; } /* Query the object name (unless it has an access of 0x0012019f, on which NtQueryObject could hang. */ if (handle.GrantedAccess == 0x0012019f) { /* We have the type, so display that. */ printf( "[%#x] %.*S: (did not get name)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer ); free(objectTypeInfo); CloseHandle(dupHandle); continue; } objectNameInfo = malloc(0x1000); if (!NT_SUCCESS(MyNtQueryObject( NtQueryObject, dupHandle, ObjectNameInformation, objectNameInfo, 0x1000, &returnLength ))) { /* Reallocate the buffer and try again. */ objectNameInfo = realloc(objectNameInfo, returnLength); if (!NT_SUCCESS(MyNtQueryObject( NtQueryObject, dupHandle, ObjectNameInformation, objectNameInfo, returnLength, NULL ))) { /* We have the type name, so just display that. */ printf( "[%#x] %.*S: (could not get name)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer ); free(objectTypeInfo); free(objectNameInfo); CloseHandle(dupHandle); continue; } } /* Cast our buffer into an UNICODE_STRING. */ objectName = *(PUNICODE_STRING)objectNameInfo; /* Print the information! */ if (objectName.Length) { /* The object has a name. */ printf( "[%#x] %.*S: %.*S\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer, objectName.Length / 2, objectName.Buffer ); if (wcscmp(objectName.Buffer, pDosDriveName) == 0) { printf("opend by process: %d", handle.ProcessId); break; } } else { /* Print something else. */ printf( "[%#x] %.*S: (unnamed)\n", handle.Handle, objectTypeInfo->Name.Length / 2, objectTypeInfo->Name.Buffer ); } free(objectTypeInfo); free(objectNameInfo); CloseHandle(dupHandle); } free(handleInfo); CloseHandle(processHandle); return 0; }
BOOL UpdateUsersShellFolderSettings(LPCWSTR lpUserProfilePath, HKEY hUserKey) { WCHAR szBuffer[MAX_PATH]; DWORD dwLength; PFOLDERDATA lpFolderData; HKEY hFoldersKey; LONG Error; DPRINT("UpdateUsersShellFolderSettings() called\n"); DPRINT("User profile path: %S\n", lpUserProfilePath); Error = RegOpenKeyExW(hUserKey, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_SET_VALUE, &hFoldersKey); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); SetLastError((DWORD)Error); return FALSE; } lpFolderData = &UserShellFolders[0]; while (lpFolderData->lpValueName != NULL) { if (lpFolderData->bShellFolder) { wcscpy(szBuffer, lpUserProfilePath); wcscat(szBuffer, L"\\"); /* Append the folder name */ dwLength = wcslen(szBuffer); if (!LoadStringW(hInstance, lpFolderData->uId, &szBuffer[dwLength], MAX_PATH - dwLength)) { /* Use the default name instead */ wcscat(szBuffer, lpFolderData->lpPath); } DPRINT("%S: %S\n", lpFolderData->lpValueName, szBuffer); dwLength = (wcslen(szBuffer) + 1) * sizeof(WCHAR); Error = RegSetValueExW(hFoldersKey, lpFolderData->lpValueName, 0, REG_SZ, (LPBYTE)szBuffer, dwLength); if (Error != ERROR_SUCCESS) { DPRINT1("Error: %lu\n", Error); RegCloseKey(hFoldersKey); SetLastError((DWORD)Error); return FALSE; } } lpFolderData++; } RegCloseKey(hFoldersKey); DPRINT("UpdateUsersShellFolderSettings() done\n"); return TRUE; }
int Songs::LoadHistory(const char *userId) { //ここでサーバに接続して前回と前々回の点数を受信 HINTERNET hSession, hConnect, hRequest; URL_COMPONENTS urlComponents; WCHAR szHostName[256], szUrlPath[2048]; //URL WCHAR szUrl[256] = L"http://globalstudios.jp/mai-archive/api_history.php?user="******"Sample Application/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) return -1; ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS)); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.lpszHostName = szHostName; urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR); urlComponents.lpszUrlPath = szUrlPath; urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR); if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) { WinHttpCloseHandle(hSession); return -1; } //接続 hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0); if (hConnect == NULL) { WinHttpCloseHandle(hSession); return -1; } hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest == NULL) { WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return -1; } if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; } WinHttpReceiveResponse(hRequest, NULL); //ボディ取得 lpData = ReadData(hRequest, &dwSize); for (int i = 0; i < NUMSONGS; i++) { char* temp = NULL; char* ctx;//内部的に使用するので深く考えない if (i == 0) { temp = strtok_s((char*)lpData, "\n", &ctx); } else { temp = strtok_s(0, "\n", &ctx); } if (temp == NULL)break; int history[2] = {}; int hoge; sscanf_s(temp, "%d||%d||%d", &hoge, &history[0], &history[1]); //以下の式を実行することによってデータを保存 //song[Search(<曲ID>)]->songHistory->Set(<前回と前々回の点数(配列ポインタ)>); song[Search(hoge)]->songHistory->Set(history); } HeapFree(GetProcessHeap(), 0, lpData); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; }
void ExchndlSetup(const char *packageVersion) { # if defined(WZ_CC_MINGW) wchar_t miniDumpPath[PATH_MAX] = {'\0'}; DWORD dwRetVal = 0; #ifdef HAVE_BFD bfd_init(); #endif /* HAVE_BFD */ // Install the unhandled exception filter function prevExceptionFilter = SetUnhandledExceptionFilter(TopLevelExceptionFilter); // Retrieve the current version formattedVersionString = strdup(packageVersion); #ifndef WZ_PORTABLE // Because of UAC on vista / win7 we use this to write our dumps to (unless we override it via OverrideRPTDirectory()) // NOTE: CSIDL_PERSONAL = C:\Users\user name\Documents if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, miniDumpPath ) )) { PathAppendW( miniDumpPath, WSTRING(WZ_WRITEDIR)); PathAppendW( miniDumpPath, L"\\logs" ); if( !PathFileExistsW( miniDumpPath ) ) { if( ERROR_SUCCESS != SHCreateDirectoryExW( NULL, miniDumpPath, NULL ) ) { //last attempt to get a path dwRetVal = GetTempPathW(PATH_MAX, miniDumpPath); if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { MessageBox((HWND)MB_ICONEXCLAMATION, "Could not created a temporary directory!\nProgram will now exit." , _T("Error"), MB_OK); exit(1); } } } } #else // we use where they installed it on, since this is a removeable drive (most likely), we will use where the program is located in. if (dwRetVal = GetCurrentDirectoryW(MAX_PATH, miniDumpPath)) { if(dwRetVal > MAX_PATH) { MessageBox((HWND)MB_ICONEXCLAMATION, "Buffer exceeds maximum path to create directory. Exiting.", _T("Error"), MB_OK); exit(1); } PathAppendW( miniDumpPath, WSTRING(WZ_WRITEDIR)); PathAppendW( miniDumpPath, L"\\logs" ); } #endif else { // should never fail, but if it does, we fall back to this dwRetVal = GetTempPathW(PATH_MAX, miniDumpPath); if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { MessageBox((HWND)MB_ICONEXCLAMATION, "Could not created a temporary directory!\nProgram will now exit." , _T("Error!"), MB_OK); exit(1); } } wcscat(szLogFileName, L"Warzone2100.RPT"); wcscat(miniDumpPath, L"\\"); wcscat(miniDumpPath,szLogFileName); wcscpy(szLogFileName, miniDumpPath); atexit(ExchndlShutdown); #endif }
VOID AddToLog(WCHAR *txt, PUNICODE_STRING txt1, ULONG *StatusCode) { IO_STATUS_BLOCK LogFileStatusBlock; HANDLE LogFileHandle = 0; NTSTATUS ns; // Проверка, разрешено ли протоколирование if (!EnableLog) return; __try { // Подготовка атрибутов файла OBJECT_ATTRIBUTES ob; InitializeObjectAttributes(&ob, &usLogFile, OBJ_CASE_INSENSITIVE + OBJ_KERNEL_HANDLE, NULL, NULL); // Создание/открытие файла ns = ZwCreateFile(&LogFileHandle, FILE_APPEND_DATA + SYNCHRONIZE, &ob, &LogFileStatusBlock, 0, FILE_ATTRIBUTE_NORMAL, 0, FILE_CREATE + FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (ns == STATUS_SUCCESS) { // Буфер строки WCHAR Buffer[1024], CodeTxt[20]; ULONG BuffSize = 0; // Очистка буфера строки RtlZeroMemory(&Buffer, sizeof(Buffer)); // Копирование строки wcscpy(Buffer, txt); // Добавление второй необязательной строки if (txt1 != NULL && txt1->Buffer != NULL) { __try { for (int i = 0; i < txt1->Length / 2; i++) if (txt1->Buffer[i] == 0) txt1->Buffer[i] = L'*'; } __except(EXCEPTION_EXECUTE_HANDLER) {} wcscat(Buffer, (wchar_t *)txt1->Buffer); } // Добавление парметра if (StatusCode != NULL) { if (*StatusCode == 0) wcscat(Buffer, L" - succeeded"); else { wcscat(Buffer, L" - failed (0x"); swprintf(CodeTxt, L"%X", *StatusCode); wcscat(Buffer, (wchar_t *)CodeTxt); wcscat(Buffer, L")"); } } // Добавление к нему CRLF wcscat(Buffer, L"\r\n"); BuffSize = wcslen(Buffer) * 2; zDbgPrint("%S", Buffer); if (AnsiLog) { // Преобразование буфера в ANSI ANSI_STRING AnsiString; UNICODE_STRING UnicodeString; RtlInitUnicodeString(&UnicodeString, Buffer); if (RtlUnicodeStringToAnsiString(&AnsiString, &UnicodeString, TRUE) == STATUS_SUCCESS) // Запись AnsiString ns = ZwWriteFile(LogFileHandle, 0, NULL,NULL, &LogFileStatusBlock, AnsiString.Buffer, AnsiString.Length, NULL,NULL); } else // Запись буфера c UNICODE строкой ns = ZwWriteFile(LogFileHandle, 0, NULL,NULL, &LogFileStatusBlock, Buffer, BuffSize, NULL,NULL); ZwClose(LogFileHandle); }
LPCWSTR GetWorkingDirectory(LPWSTR buffer, size_t bufferSize) { GetCurrentDirectoryW(bufferSize, buffer); wcscat(buffer, L"\\"); return buffer; }