Expand the passive inventory shown in device details
Rust development slice / linux (push) Failing after 9s

This commit is contained in:
2026-11-18 20:02:41 +01:00
parent 38f43f887a
commit aea2d5b379
15 changed files with 701 additions and 45 deletions
@@ -14,6 +14,8 @@ Die RAM-Spalte zeigt den für Anwendungen verfügbaren und den gesamten physisch
Kunden lassen sich in der WebUI anlegen und umbenennen. Beim Kundenwechsel erhält das Gerät eine neue Kopplung. Eine ausgeschiedene Installation kann nach Widerruf und persönlicher Bestätigung endgültig gelöscht werden. Ein noch gültiger offener Genehmigungsantrag oder ein nicht abgeschlossener Job einschließlich `unknown` sperrt die Löschung. Daten weiterhin beteiligter Zielgeräte bleiben erhalten. [Regeln zur Löschung](migrations/0036_delete_device_pairing.sql)
In den Gerätedetails erscheinen OS-Installationszeit, letzter Systemstart, Hersteller, BIOS-Seriennummer, Netzwerkkarten samt IPv4- und IPv6-Adressen, installierte Software und die bei der letzten Inventur angemeldeten Benutzer. Windows meldet den vom Betriebssystem erfassten Installationszeitpunkt. Linux kennzeichnet den Zeitstempel aus dem Installer-Verzeichnis oder dem Root-Dateisystem als Schätzung. Das Softwareinventar erfasst Linux-Pakete aus dpkg und Windows-Systeminstallationen aus der Uninstall-Registrierung. Begrenzte Meldungen werden ausgewiesen. Herstellergarantie und Firmwaredaten erscheinen bei verfügbarem Befund. Die Daten gehören zum kundengebundenen Inventar des Geräts. [Geräteansicht](web/src/device-inventory.tsx)
## Vom Skript zum Ergebnis
| Schritt | Verhalten |
+122 -8
View File
@@ -4,7 +4,7 @@ use crate::{
actions::{ServiceUnit, reboot_required},
process,
};
use rmm_domain::inventory_document::{CpuTimes, DeviceType};
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{
collections::BTreeMap,
ffi::{CStr, CString},
@@ -169,6 +169,9 @@ pub struct OperatingSystem {
pub hostname: String,
pub boot_id: String,
pub uptime_seconds: f64,
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
pub install_date_source: Option<&'static str>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Interface {
@@ -260,6 +263,8 @@ pub struct Hardware {
pub readable_dmi: BTreeMap<String, String>,
pub device_type: Option<DeviceType>,
pub proxmox_ve: bool,
pub manufacturer: Option<String>,
pub bios_serial_number: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LinuxInventory {
@@ -271,6 +276,7 @@ pub struct LinuxInventory {
pub dns: Observation<Dns>,
pub volumes: Observation<Vec<Observation<Volume>>>,
pub software: Observation<Vec<SoftwarePackage>>,
pub users: Observation<Vec<String>>,
pub updates: Observation<UpdateStatus>,
pub hardware: Observation<Hardware>,
pub smart: Observation<()>,
@@ -285,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
dns: dns(),
volumes: volumes(),
software: software(),
users: logged_in_users(),
updates: updates(),
hardware: hardware(),
smart: Observation::unavailable(
@@ -380,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
);
result
}
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
for (path, source) in [
("/var/log/installer", "installer_directory"),
("/", "root_filesystem"),
] {
if let Some(time) = fs::metadata(path)
.ok()
.and_then(|data| data.created().ok())
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
{
return Some((time.into(), source));
}
}
None
}
pub fn operating_system() -> Observation<OperatingSystem> {
let release = read("/etc/os-release", 32 * 1024);
let kernel = read("/proc/sys/kernel/osrelease", 4096);
@@ -417,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
.map(|(k, v)| (k.into(), v.trim_matches('"').into()))
})
.collect();
let booted_at = read("/proc/stat", 256 * 1024)
.data
.as_deref()
.and_then(|stat| {
let seconds = stat
.lines()
.find_map(|line| line.strip_prefix("btime "))?
.trim()
.parse()
.ok()?;
chrono::DateTime::from_timestamp(seconds, 0)
});
let installed = installed_at();
Observation::valid(
"linux.os:/etc/os-release,/proc",
"linux.os:/etc/os-release,/proc,filesystem-birth",
OperatingSystem {
release,
kernel: kernel.trim().into(),
@@ -426,12 +462,74 @@ pub fn operating_system() -> Observation<OperatingSystem> {
hostname: hostname.trim().into(),
boot_id,
uptime_seconds,
booted_at,
installed_at: installed.map(|(time, _)| time),
install_date_source: installed.map(|(_, source)| source),
},
)
} else {
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
}
}
fn logged_in_users() -> Observation<Vec<String>> {
const LOGINCTL: &str = "/usr/bin/loginctl";
let listed = command(
LOGINCTL,
&["--no-legend", "--no-pager", "list-sessions"],
16 * 1024,
);
let Some(rows) = &listed.data else {
return map(listed, |_| None);
};
let mut ids = rows
.lines()
.filter_map(|line| line.split_whitespace().next());
let mut args = vec![
"--no-pager",
"--all",
"--property=Name,Class,State",
"show-session",
"--",
];
args.extend(
ids.by_ref()
.take(64)
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
);
let limited = listed.truncated || ids.next().is_some();
if args.len() == 5 {
return Observation::valid("linux.logind:loginctl", Vec::new());
}
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
let users: std::collections::BTreeSet<_> = text
.split("\n\n")
.filter_map(|block| {
let fields: BTreeMap<_, _> = block
.lines()
.filter_map(|line| line.split_once('='))
.collect();
let class = *fields.get("Class")?;
let state = *fields.get("State")?;
let name = *fields.get("Name")?;
(matches!(
class,
"user" | "user-early" | "user-light" | "user-early-light"
) && matches!(state, "online" | "active")
&& !name.is_empty()
&& name.len() <= 255)
.then(|| name.to_owned())
})
.collect();
Some(users.into_iter().collect())
});
report.source_id = "linux.logind:loginctl".into();
if limited && report.data.is_some() {
report = report.partial("SESSION_LIMIT");
report.truncated = true;
}
report
}
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
stat.lines()
.find(|line| line.starts_with("cpu "))
@@ -583,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
}
libc::AF_INET6 => {
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
addresses.push(format!(
"{}%{}",
Ipv6Addr::from(addr.sin6_addr.s6_addr),
addr.sin6_scope_id
));
let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
addresses.push(if addr.sin6_scope_id == 0 {
ip.to_string()
} else {
format!("{ip}%{}", addr.sin6_scope_id)
});
}
_ => {}
}
@@ -1194,7 +1293,20 @@ pub fn hardware() -> Observation<Hardware> {
let proxmox_ve =
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
let device_type = machine_type(proxmox_ve);
if readable_dmi.is_empty() && device_type.is_none() {
let manufacturer = readable_dmi
.get("sys_vendor")
.and_then(|value| firmware_identifier(value));
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
let bios_serial_number = [
Some("/sys/class/dmi/id/product_serial"),
Some("/proc/device-tree/serial-number"),
serial_credential.as_deref().and_then(Path::to_str),
]
.into_iter()
.flatten()
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
} else {
Observation::valid(
@@ -1203,6 +1315,8 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi,
device_type,
proxmox_ve,
manufacturer,
bios_serial_number,
},
)
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
+14 -4
View File
@@ -1,5 +1,5 @@
//! Additive JSON observation mapping inside the existing snapshot payload. This
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
//! does not introduce a protobuf tag or a fabricated receive time.
use anyhow::Result;
use serde_json::{Value, json};
@@ -14,7 +14,12 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
observation["scope"] = json!(format!("linux.{name}"));
// Bound each scope independently. Never drop unsupported/error metadata
// or imply that absent/truncated rows were deleted from a device.
while serde_json::to_vec(&observation)?.len() > 32768 {
let max_bytes = if name == "software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
while serde_json::to_vec(&observation)?.len() > max_bytes {
observation["truncated"] = json!(true);
observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
@@ -49,7 +54,7 @@ mod tests {
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
let native = crate::inventory::collect_native();
let mapped = observations(&native).unwrap();
assert_eq!(mapped.len(), 11);
assert_eq!(mapped.len(), 12);
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
assert_eq!(smart["quality"], "unsupported");
assert!(smart["data"].is_null());
@@ -61,7 +66,12 @@ mod tests {
);
assert!(!observation["source_id"].as_str().unwrap().is_empty());
assert!(observation.get("received_at").is_none());
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
let limit = if observation["scope"] == "linux.software" {
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
}
let base = snapshot(false).unwrap();
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
+1 -1
View File
@@ -52,7 +52,7 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
[[example]]
name = "windows_reviewed_recovery"
+32 -20
View File
@@ -2,7 +2,9 @@
//! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure};
use chrono::Utc;
use rmm_domain::inventory_document::{CpuTimes, DeviceType};
use rmm_domain::inventory_document::{
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
};
use serde_json::{Value, json};
use std::{
mem::{size_of, zeroed},
@@ -120,28 +122,18 @@ fn classify_machine(
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
}
fn machine_type() -> Option<DeviceType> {
fn machine_type(manufacturer: Option<&str>, product: Option<&str>) -> Option<DeviceType> {
let hyper_v_host = open(
HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Services\vmms",
KEY_WOW64_64KEY,
)
.is_ok();
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
KEY_WOW64_64KEY,
)
.ok();
let read = |name| {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
read("SystemManufacturer").as_deref(),
read("SystemProductName").as_deref(),
manufacturer,
product,
)
}
@@ -201,16 +193,34 @@ fn hardware() -> Result<Value> {
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty());
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
KEY_WOW64_64KEY,
)
.ok();
let read = |name| {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
let manufacturer = read("SystemManufacturer").and_then(|value| firmware_identifier(&value));
let product = read("SystemProductName");
let bios_serial_number = read("SystemSerialNumber")
.and_then(|value| firmware_identifier(&value))
.or_else(crate::inventory_sources::bios_serial);
Ok(
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad,"device_type":machine_type()}),
"memory_load_percent":memory.dwMemoryLoad,
"device_type":machine_type(manufacturer.as_deref(),product.as_deref()),
"manufacturer":manufacturer,"bios_serial_number":bios_serial_number}),
)
}
fn software() -> Result<Value> {
let began = Instant::now();
let mut entries = Vec::new();
let mut entry_bytes = 0;
let mut errors = 0u32;
let mut scanned = 0u32;
let mut truncated = false;
@@ -232,7 +242,7 @@ fn software() -> Result<Value> {
}
};
for index in 0..2048 {
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
if began.elapsed() > Duration::from_millis(250) {
truncated = true;
break;
}
@@ -274,12 +284,12 @@ fn software() -> Result<Value> {
})();
match entry {
Ok(Some(entry)) => {
entries.push(entry);
if serde_json::to_vec(&entries)?.len() > 12288 {
entries.pop();
entry_bytes += serde_json::to_vec(&entry)?.len() + 1;
if entry_bytes > SOFTWARE_OBSERVATION_MAX_BYTES - 2048 {
truncated = true;
break;
}
entries.push(entry);
}
Ok(None) => {}
Err(_) => errors += 1,
@@ -310,7 +320,7 @@ pub fn observations() -> Vec<Value> {
[
(
"windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor,BIOS,vmms;cpuid",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
hardware as Provider,
),
(
@@ -318,6 +328,8 @@ pub fn observations() -> Vec<Value> {
"windows.registry:HKLM.Uninstall:64+32",
software as Provider,
),
("windows.interfaces", "windows.win32:GetAdaptersAddresses", crate::inventory_sources::interfaces as Provider),
("windows.users", "windows.win32:WTSEnumerateSessions", crate::inventory_sources::users as Provider),
]
.into_iter()
.map(|(scope, source, collect)| {
@@ -0,0 +1,266 @@
//! Local read-only inventory providers. Each result is bounded independently.
use anyhow::{Context, Result, ensure};
use rmm_domain::inventory_document::firmware_identifier;
use serde_json::{Value, json};
use std::{
collections::BTreeSet,
ffi::c_void,
mem::size_of,
net::{Ipv4Addr, Ipv6Addr},
ptr, slice,
};
use windows_sys::Win32::{
Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_NO_DATA, ERROR_SUCCESS},
NetworkManagement::IpHelper::*,
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, SOCKET_ADDRESS,
},
System::{
RemoteDesktop::*,
SystemInformation::{GetSystemFirmwareTable, RSMB},
},
};
pub(crate) fn bios_serial() -> Option<String> {
let length = unsafe { GetSystemFirmwareTable(RSMB, 0, ptr::null_mut(), 0) };
if !(8..=1024 * 1024).contains(&length) {
return None;
}
let mut data = vec![0; length as usize];
if unsafe { GetSystemFirmwareTable(RSMB, 0, data.as_mut_ptr(), length) } != length {
return None;
}
let count = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
smbios_serial(data.get(8..)?.get(..count)?)
}
fn smbios_serial(mut table: &[u8]) -> Option<String> {
while let Some(header) = table.get(..4) {
let length = usize::from(header[1]);
if length < 4 || header[0] == 127 {
break;
}
let strings = table.get(length..)?;
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
if header[0] == 1 {
let offset = usize::from(*table.get(..length)?.get(7)?).checked_sub(1)?;
let serial = strings[..end].split(|&c| c == 0).nth(offset)?;
return firmware_identifier(std::str::from_utf8(serial).ok()?);
}
table = strings.get(end + 2..)?;
}
None
}
// Pointer fields returned by IP Helper refer into its caller-provided buffer.
fn at<T>(buffer: &[u64], pointer: *const T) -> Option<&T> {
let offset = (pointer as usize).checked_sub(buffer.as_ptr() as usize)?;
if offset.checked_add(size_of::<T>())? > std::mem::size_of_val(buffer) || !pointer.is_aligned()
{
return None;
}
Some(unsafe { &*pointer })
}
fn wide_name(buffer: &[u64], pointer: *const u16) -> Option<String> {
let mut text = Vec::new();
for i in 0..256 {
let character = *at(buffer, pointer.wrapping_add(i))?;
if character == 0 {
return (!text.is_empty()).then(|| String::from_utf16_lossy(&text));
}
text.push(character);
}
None
}
fn ip_address(buffer: &[u64], address: SOCKET_ADDRESS) -> Option<String> {
let sockaddr = at(buffer, address.lpSockaddr)?;
match sockaddr.sa_family {
AF_INET if address.iSockaddrLength >= size_of::<SOCKADDR_IN>() as i32 => {
let ipv4 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN>())?;
Some(Ipv4Addr::from(unsafe { ipv4.sin_addr.S_un.S_addr }.to_ne_bytes()).to_string())
}
AF_INET6 if address.iSockaddrLength >= size_of::<SOCKADDR_IN6>() as i32 => {
let ipv6 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN6>())?;
let ip = Ipv6Addr::from(unsafe { ipv6.sin6_addr.u.Byte });
let scope = unsafe { ipv6.Anonymous.sin6_scope_id };
Some(if scope == 0 {
ip.to_string()
} else {
format!("{ip}%{scope}")
})
}
_ => None,
}
}
pub(crate) fn interfaces() -> Result<Value> {
let mut bytes = 15360_u32;
let mut buffer = vec![0_u64; (bytes as usize).div_ceil(8)];
let flags = GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_INCLUDE_ALL_INTERFACES;
let mut status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
if status == ERROR_BUFFER_OVERFLOW && bytes <= 1024 * 1024 {
buffer.resize((bytes as usize).div_ceil(8), 0);
status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
}
if status == ERROR_NO_DATA {
return Ok(json!({"entries":[],"truncated":false}));
}
ensure!(status == ERROR_SUCCESS, "ADAPTER_ADDRESSES");
let mut current = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
let mut entries = Vec::new();
let mut truncated = false;
let mut size = 0;
while !current.is_null() && entries.len() < 128 {
let adapter = at(&buffer, current).context("ADAPTER_POINTER")?;
let mut next = adapter.FirstUnicastAddress.cast_const();
let mut addresses = BTreeSet::new();
for _ in 0..64 {
if next.is_null() {
break;
}
let address = at(&buffer, next).context("ADAPTER_ADDRESS_POINTER")?;
if let Some(ip) = ip_address(&buffer, address.Address) {
addresses.insert(ip);
}
next = address.Next.cast_const();
}
truncated |= !next.is_null();
let name = wide_name(&buffer, adapter.FriendlyName)
.or_else(|| wide_name(&buffer, adapter.Description))
.unwrap_or_else(|| {
format!("Adapter {}", unsafe {
adapter.Anonymous1.Anonymous.IfIndex
})
});
let mac = adapter
.PhysicalAddress
.get(..adapter.PhysicalAddressLength as usize)
.filter(|bytes| !bytes.is_empty())
.map(|bytes| {
bytes
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<_>>()
.join(":")
});
let entry = json!({"name":name,"addresses":addresses,"mac":mac});
size += serde_json::to_vec(&entry)?.len() + 1;
if size > 30 * 1024 {
truncated = true;
break;
}
entries.push(entry);
current = adapter.Next.cast_const();
}
Ok(json!({"entries":entries,"truncated":truncated || !current.is_null()}))
}
struct WtsMemory(*mut c_void);
impl Drop for WtsMemory {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { WTSFreeMemory(self.0) };
}
}
}
fn session_text(id: u32, class: WTS_INFO_CLASS) -> Option<String> {
let mut text = ptr::null_mut();
let mut bytes = 0;
if unsafe { WTSQuerySessionInformationW(ptr::null_mut(), id, class, &mut text, &mut bytes) }
== 0
{
return None;
}
let _guard = WtsMemory(text.cast());
if text.is_null() || !(2..=512).contains(&bytes) || bytes % 2 != 0 {
return None;
}
let units = unsafe { slice::from_raw_parts(text, (bytes / 2) as usize) };
String::from_utf16(units.split(|c| *c == 0).next()?).ok()
}
pub(crate) fn users() -> Result<Value> {
let mut list = ptr::null_mut();
let mut count = 0;
ensure!(
unsafe { WTSEnumerateSessionsW(ptr::null_mut(), 0, 1, &mut list, &mut count) } != 0,
"SESSION_QUERY"
);
let _guard = WtsMemory(list.cast());
let mut entries = BTreeSet::new();
let mut errors = 0;
let mut truncated = count > 256;
if count != 0 {
ensure!(!list.is_null(), "SESSION_LIST");
for session in unsafe { slice::from_raw_parts(list, count.min(256) as usize) } {
if session.SessionId == 0
|| ![WTSActive, WTSConnected, WTSDisconnected].contains(&session.State)
{
continue;
}
match session_text(session.SessionId, WTSUserName) {
Some(name) if !name.is_empty() => {
let account = match session_text(session.SessionId, WTSDomainName) {
Some(domain) if !domain.is_empty() => format!("{domain}\\{name}"),
_ => name,
};
if entries.len() >= 64 {
truncated = true;
break;
}
if account.len() <= 255 && !account.chars().any(char::is_control) {
entries.insert(account);
} else {
errors += 1;
}
}
Some(_) => {}
None => errors += 1,
}
}
}
ensure!(
errors == 0 || !entries.is_empty(),
"SESSION_INFORMATION_UNAVAILABLE"
);
Ok(json!({"entries":entries,"read_errors":errors,"truncated":truncated}))
}
#[cfg(test)]
mod tests {
use super::smbios_serial;
#[test]
fn reads_the_system_serial_and_rejects_incomplete_entries() {
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0\0").as_deref(),
Some("ABC-123")
);
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0"),
None
);
}
}
+1
View File
@@ -24,6 +24,7 @@ pub mod helper_system;
pub mod windows_update_setup;
#[cfg(windows)]
pub mod inventory;
mod inventory_sources;
#[cfg(windows)]
pub mod job_binding;
pub mod journal;
+27 -4
View File
@@ -1,6 +1,6 @@
//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
use anyhow::{Context, Result, ensure};
use chrono::Utc;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
@@ -261,7 +261,23 @@ pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
Ok(String::from_utf16(&name[..len as usize])?)
}
fn install_date() -> Option<DateTime<Utc>> {
let key = wide(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
let name = wide("InstallDate");
let mut seconds = 0_u32;
let mut bytes = size_of::<u32>() as u32;
let status = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE,key.as_ptr(),name.as_ptr(),RRF_RT_REG_DWORD,
ptr::null_mut(),ptr::from_mut(&mut seconds).cast(),&mut bytes) };
(status == 0 && bytes as usize == size_of::<u32>() && seconds > 0)
.then(|| DateTime::from_timestamp(i64::from(seconds), 0))
.flatten().filter(|time| *time <= Utc::now())
}
pub fn snapshot() -> Result<Value> {
snapshot_with_boot(None)
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?;
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
@@ -281,7 +297,7 @@ pub fn snapshot() -> Result<Value> {
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed,
"observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]});
@@ -292,7 +308,7 @@ pub fn snapshot() -> Result<Value> {
snapshot["collection_completed_at"] = json!(Utc::now());
Ok(snapshot)
}
pub async fn boot_id() -> Result<String> {
pub async fn boot_identity() -> Result<(String, DateTime<Utc>)> {
// Fixed passive query only. Never interpolates a job or caller-supplied code.
// Avoid Win32_Product: it can cause MSI consistency checks and repairs.
let executable = Path::new(&std::env::var("SystemRoot")?)
@@ -328,7 +344,14 @@ if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
.try_into()?;
bytes[6] = (bytes[6] & 15) | 0x80;
bytes[8] = (bytes[8] & 63) | 0x80;
Ok(uuid::Uuid::from_bytes(bytes).to_string())
let ticks = text.parse::<i64>()?.checked_sub(621_355_968_000_000_000).context("BOOT_EPOCH")?;
let time = DateTime::from_timestamp(ticks.div_euclid(10_000_000), ticks.rem_euclid(10_000_000) as u32 * 100)
.context("BOOT_EPOCH")?;
Ok((uuid::Uuid::from_bytes(bytes).to_string(),time))
}
pub async fn boot_id() -> Result<String> {
boot_identity().await.map(|(id, _)| id)
}
#[cfg(test)]
+9 -7
View File
@@ -631,6 +631,7 @@ struct Agent {
certificates: RotationStore,
key_files: ProtectedKeyFiles,
boot: String,
booted_at: chrono::DateTime<Utc>,
instance: String,
started: Instant,
binding: Option<Binding>,
@@ -2420,8 +2421,8 @@ impl Agent {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(false);
}
let data = serde_json::to_vec(&native::snapshot()?)?;
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
let data = serde_json::to_vec(&native::snapshot_with_boot(Some(self.booted_at))?)?;
ensure!(data.len() <= 256 * 1024, "WINDOWS_INVENTORY_LIMIT");
let envelope = self.envelope(
generation,
Payload::InventorySnapshot(InventorySnapshot {
@@ -2537,7 +2538,7 @@ impl Agent {
};
self.renew_certificate(admission.as_deref()).await?;
}
self.boot = native::boot_id().await?;
(self.boot, self.booted_at) = native::boot_identity().await?;
let advertised = self.capabilities();
let hello = self.envelope(
0,
@@ -2819,7 +2820,7 @@ impl Agent {
self.replay(&channel, generation).await?;
replay = Instant::now();
}
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(300) {
self.queue_inventory(generation)?;
inventory = Instant::now();
}
@@ -2929,7 +2930,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let identity = enrollment(&config, &ca).await?;
let mut journal=journal;
journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?;
let (boot, booted_at) = native::boot_identity().await?;
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
#[cfg(feature = "system-helper")]
let binding = if let Some(policy) = &config.localservice_time_policy {
@@ -2979,6 +2980,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
certificates,
key_files,
boot,
booted_at,
instance: Uuid::new_v4().to_string(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
#[cfg(feature="system-helper")]
@@ -3075,8 +3077,8 @@ pub fn main() -> Result<()> {
}
if args == ["--native-probe"] {
let runtime = tokio::runtime::Runtime::new()?;
let boot = runtime.block_on(native::boot_id())?;
let inventory = native::snapshot()?;
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
let inventory = native::snapshot_with_boot(Some(booted_at))?;
println!(
"{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
+20 -1
View File
@@ -3,6 +3,20 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub fn firmware_identifier(value: &str) -> Option<String> {
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
let lower = value.to_ascii_lowercase();
(!value.is_empty()
&& value.len() <= 255
&& !value.chars().any(char::is_control)
&& !matches!(lower.as_str(), "none" | "unknown" | "not specified" | "not applicable"
| "default string" | "to be filled by o.e.m." | "system serial number")
&& !value.bytes().all(|b| b == b'0'))
.then(|| value.to_owned())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceType {
@@ -152,10 +166,15 @@ pub fn validate_for_scope(
}
let mut scopes = std::collections::BTreeSet::new();
for item in observations {
let max_bytes = match (scope, item["scope"].as_str()) {
("linux.base", Some("linux.software")) | ("windows.base", Some("windows.software")) =>
SOFTWARE_OBSERVATION_MAX_BYTES,
_ => 32768,
};
if serde_json::to_vec(item)
.map_err(|_| "INVALID_OBSERVATION")?
.len()
> 32768
> max_bytes
{
return Err("OBSERVATION_SIZE");
}
+25
View File
@@ -470,6 +470,30 @@ WantedBy=timers.target
}
def provision_serial_credential():
# DMI serial files usually require root. Pass this one value to the agent
# through systemd's read-only per-service credentials directory.
source = Path('/sys/class/dmi/id/product_serial')
try:
with source.open('rb') as stream:
serial = stream.read(256).strip()
except OSError:
return
if not serial or len(serial) >= 255:
return
target = ROOT / 'bios-serial'
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
if dropin.exists() or dropin.is_symlink():
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
else:
dropin.parent.mkdir(mode=0o755, exist_ok=True)
save(target, serial, 0o600)
if not dropin.exists():
save(dropin, content)
def enable():
for name, data in units().items():
path = UNIT_DIR / name
@@ -477,6 +501,7 @@ def enable():
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
else:
save(path, data.encode())
provision_serial_credential()
service('daemon-reload')
service('enable', '--now', SERVICE)
+1
View File
@@ -27,6 +27,7 @@ Alle acht Versuche lieferten Exitcode 0. Bei beiden Neustarts wurde die Wiederan
| Funktion | Beobachtung und Beleg |
| --- | --- |
| Öffentliche Verwaltung und Kundengrenzen | HTTPS-WebUI mit Passwort/TOTP, MCP mit widerrufbarem Token. Gerätebestand, Historie, eingeschränkter und kundenübergreifender Zugriff sowie Widerruf sind geprüft. [Öffentlicher Zugang](evidence/public-access-20261117.json) · [Kunden und Geräte](evidence/customer-fleet-20261117.json) |
| Erweitertes Inventar in den Gerätedetails | OS-Installationsdatum, letzter Neustart, Hersteller, BIOS-Seriennummer, verfügbare Garantieinformationen, Netzwerk, Software und angemeldete Benutzer. [Geräteansicht](../web/src/device-inventory.tsx) |
| RAM und CPU-Auslastung in der Übersicht | RAM als verfügbar / gesamt in GiB mit demselben Belegungsbalken wie beim Speicherplatz. Die CPU-Spalte zeigt die letzte gemessene Auslastung in Prozent. Am 18. November wurde `6ed57c4` mit Schema 41 produktiv aktiviert. Beide TLS-Healthchecks und der öffentliche WebUI-Index stimmten mit dem Build überein. Die öffentliche Übersicht zeigte die RAM-Balken auf Desktop und bei 390 px Breite für alle drei Geräte. Die Detailansicht und die automatische Aktualisierung wurden in Chromium auf Linux x64 und ARM64 nachgelesen. OTRS meldete um 18:05 UTC nach dem signierten Wechsel auf `0.1.0-arm64.3` `6,2 / 7,6 GiB` und `1,1 %`. Um 18:06 UTC meldeten Linux x64 `0.1.0-mvp.9`, Windows `0.1.18` und ARM64 frische CPU-Werte und waren authentisiert erreichbar. [Geräteansicht](../web/src/devices.tsx) · [Geräteprojektion](../crates/server/src/devices.rs) |
| Gerätetyp in der Übersicht | Spalte „Type“ nach „Hostname“ mit `physical`, `virtual` und `hypervisor`. Erkannte Proxmox-VE-Hosts zeigen `Proxmox VE` als OS. Am 18. November wurde `c599baa` auf dem öffentlichen Server aktiviert. Der Serverrunner bestätigte API, Gateway und öffentlichen API-Dienst mit Binärhash `4f9c8c60…`. Der öffentliche WebUI-Index stimmte mit dem gebauten Bundle überein. Die unveränderten Geräteidentitäten meldeten nach regulärem signierten Update `virtual` auf Linux mit `0.1.0-mvp.7` um 16:45 UTC und Windows mit `0.1.17` um 16:47 UTC. Geräteliste, Details, Mobilansicht mit 390 px und Historie sind in der öffentlichen WebUI geprüft. Beide Pakete sind in Development A und B und als Starter für leere Kataloge veröffentlicht. Die Typen `physical` und `hypervisor` sind mit Testdaten geprüft. Die Feldabnahme auf einem physischen Gerät und einem Proxmox-VE-Host steht aus. [Inventarprojektion](../crates/server/src/devices.rs) · [Geräteansicht](../web/src/devices.tsx) |
| Von der Auswahl zur Ausgabe | Die WebUI bindet die ausgewählte Skriptversion, zeigt den Inhalt vor Genehmigung und verlinkt das Ergebnis je Gerät. Ein abgelehnter Antrag erzeugte null Jobs. [Auftragsablauf](evidence/webui-auftragsablauf-20261117.json) · [Ergebnislinks und Entscheidungen](evidence/webui-order-history-20261118.json) Auf OTRS ARM64 wurde der Root-Skript-Helper nachträglich mit dem HTTPS-Installer aktiviert. Die zentrale Geräteregel bindet das berechtigte WebUI-Konto an diese Installation und den signierten Helper. Die öffentliche WebUI-Vorschau akzeptierte Root für OTRS. Die Probe blieb bei einer Vorschau und erzeugte null Anträge, Jobs, Outbox-Einträge und Startgrants. [OTRS-Nachweis](evidence/linux-arm64-otrs-root-helper-20261118.json) |
+46
View File
@@ -0,0 +1,46 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, it } from 'vitest';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
const report = (scope: string, data: unknown, truncated = false, quality = 'valid') =>
({ scope, data, truncated, quality, observed_at: '2026-11-18T08:00:00Z' });
it('reads current and older Linux snapshots, and labels approximate installation time', () => {
const device = { inventory: { observations: [
report('linux.os', { installed_at: '2025-03-12T10:00:00Z', install_date_source: 'root_filesystem', uptime_seconds: 60 }),
report('linux.hardware', { readable_dmi: { sys_vendor: 'Vendor' } }),
report('linux.interfaces', [{ name: 'eth0', addresses: ['192.0.2.1', '2001:db8::1%0'] }]),
report('linux.users', ['alice']),
report('linux.software', [{ name: 'openssh-server', version: '1.2', architecture: 'arm64' }], true)
] } };
expect(systemDetails(device, value => typeof value === 'string' ? value : 'Nicht gemeldet')).toEqual([
['OS installiert am', '2025-03-12T10:00:00Z · geschätzt (Root-Dateisystem)'],
['Letzter Neustart', '2026-11-18T07:59:00.000Z'],
['Hersteller', 'Vendor'],
['BIOS-Seriennummer', 'Nicht gemeldet'],
['Garantie bis', 'Nicht gemeldet']
]);
const view = renderToStaticMarkup(<DeviceInventoryPanels device={device} />);
expect(view).toContain('192.0.2.1, 2001:db8::1');
expect(view).toContain('alice');
expect(view).toContain('openssh-server');
expect(view).toContain('einen Teil der gefundenen Einträge');
});
it('shows Windows adapters, serial and registry software, with unknown distinct from empty sessions', () => {
const device = { inventory: { observations: [
report('windows.os', { booted_at: '2026-11-18T08:00:00Z' }),
report('windows.hardware', { manufacturer: 'Vendor', bios_serial_number: 'ABC123' }),
report('windows.interfaces', { entries: [{ name: 'Ethernet', addresses: ['192.0.2.2'] }] }),
report('windows.users', null, false, 'permission_denied'),
report('windows.software', { entries: [{ display_name: 'Produkt', publisher: 'Hersteller' }] })
] } };
const view = renderToStaticMarkup(<DeviceInventoryPanels device={device} />);
expect(view).toContain('Ethernet');
expect(view).toContain('Produkt');
expect(view).toContain('Nicht gemeldet');
expect(view).not.toContain('Keine Benutzer angemeldet');
expect(systemDetails(device, String)).toContainEqual(['BIOS-Seriennummer', 'ABC123']);
device.inventory.observations[3] = report('windows.users', { entries: [] });
expect(renderToStaticMarkup(<DeviceInventoryPanels device={device} />)).toContain('Keine Benutzer angemeldet');
});
+132
View File
@@ -0,0 +1,132 @@
import { useState, type ReactNode } from 'react';
import type { RecordValue } from './api';
const unreported = 'Nicht gemeldet';
const pageSize = 25;
function object(value: unknown): RecordValue {
return value && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : {};
}
function text(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
function values(value: unknown) {
return Array.isArray(value) ? value.flatMap(value => text(value) ?? []) : [];
}
function observation(device: RecordValue, name: string) {
const observations = object(device.inventory).observations;
return Array.isArray(observations) ? observations.map(object).find(item =>
item.quality === 'valid' && (item.scope === 'linux.' + name || item.scope === 'windows.' + name)
) : undefined;
}
export function systemDetails(device: RecordValue, formatTime: (value: unknown) => string) {
const os = observation(device, 'os');
const system = object(os?.data);
const hardware = object(observation(device, 'hardware')?.data);
const installed = formatTime(system.installed_at);
const source = system.install_date_source === 'root_filesystem' ? 'Root-Dateisystem'
: system.install_date_source === 'installer_directory' ? 'Installer-Verzeichnis' : null;
let booted = formatTime(system.booted_at);
if (booted === unreported && os?.scope === 'linux.os' && typeof system.uptime_seconds === 'number') {
const captured = Date.parse(text(os.observed_at) ?? '');
const estimated = captured - system.uptime_seconds * 1000;
if (system.uptime_seconds >= 0 && Number.isFinite(estimated) && estimated >= 0) {
booted = formatTime(new Date(estimated).toISOString());
}
}
return [
['OS installiert am', source && installed !== unreported ? installed + ' · geschätzt (' + source + ')' : installed],
['Letzter Neustart', booted],
['Hersteller', text(hardware.manufacturer) ?? text(object(hardware.readable_dmi).sys_vendor) ?? unreported],
['BIOS-Seriennummer', text(hardware.bios_serial_number) ?? unreported],
['Garantie bis', formatTime(hardware.warranty_expires_at)]
];
}
function entries(report: RecordValue | undefined): unknown[] | null {
const rows = Array.isArray(report?.data) ? report.data : object(report?.data).entries;
return Array.isArray(rows) ? rows : null;
}
function note(report: RecordValue | undefined) {
const readErrors = object(report?.data).read_errors;
return report?.truncated === true || (typeof readErrors === 'number' && readErrors > 0);
}
function InventoryTable({ headings, children }: { headings: string[]; children: ReactNode }) {
return <div className="table"><table>
<thead><tr>{headings.map(label => <th scope="col" key={label}>{label}</th>)}</tr></thead>
<tbody>{children}</tbody>
</table></div>;
}
function Software({ report }: { report: RecordValue | undefined }) {
const [query, setQuery] = useState('');
const [page, setPage] = useState(0);
const rows = entries(report)?.flatMap(entry => {
const row = object(entry);
const name = text(row.name) ?? text(row.display_name);
if (!name) return [];
return [{ name, version: text(row.version), publisher: text(row.publisher), architecture: text(row.architecture) }];
}).sort((left, right) => left.name.localeCompare(right.name, 'de'));
const matching = (rows ?? []).filter(row => Object.values(row).some(value =>
value?.toLocaleLowerCase('de').includes(query.trim().toLocaleLowerCase('de'))
));
const lastPage = Math.max(0, Math.ceil(matching.length / pageSize) - 1);
const current = Math.min(page, lastPage);
return <details>
<summary>Installierte Software{rows ? ' (' + rows.length + ')' : ''}</summary>
{note(report) && <p className="muted">Die Meldung enthält einen Teil der gefundenen Einträge.</p>}
{rows === undefined ? <p>{unreported}</p> : rows.length === 0 ? <p>Keine Softwareeinträge gemeldet.</p> : <>
<label>Software suchen
<input type="search" value={query} maxLength={120} onChange={e => { setQuery(e.target.value); setPage(0); }} />
</label>
{matching.length ? <InventoryTable headings={['Name', 'Version', 'Herausgeber', 'Architektur']}>
{matching.slice(current * pageSize, (current + 1) * pageSize).map((row, index) => <tr key={index}>
<td>{row.name}</td>
<td>{row.version ?? '–'}</td>
<td>{row.publisher ?? '–'}</td>
<td>{row.architecture ?? '–'}</td>
</tr>)}
</InventoryTable> : <p>Keine Treffer.</p>}
{lastPage > 0 && <div className="list-footer">
<span>Seite {current + 1} von {lastPage + 1}</span>
<div>
<button className="quiet" disabled={current === 0} onClick={() => setPage(current - 1)}>Zurück</button>
<button className="quiet" disabled={current === lastPage} onClick={() => setPage(current + 1)}>Weiter</button>
</div>
</div>}
</>}
</details>;
}
export function DeviceInventoryPanels({ device }: { device: RecordValue }) {
const network = observation(device, 'interfaces');
const interfaces = entries(network)?.map(object).filter(row => text(row.name));
const sessions = observation(device, 'users');
const users = values(entries(sessions)).sort((a, b) => a.localeCompare(b, 'de'));
return <>
<section>
<h2>Netzwerkkarten und IP-Adressen</h2>
{note(network) && <p className="muted">Die Meldung enthält einen Teil der Netzwerkkarten oder Adressen.</p>}
{interfaces === undefined ? <p>{unreported}</p> : interfaces.length === 0 ? <p>Keine Netzwerkkarten gemeldet.</p> :
<InventoryTable headings={['Netzwerkkarte', 'MAC-Adresse', 'IP-Adressen']}>
{interfaces.map((row, index) => <tr key={index}>
<td>{text(row.name)}</td>
<td>{text(row.mac) ?? '–'}</td>
<td>{values(row.addresses).map(address => address.replace(/%0$/, '')).join(', ') || 'Keine Adresse gemeldet'}</td>
</tr>)}
</InventoryTable>}
</section>
<section>
<h2>Angemeldete Benutzer</h2>
{note(sessions) && <p className="muted">Die Meldung enthält einen Teil der Sitzungen.</p>}
{users.length ? <ul>{users.map(name => <li key={name}>{name}</li>)}</ul>
: <p>{entries(sessions) && !note(sessions) ? 'Keine Benutzer angemeldet.' : unreported}</p>}
</section>
<section><Software report={observation(device, 'software')} /></section>
</>;
}
+3
View File
@@ -16,6 +16,7 @@ import { AdminControl } from './management';
import { allowed } from './safety';
import { CatalogCheckNotice } from './catalog-check';
import { devicePlatform } from './script-catalog';
import { DeviceInventoryPanels, systemDetails } from './device-inventory';
import { ErrorBox, errorText, useResource } from './resource';
import { NavIcon, orderDetailRoute } from './navigation';
import { orderTitle, Status } from './order-presentation';
@@ -179,6 +180,7 @@ function DeviceDetail({
['Kunde', label(d.customer_name)],
['Type', label(d.device_type)],
['Betriebssystem', label(d.os)],
...systemDetails(d, time),
['RAM frei / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes)],
['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')],
['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')],
@@ -214,6 +216,7 @@ function DeviceDetail({
))}
</dl>
</section>
<DeviceInventoryPanels device={d} />
{volumes.length > 0 && (
<section>
<h2>Laufwerke</h2>