// ------------------------------------------------ // // FUNCTION: sys_GetRegKey( PA_PluginParameters params ) // // PURPOSE: Get a key from the registry. // // DATE: MJG 12/4/03 (3.5.6) // void sys_GetRegKey( PA_PluginParameters params ) { LONG_PTR returnValue, regKey, retErr, dataSize, arraySize, expandDataSize; LONG_PTR i, len; char regSub[MAXBUF]; char regName[MAXBUF]; char *returnDataBuffer, *ptrData; HKEY hRootKey; HKEY hOpenKey; DWORD dwDataType; DWORD dwReturnLong; PA_Variable paReturnArray; // AMS2 12/9/14 #41400 Initalized the dataSize variable. In 64 bit environments this can be randomly initalized to a size in bytes // that is larger than malloc can allot, causing it to return null and crash when returning to 4D. Remember to always initialize your size variables. dataSize = 0; returnValue = regKey = retErr = arraySize = expandDataSize = 0; hRootKey = hOpenKey = 0; ptrData = returnDataBuffer = NULL; memset(regSub, 0, MAXBUF); memset(regName, 0, MAXBUF); // Get the function parameters. regKey = PA_GetLongParameter( params, 1 ); PA_GetTextParameter( params, 2, regSub ); PA_GetTextParameter( params, 3, regName ); // Convert the 4d registry constant into a Windows registry key. hRootKey = getRootKey( regKey ); // Open the registry key. retErr = RegOpenKeyEx(hRootKey, regSub, 0, KEY_READ, &hOpenKey); if(retErr == ERROR_SUCCESS){ // Get the value type and size. retErr = RegQueryValueEx(hOpenKey, regName, NULL, &dwDataType, NULL, &dataSize); if(retErr == ERROR_SUCCESS){ switch(dwDataType){ case REG_BINARY: returnDataBuffer = malloc(dataSize); retErr = RegQueryValueEx(hOpenKey, regName, NULL, NULL, (LPBYTE) returnDataBuffer, &dataSize); if(retErr == ERROR_SUCCESS){ PA_SetBlobParameter(params, 4, returnDataBuffer, dataSize); returnValue = 1; } free(returnDataBuffer); break; case REG_DWORD: case REG_DWORD_BIG_ENDIAN: dataSize = sizeof(dwReturnLong); retErr = RegQueryValueEx(hOpenKey, regName, NULL, NULL, (LPBYTE) &dwReturnLong, &dataSize); if(retErr == ERROR_SUCCESS){ PA_SetLongParameter(params, 4, dwReturnLong); returnValue = 1; } break; case REG_EXPAND_SZ: returnDataBuffer = malloc(dataSize); retErr = RegQueryValueEx (hOpenKey, regName, NULL, NULL, returnDataBuffer, &dataSize); if(retErr == ERROR_SUCCESS) { regExpandStr(&returnDataBuffer); PA_SetTextParameter(params, 4, returnDataBuffer, strlen(returnDataBuffer)); returnValue = 1; } free(returnDataBuffer); break; case REG_MULTI_SZ: returnDataBuffer = malloc(dataSize); paReturnArray = PA_GetVariableParameter( params, 4 ); retErr = RegQueryValueEx(hOpenKey, regName, NULL, NULL, returnDataBuffer, &dataSize); if(retErr == ERROR_SUCCESS) { arraySize = regGetNumElements(returnDataBuffer); PA_ResizeArray(&paReturnArray, arraySize); for(i = 1, ptrData = returnDataBuffer; i <= arraySize; i++) { len = strlen(ptrData); PA_SetTextInArray(paReturnArray, i, ptrData, len); ptrData+=len+1; } returnValue = 1; PA_SetVariableParameter( params, 4, paReturnArray, 0 ); } free(returnDataBuffer); break; case REG_SZ: returnDataBuffer = (char*)malloc(dataSize); retErr = RegQueryValueEx(hOpenKey, regName, NULL, NULL, returnDataBuffer, &dataSize); if(retErr == ERROR_SUCCESS){ PA_SetTextParameter(params, 4, returnDataBuffer, dataSize-1); returnValue = 1; } free(returnDataBuffer); break; } } } RegCloseKey( hOpenKey ); PA_ReturnLong( params, returnValue ); }
/* {{{ proto int pspell_config_create(string language [, string spelling [, string jargon [, string encoding]]]) Create a new config to be used later to create a manager */ static PHP_FUNCTION(pspell_config_create) { char *language, *spelling = NULL, *jargon = NULL, *encoding = NULL; size_t language_len, spelling_len = 0, jargon_len = 0, encoding_len = 0; zval *ind; PspellConfig *config; #ifdef PHP_WIN32 TCHAR aspell_dir[200]; TCHAR data_dir[220]; TCHAR dict_dir[220]; HKEY hkey; DWORD dwType,dwLen; #endif if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sss", &language, &language_len, &spelling, &spelling_len, &jargon, &jargon_len, &encoding, &encoding_len) == FAILURE) { return; } config = new_pspell_config(); #ifdef PHP_WIN32 /* If aspell was installed using installer, we should have a key * pointing to the location of the dictionaries */ if (0 == RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\Aspell", &hkey)) { LONG result; dwLen = sizeof(aspell_dir) - 1; result = RegQueryValueEx(hkey, "", NULL, &dwType, (LPBYTE)&aspell_dir, &dwLen); RegCloseKey(hkey); if (result == ERROR_SUCCESS) { strlcpy(data_dir, aspell_dir, sizeof(data_dir)); strlcat(data_dir, "\\data", sizeof(data_dir)); strlcpy(dict_dir, aspell_dir, sizeof(dict_dir)); strlcat(dict_dir, "\\dict", sizeof(dict_dir)); pspell_config_replace(config, "data-dir", data_dir); pspell_config_replace(config, "dict-dir", dict_dir); } } #endif pspell_config_replace(config, "language-tag", language); if (spelling_len) { pspell_config_replace(config, "spelling", spelling); } if (jargon_len) { pspell_config_replace(config, "jargon", jargon); } if (encoding_len) { pspell_config_replace(config, "encoding", encoding); } /* By default I do not want to write anything anywhere because it'll try to write to $HOME which is not what we want */ pspell_config_replace(config, "save-repl", "false"); ind = zend_list_insert(config, le_pspell_config); RETURN_LONG(Z_RES_HANDLE_P(ind)); }
/* {{{ proto int pspell_new_personal(string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]]) Load a dictionary with a personal wordlist*/ static PHP_FUNCTION(pspell_new_personal) { char *personal, *language, *spelling = NULL, *jargon = NULL, *encoding = NULL; size_t personal_len, language_len, spelling_len = 0, jargon_len = 0, encoding_len = 0; zend_long mode = Z_L(0), speed = Z_L(0); int argc = ZEND_NUM_ARGS(); zval *ind; #ifdef PHP_WIN32 TCHAR aspell_dir[200]; TCHAR data_dir[220]; TCHAR dict_dir[220]; HKEY hkey; DWORD dwType,dwLen; #endif PspellCanHaveError *ret; PspellManager *manager; PspellConfig *config; if (zend_parse_parameters(argc, "ps|sssl", &personal, &personal_len, &language, &language_len, &spelling, &spelling_len, &jargon, &jargon_len, &encoding, &encoding_len, &mode) == FAILURE) { return; } config = new_pspell_config(); #ifdef PHP_WIN32 /* If aspell was installed using installer, we should have a key * pointing to the location of the dictionaries */ if (0 == RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\Aspell", &hkey)) { LONG result; dwLen = sizeof(aspell_dir) - 1; result = RegQueryValueEx(hkey, "", NULL, &dwType, (LPBYTE)&aspell_dir, &dwLen); RegCloseKey(hkey); if (result == ERROR_SUCCESS) { strlcpy(data_dir, aspell_dir, sizeof(data_dir)); strlcat(data_dir, "\\data", sizeof(data_dir)); strlcpy(dict_dir, aspell_dir, sizeof(dict_dir)); strlcat(dict_dir, "\\dict", sizeof(dict_dir)); pspell_config_replace(config, "data-dir", data_dir); pspell_config_replace(config, "dict-dir", dict_dir); } } #endif if (php_check_open_basedir(personal)) { delete_pspell_config(config); RETURN_FALSE; } pspell_config_replace(config, "personal", personal); pspell_config_replace(config, "save-repl", "false"); pspell_config_replace(config, "language-tag", language); if (spelling_len) { pspell_config_replace(config, "spelling", spelling); } if (jargon_len) { pspell_config_replace(config, "jargon", jargon); } if (encoding_len) { pspell_config_replace(config, "encoding", encoding); } if (argc > 5) { speed = mode & PSPELL_SPEED_MASK_INTERNAL; /* First check what mode we want (how many suggestions) */ if (speed == PSPELL_FAST) { pspell_config_replace(config, "sug-mode", "fast"); } else if (speed == PSPELL_NORMAL) { pspell_config_replace(config, "sug-mode", "normal"); } else if (speed == PSPELL_BAD_SPELLERS) { pspell_config_replace(config, "sug-mode", "bad-spellers"); } /* Then we see if run-together words should be treated as valid components */ if (mode & PSPELL_RUN_TOGETHER) { pspell_config_replace(config, "run-together", "true"); } } ret = new_pspell_manager(config); delete_pspell_config(config); if (pspell_error_number(ret) != 0) { php_error_docref(NULL, E_WARNING, "PSPELL couldn't open the dictionary. reason: %s", pspell_error_message(ret)); delete_pspell_can_have_error(ret); RETURN_FALSE; } manager = to_pspell_manager(ret); ind = zend_list_insert(manager, le_pspell); RETURN_LONG(Z_RES_HANDLE_P(ind)); }
bool get_available_wsls(std::vector<std::string>& wsls, std::string& default_wsl) { const std::string lxss_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Lxss"; HKEY hKey; default_wsl = ""; LONG lRet = RegOpenKeyEx(HKEY_CURRENT_USER, lxss_path.c_str(), 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &hKey); if (lRet != ERROR_SUCCESS) return false; const int buf_len = 256; char default_wsl_guid[buf_len]; DWORD default_wsl_guid_len = sizeof(default_wsl_guid); lRet = RegQueryValueEx(hKey, "DefaultDistribution", NULL, NULL, (LPBYTE)default_wsl_guid, &default_wsl_guid_len); if ((lRet != ERROR_SUCCESS) || (default_wsl_guid_len > buf_len)) return false; int i = 0; while(true) { char wsl_guid[buf_len]; DWORD wsl_guid_len = sizeof(wsl_guid); LONG ret = RegEnumKeyEx(hKey, i++, wsl_guid, &wsl_guid_len, NULL, NULL, NULL, NULL); if (ret != ERROR_SUCCESS) { break; } HKEY hSubKey; const std::string sub_key = lxss_path + "\\" + wsl_guid; ret = RegOpenKeyEx(HKEY_CURRENT_USER, sub_key.c_str(), 0, KEY_QUERY_VALUE, &hSubKey); if (ret != ERROR_SUCCESS) { break; } char wsl_name[buf_len]; DWORD wsl_name_len = sizeof(wsl_name); DWORD wsl_state = 0; DWORD wsl_state_len = sizeof(wsl_state); ret = RegQueryValueEx(hSubKey, "State", NULL, NULL, (LPBYTE)&wsl_state, &wsl_state_len); if (ret != ERROR_SUCCESS || wsl_state != 1) { continue; } ret = RegQueryValueEx(hSubKey, "DistributionName", NULL, NULL, (LPBYTE)wsl_name, &wsl_name_len); if ((ret == ERROR_SUCCESS) && (wsl_name_len < buf_len)) { wsls.push_back(wsl_name); if (std::string(wsl_guid) == std::string(default_wsl_guid)) { default_wsl = wsl_name; } RegCloseKey(hSubKey); } } RegCloseKey(hKey); return default_wsl != ""; }
void cm_DaemonCheckInit(void) { HKEY parmKey; DWORD dummyLen; DWORD dummy; DWORD code; code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY, 0, KEY_QUERY_VALUE, &parmKey); if (code) return; dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckDownInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckDownInterval = dummy; afsi_log("daemonCheckDownInterval is %d", cm_daemonCheckDownInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckUpInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckUpInterval = dummy; afsi_log("daemonCheckUpInterval is %d", cm_daemonCheckUpInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckVolInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckVolInterval = dummy; afsi_log("daemonCheckVolInterval is %d", cm_daemonCheckVolInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckCBInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckCBInterval = dummy; afsi_log("daemonCheckCBInterval is %d", cm_daemonCheckCBInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckVolCBInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckVolCBInterval = dummy; afsi_log("daemonCheckVolCBInterval is %d", cm_daemonCheckVolCBInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckLockInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckLockInterval = dummy; afsi_log("daemonCheckLockInterval is %d", cm_daemonCheckLockInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckTokenInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonTokenCheckInterval = dummy; afsi_log("daemonCheckTokenInterval is %d", cm_daemonTokenCheckInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonCheckOfflineVolInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonCheckOfflineVolInterval = dummy; afsi_log("daemonCheckOfflineVolInterval is %d", cm_daemonCheckOfflineVolInterval); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonPerformanceTuningInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); dummyLen = sizeof(DWORD); code = RegQueryValueEx(parmKey, "daemonRankServerInterval", NULL, NULL, (BYTE *) &dummy, &dummyLen); if (code == ERROR_SUCCESS && dummy) cm_daemonRankServerInterval = dummy; afsi_log("daemonRankServerInterval is %d", cm_daemonRankServerInterval); if (code == ERROR_SUCCESS) cm_daemonPerformanceTuningInterval = dummy; afsi_log("daemonPerformanceTuningInterval is %d", cm_daemonPerformanceTuningInterval); RegCloseKey(parmKey); if (cm_daemonPerformanceTuningInterval) cm_PerformanceTuningInit(); }
BOOL CALLBACK DirSelectProc (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { HKEY hKeyResults = 0; char String[256]; char Directory[255]; long lResult; sprintf(String,"Software\\N64 Emulation\\%s",AppName); lResult = RegOpenKeyEx( HKEY_CURRENT_USER,String,0, KEY_ALL_ACCESS,&hKeyResults); if (lResult == ERROR_SUCCESS) { DWORD Type, Value, Bytes = 4; lResult = RegQueryValueEx(hKeyResults,"Use Default Plugin Dir",0,&Type,(LPBYTE)(&Value),&Bytes); if (Type != REG_DWORD || lResult != ERROR_SUCCESS) { Value = TRUE; } SendMessage(GetDlgItem(hDlg,Value?IDC_PLUGIN_DEFAULT:IDC_PLUGIN_OTHER),BM_SETCHECK, BST_CHECKED,0); lResult = RegQueryValueEx(hKeyResults,"Use Default Rom Dir",0,&Type,(LPBYTE)(&Value),&Bytes); if (Type != REG_DWORD || lResult != ERROR_SUCCESS) { Value = FALSE; } SendMessage(GetDlgItem(hDlg,Value?IDC_ROM_DEFAULT:IDC_ROM_OTHER),BM_SETCHECK, BST_CHECKED,0); lResult = RegQueryValueEx(hKeyResults,"Use Default Auto Save Dir",0,&Type,(LPBYTE)(&Value),&Bytes); if (Type != REG_DWORD || lResult != ERROR_SUCCESS) { Value = TRUE; } SendMessage(GetDlgItem(hDlg,Value?IDC_AUTO_DEFAULT:IDC_AUTO_OTHER),BM_SETCHECK, BST_CHECKED,0); lResult = RegQueryValueEx(hKeyResults,"Use Default Instant Save Dir",0,&Type,(LPBYTE)(&Value),&Bytes); if (Type != REG_DWORD || lResult != ERROR_SUCCESS) { Value = TRUE; } SendMessage(GetDlgItem(hDlg,Value?IDC_INSTANT_DEFAULT:IDC_INSTANT_OTHER),BM_SETCHECK, BST_CHECKED,0); lResult = RegQueryValueEx(hKeyResults,"Use Default Snap Shot Dir",0,&Type,(LPBYTE)(&Value),&Bytes); if (Type != REG_DWORD || lResult != ERROR_SUCCESS) { Value = TRUE; } SendMessage(GetDlgItem(hDlg,Value?IDC_SNAP_DEFAULT:IDC_SNAP_OTHER),BM_SETCHECK, BST_CHECKED,0); Bytes = sizeof(Directory); lResult = RegQueryValueEx(hKeyResults,"Plugin Directory",0,&Type,(LPBYTE)Directory,&Bytes); if (lResult != ERROR_SUCCESS) { GetPluginDir(Directory ); } SetDlgItemText(hDlg,IDC_PLUGIN_DIR,Directory); Bytes = sizeof(Directory); lResult = RegQueryValueEx(hKeyResults,"Instant Save Directory",0,&Type,(LPBYTE)Directory,&Bytes); if (lResult != ERROR_SUCCESS) { GetInstantSaveDir(Directory); } SetDlgItemText(hDlg,IDC_INSTANT_DIR,Directory); Bytes = sizeof(Directory); lResult = RegQueryValueEx(hKeyResults,"Auto Save Directory",0,&Type,(LPBYTE)Directory,&Bytes); if (lResult != ERROR_SUCCESS) { GetAutoSaveDir(Directory); } SetDlgItemText(hDlg,IDC_AUTO_DIR,Directory); Bytes = sizeof(Directory); lResult = RegQueryValueEx(hKeyResults,"Snap Shot Directory",0,&Type,(LPBYTE)Directory,&Bytes); if (lResult != ERROR_SUCCESS) { GetSnapShotDir(Directory); } SetDlgItemText(hDlg,IDC_SNAP_DIR,Directory); } else { SendMessage(GetDlgItem(hDlg,IDC_PLUGIN_DEFAULT),BM_SETCHECK, BST_CHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_ROM_DEFAULT),BM_SETCHECK, BST_CHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_AUTO_DEFAULT),BM_SETCHECK, BST_CHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_INSTANT_DEFAULT),BM_SETCHECK, BST_CHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_SNAP_DEFAULT),BM_SETCHECK, BST_CHECKED,0); GetPluginDir(Directory ); SetDlgItemText(hDlg,IDC_PLUGIN_DIR,Directory); GetInstantSaveDir(Directory); SetDlgItemText(hDlg,IDC_INSTANT_DIR,Directory); GetAutoSaveDir(Directory); SetDlgItemText(hDlg,IDC_AUTO_DIR,Directory); GetSnapShotDir(Directory); SetDlgItemText(hDlg,IDC_SNAP_DIR,Directory); } GetRomDirectory( Directory ); SetDlgItemText(hDlg,IDC_ROM_DIR,Directory); SetDlgItemText(hDlg,IDC_DIR_FRAME1,GS(DIR_PLUGIN)); SetDlgItemText(hDlg,IDC_DIR_FRAME2,GS(DIR_ROM)); SetDlgItemText(hDlg,IDC_DIR_FRAME3,GS(DIR_AUTO_SAVE)); SetDlgItemText(hDlg,IDC_DIR_FRAME4,GS(DIR_INSTANT_SAVE)); SetDlgItemText(hDlg,IDC_DIR_FRAME5,GS(DIR_SCREEN_SHOT)); SetDlgItemText(hDlg,IDC_ROM_DEFAULT,GS(DIR_ROM_DEFAULT)); } break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_SELECT_PLUGIN_DIR: case IDC_SELECT_ROM_DIR: case IDC_SELECT_INSTANT_DIR: case IDC_SELECT_AUTO_DIR: case IDC_SELECT_SNAP_DIR: { char Buffer[MAX_PATH], Directory[255], Title[255]; LPITEMIDLIST pidl; BROWSEINFO bi; switch (LOWORD(wParam)) { case IDC_SELECT_PLUGIN_DIR: strcpy(Title,GS(DIR_SELECT_PLUGIN)); GetPluginDir(Directory); break; case IDC_SELECT_ROM_DIR: GetRomDirectory(Directory); strcpy(Title,GS(DIR_SELECT_ROM)); break; case IDC_SELECT_AUTO_DIR: GetAutoSaveDir(Directory); strcpy(Title,GS(DIR_SELECT_AUTO)); break; case IDC_SELECT_INSTANT_DIR: GetInstantSaveDir(Directory); strcpy(Title,GS(DIR_SELECT_INSTANT)); break; case IDC_SELECT_SNAP_DIR: GetSnapShotDir(Directory); strcpy(Title,GS(DIR_SELECT_SCREEN)); break; } bi.hwndOwner = hDlg; bi.pidlRoot = NULL; bi.pszDisplayName = Buffer; bi.lpszTitle = Title; bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; bi.lpfn = (BFFCALLBACK)SelectDirCallBack; bi.lParam = (DWORD)Directory; if ((pidl = SHBrowseForFolder(&bi)) != NULL) { if (SHGetPathFromIDList(pidl, Directory)) { int len = strlen(Directory); if (Directory[len - 1] != '\\') { strcat(Directory,"\\"); } switch (LOWORD(wParam)) { case IDC_SELECT_PLUGIN_DIR: SetDlgItemText(hDlg,IDC_PLUGIN_DIR,Directory); SendMessage(GetDlgItem(hDlg,IDC_PLUGIN_DEFAULT),BM_SETCHECK, BST_UNCHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_PLUGIN_OTHER),BM_SETCHECK, BST_CHECKED,0); break; case IDC_SELECT_ROM_DIR: SetDlgItemText(hDlg,IDC_ROM_DIR,Directory); SendMessage(GetDlgItem(hDlg,IDC_ROM_DEFAULT),BM_SETCHECK, BST_UNCHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_ROM_OTHER),BM_SETCHECK, BST_CHECKED,0); break; case IDC_SELECT_INSTANT_DIR: SetDlgItemText(hDlg,IDC_INSTANT_DIR,Directory); SendMessage(GetDlgItem(hDlg,IDC_INSTANT_DEFAULT),BM_SETCHECK, BST_UNCHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_INSTANT_OTHER),BM_SETCHECK, BST_CHECKED,0); break; case IDC_SELECT_AUTO_DIR: SetDlgItemText(hDlg,IDC_AUTO_DIR,Directory); SendMessage(GetDlgItem(hDlg,IDC_AUTO_DEFAULT),BM_SETCHECK, BST_UNCHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_AUTO_OTHER),BM_SETCHECK, BST_CHECKED,0); break; case IDC_SELECT_SNAP_DIR: SetDlgItemText(hDlg,IDC_SNAP_DIR,Directory); SendMessage(GetDlgItem(hDlg,IDC_SNAP_DEFAULT),BM_SETCHECK, BST_UNCHECKED,0); SendMessage(GetDlgItem(hDlg,IDC_SNAP_OTHER),BM_SETCHECK, BST_CHECKED,0); break; } } } } break; } break; case WM_NOTIFY: if (((NMHDR FAR *) lParam)->code == PSN_APPLY) { long lResult; HKEY hKeyResults = 0; DWORD Disposition = 0; char String[200]; sprintf(String,"Software\\N64 Emulation\\%s",AppName); lResult = RegCreateKeyEx( HKEY_CURRENT_USER, String,0,"", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,NULL, &hKeyResults,&Disposition); if (lResult == ERROR_SUCCESS) { DWORD Value; Value = SendMessage(GetDlgItem(hDlg,IDC_PLUGIN_DEFAULT),BM_GETSTATE, 0,0) == BST_CHECKED?TRUE:FALSE; RegSetValueEx(hKeyResults,"Use Default Plugin Dir",0,REG_DWORD,(BYTE *)&Value,sizeof(DWORD)); if (Value == FALSE) { GetDlgItemText(hDlg,IDC_PLUGIN_DIR,String,sizeof(String)); RegSetValueEx(hKeyResults,"Plugin Directory",0,REG_SZ,(CONST BYTE *)String,strlen(String)); } Value = SendMessage(GetDlgItem(hDlg,IDC_ROM_DEFAULT),BM_GETSTATE, 0,0) == BST_CHECKED?TRUE:FALSE; RegSetValueEx(hKeyResults,"Use Default Rom Dir",0,REG_DWORD,(BYTE *)&Value,sizeof(DWORD)); if (Value == FALSE) { GetDlgItemText(hDlg,IDC_ROM_DIR,String,sizeof(String)); RegSetValueEx(hKeyResults,"Rom Directory",0,REG_SZ,(CONST BYTE *)String,strlen(String)); } Value = SendMessage(GetDlgItem(hDlg,IDC_AUTO_DEFAULT),BM_GETSTATE, 0,0) == BST_CHECKED?TRUE:FALSE; RegSetValueEx(hKeyResults,"Use Default Auto Save Dir",0,REG_DWORD,(BYTE *)&Value,sizeof(DWORD)); if (Value == FALSE) { GetDlgItemText(hDlg,IDC_AUTO_DIR,String,sizeof(String)); RegSetValueEx(hKeyResults,"Auto Save Directory",0,REG_SZ,(CONST BYTE *)String,strlen(String)); } Value = SendMessage(GetDlgItem(hDlg,IDC_INSTANT_DEFAULT),BM_GETSTATE, 0,0) == BST_CHECKED?TRUE:FALSE; RegSetValueEx(hKeyResults,"Use Default Instant Save Dir",0,REG_DWORD,(BYTE *)&Value,sizeof(DWORD)); if (Value == FALSE) { GetDlgItemText(hDlg,IDC_INSTANT_DIR,String,sizeof(String)); RegSetValueEx(hKeyResults,"Instant Save Directory",0,REG_SZ,(CONST BYTE *)String,strlen(String)); } Value = SendMessage(GetDlgItem(hDlg,IDC_SNAP_DEFAULT),BM_GETSTATE, 0,0) == BST_CHECKED?TRUE:FALSE; RegSetValueEx(hKeyResults,"Use Default Snap Shot Dir",0,REG_DWORD,(BYTE *)&Value,sizeof(DWORD)); if (Value == FALSE) { GetDlgItemText(hDlg,IDC_SNAP_DIR,String,sizeof(String)); RegSetValueEx(hKeyResults,"Snap Shot Directory",0,REG_SZ,(CONST BYTE *)String,strlen(String)); } } RegCloseKey(hKeyResults); } break; default: return FALSE; } return TRUE; }
rdpNla* nla_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { rdpNla* nla = (rdpNla*) calloc(1, sizeof(rdpNla)); if (!nla) return NULL; nla->identity = calloc(1, sizeof(SEC_WINNT_AUTH_IDENTITY)); if (!nla->identity) { free (nla); return NULL; } nla->instance = instance; nla->settings = settings; nla->server = settings->ServerMode; nla->transport = transport; nla->sendSeqNum = 0; nla->recvSeqNum = 0; nla->version = 3; ZeroMemory(&nla->negoToken, sizeof(SecBuffer)); ZeroMemory(&nla->pubKeyAuth, sizeof(SecBuffer)); ZeroMemory(&nla->authInfo, sizeof(SecBuffer)); SecInvalidateHandle(&nla->context); if (nla->server) { LONG status; HKEY hKey; DWORD dwType; DWORD dwSize; status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status != ERROR_SUCCESS) return nla; status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); if (status != ERROR_SUCCESS) { RegCloseKey(hKey); return nla; } nla->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); if (!nla->SspiModule) { RegCloseKey(hKey); free(nla); return NULL; } status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, (BYTE*) nla->SspiModule, &dwSize); if (status == ERROR_SUCCESS) WLog_INFO(TAG, "Using SSPI Module: %s", nla->SspiModule); RegCloseKey(hKey); } return nla; }
DWORD GetNamedValueSD ( HKEY RootKey, LPTSTR KeyName, LPTSTR ValueName, SECURITY_DESCRIPTOR **SD, BOOL *NewSD ) { DWORD returnValue; HKEY registryKey; DWORD valueType; DWORD valueSize; *NewSD = FALSE; // // Get the security descriptor from the named value. If it doesn't // exist, create a fresh one. // returnValue = RegOpenKeyEx (RootKey, KeyName, 0, KEY_ALL_ACCESS, ®istryKey); if (returnValue != ERROR_SUCCESS) { if (returnValue == ERROR_FILE_NOT_FOUND) { *SD = NULL; returnValue = CreateNewSD (SD); if (returnValue != ERROR_SUCCESS) return returnValue; *NewSD = TRUE; return ERROR_SUCCESS; } else return returnValue; } returnValue = RegQueryValueEx (registryKey, ValueName, NULL, &valueType, NULL, &valueSize); if (returnValue && returnValue != ERROR_INSUFFICIENT_BUFFER) { *SD = NULL; returnValue = CreateNewSD (SD); if (returnValue != ERROR_SUCCESS) return returnValue; *NewSD = TRUE; } else { *SD = (SECURITY_DESCRIPTOR *) malloc (valueSize); returnValue = RegQueryValueEx (registryKey, ValueName, NULL, &valueType, (LPBYTE) *SD, &valueSize); if (returnValue) { free (*SD); *SD = NULL; returnValue = CreateNewSD (SD); if (returnValue != ERROR_SUCCESS) return returnValue; *NewSD = TRUE; } } RegCloseKey (registryKey); return ERROR_SUCCESS; }
/* * Returns the value of the given property * the value is returned as a new char array and must be free'd by the user * * @param property - the property name */ char* DeviceManagementNode::readPropertyValue(const char* prop) { HKEY key = NULL; DWORD res; long err = 0; char *ret=NULL; TCHAR *p = toWideChar(prop); ULONG dim = 0; RegCreateKeyEx( HKEY_DM_ROOT, fullContext, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &res ); if (key == 0) { //lastErrorCode = ERR_INVALID_CONTEXT; //sprintf(lastErrorMsg, "Invalid context path: %ls", fullContext); setErrorF(ERR_INVALID_CONTEXT, "Invalid context path: %ls", fullContext); goto finally; } // Get value length err = RegQueryValueEx( key, p, NULL, NULL, // we currently support only strings NULL, &dim ); if (err == ERROR_SUCCESS) { if (dim > 0) { TCHAR *buf = new TCHAR[dim + 1]; err = RegQueryValueEx( key, p, NULL, NULL, // we currently support only strings (UCHAR*)buf, &dim ); if (err == ERROR_SUCCESS) ret = toMultibyte(buf); delete [] buf; } } //else MessageBox(NULL, "Error", "getConfigParameter", MB_OK); if (!ret) ret = stringdup(""); finally: if (p) delete [] p; if (key != 0) { RegCloseKey(key); } return ret; }
LLOSInfo::LLOSInfo() : mMajorVer(0), mMinorVer(0), mBuild(0) { #if LL_WINDOWS OSVERSIONINFOEX osvi; BOOL bOsVersionInfoEx; // Try calling GetVersionEx using the OSVERSIONINFOEX structure. ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) &osvi))) { // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); if(!GetVersionEx( (OSVERSIONINFO *) &osvi)) return; } mMajorVer = osvi.dwMajorVersion; mMinorVer = osvi.dwMinorVersion; mBuild = osvi.dwBuildNumber; switch(osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: { // Test for the product. if(osvi.dwMajorVersion <= 4) { mOSStringSimple = "Microsoft Windows NT "; } else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { mOSStringSimple = "Microsoft Windows 2000 "; } else if(osvi.dwMajorVersion ==5 && osvi.dwMinorVersion == 1) { mOSStringSimple = "Microsoft Windows XP "; } else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { if(osvi.wProductType == VER_NT_WORKSTATION) mOSStringSimple = "Microsoft Windows XP x64 Edition "; else mOSStringSimple = "Microsoft Windows Server 2003 "; } else if(osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) { if(osvi.wProductType == VER_NT_WORKSTATION) mOSStringSimple = "Microsoft Windows Vista "; else mOSStringSimple = "Microsoft Windows Vista Server "; } else // Use the registry on early versions of Windows NT. { HKEY hKey; WCHAR szProductType[80]; DWORD dwBufLen; RegOpenKeyEx( HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey ); RegQueryValueEx( hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen); RegCloseKey( hKey ); if ( lstrcmpi( L"WINNT", szProductType) == 0 ) { mOSStringSimple += "Professional "; } else if ( lstrcmpi( L"LANMANNT", szProductType) == 0 ) { mOSStringSimple += "Server "; } else if ( lstrcmpi( L"SERVERNT", szProductType) == 0 ) { mOSStringSimple += "Advanced Server "; } } std::string csdversion = utf16str_to_utf8str(osvi.szCSDVersion); // Display version, service pack (if any), and build number. std::string tmpstr; if(osvi.dwMajorVersion <= 4) { tmpstr = llformat("version %d.%d %s (Build %d)", osvi.dwMajorVersion, osvi.dwMinorVersion, csdversion.c_str(), (osvi.dwBuildNumber & 0xffff)); } else { tmpstr = llformat("%s (Build %d)", csdversion.c_str(), (osvi.dwBuildNumber & 0xffff)); } mOSString = mOSStringSimple + tmpstr; } break; case VER_PLATFORM_WIN32_WINDOWS: // Test for the Windows 95 product family. if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { mOSStringSimple = "Microsoft Windows 95 "; if ( osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B' ) { mOSStringSimple += "OSR2 "; } } if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { mOSStringSimple = "Microsoft Windows 98 "; if ( osvi.szCSDVersion[1] == 'A' ) { mOSStringSimple += "SE "; } } if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { mOSStringSimple = "Microsoft Windows Millennium Edition "; } mOSString = mOSStringSimple; break; } #else struct utsname un; if(uname(&un) != -1) { mOSStringSimple.append(un.sysname); mOSStringSimple.append(" "); mOSStringSimple.append(un.release); mOSString = mOSStringSimple; mOSString.append(" "); mOSString.append(un.version); mOSString.append(" "); mOSString.append(un.machine); // Simplify 'Simple' std::string ostype = mOSStringSimple.substr(0, mOSStringSimple.find_first_of(" ", 0)); if (ostype == "Darwin") { // Only care about major Darwin versions, truncate at first '.' S32 idx1 = mOSStringSimple.find_first_of(".", 0); std::string simple = mOSStringSimple.substr(0, idx1); if (simple.length() > 0) mOSStringSimple = simple; } else if (ostype == "Linux") { // Only care about major and minor Linux versions, truncate at second '.' S32 idx1 = mOSStringSimple.find_first_of(".", 0); S32 idx2 = (idx1 != std::string::npos) ? mOSStringSimple.find_first_of(".", idx1+1) : std::string::npos; std::string simple = mOSStringSimple.substr(0, idx2); if (simple.length() > 0) mOSStringSimple = simple; } } else { mOSStringSimple.append("Unable to collect OS info"); mOSString = mOSStringSimple; } #endif }
static sal_Bool GetSpecialFolder(rtl_uString **strPath, int nFolder) { sal_Bool bRet = sal_False; HINSTANCE hLibrary; sal_Char PathA[_MAX_PATH]; sal_Unicode PathW[_MAX_PATH]; if ((hLibrary = LoadLibrary("shell32.dll")) != NULL) { BOOL (WINAPI *pSHGetSpecialFolderPathA)(HWND, LPSTR, int, BOOL); BOOL (WINAPI *pSHGetSpecialFolderPathW)(HWND, LPWSTR, int, BOOL); pSHGetSpecialFolderPathA = (BOOL (WINAPI *)(HWND, LPSTR, int, BOOL))GetProcAddress(hLibrary, "SHGetSpecialFolderPathA"); pSHGetSpecialFolderPathW = (BOOL (WINAPI *)(HWND, LPWSTR, int, BOOL))GetProcAddress(hLibrary, "SHGetSpecialFolderPathW"); if (pSHGetSpecialFolderPathA) { if (pSHGetSpecialFolderPathA(GetActiveWindow(), PathA, nFolder, TRUE)) { rtl_string2UString( strPath, PathA, strlen(PathA), osl_getThreadTextEncoding(), OUSTRING_TO_OSTRING_CVTFLAGS); OSL_ASSERT(*strPath != NULL); bRet = sal_True; } } else if (pSHGetSpecialFolderPathW) { if (pSHGetSpecialFolderPathW(GetActiveWindow(), PathW, nFolder, TRUE)) { rtl_uString_newFromStr( strPath, PathW); bRet = sal_True; } } else { HRESULT (WINAPI *pSHGetSpecialFolderLocation)(HWND, int, LPITEMIDLIST *) = (HRESULT (WINAPI *)(HWND, int, LPITEMIDLIST *))GetProcAddress(hLibrary, "SHGetSpecialFolderLocation"); BOOL (WINAPI *pSHGetPathFromIDListA)(LPCITEMIDLIST, LPSTR) = (BOOL (WINAPI *)(LPCITEMIDLIST, LPSTR))GetProcAddress(hLibrary, "SHGetPathFromIDListA"); BOOL (WINAPI *pSHGetPathFromIDListW)(LPCITEMIDLIST, LPWSTR) = (BOOL (WINAPI *)(LPCITEMIDLIST, LPWSTR))GetProcAddress(hLibrary, "SHGetPathFromIDListW"); HRESULT (WINAPI *pSHGetMalloc)(LPMALLOC *) = (HRESULT (WINAPI *)(LPMALLOC *))GetProcAddress(hLibrary, "SHGetMalloc"); if (pSHGetSpecialFolderLocation && (pSHGetPathFromIDListA || pSHGetPathFromIDListW ) && pSHGetMalloc ) { LPITEMIDLIST pidl; LPMALLOC pMalloc; HRESULT hr; hr = pSHGetSpecialFolderLocation(GetActiveWindow(), nFolder, &pidl); /* Get SHGetSpecialFolderLocation fails if directory does not exists. */ /* If it fails we try to create the directory and redo the call */ if (! SUCCEEDED(hr)) { HKEY hRegKey; if (RegOpenKey(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", &hRegKey) == ERROR_SUCCESS) { LONG lRet; DWORD lSize = elementsof(PathA); DWORD Type = REG_SZ; switch (nFolder) { case CSIDL_APPDATA: lRet = RegQueryValueEx(hRegKey, "AppData", NULL, &Type, (LPBYTE)PathA, &lSize); break; case CSIDL_PERSONAL: lRet = RegQueryValueEx(hRegKey, "Personal", NULL, &Type, (LPBYTE)PathA, &lSize); break; default: lRet = -1l; } if ((lRet == ERROR_SUCCESS) && (Type == REG_SZ)) { if (_access(PathA, 0) < 0) CreateDirectory(PathA, NULL); hr = pSHGetSpecialFolderLocation(GetActiveWindow(), nFolder, &pidl); } RegCloseKey(hRegKey); } } if (SUCCEEDED(hr)) { if (pSHGetPathFromIDListW && pSHGetPathFromIDListW(pidl, PathW)) { /* if directory does not exist, create it */ if (_waccess(PathW, 0) < 0) CreateDirectoryW(PathW, NULL); rtl_uString_newFromStr( strPath, PathW); bRet = sal_True; } else if (pSHGetPathFromIDListA && pSHGetPathFromIDListA(pidl, PathA)) { /* if directory does not exist, create it */ if (_access(PathA, 0) < 0) CreateDirectoryA(PathA, NULL); rtl_string2UString( strPath, PathA, strlen(PathA), osl_getThreadTextEncoding(), OUSTRING_TO_OSTRING_CVTFLAGS); OSL_ASSERT(*strPath != NULL); bRet = sal_True; } } if (SUCCEEDED(pSHGetMalloc(&pMalloc))) { pMalloc->lpVtbl->Free(pMalloc, pidl); pMalloc->lpVtbl->Release(pMalloc); } } } } FreeLibrary(hLibrary); return (bRet); }
// 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 { std::wstring log; if (!PathFileExists(directory.c_str()) || !PathIsDirectory(directory.c_str())) { ready = false; log = L"WebParser.dll: ["; log += measure->section; log += L"] Directory does not exist: "; log += directory; RmLog(LOG_ERROR, log.c_str()); } else if (PathIsDirectory(fullpath.c_str())) { ready = false; log = L"WebParser.dll: ["; log += measure->section; log += L"] Path is a directory, not a file: "; log += fullpath; RmLog(LOG_ERROR, log.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; log = L"WebParser.dll: ["; log += measure->section; log += L"] File is READ-ONLY: "; log += fullpath; RmLog(LOG_ERROR, log.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()); } } } // Write some log info std::wstring log = L"WebParser.dll: ["; log += measure->section; log += L"] Downloading url "; log += url; log += L" to "; log += fullpath; RmLog(LOG_DEBUG, log.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()); } wsprintf(buffer, L"result=0x%08X, COM=0x%08X", result, resultCoInitialize); std::wstring log = L"WebParser.dll: ["; log += measure->section; log += L"] Download failed ("; log += buffer; log += L"): "; log += url; RmLog(LOG_ERROR, log.c_str()); } if (SUCCEEDED(resultCoInitialize)) { CoUninitialize(); } } else { std::wstring log = L"WebParser.dll: ["; log += measure->section; log += L"] Download failed: "; log += url; RmLog(LOG_ERROR, log.c_str()); } } else { std::wstring log = L"WebParser.dll: ["; log += measure->section; log += L"] Url is empty"; RmLog(LOG_ERROR, log.c_str()); } 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 }
BOOL GetNewFspRegistryData( BOOL *bLoggingEnabled, LPWSTR lpszLoggingDirectory, DWORD dwLoggingDirectoryBufferSize, PDEVICE_INFO *pDeviceInfo, LPDWORD pdwNumDevices ) { // hServiceProvidersKey is the handle to the fax service providers registry key HKEY hServiceProvidersKey = NULL; // hNewFspKey is the handle to the newfsp service provider registry key HKEY hNewFspKey = NULL; // hDevicesKey is the handle to the virtual fax devices registry key HKEY hDevicesKey = NULL; // dwSubkeys is the number of virtual fax device registry subkeys DWORD dwSubkeys; // dwIndex is a counter to enumerate each virtual fax device registry subkey DWORD dwIndex; // szDeviceSubkey is the name of a virtual fax device registry subkey WCHAR szDeviceSubkey[MAX_PATH] ={0}; // hDeviceSubkey is the handle to a virtual fax device registry subkey HKEY hDeviceSubkey = NULL; DWORD dwType; // pCurrentDeviceInfo is a pointer to the current virtual fax device PDEVICE_INFO pCurrentDeviceInfo = NULL; DWORD dwLoggingEnabledSize; DWORD dwLoggingDirectorySize = dwLoggingDirectoryBufferSize - 1; DWORD dwDirectorySize; HRESULT hr = S_OK; BOOL bRetVal = FALSE; if (bLoggingEnabled != NULL) { *bLoggingEnabled = FALSE; } if (pDeviceInfo != NULL) { *pDeviceInfo = NULL; } if (pdwNumDevices != NULL) { *pdwNumDevices = 0; } // Open the fax service providers registry key if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, FAX_PROVIDERS_REGKEY, 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &hServiceProvidersKey) != ERROR_SUCCESS) { goto Exit; } // Open the newfsp service provider registry key if (RegOpenKeyEx(hServiceProvidersKey, NEWFSP_PROVIDER, 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &hNewFspKey) != ERROR_SUCCESS) { goto Exit; } if (bLoggingEnabled != NULL) { // Get the logging enabled dwLoggingEnabledSize = sizeof(BOOL); RegQueryValueEx(hNewFspKey, NEWFSP_LOGGING_ENABLED, NULL, &dwType, (LPBYTE) bLoggingEnabled, &dwLoggingEnabledSize); } if (lpszLoggingDirectory != NULL) { // Get the logging directory if ((RegQueryValueEx(hNewFspKey, NEWFSP_LOGGING_DIRECTORY, NULL, &dwType, (LPBYTE) lpszLoggingDirectory, &dwLoggingDirectorySize) != ERROR_SUCCESS)|| (dwLoggingDirectorySize >= MAX_PATH)){ goto Exit; } } if ((pDeviceInfo != NULL) || (pdwNumDevices != NULL)) { // Open the virtual fax devices registry key if (RegOpenKeyEx(hNewFspKey, NEWFSP_DEVICES, 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &hDevicesKey) != ERROR_SUCCESS) { goto Exit; } // Determine the number of virtual fax device registry subkeys if (RegQueryInfoKey(hDevicesKey, NULL, NULL, NULL, &dwSubkeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { goto Exit; } } if (pdwNumDevices != NULL) { if (dwSubkeys < NEWFSP_DEVICE_LIMIT) { *pdwNumDevices = dwSubkeys; } else { *pdwNumDevices = NEWFSP_DEVICE_LIMIT; } } if (pDeviceInfo != NULL) { if (dwSubkeys > 0) { // Allocate a block of memory for the first virtual fax device data *pDeviceInfo = (PDEVICE_INFO) MemAllocMacro(sizeof(DEVICE_INFO)); } // Enumerate the virtual fax device registry subkeys for (pCurrentDeviceInfo = *pDeviceInfo, dwIndex = 0; (dwIndex < dwSubkeys) && (dwIndex < NEWFSP_DEVICE_LIMIT); pCurrentDeviceInfo = pCurrentDeviceInfo->pNextDeviceInfo, dwIndex++) { if (pCurrentDeviceInfo == NULL) { // A memory allocation for virtual fax device data failed, so go with what we have so far *pdwNumDevices = dwIndex; break; } // Set the name of the virtual fax device registry subkey hr = StringCchPrintf(szDeviceSubkey,MAX_PATH, L"%d", dwIndex); if(hr != S_OK) { WriteDebugString( L"StringCchPrintf failed, hr = 0x%x for szDeviceSubkey", hr ); bRetVal = FALSE; goto Exit; } // Set the identifier of the virtual fax device pCurrentDeviceInfo->DeviceId = dwIndex; if (RegOpenKeyEx(hDevicesKey, szDeviceSubkey, 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &hDeviceSubkey) == ERROR_SUCCESS) { // Get the incoming fax directory for the virtual fax device dwDirectorySize = sizeof(pCurrentDeviceInfo->Directory)/sizeof(pCurrentDeviceInfo->Directory[0]); if (RegQueryValueEx(hDeviceSubkey, NEWFSP_DEVICE_DIRECTORY, NULL, &dwType, (LPBYTE) pCurrentDeviceInfo->Directory, &dwDirectorySize) != ERROR_SUCCESS) { RegCloseKey(hDeviceSubkey); continue; } RegCloseKey(hDeviceSubkey); } // Allocate a block of memory for the next virtual fax device data if ((dwIndex < (dwSubkeys - 1)) && (dwIndex < (NEWFSP_DEVICE_LIMIT - 1))) { pCurrentDeviceInfo->pNextDeviceInfo = (_DEVICE_INFO*) MemAllocMacro(sizeof(DEVICE_INFO)); } else { pCurrentDeviceInfo->pNextDeviceInfo = NULL; } } } bRetVal = TRUE; Exit: if(hDevicesKey) { RegCloseKey(hDevicesKey); hDevicesKey = NULL; } if(hNewFspKey) { RegCloseKey(hNewFspKey); hNewFspKey = NULL; } if(hServiceProvidersKey) { RegCloseKey(hServiceProvidersKey); hServiceProvidersKey = NULL; } return TRUE; }
bool CShellUpdater::RebuildIcons() { const int BUFFER_SIZE = 1024; TCHAR buf[BUFFER_SIZE] = { 0 }; HKEY hRegKey = nullptr; DWORD dwRegValue; DWORD dwRegValueTemp; DWORD dwSize; DWORD_PTR dwResult; LONG lRegResult; lRegResult = RegOpenKeyEx(HKEY_CURRENT_USER, L"Control Panel\\Desktop\\WindowMetrics", 0, KEY_READ | KEY_WRITE, &hRegKey); if (lRegResult != ERROR_SUCCESS) return false; SCOPE_EXIT { RegCloseKey(hRegKey); }; // we're going to change the Shell Icon Size value const TCHAR* sRegValueName = L"Shell Icon Size"; // Read registry value dwSize = BUFFER_SIZE; lRegResult = RegQueryValueEx(hRegKey, sRegValueName, nullptr, nullptr, (LPBYTE) buf, &dwSize); if (lRegResult != ERROR_FILE_NOT_FOUND) { // If registry key doesn't exist create it using system current setting int iDefaultIconSize = ::GetSystemMetrics(SM_CXICON); if (0 == iDefaultIconSize) iDefaultIconSize = 32; _sntprintf_s(buf, BUFFER_SIZE, BUFFER_SIZE, L"%d", iDefaultIconSize); } else if (lRegResult != ERROR_SUCCESS) return false; // Change registry value dwRegValue = _wtoi(buf); dwRegValueTemp = dwRegValue-1; dwSize = _sntprintf_s(buf, BUFFER_SIZE, BUFFER_SIZE, L"%lu", dwRegValueTemp) + sizeof(TCHAR); lRegResult = RegSetValueEx(hRegKey, sRegValueName, 0, REG_SZ, (LPBYTE) buf, dwSize); if (lRegResult != ERROR_SUCCESS) return false; // Update all windows SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETNONCLIENTMETRICS, 0, SMTO_ABORTIFHUNG, 5000, &dwResult); // Reset registry value dwSize = _sntprintf_s(buf, BUFFER_SIZE, BUFFER_SIZE, L"%lu", dwRegValue) + sizeof(TCHAR); lRegResult = RegSetValueEx(hRegKey, sRegValueName, 0, REG_SZ, (LPBYTE) buf, dwSize); if (lRegResult != ERROR_SUCCESS) return false; // Update all windows SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETNONCLIENTMETRICS, 0, SMTO_ABORTIFHUNG, 5000, &dwResult); return true; }
void AssociateTo(char* Ext, bool SetOpen) { try { HKEY Key; DWORD Size = MAX_PATH; /* Open or create the key for this extension */ if (RegOpenKeyEx(HKEY_CLASSES_ROOT, Ext, 0, KEY_ALL_ACCESS, &Key) != ERROR_SUCCESS) RegCreateKey(HKEY_CLASSES_ROOT, Ext, &Key); else { /* Get or set the key associated to this extension */ char* Value = new char[Size]; if (RegQueryValueEx(Key, NULL, NULL, NULL, (BYTE*)Value, &Size) != ERROR_SUCCESS) { strcpy(Value, "LambdaDocument"); RegSetValueEx(Key, NULL, 0, REG_SZ, (BYTE*)Value, strlen(Value)+1); RegCloseKey(Key); } /* Open or create the key associated to this extension */ if (RegOpenKeyEx(HKEY_CLASSES_ROOT, Value, 0, KEY_ALL_ACCESS, &Key) != ERROR_SUCCESS) { RegCreateKey(HKEY_CLASSES_ROOT, Value, &Key); RegCloseKey(Key); } /* Set the icon associated to this extension */ if (SetOpen) { char* Str = new char[MAX_PATH]; strcpy(Str, Value); strcat(Str, "\\DefaultIcon"); if (RegOpenKey(HKEY_CLASSES_ROOT, Str, &Key) == ERROR_SUCCESS) { char* FileName = new char[MAX_PATH]; GetModuleFileName(hInstance, FileName, MAX_PATH); strcat(FileName, ",1"); RegSetValueEx(Key, "", 0, REG_SZ, (BYTE*)FileName, strlen(FileName)+1); RegCloseKey(Key); delete[] FileName; } delete[] Str; } /* Set the command */ if (SetOpen) strcat(Value, "\\shell\\open\\command"); else strcat(Value, "\\shell\\edit\\command"); if (RegOpenKey(HKEY_CLASSES_ROOT, Value, &Key) == ERROR_SUCCESS) { char* FileName = new char[MAX_PATH]; GetModuleFileName(hInstance, FileName, MAX_PATH); strcat(FileName, " \"%1\""); RegSetValueEx(Key, NULL, 0, REG_SZ, (BYTE*)FileName, strlen(FileName)+1); RegCloseKey(Key); delete[] FileName; } delete[] Value; } } catch (exception e) { } }
BOOL CWebFileOpenDlg::OnInitDialog() { #ifdef _WRITE_LNG_FILE_ _WriteDlgString(this,"DialogOpenFile"); this->OnCancel(); return TRUE; #endif LOADDLG("DialogOpenFile"); CDialog::OnInitDialog(); // TODO: Add extra initialization here CImageList img; img.Create(16, 16, ILC_COLORDDB|ILC_MASK, 2, 1); HBITMAP hbmp = pmf->GetBitmap("FavBar.bmp"); ImageList_AddMasked(img.GetSafeHandle(), hbmp, RGB(255,0,255)); DeleteObject(hbmp); m_conAddress.SetImageList(&img); img.Detach(); m_conAddress.SetExtendedStyle(0, m_conAddress.GetExtendedStyle()|CBES_EX_NOSIZELIMIT); //auto complete HINSTANCE hIns = LoadLibrary("shlwapi.dll"); if(hIns != NULL) { LPFNDLLFUNC1 lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hIns, "SHAutoComplete"); if(lpfnDllFunc1!=NULL) lpfnDllFunc1(m_conAddress.GetEditCtrl()->m_hWnd, 0xe); FreeLibrary(hIns); } //typed urls TCHAR sz[MAX_PATH]; HKEY hKey; DWORD dwSize; TCHAR id[9] = "url"; int i = 1; if(RegOpenKey(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Internet Explorer\\TypedUrls"), &hKey) != ERROR_SUCCESS) { TRACE0("Typed URLs not found\n"); return TRUE; } dwSize = MAX_PATH-1; itoa(i, id+3, 10); COMBOBOXEXITEM item; item.mask = CBEIF_TEXT|CBEIF_IMAGE|CBEIF_SELECTEDIMAGE ; item.iImage = 1; item.iSelectedImage = 1; dwSize = sizeof(sz); while(RegQueryValueEx(hKey, _T(id), NULL, NULL, (LPBYTE)sz, &dwSize) == ERROR_SUCCESS) { item.iItem = i-1; item.pszText = (LPTSTR)(LPCTSTR)sz; m_conAddress.InsertItem(&item); i++; itoa(i, id+3, 10); dwSize = MAX_PATH - 1; } RegCloseKey(hKey); if (m_bDirectOpenFile) { OnBrowse(); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { TCHAR *cmdline; TCHAR seekchar = _T(' '); cmdline = GetCommandLine(); if (*cmdline == _T('\"')) seekchar = *cmdline++; while (*cmdline && *cmdline != seekchar) cmdline = CharNext(cmdline); cmdline = CharNext(cmdline); while (*cmdline == _T(' ')) cmdline++; if (*cmdline++ != _T('/')) { ExitProcess(1); return 0; } if (*cmdline == _T('S')) { HKEY rootkey; TCHAR *keyname, *file; // These are turned into heap memory to avoid _chkstk keyname = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR)); file = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR)); if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"), 0, KEY_READ, &rootkey))) { while (RegEnumKey(rootkey, 0, keyname, STR_SIZE) == ERROR_SUCCESS) { HKEY key; if (SUCCEEDED(RegOpenKeyEx(rootkey, keyname, 0, KEY_READ, &key))) { DWORD t, count, l = sizeof(DWORD); if (SUCCEEDED(RegQueryValueEx(key, _T("count"), NULL, &t, (LPBYTE) &count, &l)) && t == REG_DWORD) { DWORD j; TCHAR valname[128], mode[3]; for (j = 1; j <= count; j++) { wsprintf(valname, _T("%u.mode"), j); l = sizeof(mode); if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) mode, &l)) || t != REG_SZ) continue; wsprintf(valname, _T("%u.file"), j); l = STR_SIZE*sizeof(TCHAR); if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) file, &l)) || t != REG_SZ) continue; // JP: Note, if this mode[1] is used as anything but a boolean later on, // we'll need to consider the next line carefully. RegFile(mode[0], file, mode[1] == 'X'); } } RegCloseKey(key); RegDeleteKey(rootkey, keyname); } } RegCloseKey(rootkey); RegDeleteKey(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3")); } { if (GetModuleFileName(GetModuleHandle(NULL), file, STR_SIZE)) { DeleteFileOnReboot(file); } } GlobalFree(keyname); GlobalFree(file); } else { SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); OleInitialize(NULL); if (*cmdline == _T('D')) { RegDll(cmdline + 1); } else if (*cmdline == _T('T')) { RegTypeLib(cmdline + 1); } OleUninitialize(); SetErrorMode(0); } ExitProcess(0); return 0; }
INT WSAAPI WsSetupCatalogProtection(IN HKEY CatalogKey, IN HANDLE CatalogEvent, OUT LPDWORD UniqueId) { INT ErrorCode; HKEY RegistryKey; DWORD NewUniqueId; CHAR KeyBuffer[32]; DWORD RegType = REG_DWORD; DWORD RegSize = sizeof(DWORD); /* Start loop */ do { #if 0 /* Ask for notifications */ ErrorCode = RegNotifyChangeKeyValue(CatalogKey, FALSE, REG_NOTIFY_CHANGE_NAME, CatalogEvent, TRUE); if (ErrorCode != ERROR_SUCCESS) { /* Normalize error code */ ErrorCode = WSASYSCALLFAILURE; break; } #endif /* Read the current ID */ ErrorCode = RegQueryValueEx(CatalogKey, "Serial_Access_Num", 0, &RegType, (LPBYTE)&NewUniqueId, &RegSize); if (ErrorCode != ERROR_SUCCESS) { /* Critical failure */ ErrorCode = WSASYSCALLFAILURE; break; } /* Try to open it for writing */ sprintf(KeyBuffer, "%8.8lX", NewUniqueId); ErrorCode = RegOpenKeyEx(CatalogKey, KeyBuffer, 0, MAXIMUM_ALLOWED, &RegistryKey); /* If the key doesn't exist or is being delete, that's ok for us */ if ((ErrorCode == ERROR_FILE_NOT_FOUND) || (ErrorCode == ERROR_KEY_DELETED)) { /* Set success and return the new ID */ ErrorCode = ERROR_SUCCESS; *UniqueId = NewUniqueId; break; } else if (ErrorCode != ERROR_SUCCESS) { /* Any other failure is bad */ ErrorCode = WSASYSCALLFAILURE; break; } /* If we could actually open the key, someone is using it :/ */ ErrorCode = RegCloseKey(RegistryKey); /* In case we break out prematurely */ ErrorCode = WSANO_RECOVERY; /* Keep looping until they let go of the registry writing */ } while (!WaitForSingleObject(CatalogEvent, 180 * 1000)); /* Return error code */ return ErrorCode; }
static void process_config_file(sc_context_t *ctx, struct _sc_ctx_options *opts) { int i, r, count = 0; scconf_block **blocks; const char *conf_path = NULL; #ifdef _WIN32 char temp_path[PATH_MAX]; DWORD temp_len; long rc; HKEY hKey; #endif memset(ctx->conf_blocks, 0, sizeof(ctx->conf_blocks)); #ifdef _WIN32 conf_path = getenv("OPENSC_CONF"); if (!conf_path) { rc = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey); if (rc == ERROR_SUCCESS) { temp_len = PATH_MAX; rc = RegQueryValueEx( hKey, "ConfigFile", NULL, NULL, (LPBYTE) temp_path, &temp_len); if ((rc == ERROR_SUCCESS) && (temp_len < PATH_MAX)) conf_path = temp_path; RegCloseKey(hKey); } } if (!conf_path) { rc = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "Software\\OpenSC Project\\OpenSC", 0, KEY_QUERY_VALUE, &hKey ); if (rc == ERROR_SUCCESS) { temp_len = PATH_MAX; rc = RegQueryValueEx( hKey, "ConfigFile", NULL, NULL, (LPBYTE) temp_path, &temp_len); if ((rc == ERROR_SUCCESS) && (temp_len < PATH_MAX)) conf_path = temp_path; RegCloseKey(hKey); } } if (!conf_path) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "process_config_file doesn't find opensc config file. Please set the registry key."); return; } #else conf_path = getenv("OPENSC_CONF"); if (!conf_path) conf_path = OPENSC_CONF_PATH; #endif ctx->conf = scconf_new(conf_path); if (ctx->conf == NULL) return; r = scconf_parse(ctx->conf); #ifdef OPENSC_CONFIG_STRING /* Parse the string if config file didn't exist */ if (r < 0) r = scconf_parse_string(ctx->conf, OPENSC_CONFIG_STRING); #endif if (r < 1) { /* A negative return value means the config file isn't * there, which is not an error. Nevertheless log this * fact. */ if (r < 0) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "scconf_parse failed: %s", ctx->conf->errmsg); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "scconf_parse failed: %s", ctx->conf->errmsg); scconf_free(ctx->conf); ctx->conf = NULL; return; } blocks = scconf_find_blocks(ctx->conf, NULL, "app", ctx->app_name); if (blocks[0]) ctx->conf_blocks[count++] = blocks[0]; free(blocks); if (strcmp(ctx->app_name, "default") != 0) { blocks = scconf_find_blocks(ctx->conf, NULL, "app", "default"); if (blocks[0]) ctx->conf_blocks[count] = blocks[0]; free(blocks); } /* Above we add 2 blocks at most, but conf_blocks has 3 elements, * so at least one is NULL */ for (i = 0; ctx->conf_blocks[i]; i++) load_parameters(ctx, ctx->conf_blocks[i], opts); }
/* Fallback method using the registry to poll the statistics. */ static void registry_poll (void (*add)(const void*, size_t, enum random_origins), enum random_origins requester) { static int cbPerfData = PERFORMANCE_BUFFER_SIZE; int iterations; DWORD dwSize, status; PERF_DATA_BLOCK *pPerfData; /* Get information from the system performance counters. This can take a few seconds to do. In some environments the call to RegQueryValueEx() can produce an access violation at some random time in the future, in some cases adding a short delay after the following code block makes the problem go away. This problem is extremely difficult to reproduce, I haven't been able to get it to occur despite running it on a number of machines. MS knowledge base article Q178887 covers this type of problem, it's typically caused by an external driver or other program that adds its own values under the HKEY_PERFORMANCE_DATA key. The NT kernel, via Advapi32.dll, calls the required external module to map in the data inside an SEH try/except block, so problems in the module's collect function don't pop up until after it has finished, so the fault appears to occur in Advapi32.dll. There may be problems in the NT kernel as well though, a low-level memory checker indicated that ExpandEnvironmentStrings() in Kernel32.dll, called an interminable number of calls down inside RegQueryValueEx(), was overwriting memory (it wrote twice the allocated size of a buffer to a buffer allocated by the NT kernel). OTOH this could be coming from the external module calling back into the kernel, which eventually causes the problem described above. Possibly as an extension of the problem that the krnlWaitSemaphore() call above works around, running two instances of cryptlib (e.g. two applications that use it) under NT4 can result in one of them hanging in the RegQueryValueEx() call. This happens only under NT4 and is hard to reproduce in any consistent manner. One workaround that helps a bit is to read the registry as a remote (rather than local) registry, it's possible that the use of a network RPC call isolates the calling app from the problem in that whatever service handles the RPC is taking the hit and not affecting the calling app. Since this would require another round of extensive testing to verify and the NT native API call is working fine, we'll stick with the native API call for now. Some versions of NT4 had a problem where the amount of data returned was mis-reported and would never settle down, because of this the code below includes a safety-catch that bails out after 10 attempts have been made, this results in no data being returned but at does ensure that the thread will terminate. In addition to these problems the code in RegQueryValueEx() that estimates the amount of memory required to return the performance counter information isn't very accurate (it's much worse than the "slightly-inaccurate" level that the MS docs warn about, it's usually wildly off) since it always returns a worst-case estimate which is usually nowhere near the actual amount required. For example it may report that 128K of memory is required, but only return 64K of data. Even worse than the registry-based performance counters is the performance data helper (PDH) shim that tries to make the counters look like the old Win16 API (which is also used by Win95). Under NT this can consume tens of MB of memory and huge amounts of CPU time while it gathers its data, and even running once can still consume about 1/2MB of memory */ pPerfData = gcry_xmalloc (cbPerfData); for (iterations=0; iterations < 10; iterations++) { dwSize = cbPerfData; if ( debug_me ) log_debug ("rndw32#slow_gatherer_nt: get perf data\n" ); status = RegQueryValueEx (HKEY_PERFORMANCE_DATA, _T("Global"), NULL, NULL, (LPBYTE) pPerfData, &dwSize); if (status == ERROR_SUCCESS) { if (!memcmp (pPerfData->Signature, L"PERF", 8)) (*add) ( pPerfData, dwSize, requester ); else log_debug ("rndw32: no PERF signature\n"); break; } else if (status == ERROR_MORE_DATA) { cbPerfData += PERFORMANCE_BUFFER_STEP; pPerfData = gcry_xrealloc (pPerfData, cbPerfData); } else { static int been_here; /* Silence the error message. In particular under Wine (as of 2008) we would get swamped with such diagnotiscs. One such diagnotiscs should be enough. */ if (been_here != status) { been_here = status; log_debug ("rndw32: get performance data problem: ec=%ld\n", status); } break; } } gcry_free (pPerfData); /* Although this isn't documented in the Win32 API docs, it's necessary to explicitly close the HKEY_PERFORMANCE_DATA key after use (it's implicitly opened on the first call to RegQueryValueEx()). If this isn't done then any system components which provide performance data can't be removed or changed while the handle remains active. */ RegCloseKey (HKEY_PERFORMANCE_DATA); }
static void slow_gatherer ( void (*add)(const void*, size_t, enum random_origins), enum random_origins requester ) { static int is_initialized = 0; static int is_workstation = 1; HANDLE hDevice; DWORD dwType, dwSize, dwResult; ULONG ulSize; int drive_no, status; int no_results = 0; void *buffer; if ( !is_initialized ) { HKEY hKey; if ( debug_me ) log_debug ("rndw32#slow_gatherer: init toolkit\n" ); /* Find out whether this is an NT server or workstation if necessary */ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"), 0, KEY_READ, &hKey) == ERROR_SUCCESS) { BYTE szValue[32 + 8]; dwSize = 32; if ( debug_me ) log_debug ("rndw32#slow_gatherer: check product options\n" ); status = RegQueryValueEx (hKey, _T("ProductType"), 0, NULL, szValue, &dwSize); if (status == ERROR_SUCCESS && _stricmp (szValue, "WinNT")) { /* Note: There are (at least) three cases for ProductType: WinNT = NT Workstation, ServerNT = NT Server, LanmanNT = NT Server acting as a Domain Controller. */ is_workstation = 0; if ( debug_me ) log_debug ("rndw32: this is a NT server\n"); } RegCloseKey (hKey); } /* The following are fixed for the lifetime of the process so we only add them once */ /* readPnPData (); - we have not implemented that. */ /* Initialize the NetAPI32 function pointers if necessary */ hNetAPI32 = LoadLibraryA("NETAPI32.DLL"); if (hNetAPI32) { if (debug_me) log_debug ("rndw32#slow_gatherer: netapi32 loaded\n" ); pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32, "NetStatisticsGet"); pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32, "NetApiBufferSize"); pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32, "NetApiBufferFree"); if (!pNetStatisticsGet || !pNetApiBufferSize || !pNetApiBufferFree) { FreeLibrary (hNetAPI32); hNetAPI32 = NULL; log_debug ("rndw32: No NETAPI found\n" ); } } /* Initialize the NT kernel native API function pointers if necessary */ hNTAPI = GetModuleHandleA("NTDll.dll"); if (hNTAPI) { /* Get a pointer to the NT native information query functions */ pNtQuerySystemInformation = (NTQUERYSYSTEMINFORMATION) GetProcAddress (hNTAPI, "NtQuerySystemInformation"); pNtQueryInformationProcess = (NTQUERYINFORMATIONPROCESS) GetProcAddress (hNTAPI, "NtQueryInformationProcess"); pNtPowerInformation = (NTPOWERINFORMATION) GetProcAddress(hNTAPI, "NtPowerInformation"); if (!pNtQuerySystemInformation || !pNtQueryInformationProcess) hNTAPI = NULL; } is_initialized = 1; } read_system_rng ( add, requester ); read_mbm_data ( add, requester ); /* Get network statistics. Note: Both NT Workstation and NT Server by default will be running both the workstation and server services. The heuristic below is probably useful though on the assumption that the majority of the network traffic will be via the appropriate service. In any case the network statistics return almost no randomness. */ { LPBYTE lpBuffer; if (hNetAPI32 && !pNetStatisticsGet (NULL, is_workstation ? L"LanmanWorkstation" : L"LanmanServer", 0, 0, &lpBuffer)) { if ( debug_me ) log_debug ("rndw32#slow_gatherer: get netstats\n" ); pNetApiBufferSize (lpBuffer, &dwSize); (*add) ( lpBuffer, dwSize, requester ); pNetApiBufferFree (lpBuffer); } } /* Get disk I/O statistics for all the hard drives. 100 is an arbitrary failsafe limit. */ for (drive_no = 0; drive_no < 100 ; drive_no++) { char diskPerformance[SIZEOF_DISK_PERFORMANCE_STRUCT + 8]; char szDevice[50]; /* Check whether we can access this device. */ snprintf (szDevice, sizeof szDevice, "\\\\.\\PhysicalDrive%d", drive_no); hDevice = CreateFileA(szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) break; /* No more drives. */ /* Note: This only works if you have turned on the disk performance counters with 'diskperf -y'. These counters are off by default. */ dwSize = sizeof diskPerformance; if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, diskPerformance, SIZEOF_DISK_PERFORMANCE_STRUCT, &dwSize, NULL)) { if ( debug_me ) log_debug ("rndw32#slow_gatherer: iostat drive %d\n", drive_no); (*add) (diskPerformance, dwSize, requester); } else { log_info ("NOTE: you should run 'diskperf -y' " "to enable the disk statistics\n"); } CloseHandle (hDevice); } /* In theory we should be using the Win32 performance query API to obtain unpredictable data from the system, however this is so unreliable (see the multiple sets of comments in registryPoll()) that it's too risky to rely on it except as a fallback in emergencies. Instead, we rely mostly on the NT native API function NtQuerySystemInformation(), which has the dual advantages that it doesn't have as many (known) problems as the Win32 equivalent and that it doesn't access the data indirectly via pseudo-registry keys, which means that it's much faster. Note that the Win32 equivalent actually works almost all of the time, the problem is that on one or two systems it can fail in strange ways that are never the same and can't be reproduced on any other system, which is why we use the native API here. Microsoft officially documented this function in early 2003, so it'll be fairly safe to use. */ if ( !hNTAPI ) { registry_poll (add, requester); return; } /* Scan the first 64 possible information types (we don't bother with increasing the buffer size as we do with the Win32 version of the performance data read, we may miss a few classes but it's no big deal). This scan typically yields around 20 pieces of data, there's nothing in the range 65...128 so chances are there won't be anything above there either. */ buffer = gcry_xmalloc (PERFORMANCE_BUFFER_SIZE); for (dwType = 0; dwType < 64; dwType++) { switch (dwType) { /* ID 17 = SystemObjectInformation hangs on some win2k systems. */ case 17: if (system_is_w2000) continue; break; /* Some information types are write-only (the IDs are shared with a set-information call), we skip these. */ case 26: case 27: case 38: case 46: case 47: case 48: case 52: continue; /* ID 53 = SystemSessionProcessInformation reads input from the output buffer, which has to contain a session ID and pointer to the actual buffer in which to store the session information. Because this isn't a standard query, we skip this. */ case 53: continue; } /* Query the info for this ID. Some results (for example for ID = 6, SystemCallCounts) are only available in checked builds of the kernel. A smaller subcless of results require that certain system config flags be set, for example SystemObjectInformation requires that the FLG_MAINTAIN_OBJECT_TYPELIST be set in NtGlobalFlags. To avoid having to special-case all of these, we try reading each one and only use those for which we get a success status. */ dwResult = pNtQuerySystemInformation (dwType, buffer, PERFORMANCE_BUFFER_SIZE - 2048, &ulSize); if (dwResult != ERROR_SUCCESS) continue; /* Some calls (e.g. ID = 23, SystemProcessorStatistics, and ID = 24, SystemDpcInformation) incorrectly return a length of zero, so we manually adjust the length to the correct value. */ if ( !ulSize ) { if (dwType == 23) ulSize = 6 * sizeof (ULONG); else if (dwType == 24) ulSize = 5 * sizeof (ULONG); } /* If we got some data back, add it to the entropy pool. */ if (ulSize > 0 && ulSize <= PERFORMANCE_BUFFER_SIZE - 2048) { if (debug_me) log_debug ("rndw32#slow_gatherer: %lu bytes from sysinfo %ld\n", ulSize, dwType); (*add) (buffer, ulSize, requester); no_results++; } } /* Now we would do the same for the process information. This call would rather ugly in that it requires an exact length match for the data returned, failing with a STATUS_INFO_LENGTH_MISMATCH error code (0xC0000004) if the length isn't an exact match. It requires a compiler to handle complex nested structs, alignment issues, and so on, and without the headers in which the entries are declared it's almost impossible to do. Thus we don't. */ /* Finally, do the same for the system power status information. There are only a limited number of useful information types available so we restrict ourselves to the useful types. In addition since this function doesn't return length information, we have to hardcode in length data. */ if (pNtPowerInformation) { static const struct { int type; int size; } powerInfo[] = { { 0, 128 }, /* SystemPowerPolicyAc */ { 1, 128 }, /* SystemPowerPolicyDc */ { 4, 64 }, /* SystemPowerCapabilities */ { 5, 48 }, /* SystemBatteryState */ { 11, 48 }, /* ProcessorInformation */ { 12, 24 }, /* SystemPowerInformation */ { -1, -1 } }; int i; /* The 100 is a failsafe limit. */ for (i = 0; powerInfo[i].type != -1 && i < 100; i++ ) { /* Query the info for this ID */ dwResult = pNtPowerInformation (powerInfo[i].type, NULL, 0, buffer, PERFORMANCE_BUFFER_SIZE - 2048); if (dwResult != ERROR_SUCCESS) continue; if (debug_me) log_debug ("rndw32#slow_gatherer: %u bytes from powerinfo %d\n", powerInfo[i].size, i); (*add) (buffer, powerInfo[i].size, requester); no_results++; } gcry_assert (i < 100); } gcry_free (buffer); /* We couldn't get enough results from the kernel, fall back to the somewhat troublesome registry poll. */ if (no_results < 15) registry_poll (add, requester); }
int uwin_getkeys(const char* release, char* root, size_t rootsize, char* home, size_t homesize) { int r = 0; HKEY kh; DWORD size; char key[MAX_PATH]; char rel[MAX_PATH]; if (!release) { if (uwin_release(0, 0, rel, sizeof(rel))) return -1; release = (const char*)rel; } if (*release) { sprintf(key, "%s\\%s\\%s", UWIN_KEY, release, UWIN_KEY_INST); if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE|KEY_WOW64_64KEY, &kh) && RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE|KEY_WOW64_32KEY, &kh)) { sprintf(key, "%s%s\\%s", UWIN_KEY, release, UWIN_KEY_INST); if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE|KEY_WOW64_32KEY, &kh)) kh = 0; } } else kh = 0; if (root) { if (!kh) size = 0; else { size = rootsize - 1; if (RegQueryValueEx(kh, UWIN_KEY_ROOT, 0, 0, root, &size)) size = 0; } size = rootsize - 1; if (root[size]) root[size] = 0; if (!root[0]) { if (sizeof(UWIN_DEF_ROOT) > rootsize) r = -1; else strcpy(root, UWIN_DEF_ROOT); } } if (home) { if (!kh) size = 0; else { size = homesize - 1; if (RegQueryValueEx(kh, UWIN_KEY_HOME, 0, 0, home, &size)) size = 0; } if (home[size]) home[size] = 0; if (!home[0]) { if (sizeof(UWIN_DEF_HOME) > homesize) r = -1; else strcpy(home, UWIN_DEF_HOME); } } if (kh) { RegCloseKey(kh); return r; } return -1; }
BOOL Shortcut_FixStartup (LPCTSTR pszLinkName, BOOL fAutoStart) { TCHAR szShortcut[ MAX_PATH + 10 ] = TEXT(""); BOOL bSuccess; HKEY hk; if (RegOpenKey (HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"), &hk) == 0) { DWORD dwSize = sizeof(szShortcut); DWORD dwType = REG_SZ; RegQueryValueEx (hk, TEXT("Common Startup"), NULL, &dwType, (LPBYTE)szShortcut, &dwSize); if (szShortcut[0] == TEXT('\0')) { dwSize = sizeof(szShortcut); dwType = REG_SZ; RegQueryValueEx (hk, TEXT("Startup"), NULL, &dwType, (LPBYTE)szShortcut, &dwSize); } RegCloseKey (hk); } if (szShortcut[0] == TEXT('\0')) { GetWindowsDirectory (szShortcut, MAX_PATH); lstrcat (szShortcut, TEXT("\\Start Menu\\Programs\\Startup")); } lstrcat (szShortcut, TEXT("\\")); lstrcat (szShortcut, pszLinkName); TCHAR szSource[ MAX_PATH ]; GetModuleFileName (GetModuleHandle(NULL), szSource, MAX_PATH); if (fAutoStart) { DWORD code, len, type; TCHAR szParams[ 64 ] = TEXT(AFSCREDS_SHORTCUT_OPTIONS); code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY, 0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &hk); if (code == ERROR_SUCCESS) { len = sizeof(szParams); type = REG_SZ; code = RegQueryValueEx(hk, "AfscredsShortcutParams", NULL, &type, (BYTE *) &szParams, &len); RegCloseKey (hk); } if (code != ERROR_SUCCESS) { code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY, 0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &hk); if (code == ERROR_SUCCESS) { len = sizeof(szParams); type = REG_SZ; code = RegQueryValueEx(hk, "AfscredsShortcutParams", NULL, &type, (BYTE *) &szParams, &len); RegCloseKey (hk); } } bSuccess = Shortcut_Create (szShortcut, szSource, "Autostart Authentication Agent", szParams); } else // (!g.fAutoStart) { bSuccess = DeleteFile (szShortcut); } return bSuccess; }
bool DebugFrontend::AttachDebuggerToHost() { if (m_processId != 0) { // Get the default debugger on the machine. std::string commandLine; HKEY key; if (RegOpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\AEDEBUG", &key) == ERROR_SUCCESS) { DWORD type; DWORD size; if (RegQueryValueEx(key, "Debugger", NULL, &type, NULL, &size) == ERROR_SUCCESS && type == REG_SZ) { char* buffer = new char[size + 1]; RegQueryValueEx(key, "Debugger", NULL, &type, reinterpret_cast<PBYTE>(buffer), &size); commandLine = buffer; delete [] buffer; } RegCloseKey(key); } if (!commandLine.empty()) { // Substitute the process id into the command line. char processId[10]; sprintf(processId, "%d", m_processId); ReplaceAll(commandLine, "%ld", processId); // Invoke the command line. STARTUPINFO startUpInfo = { 0 }; startUpInfo.cb = sizeof(startUpInfo); PROCESS_INFORMATION processInfo; if (!CreateProcess(NULL, (LPTSTR)((LPCTSTR)(commandLine.c_str())), NULL, NULL, TRUE, 0, NULL, NULL, &startUpInfo, &processInfo)) { return false; } CloseHandle(processInfo.hProcess); return true; } } return false; }
void RegisterExtension(const EXTENSION_INFO *pExtensionInfo, BOOL fOpenWith) { HKEY hExtensionKey; DWORD dwDisposition; /* the actual link used */ TCHAR *pExtensionLinkName = NULL; if (RegCreateKeyEx(HKEY_CLASSES_ROOT, pExtensionInfo->pExtensionKeyName,0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hExtensionKey, &dwDisposition)==ERROR_SUCCESS) { /* create if it doesn't exist, otherwise just opens it */ BOOL fExists = FALSE; if (dwDisposition==REG_OPENED_EXISTING_KEY) { /* if friendly then use existing key; don't replace with our own */ if (fOpenWith) { DWORD dwLength; DWORD dwType; dwLength = 0; /* query existing link */ if (RegQueryValueEx(hExtensionKey, NULL, NULL, &dwType, NULL, &dwLength)==ERROR_SUCCESS) { pExtensionLinkName = malloc(dwLength); if (pExtensionLinkName) { DWORD dwType; RegQueryValueEx(hExtensionKey, NULL, NULL, &dwType, (BYTE *)pExtensionLinkName, &dwLength); fExists = TRUE; } } } } if (!fExists) { DWORD nLen = StringLengthBytes(pExtensionInfo->pExtensionLinkKeyName); pExtensionLinkName = malloc(nLen); if (pExtensionLinkName) { memcpy(pExtensionLinkName, pExtensionInfo->pExtensionLinkKeyName,nLen); } /* replace value of default key */ RegSetValueEx(hExtensionKey, NULL, 0, REG_SZ, (const BYTE *)pExtensionLinkName, nLen); } RegCloseKey(hExtensionKey); } if (pExtensionLinkName!=NULL) { DWORD dwDisposition; /* create it if it doesn't exist, otherwise open it */ if (RegCreateKeyEx(HKEY_CLASSES_ROOT, pExtensionLinkName, 0, _T(""),REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,NULL, &hExtensionKey,&dwDisposition)==ERROR_SUCCESS) { if (!fOpenWith) { /* if not friendly, replace description and icon for our own */ HKEY hDefaultIcon; TCHAR Buffer[256]; /* set the description of the extension */ RegSetValueEx(hExtensionKey, NULL, 0, REG_SZ, (const BYTE *)pExtensionInfo->pExtensionDescription, StringLengthBytes(pExtensionInfo->pExtensionDescription)); _stprintf(Buffer,_T("\"%s\",-%d"),pExtensionInfo->pApplicationPath,pExtensionInfo->nIconIndex); if (RegCreateKeyEx(hExtensionKey,_T("DefaultIcon"), 0, _T(""),REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hDefaultIcon, &dwDisposition)==ERROR_SUCCESS) { RegSetValueEx(hDefaultIcon, NULL, 0, REG_SZ, (const BYTE *)Buffer, StringLengthBytes(Buffer)); RegCloseKey(hDefaultIcon); } } { HKEY hShellKey; if (RegCreateKeyEx(hExtensionKey,_T("shell"), 0, _T(""), REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS, NULL, &hShellKey, &dwDisposition)==ERROR_SUCCESS) { HKEY hOpenKey; const TCHAR *sKey; /* if not friendly replace the default "open" with our own */ /* if friendly, create a open with */ if (!fOpenWith) { sKey = _T("open"); } else { sKey = OpenWithString; } if (RegCreateKeyEx(hShellKey,sKey, 0, _T(""),REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,&hOpenKey, &dwDisposition)==ERROR_SUCCESS) { RegisterExtension_OpenKeySetup(pExtensionInfo,hOpenKey, fOpenWith); RegCloseKey(hOpenKey); } RegCloseKey(hShellKey); } } RegCloseKey(hExtensionKey); } free(pExtensionLinkName); } }
void GetClassServerPath( REFCLSID clsid, CString& strServerPath ) { HKEY hKey; HKEY hServerKey; OLECHAR szCLSID[64]; LONG nResult; ULONG nBytes; DWORD dwType; LPTSTR pszServerPath; StringFromGUID2( clsid, szCLSID, 64 ); hKey = NULL; hServerKey = NULL; try { nResult = RegOpenKeyEx( HKEY_CLASSES_ROOT, CString( "CLSID\\" )+CString( szCLSID ), 0, KEY_READ, &hKey ); if( nResult != ERROR_SUCCESS ) { throw( E_FAIL ); } nResult = RegOpenKeyEx( hKey, _T( "InprocServer32" ), 0, KEY_READ, &hServerKey ); if( nResult != ERROR_SUCCESS ) { nResult = RegOpenKeyEx( hKey, _T( "InprocHandler32" ), 0, KEY_READ, &hServerKey ); if( nResult != ERROR_SUCCESS ) { nResult = RegOpenKeyEx( hKey, _T( "LocalServer32" ), 0, KEY_READ, &hServerKey ); if( nResult != ERROR_SUCCESS ) { throw( E_FAIL ); } } } nBytes = 0; nResult = RegQueryValueEx( hServerKey, NULL, NULL, &dwType, NULL, &nBytes ); if( (nResult != ERROR_SUCCESS) || (dwType != REG_SZ) ) { throw( E_FAIL ); } pszServerPath = LPTSTR( _alloca( nBytes ) ); nResult = RegQueryValueEx( hServerKey, NULL, NULL, &dwType, LPBYTE( pszServerPath ), &nBytes ); if( (nResult != ERROR_SUCCESS) || (dwType != REG_SZ) ) { throw( E_FAIL ); } strServerPath = pszServerPath; RegCloseKey( hKey ); hKey = NULL; RegCloseKey( hServerKey ); hServerKey = NULL; } catch( HRESULT ) { if( hKey != NULL ) { RegCloseKey( hKey ); } if( hServerKey != NULL ) { RegCloseKey( hServerKey ); } LOAD_STRING_FROM_RESOURCE( strServerPath, IDS_SERVERNOTFOUND ); return; } }
CFilePath CFilePath::FromRegistry( HKEY hBaseKey, LPCTSTR psSubKey, LPCTSTR psName) { SetLastError(0); CAutoHKEY Key; DWORD dwRetCode = RegOpenKeyEx(hBaseKey, psSubKey, 0, KEY_READ, Key.OutArg()); if (dwRetCode != ERROR_SUCCESS) { SetLastError(dwRetCode); return CFilePath(); } DWORD dwLen = 256; DWORD dwType = 0; CString sPath; do { CStringLock Buffer(sPath, dwLen); if (!Buffer) { SetLastError(ERROR_OUTOFMEMORY); return CFilePath(); } DWORD dwSize = (dwLen + 1) * sizeof(TCHAR); dwRetCode = RegQueryValueEx(Key, psName, NULL, &dwType, (LPBYTE) Buffer.operator LPTSTR(), &dwSize); if (dwRetCode == ERROR_SUCCESS) { if (dwType != REG_SZ && dwType != REG_EXPAND_SZ) { SetLastError(ERROR_INVALID_DATA); return CFilePath(); } break; } if (dwRetCode == ERROR_MORE_DATA) { dwLen = (dwSize + sizeof(TCHAR) - 1) / sizeof(TCHAR); continue; } SetLastError(dwRetCode); return CFilePath(); } while(1); DWORD dwCleanup = epc_Default; if (dwType == REG_SZ) dwCleanup &= ~epcExpandEnvStrings; else dwCleanup |= epcExpandEnvStrings; return CFilePath(sPath, dwCleanup); }
__declspec(dllexport) void download (HWND parent, int string_size, char *variables, nsis_stack_t **stacktop) { char buf[1024]; char url[1024]; char filename[1024]; static char proxy[1024]; BOOL bSuccess=FALSE; int timeout_ms=30000; int getieproxy=1; int manualproxy=0; int translation_version; char *error=NULL; // translation version 2 & 1 static char szDownloading[1024]; // "Downloading %s" static char szConnecting[1024]; // "Connecting ..." static char szSecond[1024]; // " (1 second remaining)" for v2 // "second" for v1 static char szMinute[1024]; // " (1 minute remaining)" for v2 // "minute" for v1 static char szHour[1024]; // " (1 hour remaining)" for v2 // "hour" for v1 static char szProgress[1024]; // "%skB (%d%%) of %skB at %u.%01ukB/s" for v2 // "%dkB (%d%%) of %dkB at %d.%01dkB/s" for v1 // translation version 2 only static char szSeconds[1024]; // " (%u seconds remaining)" static char szMinutes[1024]; // " (%u minutes remaining)" static char szHours[1024]; // " (%u hours remaining)" // translation version 1 only static char szPlural[1024]; // "s"; static char szRemaining[1024]; // " (%d %s%s remaining)"; EXDLL_INIT(); popstring(url); if (!lstrcmpi(url, "/TRANSLATE2")) { popstring(szDownloading); popstring(szConnecting); popstring(szSecond); popstring(szMinute); popstring(szHour); popstring(szSeconds); popstring(szMinutes); popstring(szHours); popstring(szProgress); popstring(url); translation_version=2; } else if (!lstrcmpi(url, "/TRANSLATE")) { popstring(szDownloading); popstring(szConnecting); popstring(szSecond); popstring(szMinute); popstring(szHour); popstring(szPlural); popstring(szProgress); popstring(szRemaining); popstring(url); translation_version=1; } else { lstrcpy(szDownloading, "Downloading %s"); lstrcpy(szConnecting, "Connecting ..."); lstrcpy(szSecond, " (1 second remaining)"); lstrcpy(szMinute, " (1 minute remaining)"); lstrcpy(szHour, " (1 hour remaining)"); lstrcpy(szSeconds, " (%u seconds remaining)"); lstrcpy(szMinutes, " (%u minutes remaining)"); lstrcpy(szHours, " (%u hours remaining)"); lstrcpy(szProgress, "%skB (%d%%) of %skB at %u.%01ukB/s"); translation_version=2; } lstrcpyn(buf, url, 10); if (!lstrcmpi(buf, "/TIMEOUT=")) { timeout_ms=my_atoi(url+9); popstring(url); } if (!lstrcmpi(url, "/PROXY")) { getieproxy=0; manualproxy=1; popstring(proxy); popstring(url); } if (!lstrcmpi(url, "/NOIEPROXY")) { getieproxy=0; popstring(url); } popstring(filename); HANDLE hFile = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL); if (hFile == INVALID_HANDLE_VALUE) { wsprintf(buf, "Unable to open %s", filename); error = buf; } else { if (parent) { uMsgCreate = RegisterWindowMessage("nsisdl create"); lpWndProcOld = (void *)SetWindowLong(parent,GWL_WNDPROC,(long)ParentWndProc); SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent); // set initial text char *p = filename; while (*p) p++; while (*p != '\\' && p != filename) p = CharPrev(filename, p); wsprintf(buf, szDownloading, p != filename ? p + 1 : p); SetDlgItemText(childwnd, 1006, buf); SetWindowText(g_hwndStatic, szConnecting); } { WSADATA wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); JNL_HTTPGet *get = 0; static char main_buf[8192]; char *buf=main_buf; char *p=NULL; HKEY hKey; if (getieproxy && RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS) { DWORD l = 4; DWORD t; DWORD v; if (RegQueryValueEx(hKey,"ProxyEnable",NULL,&t,(unsigned char *)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v) { l=8192; if (RegQueryValueEx(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ) { p=strstr(buf,"http="); if (!p) p=buf; else { p+=5; } char *tp=strstr(p,";"); if (tp) *tp=0; char *p2=strstr(p,"="); if (p2) p=0; // we found the wrong proxy } } buf[8192-1]=0; RegCloseKey(hKey); } if (manualproxy == 1) { p = proxy; } DWORD start_time=GetTickCount(); get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL); int st; int has_printed_headers = 0; __int64 cl = 0; int len; __int64 sofar = 0; DWORD last_recv_time=start_time; get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)"); get->addheader ("Accept: */*"); get->connect (url); while (1) { if (g_cancelled) error = "cancel"; if (error) { if (parent) { SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent); SetWindowLong(parent, GWL_WNDPROC, (long)lpWndProcOld); } break; } st = get->run (); if (st == -1) { lstrcpyn(url, get->geterrorstr(), sizeof(url)); error = url; } else if (st == 1) { if (sofar < cl || get->get_status () != 2) error="download incomplete"; else { bSuccess=TRUE; error = "success"; } } else { if (get->get_status () == 0) { // progressFunc ("Connecting ...", 0); if (last_recv_time+timeout_ms < GetTickCount()) error = "Timed out on connecting."; else Sleep(10); // don't busy-loop while connecting } else if (get->get_status () == 1) { progress_callback("Reading headers", 0); if (last_recv_time+timeout_ms < GetTickCount()) error = "Timed out on getting headers."; else Sleep(10); // don't busy-loop while reading headers } else if (get->get_status () == 2) { if (! has_printed_headers) { has_printed_headers = 1; last_recv_time=GetTickCount(); cl = get->content_length (); if (cl == 0) error = "Server did not specify content length."; else if (g_hwndProgressBar) { SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000)); g_file_size = cl; } } int data_downloaded = 0; while ((len = get->bytes_available ()) > 0) { data_downloaded++; if (len > 8192) len = 8192; len = get->get_bytes (buf, len); if (len > 0) { last_recv_time=GetTickCount(); DWORD dw; WriteFile(hFile,buf,len,&dw,NULL); sofar += len; int time_sofar=(GetTickCount()-start_time)/1000; int bps = (int)(sofar/(time_sofar?time_sofar:1)); int remain = MulDiv64(time_sofar, cl, sofar) - time_sofar; if (translation_version == 2) { char *rtext=remain==1?szSecond:szSeconds;; if (remain >= 60) { remain/=60; rtext=remain==1?szMinute:szMinutes; if (remain >= 60) { remain/=60; rtext=remain==1?szHour:szHours; } } char sofar_str[128]; char cl_str[128]; myitoa64(sofar/1024, sofar_str); myitoa64(cl/1024, cl_str); wsprintf (buf, szProgress, //%skB (%d%%) of %skB @ %u.%01ukB/s sofar_str, MulDiv64(100, sofar, cl), cl_str, bps/1024,((bps*10)/1024)%10 ); if (remain) wsprintf(buf+lstrlen(buf),rtext, remain ); } else if (translation_version == 1) { char *rtext=szSecond; if (remain >= 60) { remain/=60; rtext=szMinute; if (remain >= 60) { remain/=60; rtext=szHour; } } wsprintf (buf, szProgress, //%dkB (%d%%) of %dkB @ %d.%01dkB/s int(sofar/1024), MulDiv64(100, sofar, cl), int(cl/1024), bps/1024,((bps*10)/1024)%10 ); if (remain) wsprintf(buf+lstrlen(buf),szRemaining, remain, rtext, remain==1?"":szPlural ); } progress_callback(buf, sofar); } else { if (sofar < cl) error = "Server aborted."; } } if (GetTickCount() > last_recv_time+timeout_ms) { if (sofar != cl) { error = "Downloading timed out."; } else { // workaround for bug #1713562 // buggy servers that wait for the client to close the connection. // another solution would be manually stopping when cl == sofar, // but then buggy servers that return wrong content-length will fail. bSuccess = TRUE; error = "success"; } } else if (!data_downloaded) Sleep(10); } else { error = "Bad response status."; } } } // Clean up the connection then release winsock if (get) delete get; WSACleanup(); } CloseHandle(hFile); } if (g_cancelled || !bSuccess) { DeleteFile(filename); } pushstring(error); }
/** get uname for windows **/ char *getuname() { int ret_size = OS_SIZE_1024 -2; char *ret = NULL; char os_v[128 +1]; typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO); typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); /* Extracted from ms web site * http://msdn.microsoft.com/library/en-us/sysinfo/base/getting_the_system_version.asp */ OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; PGPI pGPI; BOOL bOsVersionInfoEx; DWORD dwType; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(!(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx((OSVERSIONINFO *)&osvi)) return(NULL); } /* Allocating the memory */ os_calloc(OS_SIZE_1024 +1, sizeof(char), ret); ret[OS_SIZE_1024] = '\0'; switch(osvi.dwPlatformId) { /* Test for the Windows NT product family. */ case VER_PLATFORM_WIN32_NT: if(osvi.dwMajorVersion == 6) { if(osvi.dwMinorVersion == 0) { if(osvi.wProductType == VER_NT_WORKSTATION ) strncat(ret, "Microsoft Windows Vista ", ret_size -1); else { strncat(ret, "Microsoft Windows Server 2008 ", ret_size -1); } } else if(osvi.dwMinorVersion == 1) { if(osvi.wProductType == VER_NT_WORKSTATION ) strncat(ret, "Microsoft Windows 7 ", ret_size -1); else { strncat(ret, "Microsoft Windows Server 2008 R2 ", ret_size -1); } } ret_size-=strlen(ret) +1; /* Getting product version. */ pGPI = (PGPI) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); pGPI( 6, 0, 0, 0, &dwType); switch(dwType) { case PRODUCT_UNLICENSED: strncat(ret, PRODUCT_UNLICENSED_C, ret_size -1); break; case PRODUCT_BUSINESS: strncat(ret, PRODUCT_BUSINESS_C, ret_size -1); break; case PRODUCT_BUSINESS_N: strncat(ret, PRODUCT_BUSINESS_N_C, ret_size -1); break; case PRODUCT_CLUSTER_SERVER: strncat(ret, PRODUCT_CLUSTER_SERVER_C, ret_size -1); break; case PRODUCT_DATACENTER_SERVER: strncat(ret, PRODUCT_DATACENTER_SERVER_C, ret_size -1); break; case PRODUCT_DATACENTER_SERVER_CORE: strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_C, ret_size -1); break; case PRODUCT_DATACENTER_SERVER_CORE_V: strncat(ret, PRODUCT_DATACENTER_SERVER_CORE_V_C, ret_size -1); break; case PRODUCT_DATACENTER_SERVER_V: strncat(ret, PRODUCT_DATACENTER_SERVER_V_C, ret_size -1); break; case PRODUCT_ENTERPRISE: strncat(ret, PRODUCT_ENTERPRISE_C, ret_size -1); break; case PRODUCT_ENTERPRISE_N: strncat(ret, PRODUCT_ENTERPRISE_N_C, ret_size -1); break; case PRODUCT_ENTERPRISE_SERVER: strncat(ret, PRODUCT_ENTERPRISE_SERVER_C, ret_size -1); break; case PRODUCT_ENTERPRISE_SERVER_CORE: strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_C, ret_size -1); break; case PRODUCT_ENTERPRISE_SERVER_CORE_V: strncat(ret, PRODUCT_ENTERPRISE_SERVER_CORE_V_C, ret_size -1); break; case PRODUCT_ENTERPRISE_SERVER_IA64: strncat(ret, PRODUCT_ENTERPRISE_SERVER_IA64_C, ret_size -1); break; case PRODUCT_ENTERPRISE_SERVER_V: strncat(ret, PRODUCT_ENTERPRISE_SERVER_V_C, ret_size -1); break; case PRODUCT_HOME_BASIC: strncat(ret, PRODUCT_HOME_BASIC_C, ret_size -1); break; case PRODUCT_HOME_BASIC_N: strncat(ret, PRODUCT_HOME_BASIC_N_C, ret_size -1); break; case PRODUCT_HOME_PREMIUM: strncat(ret, PRODUCT_HOME_PREMIUM_C, ret_size -1); break; case PRODUCT_HOME_PREMIUM_N: strncat(ret, PRODUCT_HOME_PREMIUM_N_C, ret_size -1); break; case PRODUCT_HOME_SERVER: strncat(ret, PRODUCT_HOME_SERVER_C, ret_size -1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT: strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT_C, ret_size -1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING: strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING_C, ret_size -1); break; case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY: strncat(ret, PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY_C, ret_size -1); break; case PRODUCT_SERVER_FOR_SMALLBUSINESS: strncat(ret, PRODUCT_SERVER_FOR_SMALLBUSINESS_C, ret_size -1); break; case PRODUCT_SMALLBUSINESS_SERVER: strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_C, ret_size -1); break; case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: strncat(ret, PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_C, ret_size -1); break; case PRODUCT_STANDARD_SERVER: strncat(ret, PRODUCT_STANDARD_SERVER_C, ret_size -1); break; case PRODUCT_STANDARD_SERVER_CORE: strncat(ret, PRODUCT_STANDARD_SERVER_CORE_C, ret_size -1); break; case PRODUCT_STANDARD_SERVER_CORE_V: strncat(ret, PRODUCT_STANDARD_SERVER_CORE_V_C, ret_size -1); break; case PRODUCT_STANDARD_SERVER_V: strncat(ret, PRODUCT_STANDARD_SERVER_V_C, ret_size -1); break; case PRODUCT_STARTER: strncat(ret, PRODUCT_STARTER_C, ret_size -1); break; case PRODUCT_STORAGE_ENTERPRISE_SERVER: strncat(ret, PRODUCT_STORAGE_ENTERPRISE_SERVER_C, ret_size -1); break; case PRODUCT_STORAGE_EXPRESS_SERVER: strncat(ret, PRODUCT_STORAGE_EXPRESS_SERVER_C, ret_size -1); break; case PRODUCT_STORAGE_STANDARD_SERVER: strncat(ret, PRODUCT_STORAGE_STANDARD_SERVER_C, ret_size -1); break; case PRODUCT_STORAGE_WORKGROUP_SERVER: strncat(ret, PRODUCT_STORAGE_WORKGROUP_SERVER_C, ret_size -1); break; case PRODUCT_ULTIMATE: strncat(ret, PRODUCT_ULTIMATE_C, ret_size -1); break; case PRODUCT_ULTIMATE_N: strncat(ret, PRODUCT_ULTIMATE_N_C, ret_size -1); break; case PRODUCT_WEB_SERVER: strncat(ret, PRODUCT_WEB_SERVER_C, ret_size -1); break; case PRODUCT_WEB_SERVER_CORE: strncat(ret, PRODUCT_WEB_SERVER_CORE_C, ret_size -1); break; } ret_size-=strlen(ret) +1; } else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { pGNSI = (PGNSI) GetProcAddress( GetModuleHandle("kernel32.dll"), "GetNativeSystemInfo"); if(NULL != pGNSI) pGNSI(&si); if( GetSystemMetrics(89) ) strncat(ret, "Microsoft Windows Server 2003 R2 ", ret_size -1); else if(osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) { strncat(ret, "Microsoft Windows XP Professional x64 Edition ", ret_size -1 ); } else { strncat(ret, "Microsoft Windows Server 2003, ",ret_size-1); } ret_size-=strlen(ret) +1; } else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) { strncat(ret, "Microsoft Windows XP ", ret_size -1); ret_size-=strlen(ret) +1; } else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { strncat(ret, "Microsoft Windows 2000 ", ret_size -1); ret_size-=strlen(ret) +1; } else if (osvi.dwMajorVersion <= 4) { strncat(ret, "Microsoft Windows NT ", ret_size -1); ret_size-=strlen(ret) +1; } else { strncat(ret, "Microsoft Windows Unknown ", ret_size -1); ret_size-=strlen(ret) +1; } /* Test for specific product on Windows NT 4.0 SP6 and later. */ if(bOsVersionInfoEx) { /* Test for the workstation type. */ if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture!=PROCESSOR_ARCHITECTURE_AMD64) { if( osvi.dwMajorVersion == 4 ) strncat(ret, "Workstation 4.0 ", ret_size -1); else if( osvi.wSuiteMask & VER_SUITE_PERSONAL ) strncat(ret, "Home Edition ", ret_size -1); else strncat(ret, "Professional ",ret_size -1); /* Fixing size */ ret_size-=strlen(ret) +1; } /* Test for the server type. */ else if( osvi.wProductType == VER_NT_SERVER || osvi.wProductType == VER_NT_DOMAIN_CONTROLLER ) { if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==2) { if (si.wProcessorArchitecture== PROCESSOR_ARCHITECTURE_IA64 ) { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter Edition for Itanium-based Systems ", ret_size -1); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Enterprise Edition for Itanium-based Systems ", ret_size -1); ret_size-=strlen(ret) +1; } else if ( si.wProcessorArchitecture== PROCESSOR_ARCHITECTURE_AMD64 ) { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter x64 Edition ", ret_size -1 ); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Enterprise x64 Edition ", ret_size -1 ); else strncat(ret, "Standard x64 Edition ", ret_size -1 ); ret_size-=strlen(ret) +1; } else { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter Edition ", ret_size -1 ); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret,"Enterprise Edition ",ret_size -1); else if ( osvi.wSuiteMask == VER_SUITE_BLADE ) strncat(ret,"Web Edition ",ret_size -1 ); else strncat(ret, "Standard Edition ",ret_size -1); ret_size-=strlen(ret) +1; } } else if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==0) { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) strncat(ret, "Datacenter Server ",ret_size -1); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Advanced Server ",ret_size -1 ); else strncat(ret, "Server ",ret_size -1); ret_size-=strlen(ret) +1; } else if(osvi.dwMajorVersion <= 4) /* Windows NT 4.0 */ { if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Server 4.0, Enterprise Edition ", ret_size -1 ); else strncat(ret, "Server 4.0 ",ret_size -1); ret_size-=strlen(ret) +1; } } } /* Test for specific product on Windows NT 4.0 SP5 and earlier */ else { HKEY hKey; char szProductType[81]; DWORD dwBufLen=80; LONG lRet; lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey ); if(lRet == ERROR_SUCCESS) { char __wv[32]; lRet = RegQueryValueEx( hKey, "ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen); RegCloseKey( hKey ); if((lRet == ERROR_SUCCESS) && (dwBufLen < 80) ) { if (lstrcmpi( "WINNT", szProductType) == 0 ) strncat(ret, "Workstation ",ret_size -1); else if(lstrcmpi( "LANMANNT", szProductType) == 0 ) strncat(ret, "Server ",ret_size -1); else if(lstrcmpi( "SERVERNT", szProductType) == 0 ) strncat(ret, "Advanced Server " ,ret_size -1); ret_size-=strlen(ret) +1; memset(__wv, '\0', 32); snprintf(__wv, 31, "%d.%d ", (int)osvi.dwMajorVersion, (int)osvi.dwMinorVersion); strncat(ret, __wv, ret_size -1); ret_size-=strlen(__wv) +1; } } } /* Display service pack (if any) and build number. */ if( osvi.dwMajorVersion == 4 && lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 ) { HKEY hKey; LONG lRet; char __wp[64]; memset(__wp, '\0', 64); /* Test for SP6 versus SP6a. */ lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009", 0, KEY_QUERY_VALUE, &hKey ); if( lRet == ERROR_SUCCESS ) snprintf(__wp, 63, "Service Pack 6a (Build %d)", (int)osvi.dwBuildNumber & 0xFFFF ); else /* Windows NT 4.0 prior to SP6a */ { snprintf(__wp, 63, "%s (Build %d)", osvi.szCSDVersion, (int)osvi.dwBuildNumber & 0xFFFF); } strncat(ret, __wp, ret_size -1); ret_size-=strlen(__wp) +1; RegCloseKey( hKey ); } else { char __wp[64]; memset(__wp, '\0', 64); snprintf(__wp, 63, "%s (Build %d)", osvi.szCSDVersion, (int)osvi.dwBuildNumber & 0xFFFF); strncat(ret, __wp, ret_size -1); ret_size-=strlen(__wp) +1; } break; /* Test for the Windows Me/98/95. */ case VER_PLATFORM_WIN32_WINDOWS: if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { strncat(ret, "Microsoft Windows 95 ", ret_size -1); ret_size-=strlen(ret) +1; } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { strncat(ret, "Microsoft Windows 98 ", ret_size -1); ret_size-=strlen(ret) +1; } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { strncat(ret, "Microsoft Windows Millennium Edition", ret_size -1); ret_size-=strlen(ret) +1; } break; case VER_PLATFORM_WIN32s: strncat(ret, "Microsoft Win32s", ret_size -1); ret_size-=strlen(ret) +1; break; } /* Adding ossec version */ snprintf(os_v, 128, " - %s %s", __name, __version); strncat(ret, os_v, ret_size -1); /* Returning system information */ return(ret); }
bool wxRegKey::QueryValue(const wxString& szValue, wxString& strValue, bool WXUNUSED_IN_WINCE(raw)) const { if ( CONST_CAST Open(Read) ) { // first get the type and size of the data DWORD dwType=REG_NONE, dwSize=0; m_dwLastError = RegQueryValueEx((HKEY) m_hKey, RegValueStr(szValue), RESERVED, &dwType, NULL, &dwSize); if ( m_dwLastError == ERROR_SUCCESS ) { if ( !dwSize ) { // must treat this case specially as GetWriteBuf() doesn't like // being called with 0 size strValue.Empty(); } else { m_dwLastError = RegQueryValueEx((HKEY) m_hKey, RegValueStr(szValue), RESERVED, &dwType, (RegString)(wxChar*)wxStringBuffer(strValue, dwSize), &dwSize); // expand the var expansions in the string unless disabled #ifndef __WXWINCE__ if ( (dwType == REG_EXPAND_SZ) && !raw ) { DWORD dwExpSize = ::ExpandEnvironmentStrings(strValue.t_str(), NULL, 0); bool ok = dwExpSize != 0; if ( ok ) { wxString strExpValue; ok = ::ExpandEnvironmentStrings(strValue.t_str(), wxStringBuffer(strExpValue, dwExpSize), dwExpSize ) != 0; strValue = strExpValue; } if ( !ok ) { wxLogLastError(wxT("ExpandEnvironmentStrings")); } } #endif // __WXWINCE__ } if ( m_dwLastError == ERROR_SUCCESS ) { // check that it was the right type wxASSERT_MSG( !IsNumericValue(szValue), wxT("Type mismatch in wxRegKey::QueryValue().") ); return true; } } } wxLogSysError(m_dwLastError, _("Can't read value of '%s'"), GetFullName(this, szValue)); return false; }