Skip to content

Commit

Permalink
Merge pull request #4 from 21pages/master
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanaasagi committed Jul 11, 2023
2 parents 08c1c91 + 381ff57 commit cd8c8e9
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 2 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ Get os native machine id without root permission.

[target.'cfg(windows)'.dependencies]
winreg = "0.11"

[build-dependencies]
cc = "1.0"
bindgen = "0.59"
10 changes: 10 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use cc::Build;

fn main() {
println!("cargo:rerun-if-changed=src");
#[cfg(target_os = "windows")]
{
println!("cargo:rustc-link-lib=Kernel32");
Build::new().file("src/win.cpp").compile("machine-uid");
}
}
16 changes: 14 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,25 @@ mod machine_id {
#[cfg(target_os = "windows")]
pub mod machine_id {
use std::error::Error;
use winreg::enums::HKEY_LOCAL_MACHINE;
use std::ffi::c_int;
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY};
use winreg::RegKey;

extern "C" {
fn MachineUidIsWow64() -> c_int;
}

/// Return machine id
pub fn get_machine_id() -> Result<String, Box<dyn Error>> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let crypto = hklm.open_subkey("SOFTWARE\\Microsoft\\Cryptography")?;

let flag = if unsafe { MachineUidIsWow64() == 1 } && cfg!(target_pointer_width = "32") {
KEY_READ | KEY_WOW64_64KEY
} else {
KEY_READ
};

let crypto = hklm.open_subkey_with_flags("SOFTWARE\\Microsoft\\Cryptography", flag)?;
let id: String = crypto.get_value("MachineGuid")?;

Ok(id.trim().to_string())
Expand Down
29 changes: 29 additions & 0 deletions src/win.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <windows.h>
#include <tchar.h>

// https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

static LPFN_ISWOW64PROCESS fnIsWow64Process;

extern "C" BOOL MachineUidIsWow64()
{
BOOL bIsWow64 = FALSE;

//IsWow64Process is not available on all supported versions of Windows.
//Use GetModuleHandle to get a handle to the DLL that contains the function
//and GetProcAddress to get a pointer to the function if available.

fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
GetModuleHandle(TEXT("kernel32")),"IsWow64Process");

if(NULL != fnIsWow64Process)
{
if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
{
//handle error
}
}
return bIsWow64;
}

0 comments on commit cd8c8e9

Please sign in to comment.