/*********************************************************************** * register_decoders */ static HRESULT register_decoders(struct regsvr_decoder const *list) { LONG res = ERROR_SUCCESS; HKEY coclass_key; WCHAR buf[39]; HKEY decoders_key; HKEY instance_key; res = RegCreateKeyExW(HKEY_CLASSES_ROOT, clsid_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &coclass_key, NULL); if (res == ERROR_SUCCESS) { StringFromGUID2(&CATID_WICBitmapDecoders, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &decoders_key, NULL); if (res == ERROR_SUCCESS) { res = RegCreateKeyExW(decoders_key, instance_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &instance_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; } if (res != ERROR_SUCCESS) RegCloseKey(coclass_key); } if (res != ERROR_SUCCESS) goto error_return; for (; res == ERROR_SUCCESS && list->clsid; ++list) { HKEY clsid_key; HKEY instance_clsid_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &clsid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(instance_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &instance_clsid_key, NULL); if (res == ERROR_SUCCESS) { res = RegSetValueExW(instance_clsid_key, clsid_valuename, 0, REG_SZ, (CONST BYTE*)(buf), 78); RegCloseKey(instance_clsid_key); } if (res != ERROR_SUCCESS) goto error_close_clsid_key; if (list->author) { res = RegSetValueExA(clsid_key, author_valuename, 0, REG_SZ, (CONST BYTE*)(list->author), strlen(list->author) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->friendlyname) { res = RegSetValueExA(clsid_key, friendlyname_valuename, 0, REG_SZ, (CONST BYTE*)(list->friendlyname), strlen(list->friendlyname) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->vendor) { StringFromGUID2(list->vendor, buf, 39); res = RegSetValueExW(clsid_key, vendor_valuename, 0, REG_SZ, (CONST BYTE*)(buf), 78); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->version) { res = RegSetValueExA(clsid_key, version_valuename, 0, REG_SZ, (CONST BYTE*)(list->version), strlen(list->version) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->mimetypes) { res = RegSetValueExA(clsid_key, mimetypes_valuename, 0, REG_SZ, (CONST BYTE*)(list->mimetypes), strlen(list->mimetypes) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->extensions) { res = RegSetValueExA(clsid_key, extensions_valuename, 0, REG_SZ, (CONST BYTE*)(list->extensions), strlen(list->extensions) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->formats) { HKEY formats_key; GUID const * const *format; res = RegCreateKeyExW(clsid_key, formats_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &formats_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; for (format=list->formats; *format; ++format) { HKEY format_key; StringFromGUID2(*format, buf, 39); res = RegCreateKeyExW(formats_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &format_key, NULL); if (res != ERROR_SUCCESS) break; RegCloseKey(format_key); } RegCloseKey(formats_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->patterns) { HKEY patterns_key; int i; res = RegCreateKeyExW(clsid_key, patterns_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &patterns_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; for (i=0; list->patterns[i].length; i++) { HKEY pattern_key; static const WCHAR int_format[] = {'%','i',0}; snprintfW(buf, 39, int_format, i); res = RegCreateKeyExW(patterns_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &pattern_key, NULL); if (res != ERROR_SUCCESS) break; res = RegSetValueExA(pattern_key, length_valuename, 0, REG_DWORD, (CONST BYTE*)(&list->patterns[i].length), 4); if (res == ERROR_SUCCESS) res = RegSetValueExA(pattern_key, position_valuename, 0, REG_DWORD, (CONST BYTE*)(&list->patterns[i].position), 4); if (res == ERROR_SUCCESS) res = RegSetValueExA(pattern_key, pattern_valuename, 0, REG_BINARY, list->patterns[i].pattern, list->patterns[i].length); if (res == ERROR_SUCCESS) res = RegSetValueExA(pattern_key, mask_valuename, 0, REG_BINARY, list->patterns[i].mask, list->patterns[i].length); if (res == ERROR_SUCCESS) res = RegSetValueExA(pattern_key, endofstream_valuename, 0, REG_DWORD, (CONST BYTE*)&(list->patterns[i].endofstream), 4); RegCloseKey(pattern_key); } RegCloseKey(patterns_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } error_close_clsid_key: RegCloseKey(clsid_key); } error_close_coclass_key: RegCloseKey(instance_key); RegCloseKey(decoders_key); RegCloseKey(coclass_key); error_return: return res != ERROR_SUCCESS ? HRESULT_FROM_WIN32(res) : S_OK; }
/* return 1 if success, return 0 if fail */ int win9x_service_un_install(int argc, char **argv) { int i, j, all, rc = 1; HKEY hk=0; binkd_win9x_srvlst *srvlst; if (!quiet_flag) AllocTempConsole(); all = win9x_check_name_all(); if (all&&(service_flag != w32_uninstallservice)) { Log((quiet_flag?0:-1), "Invalid service name!%s", quiet_flag?"":"\n"); return 0; } if (!all) { j = win9x_checkservice(service_name); if (service_flag == w32_uninstallservice) j = !j; if (j) { if (!quiet_flag) Log(-1, "Service already %sinstalled...\n", service_flag==w32_installservice?"":"UN"); return 1; } } if (service_flag == w32_uninstallservice) { if (all) { srvlst = win9x_get_services_list(1); if (!srvlst->count) Log(-1, "No installed services.\n"); else for(i=0; i<srvlst->count; i++) if (!win9x_service_do_uninstall(srvlst->names[i], quiet_flag)) rc = 0; win9x_free_services_list(srvlst); } else rc = win9x_service_do_uninstall(service_name, quiet_flag); return rc; } /* service_flag == w32_installservice */ if (RegOpenKey(HKEY_LOCAL_MACHINE, Win9xRegServ, &hk)!=ERROR_SUCCESS) if (RegCreateKey(HKEY_LOCAL_MACHINE, Win9xRegServ, &hk)!=ERROR_SUCCESS) rc = 0; if (rc) { char *sp, *path, *asp, *p; int q = 0, q1, tmplen1, tmplen2, len = 1; /* '\0' */ build_service_arguments(&asp, argv, 1); for(p=asp, tmplen1=0; *p; p++, tmplen1++) if (*p == ' ') { q = 1; } p++; len += tmplen1+1; /* binkd9x path & filename + (' ') */ if (q) { len += 2; } tmplen2 = strlen(Win9xStartService); len += tmplen2; /* Win9xStartService */ for (sp = p; *sp; sp++) { len++; for(q1 = 0; *sp; sp++) { len++; if (!q1 && *sp == ' ') { q1 = 1; len += 2; } } } sp = path = (char *)malloc(len); if (q) { *(sp++) = '"'; } memcpy(sp, asp, tmplen1); sp += tmplen1; if (q) { *(sp++) = '"'; } *(sp++) = ' '; memcpy(sp, Win9xStartService, tmplen2); sp += tmplen2; for(; *p; p++) { *(sp++) = ' '; if (strchr(p, ' ')) { *(sp++) = '"'; q = 1; } else { q = 0; } for(;*p;p++) { *(sp++) = *p; } if (q) { *(sp++) = '"'; } } *sp = '\0'; if (RegSetValueEx(hk, service_name, 0, REG_SZ, (unsigned char *)path, len-1) != ERROR_SUCCESS) rc = 0; free(path); free(asp); RegCloseKey(hk); /* Store current directory */ if (rc) { sp = win9x_make_Win9xRegParm(service_name); if (RegOpenKey(HKEY_LOCAL_MACHINE, sp, &hk)!=ERROR_SUCCESS) if (RegCreateKey(HKEY_LOCAL_MACHINE, sp, &hk)!=ERROR_SUCCESS) rc = 0; if (rc) { j = GetCurrentDirectory(0, NULL); path = (char *)malloc(j); GetCurrentDirectory(j, path); if (RegSetValueEx(hk, Win9xRegParm_Path, 0, REG_SZ, (unsigned char *)path, j-1) != ERROR_SUCCESS) rc = 0; free(path); } free(sp); RegCloseKey(hk); if (!rc) win9x_service_do_uninstall(service_name, 1); /* Rollback */ } } if (!rc) Log((quiet_flag?0:-1), "Unable to store data in registry...%s", quiet_flag?"":"\n"); else { if (win9x_service_start(service_name)) { if (!quiet_flag) Log(-1, "\'%s\' installed and started...\n", service_name); } else { rc = 0; if (!quiet_flag) { Log(-1, "\'%s\' installed...\n", service_name); Log(-1, "Unable to start service!\n"); } } } return rc; }
static void windowsOSVersionString(char stringbuf[], size_t stringbuflen) { /* copy OS version to string buffer in 'uname -a' format */ OSVERSIONINFOEX osVersionInfo; BOOL gotOsVersionInfoEx; char windowsVersion[256] = ""; char hostname[256] = ""; char identifier[256] = ""; DWORD identifierSz = 256; HKEY hKey; ZeroMemory(&osVersionInfo, sizeof(OSVERSIONINFOEX)); osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); gotOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osVersionInfo); if (gotOsVersionInfoEx == FALSE) { GetVersionEx((OSVERSIONINFO *)&osVersionInfo); } switch (osVersionInfo.dwPlatformId) { case VER_PLATFORM_WIN32_NT: if ((osVersionInfo.dwMajorVersion == 5) && (osVersionInfo.dwMinorVersion == 2)) { strcat(windowsVersion, "Server 2003"); } else if ((osVersionInfo.dwMajorVersion == 5) && (osVersionInfo.dwMinorVersion == 1)) { strcat(windowsVersion, "XP"); } else if ((osVersionInfo.dwMajorVersion == 5) && (osVersionInfo.dwMinorVersion == 0)) { strcat(windowsVersion, "2000"); } else if (osVersionInfo.dwMajorVersion <= 4) { strcat(windowsVersion, "NT"); } if (gotOsVersionInfoEx == TRUE) { if (osVersionInfo.wProductType == VER_NT_WORKSTATION) { if (osVersionInfo.dwMajorVersion == 4) { strcat(windowsVersion, " Workstation 4.0"); } else if (osVersionInfo.wSuiteMask & VER_SUITE_PERSONAL) { strcat(windowsVersion, " Home Edition"); } else { strcat(windowsVersion, " Professional"); } } else if (osVersionInfo.wProductType == VER_NT_SERVER) { if ((osVersionInfo.dwMajorVersion == 5) && (osVersionInfo.dwMinorVersion == 2)) { if (osVersionInfo.wSuiteMask & VER_SUITE_DATACENTER) { strcat(windowsVersion, " Datacenter Edition"); } else if (osVersionInfo.wSuiteMask & VER_SUITE_ENTERPRISE) { strcat(windowsVersion, " Enterprise Edition"); } else if (osVersionInfo.wSuiteMask == VER_SUITE_BLADE) { strcat(windowsVersion, " Web Edition"); } else { strcat(windowsVersion, " Standard Edition"); } } else if ((osVersionInfo.dwMajorVersion == 5) && (osVersionInfo.dwMinorVersion == 0)) { if (osVersionInfo.wSuiteMask & VER_SUITE_DATACENTER) { strcat(windowsVersion, " Datacenter Server"); } else if (osVersionInfo.wSuiteMask & VER_SUITE_ENTERPRISE) { strcat(windowsVersion, " Advanced Server"); } else { strcat(windowsVersion, " Server"); } } else { if (osVersionInfo.wSuiteMask & VER_SUITE_ENTERPRISE) { strcat(windowsVersion, " Server 4.0, Enterprise Edition"); } else { strcat(windowsVersion, " Server 4.0"); } } } } else { char productType[80]; DWORD productTypeSz = 80; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, "ProductType", NULL, NULL, (LPBYTE) productType, &productTypeSz) == ERROR_SUCCESS) { char versionStr[10]; if (strcmpi("WINNT", productType) == 0) { strcat(windowsVersion, " Workstation"); } else if (strcmpi("LANMANNT", productType) == 0) { strcat(windowsVersion, " Server"); } else if (strcmpi("SERVERNT", productType) == 0) { strcat(windowsVersion, " Advanced Server"); } sprintf(versionStr, " %d.%d", (int)osVersionInfo.dwMajorVersion, (int)osVersionInfo.dwMinorVersion); strcat(windowsVersion, versionStr); } RegCloseKey(hKey); } } break; case VER_PLATFORM_WIN32_WINDOWS: if ((osVersionInfo.dwMajorVersion == 4) && (osVersionInfo.dwMinorVersion == 90)) { strcat(windowsVersion, "ME"); } else if ((osVersionInfo.dwMajorVersion == 4) && (osVersionInfo.dwMinorVersion == 10)) { strcat(windowsVersion, "98"); if (osVersionInfo.szCSDVersion[1] == 'A') { strcat(windowsVersion, " SE"); } } else if ((osVersionInfo.dwMajorVersion == 4) && (osVersionInfo.dwMinorVersion == 0)) { strcat(windowsVersion, "95"); if ((osVersionInfo.szCSDVersion[1] == 'C') || (osVersionInfo.szCSDVersion[1] == 'B')) { strcat(windowsVersion, " OSR2"); } } break; } gethostname(hostname, sizeof(hostname)); if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) { RegQueryValueEx(hKey, "Identifier", NULL, NULL, (LPBYTE)&identifier, &identifierSz); RegCloseKey(hKey); } /* Output is made to look like results from uname -a */ snprintf(stringbuf, stringbuflen, "Windows %s %d.%d.%d %s %s %s", hostname, (int)osVersionInfo.dwMajorVersion, (int)osVersionInfo.dwMinorVersion, (int)osVersionInfo.dwBuildNumber, osVersionInfo.szCSDVersion, windowsVersion, identifier); }
wfInfo* wf_info_init() { wfInfo* wfi; wfi = (wfInfo*) malloc(sizeof(wfInfo)); ZeroMemory(wfi, sizeof(wfInfo)); if (wfi != NULL) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; DWORD dwValue; wfi->mutex = CreateMutex(NULL, FALSE, NULL); if (wfi->mutex == NULL) { WLog_ERR(TAG, "CreateMutex error: %d", GetLastError()); } wfi->updateSemaphore = CreateSemaphore(NULL, 0, 32, NULL); wfi->updateThread = CreateThread(NULL, 0, wf_update_thread, wfi, CREATE_SUSPENDED, NULL); if (!wfi->updateThread) { WLog_ERR(TAG, "Failed to create update thread"); } wfi->peers = (freerdp_peer**) malloc(sizeof(freerdp_peer*) * WF_INFO_MAXPEERS); memset(wfi->peers, 0, sizeof(freerdp_peer*) * WF_INFO_MAXPEERS); //Set FPS wfi->framesPerSecond = WF_INFO_DEFAULT_FPS; status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, _T("FramesPerSecond"), NULL, &dwType, (BYTE*) &dwValue, &dwSize) == ERROR_SUCCESS) wfi->framesPerSecond = dwValue; } RegCloseKey(hKey); //Set input toggle wfi->input_disabled = FALSE; status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, _T("DisableInput"), NULL, &dwType, (BYTE*) &dwValue, &dwSize) == ERROR_SUCCESS) { if (dwValue != 0) wfi->input_disabled = TRUE; } } RegCloseKey(hKey); } return wfi; }
int parse_command_line(char *cmd) { const char *run_key = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; const char *kernel = "kernel32.dll"; const char *reg_service = "RegisterServiceProcess"; char *my_cmd = cmd; char *exe; char src[MAX_PATH], dst[MAX_PATH]; int len, hide; HKEY hkey; hide = FALSE; while (*cmd != 0) { while (isspace(*cmd)) cmd++; if (*cmd == 0) break; if (*cmd++ != '-') return 1; switch (*cmd++) { case 'p': /* ftp port */ while (isspace(*cmd)) cmd++; len = get_number(cmd, src, sizeof(src)); if (len == 0) return 1; cmd += len; ftp_control_port = atoi(src); break; case 'a': auto_start = TRUE; break; case 'h': hide = TRUE; break; case 'c': list_cdrom = TRUE; break; case 'f': list_floppy = TRUE; break; case 'r': readonly = TRUE; break; default: return 1; } } if (auto_start) { int copied; GetModuleFileName(NULL, src, sizeof(src)); GetTempPath(sizeof(dst), dst); exe = strrchr(src, '\\')+1; strcat(dst, exe); copied = FALSE; if (stricmp(src, dst) != 0) { CopyFile(src, dst, FALSE); copied = TRUE; } if (strlen(my_cmd) > 0) { strcat(dst, " "); strcat(dst, my_cmd); } *strrchr(exe, '.') = 0; RegCreateKey(HKEY_CURRENT_USER, run_key, &hkey); RegSetValueEx(hkey, exe, 0, REG_SZ, dst, strlen(dst)); RegCloseKey(hkey); if (copied) { STARTUPINFO si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_FORCEOFFFEEDBACK; CreateProcess(NULL, dst, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); exit(0); } } if (hide) { DWORD (WINAPI *RegisterServiceProcess)(DWORD, DWORD); RegisterServiceProcess = (void *) GetProcAddress(GetModuleHandle(kernel), reg_service); if (RegisterServiceProcess) RegisterServiceProcess(GetCurrentProcessId(), 1); } return 0; }
main( int argc, char* argv[] ) { DWORD i; HKEY RemoteUsers; HKEY RemoteLocalMachine; LONG Status; if( argc <= 1 ) { printf( "\n******* Examining HKEY_LOCAL_MACHINE on local machine\n\n" ); ExamineKey( HKEY_LOCAL_MACHINE, L"", L"", L"HKEY_LOCAL_MACHINE" ); printf( "\n******* Examining HKEY_USERS on local machine\n\n" ); ExamineKey( HKEY_USERS, L"", L"", L"HKEY_USERS" ); printf( "\n******* Examining HKEY_CLASSES_ROOT on local machine\n\n" ); ExamineKey( HKEY_CLASSES_ROOT, L"", L"", L"HKEY_CLASSES_ROOT" ); printf( "\n******* Examining HKEY_CURRENT_USER on local machine\n\n" ); ExamineKey( HKEY_CURRENT_USER, L"", L"", L"HKEY_CURRENT_USER" ); } else { for( i = 1; i < argc; i++ ) { // // printf( "Machine name = %s \n", argv[ i ] ); // Status = RegConnectRegistry( argv[ i ], HKEY_LOCAL_MACHINE, &RemoteLocalMachine ); if( Status != ERROR_SUCCESS ) { printf( MSG_ERROR_REG_CONNECT_REGISTRY, argv[i], Status ); continue; } Status = RegConnectRegistry( argv[ i ], HKEY_USERS, &RemoteUsers ); if( Status != ERROR_SUCCESS ) { RegCloseKey( RemoteLocalMachine ); printf( MSG_ERROR_REG_CONNECT_REGISTRY, argv[i], Status ); continue; } printf( "\n******* Examining HKEY_LOCAL_MACHINE on %s \n\n", argv[i] ); ExamineKey( RemoteLocalMachine, L"", L"", L"HKEY_LOCAL_MACHINE" ); printf( "\n******* Examining HKEY_USERS on %s \n\n", argv[i] ); ExamineKey( RemoteUsers, L"", L"", L"HKEY_USERS" ); RegCloseKey( RemoteLocalMachine ); RegCloseKey( RemoteUsers ); } } }
int GetRegistryKeys() { TCHAR windows_dir[MAX_PATH]; TCHAR temp_path[MAX_PATH]; TCHAR openvpn_path[MAX_PATH]; TCHAR profile_dir[MAX_PATH]; HKEY regkey; if (!GetWindowsDirectory(windows_dir, _countof(windows_dir))) { /* can't get windows dir */ ShowLocalizedMsg(IDS_ERR_GET_WINDOWS_DIR); return(false); } if (SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, profile_dir) != S_OK) { ShowLocalizedMsg(IDS_ERR_GET_PROFILE_DIR); return(false); } /* Get path to OpenVPN installation. */ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\OpenVPN"), 0, KEY_READ, ®key) != ERROR_SUCCESS) { /* registry key not found */ ShowLocalizedMsg(IDS_ERR_OPEN_REGISTRY); return(false); } if (!GetRegistryValue(regkey, _T(""), openvpn_path, _countof(openvpn_path))) { /* error reading registry value */ ShowLocalizedMsg(IDS_ERR_READING_REGISTRY); RegCloseKey(regkey); return(false); } if (openvpn_path[_tcslen(openvpn_path) - 1] != _T('\\')) _tcscat(openvpn_path, _T("\\")); /* an admin-defined global config dir defined in HKLM\OpenVPN\config_dir */ if (!GetRegistryValue(regkey, _T("config_dir"), o.global_config_dir, _countof(o.global_config_dir))) { /* use default = openvpnpath\config */ _sntprintf_0(o.global_config_dir, _T("%sconfig"), openvpn_path); } if (!GetRegistryValue(regkey, _T("ovpn_admin_group"), o.ovpn_admin_group, _countof(o.ovpn_admin_group))) { _tcsncpy(o.ovpn_admin_group, OVPN_ADMIN_GROUP, _countof(o.ovpn_admin_group)); } RegCloseKey(regkey); /* config_dir in user's profile by default */ _sntprintf_0(temp_path, _T("%s\\OpenVPN\\config"), profile_dir); if (!GetRegKey(_T("config_dir"), o.config_dir, temp_path, _countof(o.config_dir))) return(false); if (!GetRegKey(_T("config_ext"), o.ext_string, _T("ovpn"), _countof(o.ext_string))) return(false); _sntprintf_0(temp_path, _T("%sbin\\openvpn.exe"), openvpn_path); if (!GetRegKey(_T("exe_path"), o.exe_path, temp_path, _countof(o.exe_path))) return(false); _sntprintf_0(temp_path, _T("%s\\OpenVPN\\log"), profile_dir); if (!GetRegKey(_T("log_dir"), o.log_dir, temp_path, _countof(o.log_dir))) return(false); if (!GetRegKey(_T("log_append"), o.append_string, _T("0"), _countof(o.append_string))) return(false); if (!GetRegKey(_T("priority"), o.priority_string, _T("NORMAL_PRIORITY_CLASS"), _countof(o.priority_string))) return(false); _sntprintf_0(temp_path, _T("%s\\system32\\notepad.exe"), windows_dir); if (!GetRegKey(_T("log_viewer"), o.log_viewer, temp_path, _countof(o.log_viewer))) return(false); _sntprintf_0(temp_path, _T("%s\\system32\\notepad.exe"), windows_dir); if (!GetRegKey(_T("editor"), o.editor, temp_path, _countof(o.editor))) return(false); if (!GetRegKey(_T("allow_edit"), o.allow_edit, _T("1"), _countof(o.allow_edit))) return(false); if (!GetRegKey(_T("allow_service"), o.allow_service, _T("0"), _countof(o.allow_service))) return(false); if (!GetRegKey(_T("allow_password"), o.allow_password, _T("1"), _countof(o.allow_password))) return(false); if (!GetRegKey(_T("allow_proxy"), o.allow_proxy, _T("1"), _countof(o.allow_proxy))) return(false); if (!GetRegKey(_T("service_only"), o.service_only, _T("0"), _countof(o.service_only))) return(false); if (!GetRegKey(_T("show_balloon"), o.show_balloon, _T("1"), _countof(o.show_balloon))) return(false); if (!GetRegKey(_T("silent_connection"), o.silent_connection, _T("0"), _countof(o.silent_connection))) return(false); if (!GetRegKey(_T("show_script_window"), o.show_script_window, _T("1"), _countof(o.show_script_window))) return(false); if (!GetRegKey(_T("disconnect_on_suspend"), o.disconnect_on_suspend, _T("0"), _countof(o.disconnect_on_suspend))) return(false); if (!GetRegKey(_T("passphrase_attempts"), o.psw_attempts_string, _T("3"), _countof(o.psw_attempts_string))) return(false); o.psw_attempts = _ttoi(o.psw_attempts_string); if ((o.psw_attempts < 1) || (o.psw_attempts > 9)) { /* 0 <= passphrase_attempts <= 9 */ ShowLocalizedMsg(IDS_ERR_PASSPHRASE_ATTEMPTS); return(false); } if (!GetRegKey(_T("connectscript_timeout"), o.connectscript_timeout_string, _T("15"), _countof(o.connectscript_timeout_string))) return(false); o.connectscript_timeout = _ttoi(o.connectscript_timeout_string); if ((o.connectscript_timeout < 0) || (o.connectscript_timeout > 99)) { /* 0 <= connectscript_timeout <= 99 */ ShowLocalizedMsg(IDS_ERR_CONN_SCRIPT_TIMEOUT); return(false); } if (!GetRegKey(_T("disconnectscript_timeout"), o.disconnectscript_timeout_string, _T("10"), _countof(o.disconnectscript_timeout_string))) return(false); o.disconnectscript_timeout = _ttoi(o.disconnectscript_timeout_string); if ((o.disconnectscript_timeout <= 0) || (o.disconnectscript_timeout > 99)) { /* 0 < disconnectscript_timeout <= 99 */ ShowLocalizedMsg(IDS_ERR_DISCONN_SCRIPT_TIMEOUT); return(false); } if (!GetRegKey(_T("preconnectscript_timeout"), o.preconnectscript_timeout_string, _T("10"), _countof(o.preconnectscript_timeout_string))) return(false); o.preconnectscript_timeout = _ttoi(o.preconnectscript_timeout_string); if ((o.preconnectscript_timeout <= 0) || (o.preconnectscript_timeout > 99)) { /* 0 < disconnectscript_timeout <= 99 */ ShowLocalizedMsg(IDS_ERR_PRECONN_SCRIPT_TIMEOUT); return(false); } return(true); }
// main thread for monitoring keys DWORD WatchKey(PREGMON p) { HANDLE hEvent; HKEY hKey; LONG ret; Output(0, _T("Monitoring HKEY %x\\%s\n"), p->hMainKey, p->szSubkey); /* WinReg.h RegOpenKeyEx : Opens the specified registry key. Note that key names are not case sensitive. To perform transacted registry operations on a key, call the RegOpenKeyTransacted function. RegOpenKeyTransacted : Opens the specified registry key and associates it with a transaction. Note that key names are not case sensitive. */ ret = RegOpenKeyEx( p->hMainKey, p->szSubkey, 0, KEY_READ | KEY_NOTIFY, &hKey); if (ret != ERROR_SUCCESS) { return -1; } // create an event that will get signaled by the system // when a change is made to the monitored key hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (hEvent == NULL) { return -1; } // this event gets signaled if a user enters CTRL+C to stop while(WaitForSingleObject(g_hStopEvent, 1) != WAIT_OBJECT_0) { UpdateTime(); // register to receive change notification ret = RegNotifyChangeKeyValue(hKey, TRUE, REG_CHANGE_FLAGS, hEvent, TRUE); if (ret != ERROR_SUCCESS) { break; } if (WaitForSingleObject(hEvent, INFINITE) == WAIT_FAILED) { break; } GetRegistryChanges(hKey); } Output(0, _T("Closing HKEY %x\\%s\n"), p->hMainKey, p->szSubkey); RegCloseKey(hKey); CloseHandle(hEvent); return 0; }
void CKeyboardLayout::LoadScanCodeMap(const HKEY_TYPE hkeyType) { memset(m_ScanCodeMap[hkeyType], 0, sizeof(m_ScanCodeMap[hkeyType])); memset(m_CurrentScanCodeMap[hkeyType], 0, sizeof(m_CurrentScanCodeMap[hkeyType])); CString szSubKey; CString szValueName; HKEY hKey = HKEY_LOCAL_MACHINE; switch (hkeyType) { case CURRENT_USER: hKey = HKEY_CURRENT_USER; szSubKey.LoadString(IDS_REGSUBKEY_KEYBOARD_LAYOUT); break; case LOCAL_MACHINE: szSubKey.LoadString(IDS_REGSUBKEY_KEYBOARD_LAYOUT_ANY_USER); break; default: return; } szValueName.LoadString(IDS_SCANCODE_MAP); HKEY hkResult = NULL; if (RegOpenKeyEx(hKey, szSubKey, 0, KEY_QUERY_VALUE, &hkResult) == ERROR_SUCCESS) { // get data size DWORD dwType = REG_BINARY; DWORD dwData = 0; RegQueryValueEx(hkResult, szValueName, NULL, &dwType, NULL, &dwData); // get data LPBYTE lpData = new BYTE[dwData]; if (lpData) { RegQueryValueEx(hkResult, szValueName, NULL, &dwType, lpData, &dwData); } RegCloseKey(hkResult); if (lpData && dwData) { DWORD offset = 0; offset += 8; // skip Version Information and Flags DWORD *pdwMappings = (DWORD *)(lpData + offset); offset += 4; // skip Number of Mappings DWORD *pdwNullTerminator = (DWORD *)(lpData + dwData - 4); if (4 * *pdwMappings + 12 != dwData) { // illegal data } else if (*pdwNullTerminator != 0) { // illegal data } else { while (offset < dwData - 4) { ScanCodeMapping *pMapping = (ScanCodeMapping *)(lpData + offset); offset += 4; // go to next data m_CurrentScanCodeMap[hkeyType][Prefix2ID(pMapping->original.nPrefix)][pMapping->original.nScanCode].nPrefix = pMapping->current.nPrefix; m_CurrentScanCodeMap[hkeyType][Prefix2ID(pMapping->original.nPrefix)][pMapping->original.nScanCode].nScanCode = pMapping->current.nScanCode; m_ScanCodeMap[hkeyType][Prefix2ID(pMapping->original.nPrefix)][pMapping->original.nScanCode].nPrefix = pMapping->current.nPrefix; m_ScanCodeMap[hkeyType][Prefix2ID(pMapping->original.nPrefix)][pMapping->original.nScanCode].nScanCode = pMapping->current.nScanCode; } } } delete[] lpData; lpData = NULL; } }
static jboolean GetPublicJREHome(char *buf, jint bufsize) { HKEY key, subkey; char version[MAXPATHLEN]; /* * Note: There is a very similar implementation of the following * registry reading code in the Windows java control panel (javacp.cpl). * If there are bugs here, a similar bug probably exists there. Hence, * changes here require inspection there. */ /* Find the current version of the JRE */ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_READ, &key) != 0) { JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY); return JNI_FALSE; } if (!GetStringFromRegistry(key, "CurrentVersion", version, sizeof(version))) { JLI_ReportErrorMessage(REG_ERROR2, JRE_KEY); RegCloseKey(key); return JNI_FALSE; } if (JLI_StrCmp(version, GetDotVersion()) != 0) { JLI_ReportErrorMessage(REG_ERROR3, JRE_KEY, version, GetDotVersion() ); RegCloseKey(key); return JNI_FALSE; } /* Find directory where the current version is installed. */ if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) { JLI_ReportErrorMessage(REG_ERROR1, JRE_KEY, version); RegCloseKey(key); return JNI_FALSE; } if (!GetStringFromRegistry(subkey, "JavaHome", buf, bufsize)) { JLI_ReportErrorMessage(REG_ERROR4, JRE_KEY, version); RegCloseKey(key); RegCloseKey(subkey); return JNI_FALSE; } if (JLI_IsTraceLauncher()) { char micro[MAXPATHLEN]; if (!GetStringFromRegistry(subkey, "MicroVersion", micro, sizeof(micro))) { printf("Warning: Can't read MicroVersion\n"); micro[0] = '\0'; } printf("Version major.minor.micro = %s.%s\n", version, micro); } RegCloseKey(key); RegCloseKey(subkey); return JNI_TRUE; }
PRBool GRE_GetPathFromRegKey(HKEY aRegKey, const GREVersionRange *versions, PRUint32 versionsLength, const GREProperty *properties, PRUint32 propertiesLength, char* aBuffer, PRUint32 aBufLen) { // Formerly, GREs were registered at the registry key // HKLM/Software/mozilla.org/GRE/<version> valuepair GreHome=Path. // Nowadays, they are registered in any subkey of // Software/mozilla.org/GRE, with the following valuepairs: // Version=<version> (REG_SZ) // GreHome=<path> (REG_SZ or REG_EXPAND_SZ) // <Property>=<value> (REG_SZ) // // Additional meta-info may be available in the future, including // localization info and other information which might be pertinent // to selecting one GRE over another. // // When a GRE is being registered, it should try to register itself at // HKLM/Software/mozilla.org/GRE/<Version> first, to preserve compatibility // with older glue. If this key is already taken (i.e. there is more than // one GRE of that version installed), it should append a unique number to // the version, for example: // 1.1 (already in use), 1.1_1, 1.1_2, etc... DWORD i = 0; while (PR_TRUE) { char name[MAXPATHLEN + 1]; DWORD nameLen = MAXPATHLEN; if (::RegEnumKeyEx(aRegKey, i, name, &nameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } HKEY subKey = NULL; if (::RegOpenKeyEx(aRegKey, name, 0, KEY_QUERY_VALUE, &subKey) != ERROR_SUCCESS) { continue; } char version[40]; DWORD versionlen = 40; char pathbuf[MAXPATHLEN]; DWORD pathlen; DWORD pathtype; PRBool ok = PR_FALSE; if (::RegQueryValueEx(subKey, "Version", NULL, NULL, (BYTE*) version, &versionlen) == ERROR_SUCCESS && CheckVersion(version, versions, versionsLength)) { ok = PR_TRUE; const GREProperty *props = properties; const GREProperty *propsEnd = properties + propertiesLength; for (; ok && props < propsEnd; ++props) { pathlen = sizeof(pathbuf); if (::RegQueryValueEx(subKey, props->property, NULL, &pathtype, (BYTE*) pathbuf, &pathlen) != ERROR_SUCCESS || strcmp(pathbuf, props->value)) ok = PR_FALSE; } pathlen = sizeof(pathbuf); if (ok && (!::RegQueryValueEx(subKey, "GreHome", NULL, &pathtype, (BYTE*) pathbuf, &pathlen) == ERROR_SUCCESS || !*pathbuf || !CopyWithEnvExpansion(aBuffer, pathbuf, aBufLen, pathtype))) { ok = PR_FALSE; } else if (!safe_strncat(aBuffer, "\\" XPCOM_DLL, aBufLen) || access(aBuffer, R_OK)) { ok = PR_FALSE; } } RegCloseKey(subKey); if (ok) return PR_TRUE; ++i; } aBuffer[0] = '\0'; return PR_FALSE; }
int RAND_poll(void) { MEMORYSTATUS m; HCRYPTPROV hProvider = 0; DWORD w; int good = 0; /* Determine the OS version we are on so we can turn off things * that do not work properly. */ OSVERSIONINFO osverinfo ; osverinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO) ; GetVersionEx( &osverinfo ) ; #if defined(OPENSSL_SYS_WINCE) # if defined(_WIN32_WCE) && _WIN32_WCE>=300 /* Even though MSDN says _WIN32_WCE>=210, it doesn't seem to be available * in commonly available implementations prior 300... */ { BYTE buf[64]; /* poll the CryptoAPI PRNG */ /* The CryptoAPI returns sizeof(buf) bytes of randomness */ if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { if (CryptGenRandom(hProvider, sizeof(buf), buf)) RAND_add(buf, sizeof(buf), sizeof(buf)); CryptReleaseContext(hProvider, 0); } } # endif #else /* OPENSSL_SYS_WINCE */ /* * None of below libraries are present on Windows CE, which is * why we #ifndef the whole section. This also excuses us from * handling the GetProcAddress issue. The trouble is that in * real Win32 API GetProcAddress is available in ANSI flavor * only. In WinCE on the other hand GetProcAddress is a macro * most commonly defined as GetProcAddressW, which accepts * Unicode argument. If we were to call GetProcAddress under * WinCE, I'd recommend to either redefine GetProcAddress as * GetProcAddressA (there seem to be one in common CE spec) or * implement own shim routine, which would accept ANSI argument * and expand it to Unicode. */ { /* load functions dynamically - not available on all systems */ HMODULE advapi = LoadLibrary(TEXT("ADVAPI32.DLL")); HMODULE kernel = LoadLibrary(TEXT("KERNEL32.DLL")); HMODULE user = NULL; HMODULE netapi = LoadLibrary(TEXT("NETAPI32.DLL")); CRYPTACQUIRECONTEXTW acquire = NULL; CRYPTGENRANDOM gen = NULL; CRYPTRELEASECONTEXT release = NULL; NETSTATGET netstatget = NULL; NETFREE netfree = NULL; BYTE buf[64]; if (netapi) { netstatget = (NETSTATGET) GetProcAddress(netapi,"NetStatisticsGet"); netfree = (NETFREE) GetProcAddress(netapi,"NetApiBufferFree"); } if (netstatget && netfree) { LPBYTE outbuf; /* NetStatisticsGet() is a Unicode only function * STAT_WORKSTATION_0 contains 45 fields and STAT_SERVER_0 * contains 17 fields. We treat each field as a source of * one byte of entropy. */ if (netstatget(NULL, L"LanmanWorkstation", 0, 0, &outbuf) == 0) { RAND_add(outbuf, sizeof(STAT_WORKSTATION_0), 45); netfree(outbuf); } if (netstatget(NULL, L"LanmanServer", 0, 0, &outbuf) == 0) { RAND_add(outbuf, sizeof(STAT_SERVER_0), 17); netfree(outbuf); } } if (netapi) FreeLibrary(netapi); /* It appears like this can cause an exception deep within ADVAPI32.DLL * at random times on Windows 2000. Reported by Jeffrey Altman. * Only use it on NT. */ /* Wolfgang Marczy <*****@*****.**> reports that * the RegQueryValueEx call below can hang on NT4.0 (SP6). * So we don't use this at all for now. */ #if 0 if ( osverinfo.dwPlatformId == VER_PLATFORM_WIN32_NT && osverinfo.dwMajorVersion < 5) { /* Read Performance Statistics from NT/2000 registry * The size of the performance data can vary from call * to call so we must guess the size of the buffer to use * and increase its size if we get an ERROR_MORE_DATA * return instead of ERROR_SUCCESS. */ LONG rc=ERROR_MORE_DATA; char * buf=NULL; DWORD bufsz=0; DWORD length; while (rc == ERROR_MORE_DATA) { buf = realloc(buf,bufsz+8192); if (!buf) break; bufsz += 8192; length = bufsz; rc = RegQueryValueEx(HKEY_PERFORMANCE_DATA, TEXT("Global"), NULL, NULL, buf, &length); } if (rc == ERROR_SUCCESS) { /* For entropy count assume only least significant * byte of each DWORD is random. */ RAND_add(&length, sizeof(length), 0); RAND_add(buf, length, length / 4.0); /* Close the Registry Key to allow Windows to cleanup/close * the open handle * Note: The 'HKEY_PERFORMANCE_DATA' key is implicitly opened * when the RegQueryValueEx above is done. However, if * it is not explicitly closed, it can cause disk * partition manipulation problems. */ RegCloseKey(HKEY_PERFORMANCE_DATA); } if (buf) free(buf); } #endif if (advapi) { /* * If it's available, then it's available in both ANSI * and UNICODE flavors even in Win9x, documentation says. * We favor Unicode... */ acquire = (CRYPTACQUIRECONTEXTW) GetProcAddress(advapi, "CryptAcquireContextW"); gen = (CRYPTGENRANDOM) GetProcAddress(advapi, "CryptGenRandom"); release = (CRYPTRELEASECONTEXT) GetProcAddress(advapi, "CryptReleaseContext"); } if (acquire && gen && release) { /* poll the CryptoAPI PRNG */ /* The CryptoAPI returns sizeof(buf) bytes of randomness */ if (acquire(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { if (gen(hProvider, sizeof(buf), buf) != 0) { RAND_add(buf, sizeof(buf), 0); good = 1; #if 0 printf("randomness from PROV_RSA_FULL\n"); #endif } release(hProvider, 0); } /* poll the Pentium PRG with CryptoAPI */ if (acquire(&hProvider, 0, INTEL_DEF_PROV, PROV_INTEL_SEC, 0)) { if (gen(hProvider, sizeof(buf), buf) != 0) { RAND_add(buf, sizeof(buf), sizeof(buf)); good = 1; #if 0 printf("randomness from PROV_INTEL_SEC\n"); #endif } release(hProvider, 0); } } if (advapi) FreeLibrary(advapi); if ((osverinfo.dwPlatformId != VER_PLATFORM_WIN32_NT || !OPENSSL_isservice()) && (user = LoadLibrary(TEXT("USER32.DLL")))) { GETCURSORINFO cursor; GETFOREGROUNDWINDOW win; GETQUEUESTATUS queue; win = (GETFOREGROUNDWINDOW) GetProcAddress(user, "GetForegroundWindow"); cursor = (GETCURSORINFO) GetProcAddress(user, "GetCursorInfo"); queue = (GETQUEUESTATUS) GetProcAddress(user, "GetQueueStatus"); if (win) { /* window handle */ HWND h = win(); RAND_add(&h, sizeof(h), 0); } if (cursor) { /* unfortunately, its not safe to call GetCursorInfo() * on NT4 even though it exists in SP3 (or SP6) and * higher. */ if ( osverinfo.dwPlatformId == VER_PLATFORM_WIN32_NT && osverinfo.dwMajorVersion < 5) cursor = 0; } if (cursor) { /* cursor position */ /* assume 2 bytes of entropy */ CURSORINFO ci; ci.cbSize = sizeof(CURSORINFO); if (cursor(&ci)) RAND_add(&ci, ci.cbSize, 2); } if (queue) { /* message queue status */ /* assume 1 byte of entropy */ w = queue(QS_ALLEVENTS); RAND_add(&w, sizeof(w), 1); } FreeLibrary(user); } /* Toolhelp32 snapshot: enumerate processes, threads, modules and heap * http://msdn.microsoft.com/library/psdk/winbase/toolhelp_5pfd.htm * (Win 9x and 2000 only, not available on NT) * * This seeding method was proposed in Peter Gutmann, Software * Generation of Practically Strong Random Numbers, * http://www.usenix.org/publications/library/proceedings/sec98/gutmann.html * revised version at http://www.cryptoengines.com/~peter/06_random.pdf * (The assignment of entropy estimates below is arbitrary, but based * on Peter's analysis the full poll appears to be safe. Additional * interactive seeding is encouraged.) */ if (kernel) { CREATETOOLHELP32SNAPSHOT snap; CLOSETOOLHELP32SNAPSHOT close_snap; HANDLE handle; HEAP32FIRST heap_first; HEAP32NEXT heap_next; HEAP32LIST heaplist_first, heaplist_next; PROCESS32 process_first, process_next; THREAD32 thread_first, thread_next; MODULE32 module_first, module_next; HEAPLIST32 hlist; HEAPENTRY32 hentry; PROCESSENTRY32 p; THREADENTRY32 t; MODULEENTRY32 m; DWORD starttime = 0; snap = (CREATETOOLHELP32SNAPSHOT) GetProcAddress(kernel, "CreateToolhelp32Snapshot"); close_snap = (CLOSETOOLHELP32SNAPSHOT) GetProcAddress(kernel, "CloseToolhelp32Snapshot"); heap_first = (HEAP32FIRST) GetProcAddress(kernel, "Heap32First"); heap_next = (HEAP32NEXT) GetProcAddress(kernel, "Heap32Next"); heaplist_first = (HEAP32LIST) GetProcAddress(kernel, "Heap32ListFirst"); heaplist_next = (HEAP32LIST) GetProcAddress(kernel, "Heap32ListNext"); process_first = (PROCESS32) GetProcAddress(kernel, "Process32First"); process_next = (PROCESS32) GetProcAddress(kernel, "Process32Next"); thread_first = (THREAD32) GetProcAddress(kernel, "Thread32First"); thread_next = (THREAD32) GetProcAddress(kernel, "Thread32Next"); module_first = (MODULE32) GetProcAddress(kernel, "Module32First"); module_next = (MODULE32) GetProcAddress(kernel, "Module32Next"); if (snap && heap_first && heap_next && heaplist_first && heaplist_next && process_first && process_next && thread_first && thread_next && module_first && module_next && (handle = snap(TH32CS_SNAPALL,0)) != INVALID_HANDLE_VALUE) { /* heap list and heap walking */ /* HEAPLIST32 contains 3 fields that will change with * each entry. Consider each field a source of 1 byte * of entropy. * HEAPENTRY32 contains 5 fields that will change with * each entry. Consider each field a source of 1 byte * of entropy. */ ZeroMemory(&hlist, sizeof(HEAPLIST32)); hlist.dwSize = sizeof(HEAPLIST32); if (good) starttime = GetTickCount(); #ifdef _MSC_VER if (heaplist_first(handle, &hlist)) { /* following discussion on dev ML, exception on WinCE (or other Win platform) is theoretically of unknown origin; prevent infinite loop here when this theoretical case occurs; otherwise cope with the expected (MSDN documented) exception-throwing behaviour of Heap32Next() on WinCE. based on patch in original message by Tanguy Fautré (2009/03/02) Subject: RAND_poll() and CreateToolhelp32Snapshot() stability */ int ex_cnt_limit = 42; do { RAND_add(&hlist, hlist.dwSize, 3); __try { ZeroMemory(&hentry, sizeof(HEAPENTRY32)); hentry.dwSize = sizeof(HEAPENTRY32); if (heap_first(&hentry, hlist.th32ProcessID, hlist.th32HeapID)) { int entrycnt = 80; do RAND_add(&hentry, hentry.dwSize, 5); while (heap_next(&hentry) && (!good || (GetTickCount()-starttime)<MAXDELAY) && --entrycnt > 0); } } __except (EXCEPTION_EXECUTE_HANDLER) { /* ignore access violations when walking the heap list */ ex_cnt_limit--; } } while (heaplist_next(handle, &hlist) && (!good || (GetTickCount()-starttime)<MAXDELAY) && ex_cnt_limit > 0); } #else if (heaplist_first(handle, &hlist)) { do { RAND_add(&hlist, hlist.dwSize, 3); hentry.dwSize = sizeof(HEAPENTRY32); if (heap_first(&hentry, hlist.th32ProcessID, hlist.th32HeapID)) { int entrycnt = 80; do RAND_add(&hentry, hentry.dwSize, 5); while (heap_next(&hentry) && --entrycnt > 0); } } while (heaplist_next(handle, &hlist) && (!good || (GetTickCount()-starttime)<MAXDELAY)); } #endif /* process walking */ /* PROCESSENTRY32 contains 9 fields that will change * with each entry. Consider each field a source of * 1 byte of entropy. */ p.dwSize = sizeof(PROCESSENTRY32); if (good) starttime = GetTickCount(); if (process_first(handle, &p)) do RAND_add(&p, p.dwSize, 9); while (process_next(handle, &p) && (!good || (GetTickCount()-starttime)<MAXDELAY)); /* thread walking */ /* THREADENTRY32 contains 6 fields that will change * with each entry. Consider each field a source of * 1 byte of entropy. */ t.dwSize = sizeof(THREADENTRY32); if (good) starttime = GetTickCount(); if (thread_first(handle, &t)) do RAND_add(&t, t.dwSize, 6); while (thread_next(handle, &t) && (!good || (GetTickCount()-starttime)<MAXDELAY)); /* module walking */ /* MODULEENTRY32 contains 9 fields that will change * with each entry. Consider each field a source of * 1 byte of entropy. */ m.dwSize = sizeof(MODULEENTRY32); if (good) starttime = GetTickCount(); if (module_first(handle, &m)) do RAND_add(&m, m.dwSize, 9); while (module_next(handle, &m) && (!good || (GetTickCount()-starttime)<MAXDELAY)); if (close_snap) close_snap(handle); else CloseHandle(handle); } FreeLibrary(kernel); }
void BOT_INFO::resetSystemInfo() { // CPU type SYSTEM_INFO si; GetSystemInfo(&si); processor = si.dwProcessorType; // Windows registration name { char buffer[40]; // Get platform OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); Uint32 PlatformId = osvi.dwPlatformId; // Prepare for registry access HKEY key; // Handle to a session with a registry key Uint32 buflen; // Length of the buffer Uint32 type; // Type will contain type of data transfered if (PlatformId != VER_PLATFORM_WIN32_NT) { // Look up Windows 9x or Windows 3.1 version information RegOpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", (HKEY*)&key); } else { // Look up Windows NT version information RegOpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", (HKEY*)&key); } buflen = 40; RegQueryValueEx(key, "RegisteredOwner", NULL, &type, (BYTE*)&buffer, &buflen); strncpy(regName, buffer, 40); buflen = 40; RegQueryValueEx(key, "RegisteredOrganization", NULL, &type, (BYTE*)&buffer, &buflen); strncpy(regOrg, buffer, 40); RegCloseKey(key); } // Timezone Bias TIME_ZONE_INFORMATION tzi; GetTimeZoneInformation(&tzi); timeZoneBias = (SHORT)tzi.Bias; // Permission ID permissionID = getSetting32(HKEY_LOCAL_MACHINE, "SOFTWARE", "D2"); // Install some SubSpace registry keys if (permissionID == -1) { do { permissionID = (GetTickCount() ^ 0xAAAAAAAA) * 0x5f346d + 0x5abcdef; } while (!permissionID || permissionID == 1 || permissionID == -1); setSetting32(HKEY_LOCAL_MACHINE, "SOFTWARE", "D2", permissionID); } // Machine ID GetVolumeInformation("C:\\", NULL, 0, &machineID, NULL, NULL, NULL, 0); if (!machineID || machineID == 1 || machineID == -1) { machineID = getSetting32(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProductCode"); if (!machineID || machineID == 1 || machineID == -1) { machineID = permissionID; setSetting32(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProductCode", machineID); } } if (machineID > 0x7fffffff) machineID += 0x7fffffff; setSetting32(HKEY_LOCAL_MACHINE, "SOFTWARE", "D1", machineID); }
/*********************************************************************** * register_converters */ static HRESULT register_converters(struct regsvr_converter const *list) { LONG res = ERROR_SUCCESS; HKEY coclass_key; WCHAR buf[39]; HKEY converters_key; HKEY instance_key; res = RegCreateKeyExW(HKEY_CLASSES_ROOT, clsid_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &coclass_key, NULL); if (res == ERROR_SUCCESS) { StringFromGUID2(&CATID_WICFormatConverters, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &converters_key, NULL); if (res == ERROR_SUCCESS) { res = RegCreateKeyExW(converters_key, instance_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &instance_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; } if (res != ERROR_SUCCESS) RegCloseKey(coclass_key); } if (res != ERROR_SUCCESS) goto error_return; for (; res == ERROR_SUCCESS && list->clsid; ++list) { HKEY clsid_key; HKEY instance_clsid_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &clsid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(instance_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &instance_clsid_key, NULL); if (res == ERROR_SUCCESS) { res = RegSetValueExW(instance_clsid_key, clsid_valuename, 0, REG_SZ, (CONST BYTE*)(buf), 78); RegCloseKey(instance_clsid_key); } if (res != ERROR_SUCCESS) goto error_close_clsid_key; if (list->author) { res = RegSetValueExA(clsid_key, author_valuename, 0, REG_SZ, (CONST BYTE*)(list->author), strlen(list->author) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->friendlyname) { res = RegSetValueExA(clsid_key, friendlyname_valuename, 0, REG_SZ, (CONST BYTE*)(list->friendlyname), strlen(list->friendlyname) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->vendor) { StringFromGUID2(list->vendor, buf, 39); res = RegSetValueExW(clsid_key, vendor_valuename, 0, REG_SZ, (CONST BYTE*)(buf), 78); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->version) { res = RegSetValueExA(clsid_key, version_valuename, 0, REG_SZ, (CONST BYTE*)(list->version), strlen(list->version) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->formats) { HKEY formats_key; GUID const * const *format; res = RegCreateKeyExW(clsid_key, pixelformats_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &formats_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; for (format=list->formats; *format; ++format) { HKEY format_key; StringFromGUID2(*format, buf, 39); res = RegCreateKeyExW(formats_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &format_key, NULL); if (res != ERROR_SUCCESS) break; RegCloseKey(format_key); } RegCloseKey(formats_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } error_close_clsid_key: RegCloseKey(clsid_key); } error_close_coclass_key: RegCloseKey(instance_key); RegCloseKey(converters_key); RegCloseKey(coclass_key); error_return: return res != ERROR_SUCCESS ? HRESULT_FROM_WIN32(res) : S_OK; }
UINT WINAPI WNetEnumCachedPasswords( LPSTR pbPrefix, /* [in] prefix to filter cache entries */ WORD cbPrefix, /* [in] number of bytes in Prefix substring */ BYTE nType, /* [in] match the Type ID of the entry */ ENUMPASSWORDPROC enumPasswordProc, /* [in] callback function */ DWORD param) /* [in] parameter passed to enum function */ { HKEY hkey; DWORD r, type, val_sz, data_sz, i, j, size; PASSWORD_CACHE_ENTRY *entry; CHAR val[256], prefix[6]; WARN( "(%s, %d, %d, %p, 0x%08x) totally insecure\n", debugstr_an(pbPrefix,cbPrefix), cbPrefix, nType, enumPasswordProc, param ); /* @@ Wine registry key: HKCU\Software\Wine\Wine\Mpr */ r = RegCreateKeyA( HKEY_CURRENT_USER, mpr_key, &hkey ); if( r ) return WN_ACCESS_DENIED; sprintf(prefix, "X-%02X-", nType ); for( i=0; ; i++ ) { val_sz = sizeof val; data_sz = 0; type = 0; val[0] = 0; r = RegEnumValueA( hkey, i, val, &val_sz, NULL, &type, NULL, &data_sz ); if( r != ERROR_SUCCESS ) break; if( type != REG_BINARY ) continue; /* check the value is in the format we expect */ if( val_sz < sizeof prefix ) continue; if( memcmp( prefix, val, 5 ) ) continue; /* decode the value */ for(j=5; j<val_sz; j+=2 ) { signed char hi = ctox( val[j] ), lo = ctox( val[j+1] ); if( ( hi < 0 ) || ( lo < 0 ) ) break; val[(j-5)/2] = (hi<<4) | lo; } /* find the decoded length */ val_sz = (j - 5)/2; val[val_sz]=0; if( val_sz < cbPrefix ) continue; /* check the prefix matches */ if( memcmp(val, pbPrefix, cbPrefix) ) continue; /* read the value data */ size = offsetof( PASSWORD_CACHE_ENTRY, abResource[val_sz + data_sz] ); entry = HeapAlloc( GetProcessHeap(), 0, size ); memcpy( entry->abResource, val, val_sz ); entry->cbEntry = size; entry->cbResource = val_sz; entry->cbPassword = data_sz; entry->iEntry = i; entry->nType = nType; r = RegEnumValueA( hkey, i, NULL, &val_sz, NULL, &type, &entry->abResource[val_sz], &data_sz ); if( r == ERROR_SUCCESS ) enumPasswordProc( entry, param ); HeapFree( GetProcessHeap(), 0, entry ); } RegCloseKey( hkey ); return WN_SUCCESS; }
void CKeyboardLayout::SaveScanCodeMap(const HKEY_TYPE hkeyType) { CString szSubKey; CString szValueName; HKEY hKey = HKEY_LOCAL_MACHINE; switch (hkeyType) { case CURRENT_USER: hKey = HKEY_CURRENT_USER; szSubKey.LoadString(IDS_REGSUBKEY_KEYBOARD_LAYOUT); break; case LOCAL_MACHINE: szSubKey.LoadString(IDS_REGSUBKEY_KEYBOARD_LAYOUT_ANY_USER); break; default: return; } szValueName.LoadString(IDS_SCANCODE_MAP); HKEY hkResult = NULL; if (RegCreateKeyEx(hKey, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkResult, NULL) == ERROR_SUCCESS) { DWORD cbData = GetScanCodeLength(hkeyType); if (cbData <= 16) { RegDeleteValue(hkResult, szValueName); } else { LPBYTE lpData = new BYTE[cbData]; memset(lpData, 0, sizeof(BYTE) * cbData); { DWORD dwMappings = (cbData - 12) / 4; memmove(lpData + 8, &dwMappings, 4); } int offset = 12; for (int nPrefixID = 0; nPrefixID < 3; ++nPrefixID) { for (int nScanCode = 0; nScanCode < 256; ++nScanCode) { if (m_ScanCodeMap[hkeyType][nPrefixID][nScanCode].nScanCode) { ScanCodeMapping sScanCodeMapping = {'\0'}; sScanCodeMapping.original.nPrefix = PrefixID2Code(nPrefixID); sScanCodeMapping.original.nScanCode = (BYTE)nScanCode; sScanCodeMapping.current.nPrefix = m_ScanCodeMap[hkeyType][nPrefixID][nScanCode].nPrefix; sScanCodeMapping.current.nScanCode = m_ScanCodeMap[hkeyType][nPrefixID][nScanCode].nScanCode; memcpy(lpData + offset, &sScanCodeMapping, sizeof(sScanCodeMapping)); offset += sizeof(sScanCodeMapping); } } } RegSetValueEx(hkResult, szValueName, 0, REG_BINARY, lpData, cbData); delete[] lpData; lpData = NULL; } RegCloseKey(hkResult); } // Do you want to restart computer? if (ChangedKeyboardLayout(hkeyType)) { if (AfxMessageBox(CString(MAKEINTRESOURCE(IDS_RESTART_OR_NOT)), MB_YESNO | MB_ICONQUESTION) == IDYES) { CProfile::RestartComputer(); } } }
VOID ExamineKey( IN HKEY PredefinedKey, IN LPCWSTR ParentName, IN LPCWSTR KeyName, IN LPCWSTR PredefinedKeyName ) { LPWSTR CompleteKeyName; HKEY Key; LONG Status; WCHAR szClass[ MAX_PATH + 1 ]; DWORD cchClass; DWORD cSubKeys; DWORD cchMaxSubKey; DWORD cchMaxClass; DWORD cValues; DWORD cchMaxValueName; DWORD cbMaxValueData; DWORD cbSecurityDescriptor; FILETIME ftLastWriteTime; WCHAR szSubKeyName[ MAX_PATH + 1 ]; DWORD cchSubKeyNameLength; DWORD iSubKey; BOOLEAN KeyNameAlreadyPrinted; // // Build the complete key name // if( wcslen( ParentName ) == 0 ) { CompleteKeyName = wcsdup( KeyName ); if( CompleteKeyName == NULL ) { printf( "ERROR: wcsdup( KeyName ) failed \n" ); return; } } else { CompleteKeyName = wcsdup( ParentName ); if( CompleteKeyName == NULL ) { printf( "ERROR: wcsdup( ParentName ) failed \n" ); return; } if( wcslen( KeyName ) != 0 ) { CompleteKeyName = realloc( CompleteKeyName, ( wcslen( CompleteKeyName ) + wcslen( L"\\" ) + wcslen( KeyName ) + 1 )*sizeof( WCHAR ) ); wcscat( CompleteKeyName, L"\\" ); wcscat( CompleteKeyName, KeyName ); } } // // For debugging only // // printf( "%ls\\%ls \n", PredefinedKeyName, CompleteKeyName ); // // // Open the key // Status = RegOpenKeyExW( PredefinedKey, CompleteKeyName, 0, MAXIMUM_ALLOWED, &Key ); if( Status != ERROR_SUCCESS ) { printf( MSG_COMPLETE_KEY_NAME, PredefinedKeyName, CompleteKeyName ); printf( MSG_ERROR_REG_OPEN_KEY_EX, Status ); free( CompleteKeyName ); return; } // // Determine the number of value entries, the maximum length of a value // entry name, the maximum data size, and the number of subkeys // cchClass = sizeof( szClass ) / sizeof( WCHAR ); Status = RegQueryInfoKeyW( Key, szClass, &cchClass, 0, &cSubKeys, &cchMaxSubKey, &cchMaxClass, &cValues, &cchMaxValueName, &cbMaxValueData, &cbSecurityDescriptor, &ftLastWriteTime ); if( Status != ERROR_SUCCESS ) { printf( MSG_COMPLETE_KEY_NAME, PredefinedKeyName, CompleteKeyName ); printf( MSG_ERROR_REG_QUERY_INFO_KEY, Status ); free( CompleteKeyName ); RegCloseKey( Key ); return; } if( cValues != 0 ) { // // Examine the value entries // ExamineValueEntries( Key, CompleteKeyName, cchMaxValueName, cbMaxValueData, cValues, PredefinedKeyName ); } // // Traverse each subkey // if( cSubKeys != 0 ) { KeyNameAlreadyPrinted = FALSE; for( iSubKey = 0; iSubKey < cSubKeys; iSubKey++ ) { cchSubKeyNameLength = sizeof( szSubKeyName )/sizeof( WCHAR ); cchClass = sizeof( szClass ) / sizeof( WCHAR ); Status = RegEnumKeyExW( Key, iSubKey, szSubKeyName, &cchSubKeyNameLength, 0, NULL, NULL, &ftLastWriteTime ); if( Status != ERROR_SUCCESS ) { if( !KeyNameAlreadyPrinted ) { KeyNameAlreadyPrinted = TRUE; printf( MSG_COMPLETE_KEY_NAME, PredefinedKeyName, CompleteKeyName ); } printf( MSG_ERROR_REG_ENUM_KEY_EX, Status, iSubKey ); continue; } ExamineKey( PredefinedKey, CompleteKeyName, szSubKeyName, PredefinedKeyName ); } } RegCloseKey( Key ); free( CompleteKeyName ); }
int WIN32_Subsystem_Init(int *argc, char ***argv) { WIN32_OS_version = GetOSVersion(); if ((WIN32_OS_version == _WIN_OS_UNKNOWN) || (WIN32_OS_version == _WIN_OS_WIN32S)) return 1; if (atexit(WIN32_Exit) != 0) return 1; #if USE_WIN32_SERVICE if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) { char path[512]; HKEY hndKey; if (signal(SIGABRT, WIN32_Abort) == SIG_ERR) return 1; /* Register the service Handler function */ svcHandle = RegisterServiceCtrlHandler(WIN32_Service_name, WIN32_svcHandler); if (svcHandle == 0) return 1; /* Set Process work dir to directory cointaining squid.exe */ GetModuleFileName(NULL, path, 512); WIN32_module_name = xstrdup(path); path[strlen(path) - 10] = '\0'; if (SetCurrentDirectory(path) == 0) return 1; safe_free(ConfigFile); /* get config file from Windows Registry */ if (RegOpenKey(HKEY_LOCAL_MACHINE, REGKEY, &hndKey) == ERROR_SUCCESS) { DWORD Type = 0; DWORD Size = 0; LONG Result; Result = RegQueryValueEx(hndKey, CONFIGFILE, NULL, &Type, NULL, &Size); if (Result == ERROR_SUCCESS && Size) { ConfigFile = xmalloc(Size); RegQueryValueEx(hndKey, CONFIGFILE, NULL, &Type, ConfigFile, &Size); } else ConfigFile = xstrdup(DefaultConfigFile); Size = 0; Type = 0; Result = RegQueryValueEx(hndKey, COMMANDLINE, NULL, &Type, NULL, &Size); if (Result == ERROR_SUCCESS && Size) { WIN32_Service_Command_Line = xmalloc(Size); RegQueryValueEx(hndKey, COMMANDLINE, NULL, &Type, WIN32_Service_Command_Line, &Size); } else WIN32_Service_Command_Line = xstrdup(""); RegCloseKey(hndKey); } else { ConfigFile = xstrdup(DefaultConfigFile); WIN32_Service_Command_Line = xstrdup(""); } WIN32_build_argv(WIN32_Service_Command_Line); *argc = WIN32_argc; *argv = WIN32_argv; /* Set Service Status to SERVICE_START_PENDING */ svcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; svcStatus.dwCurrentState = SERVICE_START_PENDING; svcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; svcStatus.dwWin32ExitCode = 0; svcStatus.dwServiceSpecificExitCode = 0; svcStatus.dwCheckPoint = 0; svcStatus.dwWaitHint = 10000; SetServiceStatus(svcHandle, &svcStatus); #ifdef _SQUID_MSWIN_ _setmaxstdio(Squid_MaxFD); #endif } #endif #ifdef _SQUID_MSWIN_ if (Win32SockInit() < 0) return 1; #endif return 0; }
int GetRegKey(const TCHAR name[], TCHAR *data, const TCHAR default_data[], DWORD len) { LONG status; DWORD type; HKEY openvpn_key; HKEY openvpn_key_write; DWORD dwDispos; TCHAR expanded_string[MAX_PATH]; DWORD size = len * sizeof(*data); DWORD max_len = len - 1; /* If option is already set via cmd-line, return */ if (data[0] != 0) { // Expand environment variables inside the string. ExpandEnvironmentStrings(data, expanded_string, _countof(expanded_string)); _tcsncpy(data, expanded_string, max_len); return(true); } status = RegOpenKeyEx(HKEY_CURRENT_USER, _T("SOFTWARE\\OpenVPN-GUI"), 0, KEY_READ, &openvpn_key); if (status != ERROR_SUCCESS) { if (RegCreateKeyEx(HKEY_CURRENT_USER, _T("Software\\OpenVPN-GUI"), 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &openvpn_key, &dwDispos) != ERROR_SUCCESS) { /* error creating registry key */ ShowLocalizedMsg(IDS_ERR_CREATE_REG_HKCU_KEY, _T("OpenVPN-GUI")); return(false); } } /* get a registry string */ status = RegQueryValueEx(openvpn_key, name, NULL, &type, (byte *) data, &size); if (status != ERROR_SUCCESS || type != REG_SZ) { /* key did not exist - set default value */ status = RegOpenKeyEx(HKEY_CURRENT_USER, _T("SOFTWARE\\OpenVPN-GUI"), 0, KEY_READ | KEY_WRITE, &openvpn_key_write); if (status != ERROR_SUCCESS) { /* can't open registry for writing */ ShowLocalizedMsg(IDS_ERR_WRITE_REGVALUE, _T("OpenVPN-GUI"), name); return(false); } if(!SetRegistryValue(openvpn_key_write, name, default_data)) { /* cant read / set reg-key */ return(false); } _tcsncpy(data, default_data, max_len); RegCloseKey(openvpn_key_write); } else { size /= sizeof(*data); data[size - 1] = L'\0'; /* REG_SZ strings are not guaranteed to be null-terminated */ } RegCloseKey(openvpn_key); // Expand environment variables inside the string. ExpandEnvironmentStrings(data, expanded_string, _countof(expanded_string)); _tcsncpy(data, expanded_string, max_len); return(true); }
/** * Process a "Run" type registry key. * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is * opened. * szKeyName is the key holding the actual entries. * bDelete tells whether we should delete each value right before executing it. * bSynchronous tells whether we should wait for the prog to complete before * going on to the next prog. */ static BOOL ProcessRunKeys(HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete, BOOL bSynchronous) { static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\', 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\', 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0}; HKEY hkWin=NULL, hkRun=NULL; LONG res=ERROR_SUCCESS; DWORD i, nMaxCmdLine=0, nMaxValue=0; WCHAR *szCmdLine=NULL; WCHAR *szValue=NULL; if (hkRoot==HKEY_LOCAL_MACHINE) wprintf(L"processing %s entries under HKLM\n", szKeyName); else wprintf(L"processing %s entries under HKCU\n", szKeyName); if ((res=RegOpenKeyExW(hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin))!=ERROR_SUCCESS) { printf("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%ld)\n", res); goto end; } if ((res=RegOpenKeyExW(hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun))!= ERROR_SUCCESS) { if (res==ERROR_FILE_NOT_FOUND) { printf("Key doesn't exist - nothing to be done\n"); res=ERROR_SUCCESS; } else printf("RegOpenKey failed on run key (%ld)\n", res); goto end; } if ((res=RegQueryInfoKeyW(hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue, &nMaxCmdLine, NULL, NULL))!=ERROR_SUCCESS) { printf("Couldn't query key info (%ld)\n", res); goto end; } if (i==0) { printf("No commands to execute.\n"); res=ERROR_SUCCESS; goto end; } if ((szCmdLine=malloc(nMaxCmdLine))==NULL) { printf("Couldn't allocate memory for the commands to be executed\n"); res=ERROR_NOT_ENOUGH_MEMORY; goto end; } if ((szValue=malloc((++nMaxValue)*sizeof(*szValue)))==NULL) { printf("Couldn't allocate memory for the value names\n"); res=ERROR_NOT_ENOUGH_MEMORY; goto end; } while(i>0) { DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine; DWORD type; --i; if ((res=RegEnumValueW(hkRun, i, szValue, &nValLength, 0, &type, (LPBYTE)szCmdLine, &nDataLength))!=ERROR_SUCCESS) { printf("Couldn't read in value %ld - %ld\n", i, res); continue; } if (bDelete && (res=RegDeleteValueW(hkRun, szValue))!=ERROR_SUCCESS) { printf("Couldn't delete value - %ld, %ld. Running command anyways.\n", i, res); } if (type!=REG_SZ) { printf("Incorrect type of value #%ld (%ld)\n", i, type); continue; } if ((res=runCmd(szCmdLine, NULL, bSynchronous, FALSE))==INVALID_RUNCMD_RETURN) { printf("Error running cmd #%ld (%ld)\n", i, GetLastError()); } printf("Done processing cmd #%ld\n", i); } res=ERROR_SUCCESS; end: if (hkRun!=NULL) RegCloseKey(hkRun); if (hkWin!=NULL) RegCloseKey(hkWin); printf("done\n"); return res==ERROR_SUCCESS?TRUE:FALSE; }
CRegistryConfig::~CRegistryConfig() { if (m_hKey!=NULL) { RegCloseKey(m_hKey); } }
static BOOL pendingRename() { static const WCHAR ValueName[] = {'P','e','n','d','i','n','g', 'F','i','l','e','R','e','n','a','m','e', 'O','p','e','r','a','t','i','o','n','s',0}; static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\', 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\', 'C','o','n','t','r','o','l','\\', 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0}; WCHAR *buffer=NULL; const WCHAR *src=NULL, *dst=NULL; DWORD dataLength=0; HKEY hSession=NULL; DWORD res; printf("Entered\n"); if ((res=RegOpenKeyExW(HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession)) !=ERROR_SUCCESS) { if (res==ERROR_FILE_NOT_FOUND) { printf("The key was not found - skipping\n"); res=TRUE; } else { printf("Couldn't open key, error %ld\n", res); res=FALSE; } goto end; } res=RegQueryValueExW(hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not truely a REG_MULTI_SZ anyways */, NULL, &dataLength); if (res==ERROR_FILE_NOT_FOUND) { /* No value - nothing to do. Great! */ printf("Value not present - nothing to rename\n"); res=TRUE; goto end; } if (res!=ERROR_SUCCESS) { printf("Couldn't query value's length (%ld)\n", res); res=FALSE; goto end; } buffer=malloc(dataLength); if (buffer==NULL) { printf("Couldn't allocate %lu bytes for the value\n", dataLength); res=FALSE; goto end; } res=RegQueryValueExW(hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength); if (res!=ERROR_SUCCESS) { printf("Couldn't query value after successfully querying before (%lu),\n" "please report to [email protected]\n", res); res=FALSE; goto end; } /* Make sure that the data is long enough and ends with two NULLs. This * simplifies the code later on. */ if (dataLength<2*sizeof(buffer[0]) || buffer[dataLength/sizeof(buffer[0])-1]!='\0' || buffer[dataLength/sizeof(buffer[0])-2]!='\0') { printf("Improper value format - doesn't end with NULL\n"); res=FALSE; goto end; } for(src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0'; src=dst+lstrlenW(dst)+1) { DWORD dwFlags=0; printf("processing next command\n"); dst=src+lstrlenW(src)+1; /* We need to skip the \??\ header */ if (src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\') src+=4; if (dst[0]=='!') { dwFlags|=MOVEFILE_REPLACE_EXISTING; dst++; } if (dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\') dst+=4; if (*dst!='\0') { /* Rename the file */ MoveFileExW(src, dst, dwFlags); } else { /* Delete the file or directory */ res = GetFileAttributesW (src); if (res != (DWORD)-1) { if ((res&FILE_ATTRIBUTE_DIRECTORY)==0) { /* It's a file */ DeleteFileW(src); } else { /* It's a directory */ RemoveDirectoryW(src); } } else { printf("couldn't get file attributes (%ld)\n", GetLastError()); } } } if ((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS) { printf("Error deleting the value (%lu)\n", GetLastError()); res=FALSE; } else res=TRUE; end: if (buffer!=NULL) free(buffer); if (hSession!=NULL) RegCloseKey(hSession); return res; }
static int init_by_resolv_conf(ares_channel channel) { #ifndef WATT32 char *line = NULL; #endif int status = -1, nservers = 0, nsort = 0; struct server_state *servers = NULL; struct apattern *sortlist = NULL; #ifdef WIN32 /* NameServer info via IPHLPAPI (IP helper API): GetNetworkParams() should be the trusted source for this. Available in Win-98/2000 and later. If that fail, fall-back to registry information. NameServer Registry: On Windows 9X, the DNS server can be found in: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer On Windows NT/2000/XP/2003: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer or HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer or HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\ NameServer or HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\ DhcpNameServer */ HKEY mykey; HKEY subkey; DWORD data_type; DWORD bytes; DWORD result; char buf[512]; win_platform platform; if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */ return ARES_SUCCESS; if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0) { status = config_nameserver(&servers, &nservers, buf); if (status == ARES_SUCCESS) goto okay; } platform = ares__getplatform(); if (platform == WIN_NT) { if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ, &mykey ) == ERROR_SUCCESS) { RegOpenKeyEx(mykey, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey); if (get_res_nt(mykey, NAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } else if (get_res_nt(mykey, DHCPNAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } /* Try the interfaces */ else if (get_res_interfaces_nt(subkey, NAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } RegCloseKey(subkey); RegCloseKey(mykey); } } else if (platform == WIN_9X) { if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, WIN_NS_9X, 0, KEY_READ, &mykey ) == ERROR_SUCCESS) { if ((result = RegQueryValueEx( mykey, NAMESERVER, NULL, &data_type, NULL, &bytes ) ) == ERROR_SUCCESS || result == ERROR_MORE_DATA) { if (bytes) { line = malloc(bytes+1); if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type, (unsigned char *)line, &bytes) == ERROR_SUCCESS) { status = config_nameserver(&servers, &nservers, line); } free(line); } } } RegCloseKey(mykey); } if (status == ARES_SUCCESS) status = ARES_EOF; else /* Catch the case when all the above checks fail (which happens when there is no network card or the cable is unplugged) */ status = ARES_EFILE; #elif defined(__riscos__) /* Under RISC OS, name servers are listed in the system variable Inet$Resolvers, space separated. */ line = getenv("Inet$Resolvers"); status = ARES_EOF; if (line) { char *resolvers = strdup(line), *pos, *space; if (!resolvers) return ARES_ENOMEM; pos = resolvers; do { space = strchr(pos, ' '); if (space) *space = '\0'; status = config_nameserver(&servers, &nservers, pos); if (status != ARES_SUCCESS) break; pos = space + 1; } while (space); if (status == ARES_SUCCESS) status = ARES_EOF; free(resolvers); } #elif defined(WATT32) int i; sock_init(); for (i = 0; def_nameservers[i]; i++) ; if (i == 0) return ARES_SUCCESS; /* use localhost DNS server */ nservers = i; servers = calloc(i, sizeof(struct server_state)); if (!servers) return ARES_ENOMEM; for (i = 0; def_nameservers[i]; i++) { servers[i].addr.addrV4.s_addr = htonl(def_nameservers[i]); servers[i].addr.family = AF_INET; } status = ARES_EOF; #elif defined(ANDROID) char value[PROP_VALUE_MAX]=""; __system_property_get("net.dns1", value); status = config_nameserver(&servers, &nservers, value); if (status == ARES_SUCCESS) status = ARES_EOF; #else { char *p; FILE *fp; size_t linesize; int error; /* Don't read resolv.conf and friends if we don't have to */ if (ARES_CONFIG_CHECK(channel)) return ARES_SUCCESS; fp = fopen(PATH_RESOLV_CONF, "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "domain", ';'))) status = config_domain(channel, p); else if ((p = try_config(line, "lookup", ';')) && !channel->lookups) status = config_lookup(channel, p, "bind", "file"); else if ((p = try_config(line, "search", ';'))) status = set_search(channel, p); else if ((p = try_config(line, "nameserver", ';')) && channel->nservers == -1) status = config_nameserver(&servers, &nservers, p); else if ((p = try_config(line, "sortlist", ';')) && channel->nsort == -1) status = config_sortlist(&sortlist, &nsort, p); else if ((p = try_config(line, "options", ';'))) status = set_options(channel, p); else status = ARES_SUCCESS; if (status != ARES_SUCCESS) break; } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF)); status = ARES_EFILE; } } if ((status == ARES_EOF) && (!channel->lookups)) { /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */ fp = fopen("/etc/nsswitch.conf", "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "hosts:", '\0')) && !channel->lookups) /* ignore errors */ (void)config_lookup(channel, p, "dns", "files"); } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf")); status = ARES_EFILE; } } } if ((status == ARES_EOF) && (!channel->lookups)) { /* Linux / GNU libc 2.x and possibly others have host.conf */ fp = fopen("/etc/host.conf", "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "order", '\0')) && !channel->lookups) /* ignore errors */ (void)config_lookup(channel, p, "bind", "hosts"); } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf")); status = ARES_EFILE; } } } if ((status == ARES_EOF) && (!channel->lookups)) { /* Tru64 uses /etc/svc.conf */ fp = fopen("/etc/svc.conf", "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "hosts=", '\0')) && !channel->lookups) /* ignore errors */ (void)config_lookup(channel, p, "bind", "local"); } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf")); status = ARES_EFILE; } } } if(line) free(line); } #endif /* Handle errors. */ if (status != ARES_EOF) { if (servers != NULL) free(servers); if (sortlist != NULL) free(sortlist); return status; } /* If we got any name server entries, fill them in. */ #ifdef WIN32 okay: #endif if (servers) { channel->servers = servers; channel->nservers = nservers; } /* If we got any sortlist entries, fill them in. */ if (sortlist) { channel->sortlist = sortlist; channel->nsort = nsort; } return ARES_SUCCESS; }
/************************************************************************** * IQueryAssociations_GetString * * Get a file association string from the registry. * * PARAMS * cfFlags [I] ASSOCF_ flags from "shlwapi.h" * str [I] Type of string to get (ASSOCSTR enum from "shlwapi.h") * pszExtra [I] Extra information about the string location * pszOut [O] Destination for the association string * pcchOut [I/O] Length of pszOut * * RETURNS * Success: S_OK. pszOut contains the string, pcchOut contains its length. * Failure: An HRESULT error code indicating the error. */ HRESULT STDMETHODCALLTYPE CQueryAssociations::GetString( ASSOCF flags, ASSOCSTR str, LPCWSTR pszExtra, LPWSTR pszOut, DWORD *pcchOut) { const ASSOCF unimplemented_flags = ~ASSOCF_NOTRUNCATE; DWORD len = 0; HRESULT hr; WCHAR path[MAX_PATH]; TRACE("(%p)->(0x%08x, %u, %s, %p, %p)\n", this, flags, str, debugstr_w(pszExtra), pszOut, pcchOut); if (flags & unimplemented_flags) { FIXME("%08x: unimplemented flags\n", flags & unimplemented_flags); } if (!pcchOut) { return E_UNEXPECTED; } if (!this->hkeySource && !this->hkeyProgID) { return HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION); } switch (str) { case ASSOCSTR_COMMAND: { WCHAR *command; hr = this->GetCommand(pszExtra, &command); if (SUCCEEDED(hr)) { hr = this->ReturnString(flags, pszOut, pcchOut, command, strlenW(command) + 1); HeapFree(GetProcessHeap(), 0, command); } return hr; } case ASSOCSTR_EXECUTABLE: { hr = this->GetExecutable(pszExtra, path, MAX_PATH, &len); if (FAILED(hr)) { return hr; } len++; return this->ReturnString(flags, pszOut, pcchOut, path, len); } case ASSOCSTR_FRIENDLYDOCNAME: { WCHAR *pszFileType; hr = this->GetValue(this->hkeySource, NULL, (void**)&pszFileType, NULL); if (FAILED(hr)) { return hr; } DWORD size = 0; DWORD ret = RegGetValueW(HKEY_CLASSES_ROOT, pszFileType, NULL, RRF_RT_REG_SZ, NULL, NULL, &size); if (ret == ERROR_SUCCESS) { WCHAR *docName = static_cast<WCHAR *>(HeapAlloc(GetProcessHeap(), 0, size)); if (docName) { ret = RegGetValueW(HKEY_CLASSES_ROOT, pszFileType, NULL, RRF_RT_REG_SZ, NULL, docName, &size); if (ret == ERROR_SUCCESS) { hr = this->ReturnString(flags, pszOut, pcchOut, docName, strlenW(docName) + 1); } else { hr = HRESULT_FROM_WIN32(ret); } HeapFree(GetProcessHeap(), 0, docName); } else { hr = E_OUTOFMEMORY; } } else { hr = HRESULT_FROM_WIN32(ret); } HeapFree(GetProcessHeap(), 0, pszFileType); return hr; } case ASSOCSTR_FRIENDLYAPPNAME: { PVOID verinfoW = NULL; DWORD size, retval = 0; UINT flen; WCHAR *bufW; static const WCHAR translationW[] = L"\\VarFileInfo\\Translation"; static const WCHAR fileDescFmtW[] = L"\\StringFileInfo\\%04x%04x\\FileDescription"; WCHAR fileDescW[41]; hr = this->GetExecutable(pszExtra, path, MAX_PATH, &len); if (FAILED(hr)) { return hr; } retval = GetFileVersionInfoSizeW(path, &size); if (!retval) { goto get_friendly_name_fail; } verinfoW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, retval); if (!verinfoW) { return E_OUTOFMEMORY; } if (!GetFileVersionInfoW(path, 0, retval, verinfoW)) { goto get_friendly_name_fail; } if (VerQueryValueW(verinfoW, translationW, (LPVOID *)&bufW, &flen)) { UINT i; DWORD *langCodeDesc = (DWORD *)bufW; for (i = 0; i < flen / sizeof(DWORD); i++) { sprintfW(fileDescW, fileDescFmtW, LOWORD(langCodeDesc[i]), HIWORD(langCodeDesc[i])); if (VerQueryValueW(verinfoW, fileDescW, (LPVOID *)&bufW, &flen)) { /* Does strlenW(bufW) == 0 mean we use the filename? */ len = strlenW(bufW) + 1; TRACE("found FileDescription: %s\n", debugstr_w(bufW)); hr = this->ReturnString(flags, pszOut, pcchOut, bufW, len); HeapFree(GetProcessHeap(), 0, verinfoW); return hr; } } } get_friendly_name_fail: PathRemoveExtensionW(path); PathStripPathW(path); TRACE("using filename: %s\n", debugstr_w(path)); hr = this->ReturnString(flags, pszOut, pcchOut, path, strlenW(path) + 1); HeapFree(GetProcessHeap(), 0, verinfoW); return hr; } case ASSOCSTR_CONTENTTYPE: { static const WCHAR Content_TypeW[] = L"Content Type"; DWORD size = 0; DWORD ret = RegGetValueW(this->hkeySource, NULL, Content_TypeW, RRF_RT_REG_SZ, NULL, NULL, &size); if (ret != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(ret); } WCHAR *contentType = static_cast<WCHAR *>(HeapAlloc(GetProcessHeap(), 0, size)); if (contentType != NULL) { ret = RegGetValueW(this->hkeySource, NULL, Content_TypeW, RRF_RT_REG_SZ, NULL, contentType, &size); if (ret == ERROR_SUCCESS) { hr = this->ReturnString(flags, pszOut, pcchOut, contentType, strlenW(contentType) + 1); } else { hr = HRESULT_FROM_WIN32(ret); } HeapFree(GetProcessHeap(), 0, contentType); } else { hr = E_OUTOFMEMORY; } return hr; } case ASSOCSTR_DEFAULTICON: { static const WCHAR DefaultIconW[] = L"DefaultIcon"; DWORD ret; DWORD size = 0; ret = RegGetValueW(this->hkeyProgID, DefaultIconW, NULL, RRF_RT_REG_SZ, NULL, NULL, &size); if (ret == ERROR_SUCCESS) { WCHAR *icon = static_cast<WCHAR *>(HeapAlloc(GetProcessHeap(), 0, size)); if (icon) { ret = RegGetValueW(this->hkeyProgID, DefaultIconW, NULL, RRF_RT_REG_SZ, NULL, icon, &size); if (ret == ERROR_SUCCESS) { hr = this->ReturnString(flags, pszOut, pcchOut, icon, strlenW(icon) + 1); } else { hr = HRESULT_FROM_WIN32(ret); } HeapFree(GetProcessHeap(), 0, icon); } else { hr = HRESULT_FROM_WIN32(ret); } } else { hr = HRESULT_FROM_WIN32(ret); } return hr; } case ASSOCSTR_SHELLEXTENSION: { static const WCHAR shellexW[] = L"ShellEx\\"; WCHAR keypath[sizeof(shellexW) / sizeof(shellexW[0]) + 39], guid[39]; CLSID clsid; HKEY hkey; hr = CLSIDFromString(pszExtra, &clsid); if (FAILED(hr)) { return hr; } strcpyW(keypath, shellexW); strcatW(keypath, pszExtra); LONG ret = RegOpenKeyExW(this->hkeySource, keypath, 0, KEY_READ, &hkey); if (ret) { return HRESULT_FROM_WIN32(ret); } DWORD size = sizeof(guid); ret = RegGetValueW(hkey, NULL, NULL, RRF_RT_REG_SZ, NULL, guid, &size); RegCloseKey(hkey); if (ret) { return HRESULT_FROM_WIN32(ret); } return this->ReturnString(flags, pszOut, pcchOut, guid, size / sizeof(WCHAR)); } default: { FIXME("assocstr %d unimplemented!\n", str); return E_NOTIMPL; } } }
/* return -1 for normal run or any other value as exitcode */ int win9x_process(int argc, char **argv) { win9x_extend_service_name(); if (service_flag != w32_noservice && !Is9x()) { if (!quiet_flag) AllocTempConsole(); Log((quiet_flag?0:-1), "Can't operate witn Windows 9x services: incompatible OS type%s", quiet_flag?"":"\n"); return 1; } switch(service_flag) { case w32_queryservice: /* service control */ case w32_startservice: case w32_stopservice: case w32_restartservice: return !win9x_service_control(); case w32_installservice: /* (un)install binkd9x service */ case w32_uninstallservice: return !win9x_service_un_install(argc, argv); case w32_noservice: /* Run binkd9x */ quiet_flag = 1; return -1; case w32_run_as_service: /* Run binkd9x as service */ { char *tmp = NULL; unsigned char *path = NULL; int pathlen; HINSTANCE hl; HKEY hk; DWORD reg_type, size; tmp = win9x_make_Win9xRegParm(service_name); if (RegOpenKey(HKEY_LOCAL_MACHINE, tmp, &hk)==ERROR_SUCCESS) { /* extract current directory from registry */ size = 0; if ((RegQueryValueEx(hk, Win9xRegParm_Path, NULL, ®_type, NULL, &size)==ERROR_SUCCESS)&&(reg_type == REG_SZ)) { path = (unsigned char *)malloc(size); if ((RegQueryValueEx(hk, Win9xRegParm_Path, NULL, ®_type, path, &size) != ERROR_SUCCESS)||(reg_type != REG_SZ)) { free(path); path = NULL; } } RegCloseKey(hk); } free(tmp); if (!path) { /* extract current directory from argv[0] */ tmp = extract_filename(argv[0]); pathlen = tmp-argv[0]; if (pathlen>0) { path = (unsigned char *)malloc(pathlen+1); memcpy(path, argv[0], pathlen); path[pathlen] = 0; } } if (path) { SetCurrentDirectory((char*)path); free(path); } hl = LoadLibrary("KERNEL32.DLL"); if (hl != NULL) { RegisterServiceProcess = (RSPType)GetProcAddress(hl, "RegisterServiceProcess"); if (RegisterServiceProcess!=NULL) if (RegisterServiceProcess(0, RSP_SIMPLE_SERVICE)) w9x_service_reg = 1; FreeLibrary(hl); } quiet_flag = 1; } return -1; default: Log((quiet_flag?0:-1), "Unknown service control code (%i)\n", service_flag); return 1; } return -1; }
HRESULT CQueryAssociations::GetCommand(const WCHAR *extra, WCHAR **command) { HKEY hkeyCommand; HKEY hkeyShell; HKEY hkeyVerb; HRESULT hr; LONG ret; WCHAR *extra_from_reg = NULL; WCHAR *filetype; static const WCHAR commandW[] = L"command"; static const WCHAR shellW[] = L"shell"; /* When looking for file extension it's possible to have a default value that points to another key that contains 'shell/<verb>/command' subtree. */ hr = this->GetValue(this->hkeySource, NULL, (void**)&filetype, NULL); if (hr == S_OK) { HKEY hkeyFile; ret = RegOpenKeyExW(HKEY_CLASSES_ROOT, filetype, 0, KEY_READ, &hkeyFile); HeapFree(GetProcessHeap(), 0, filetype); if (ret == ERROR_SUCCESS) { ret = RegOpenKeyExW(hkeyFile, shellW, 0, KEY_READ, &hkeyShell); RegCloseKey(hkeyFile); } else { ret = RegOpenKeyExW(this->hkeySource, shellW, 0, KEY_READ, &hkeyShell); } } else { ret = RegOpenKeyExW(this->hkeySource, shellW, 0, KEY_READ, &hkeyShell); } if (ret) { return HRESULT_FROM_WIN32(ret); } if (!extra) { /* check for default verb */ hr = this->GetValue(hkeyShell, NULL, (void**)&extra_from_reg, NULL); if (FAILED(hr)) { /* no default verb, try first subkey */ DWORD max_subkey_len; ret = RegQueryInfoKeyW(hkeyShell, NULL, NULL, NULL, NULL, &max_subkey_len, NULL, NULL, NULL, NULL, NULL, NULL); if (ret) { RegCloseKey(hkeyShell); return HRESULT_FROM_WIN32(ret); } max_subkey_len++; extra_from_reg = static_cast<WCHAR*>(HeapAlloc(GetProcessHeap(), 0, max_subkey_len * sizeof(WCHAR))); if (!extra_from_reg) { RegCloseKey(hkeyShell); return E_OUTOFMEMORY; } ret = RegEnumKeyExW(hkeyShell, 0, extra_from_reg, &max_subkey_len, NULL, NULL, NULL, NULL); if (ret) { HeapFree(GetProcessHeap(), 0, extra_from_reg); RegCloseKey(hkeyShell); return HRESULT_FROM_WIN32(ret); } } extra = extra_from_reg; } /* open verb subkey */ ret = RegOpenKeyExW(hkeyShell, extra, 0, KEY_READ, &hkeyVerb); HeapFree(GetProcessHeap(), 0, extra_from_reg); RegCloseKey(hkeyShell); if (ret) { return HRESULT_FROM_WIN32(ret); } /* open command subkey */ ret = RegOpenKeyExW(hkeyVerb, commandW, 0, KEY_READ, &hkeyCommand); RegCloseKey(hkeyVerb); if (ret) { return HRESULT_FROM_WIN32(ret); } hr = this->GetValue(hkeyCommand, NULL, (void**)command, NULL); RegCloseKey(hkeyCommand); return hr; }
void init_system_mib(void) { #ifdef HAVE_UNAME struct utsname utsName; uname(&utsName); snprintf(version_descr, sizeof(version_descr), "%s %s %s %s %s", utsName.sysname, utsName.nodename, utsName.release, utsName.version, utsName.machine); version_descr[ sizeof(version_descr)-1 ] = 0; #else #if HAVE_EXECV struct extensible extmp; /* * set default values of system stuff */ sprintf(extmp.command, "%s -a", UNAMEPROG); /* * setup defaults */ extmp.type = EXECPROC; extmp.next = NULL; exec_command(&extmp); strncpy(version_descr, extmp.output, sizeof(version_descr)); version_descr[sizeof(version_descr) - 1] = 0; version_descr[strlen(version_descr) - 1] = 0; /* chomp new line */ #else #if (defined (WIN32) && defined (HAVE_WIN32_PLATFORM_SDK)) || defined (mingw32) windowsOSVersionString(version_descr, sizeof(version_descr)); #else strcpy(version_descr, "unknown"); #endif #endif #endif #ifdef HAVE_GETHOSTNAME gethostname(sysName, sizeof(sysName)); #else #ifdef HAVE_UNAME strncpy(sysName, utsName.nodename, sizeof(sysName)); #else #if defined (HAVE_EXECV) && !defined (mingw32) sprintf(extmp.command, "%s -n", UNAMEPROG); /* * setup defaults */ extmp.type = EXECPROC; extmp.next = NULL; exec_command(&extmp); strncpy(sysName, extmp.output, sizeof(sysName)); sysName[strlen(sysName) - 1] = 0; /* chomp new line */ #else strcpy(sysName, "unknown"); #endif /* HAVE_EXECV */ #endif /* HAVE_UNAME */ #endif /* HAVE_GETHOSTNAME */ #if (defined (WIN32) && defined (HAVE_WIN32_PLATFORM_SDK)) || defined (mingw32) { HKEY hKey; /* Default sysContact is the registered windows user */ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) { char registeredOwner[256] = ""; DWORD registeredOwnerSz = 256; if (RegQueryValueEx(hKey, "RegisteredOwner", NULL, NULL, (LPBYTE)registeredOwner, ®isteredOwnerSz) == ERROR_SUCCESS) { strcpy(sysContact, registeredOwner); } RegCloseKey(hKey); } } #endif /* default sysObjectID */ memcpy(sysObjectID, version_sysoid, version_sysoid_len * sizeof(oid)); sysObjectIDByteLength = version_sysoid_len * sizeof(oid); { const oid sysDescr_oid[] = { 1, 3, 6, 1, 2, 1, 1, 1 }; static netsnmp_watcher_info sysDescr_winfo; netsnmp_register_watched_scalar( netsnmp_create_handler_registration( "mibII/sysDescr", NULL, sysDescr_oid, OID_LENGTH(sysDescr_oid), HANDLER_CAN_RONLY), netsnmp_init_watcher_info(&sysDescr_winfo, version_descr, 0, ASN_OCTET_STR, WATCHER_SIZE_STRLEN)); } { const oid sysObjectID_oid[] = { 1, 3, 6, 1, 2, 1, 1, 2 }; static netsnmp_watcher_info sysObjectID_winfo; netsnmp_register_watched_scalar( netsnmp_create_handler_registration( "mibII/sysObjectID", NULL, sysObjectID_oid, OID_LENGTH(sysObjectID_oid), HANDLER_CAN_RONLY), netsnmp_init_watcher_info6( &sysObjectID_winfo, sysObjectID, 0, ASN_OBJECT_ID, WATCHER_MAX_SIZE | WATCHER_SIZE_IS_PTR, MAX_OID_LEN, &sysObjectIDByteLength)); } { const oid sysUpTime_oid[] = { 1, 3, 6, 1, 2, 1, 1, 3 }; netsnmp_register_scalar( netsnmp_create_handler_registration( "mibII/sysUpTime", handle_sysUpTime, sysUpTime_oid, OID_LENGTH(sysUpTime_oid), HANDLER_CAN_RONLY)); } { const oid sysContact_oid[] = { 1, 3, 6, 1, 2, 1, 1, 4 }; static netsnmp_watcher_info sysContact_winfo; netsnmp_register_watched_scalar( netsnmp_create_update_handler_registration( "mibII/sysContact", sysContact_oid, OID_LENGTH(sysContact_oid), HANDLER_CAN_RWRITE, &sysContactSet), netsnmp_init_watcher_info( &sysContact_winfo, sysContact, SYS_STRING_LEN - 1, ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN)); } { const oid sysName_oid[] = { 1, 3, 6, 1, 2, 1, 1, 5 }; static netsnmp_watcher_info sysName_winfo; netsnmp_register_watched_scalar( netsnmp_create_update_handler_registration( "mibII/sysName", sysName_oid, OID_LENGTH(sysName_oid), HANDLER_CAN_RWRITE, &sysNameSet), netsnmp_init_watcher_info( &sysName_winfo, sysName, SYS_STRING_LEN - 1, ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN)); } { const oid sysLocation_oid[] = { 1, 3, 6, 1, 2, 1, 1, 6 }; static netsnmp_watcher_info sysLocation_winfo; netsnmp_register_watched_scalar( netsnmp_create_update_handler_registration( "mibII/sysLocation", sysLocation_oid, OID_LENGTH(sysLocation_oid), HANDLER_CAN_RWRITE, &sysLocationSet), netsnmp_init_watcher_info( &sysLocation_winfo, sysLocation, SYS_STRING_LEN - 1, ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN)); } { const oid sysServices_oid[] = { 1, 3, 6, 1, 2, 1, 1, 7 }; netsnmp_register_read_only_int_scalar( "mibII/sysServices", sysServices_oid, OID_LENGTH(sysServices_oid), &sysServices, handle_sysServices); } if (++system_module_count == 3) REGISTER_SYSOR_ENTRY(system_module_oid, "The MIB module for SNMPv2 entities"); sysContactSet = sysLocationSet = sysNameSet = 0; /* * register our config handlers */ snmpd_register_config_handler("sysdescr", system_parse_config_sysdescr, NULL, "description"); snmpd_register_config_handler("syslocation", system_parse_config_sysloc, NULL, "location"); snmpd_register_config_handler("syscontact", system_parse_config_syscon, NULL, "contact-name"); snmpd_register_config_handler("sysname", system_parse_config_sysname, NULL, "node-name"); snmpd_register_config_handler("psyslocation", system_parse_config_sysloc, NULL, NULL); snmpd_register_config_handler("psyscontact", system_parse_config_syscon, NULL, NULL); snmpd_register_config_handler("psysname", system_parse_config_sysname, NULL, NULL); snmpd_register_config_handler("sysservices", system_parse_config_sysServices, NULL, "NUMBER"); snmpd_register_config_handler("sysobjectid", system_parse_config_sysObjectID, NULL, "OID"); snmp_register_callback(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_STORE_DATA, system_store, NULL); }
/************************************************************************** * IQueryAssociations_Init * * Initialise an IQueryAssociations object. * * PARAMS * cfFlags [I] ASSOCF_ flags from "shlwapi.h" * pszAssoc [I] String for the root key name, or NULL if hkeyProgid is given * hkeyProgid [I] Handle for the root key, or NULL if pszAssoc is given * hWnd [I] Reserved, must be NULL. * * RETURNS * Success: S_OK. iface is initialised with the parameters given. * Failure: An HRESULT error code indicating the error. */ HRESULT STDMETHODCALLTYPE CQueryAssociations::Init( ASSOCF cfFlags, LPCWSTR pszAssoc, HKEY hkeyProgid, HWND hWnd) { static const WCHAR szProgID[] = L"ProgID"; TRACE("(%p)->(%d,%s,%p,%p)\n", this, cfFlags, debugstr_w(pszAssoc), hkeyProgid, hWnd); if (hWnd != NULL) { FIXME("hwnd != NULL not supported\n"); } if (cfFlags != 0) { FIXME("unsupported flags: %x\n", cfFlags); } RegCloseKey(this->hkeySource); RegCloseKey(this->hkeyProgID); this->hkeySource = this->hkeyProgID = NULL; if (pszAssoc != NULL) { WCHAR *progId; HRESULT hr; LONG ret = RegOpenKeyExW(HKEY_CLASSES_ROOT, pszAssoc, 0, KEY_READ, &this->hkeySource); if (ret) { return S_OK; } /* if this is a progid */ if (*pszAssoc != '.' && *pszAssoc != '{') { this->hkeyProgID = this->hkeySource; return S_OK; } /* if it's not a progid, it's a file extension or clsid */ if (*pszAssoc == '.') { /* for a file extension, the progid is the default value */ hr = this->GetValue(this->hkeySource, NULL, (void**)&progId, NULL); if (FAILED(hr)) return S_OK; } else /* if (*pszAssoc == '{') */ { HKEY progIdKey; /* for a clsid, the progid is the default value of the ProgID subkey */ ret = RegOpenKeyExW(this->hkeySource, szProgID, 0, KEY_READ, &progIdKey); if (ret != ERROR_SUCCESS) return S_OK; hr = this->GetValue(progIdKey, NULL, (void**)&progId, NULL); if (FAILED(hr)) return S_OK; RegCloseKey(progIdKey); } /* open the actual progid key, the one with the shell subkey */ ret = RegOpenKeyExW(HKEY_CLASSES_ROOT, progId, 0, KEY_READ, &this->hkeyProgID); HeapFree(GetProcessHeap(), 0, progId); return S_OK; } else if (hkeyProgid != NULL) { /* reopen the key so we don't end up closing a key owned by the caller */ RegOpenKeyExW(hkeyProgid, NULL, 0, KEY_READ, &this->hkeyProgID); this->hkeySource = this->hkeyProgID; return S_OK; } else return E_INVALIDARG; }
static VOID SetScreenSaver(HWND hwndDlg, PDATA pData) { HKEY regKey; BOOL DeleteMode = FALSE; if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("Control Panel\\Desktop"), 0, KEY_ALL_ACCESS, ®Key) == ERROR_SUCCESS) { INT Time; BOOL bRet; TCHAR Sec; UINT Ret; /* Set the screensaver */ if (pData->ScreenSaverItems[pData->Selection].bIsScreenSaver) { RegSetValueEx(regKey, _T("SCRNSAVE.EXE"), 0, REG_SZ, (PBYTE)pData->ScreenSaverItems[pData->Selection].szFilename, _tcslen(pData->ScreenSaverItems[pData->Selection].szFilename) * sizeof(TCHAR)); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, TRUE, 0, SPIF_UPDATEINIFILE); } else { /* Windows deletes the value if no screensaver is set */ RegDeleteValue(regKey, _T("SCRNSAVE.EXE")); DeleteMode = TRUE; SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, 0, SPIF_UPDATEINIFILE); } /* Set the secure value */ Ret = SendDlgItemMessage(hwndDlg, IDC_SCREENS_USEPASSCHK, BM_GETCHECK, 0, 0); Sec = (Ret == BST_CHECKED) ? _T('1') : _T('0'); RegSetValueEx(regKey, _T("ScreenSaverIsSecure"), 0, REG_SZ, (PBYTE)&Sec, sizeof(TCHAR)); /* Set the screensaver time delay */ Time = GetDlgItemInt(hwndDlg, IDC_SCREENS_TIMEDELAY, &bRet, FALSE); if (Time == 0) Time = 60; else Time *= 60; SystemParametersInfoW(SPI_SETSCREENSAVETIMEOUT, Time, 0, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE); RegCloseKey(regKey); } }
/*********************************************************************** * register_coclasses */ static HRESULT register_coclasses(struct regsvr_coclass const *list) { LONG res = ERROR_SUCCESS; HKEY coclass_key; res = RegCreateKeyExW(HKEY_CLASSES_ROOT, clsid_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &coclass_key, NULL); if (res != ERROR_SUCCESS) goto error_return; for (; res == ERROR_SUCCESS && list->clsid; ++list) { WCHAR buf[39]; HKEY clsid_key; StringFromGUID2(list->clsid, buf, 39); res = RegCreateKeyExW(coclass_key, buf, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &clsid_key, NULL); if (res != ERROR_SUCCESS) goto error_close_coclass_key; if (list->name) { res = RegSetValueExA(clsid_key, NULL, 0, REG_SZ, (CONST BYTE*)(list->name), strlen(list->name) + 1); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->ips) { res = register_key_defvalueA(clsid_key, ips_keyname, list->ips); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->ips32) { HKEY ips32_key; res = RegCreateKeyExW(clsid_key, ips32_keyname, 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &ips32_key, NULL); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = RegSetValueExA(ips32_key, NULL, 0, REG_SZ, (CONST BYTE*)list->ips32, lstrlenA(list->ips32) + 1); if (res == ERROR_SUCCESS && list->ips32_tmodel) res = RegSetValueExA(ips32_key, tmodel_valuename, 0, REG_SZ, (CONST BYTE*)list->ips32_tmodel, strlen(list->ips32_tmodel) + 1); RegCloseKey(ips32_key); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->progid) { res = register_key_defvalueA(clsid_key, progid_keyname, list->progid); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = register_progid(buf, list->progid, NULL, list->name, list->progid_extra); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } if (list->viprogid) { res = register_key_defvalueA(clsid_key, viprogid_keyname, list->viprogid); if (res != ERROR_SUCCESS) goto error_close_clsid_key; res = register_progid(buf, list->viprogid, list->progid, list->name, list->progid_extra); if (res != ERROR_SUCCESS) goto error_close_clsid_key; } error_close_clsid_key: RegCloseKey(clsid_key); } error_close_coclass_key: RegCloseKey(coclass_key); error_return: return res != ERROR_SUCCESS ? HRESULT_FROM_WIN32(res) : S_OK; }