commit 6c29ab88e8875897f2b6b0a88e8910d666a292d1 Author: Thomas Peterson Date: Mon May 18 15:24:46 2026 +0200 first init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..c6692e4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,589 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mini-inventory" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "serde", + "serde_json", + "tokio", + "toml", +] + +[[package]] +name = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.3", +] + +[[package]] +name = "toml_writer" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1269278 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "mini-inventory" +version = "0.1.0" +edition = "2024" + +[dependencies] +anyhow = "1.0" +axum = "0.8" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +tokio = { version = "1.0", features = ["fs", "macros", "net", "rt-multi-thread"] } +toml = "0.9" diff --git a/README.md b/README.md new file mode 100644 index 0000000..6d570a3 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# Mini Inventory + +Kleine Rust-Webanwendung fuer eine Windows-Domaene. Der Server liest JSON-Dateien aus einem lokalen Ordner, zeigt Computer und installierte Software an und kann Wake-on-LAN-Pakete senden. + +## Ordnerstruktur + +```text +D:\Inventory\ +├─ mini-inventory.exe +├─ config.toml +└─ clients\ + ├─ PC-001.json + ├─ PC-002.json + └─ PC-003.json +``` + +## Konfiguration + +```toml +bind_address = "0.0.0.0:8080" +clients_dir = "clients" +wol_broadcast = "255.255.255.255:9" +``` + +`clients_dir` ist relativ zum Arbeitsverzeichnis der EXE, wenn kein absoluter Pfad angegeben wird. + +## Start + +```powershell +.\mini-inventory.exe +``` + +Danach ist die Weboberflaeche unter `http://server-name:8080` erreichbar. + +## Windows-Build + +Auf einem Windows-Rechner mit Rust: + +```powershell +cargo build --release +``` + +Die Binary liegt danach unter: + +```text +target\release\mini-inventory.exe +``` + +## Client-JSON + +Die Dateien muessen die Feldnamen im PowerShell-/Windows-Stil enthalten: + +```json +{ + "ComputerName": "PC-001", + "User": "FIRMA\\max.mustermann", + "IPAddress": "192.168.178.51", + "MacAddress": "00-11-22-33-44-55", + "LastSeen": "2026-05-18 10:15:00", + "Software": [ + { + "Name": "JTL-Wawi", + "Version": "2.0.3" + } + ] +} +``` diff --git a/agent.ps1 b/agent.ps1 new file mode 100644 index 0000000..29a5446 --- /dev/null +++ b/agent.ps1 @@ -0,0 +1,47 @@ +param( + [string]$ServerUrl = "http://192.168.178.24:8080" +) + +$ComputerName = $env:COMPUTERNAME +$User = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name +$IPAddress = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias "Ethernet*", "Wi-Fi*" | Select-Object -First 1).IPAddress +$MacAddress = (Get-NetAdapter | Where-Object { $_.Status -eq 'Up' } | Select-Object -First 1).MacAddress +$LastSeen = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + +# Get installed software from registry (32 and 64 bit) +$Software = @() +$RegistryPaths = @( + "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*", + "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", + "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" +) + +foreach ($Path in $RegistryPaths) { + Get-ItemProperty $Path -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -ne $null } | ForEach-Object { + $Software += @{ + Name = $_.DisplayName + Version = $_.DisplayVersion + } + } +} + +# Unique list and sort +$Software = $Software | Sort-Object Name -Unique + +$Inventory = @{ + ComputerName = $ComputerName + User = $User + IPAddress = $IPAddress + MacAddress = $MacAddress + LastSeen = $LastSeen + Software = $Software +} + +$Json = $Inventory | ConvertTo-Json -Depth 10 + +try { + Invoke-RestMethod -Uri "$ServerUrl/inventory" -Method Post -Body $Json -ContentType "application/json" + Write-Host "Inventory sent successfully to $ServerUrl" +} catch { + Write-Error "Failed to send inventory: $_" +} diff --git a/agent.wxs b/agent.wxs new file mode 100644 index 0000000..5941cab --- /dev/null +++ b/agent.wxs @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NOT Removed + Removed + + + + + diff --git a/clients/PC-001.json b/clients/PC-001.json new file mode 100644 index 0000000..25c3100 --- /dev/null +++ b/clients/PC-001.json @@ -0,0 +1,17 @@ +{ + "ComputerName": "PC-001", + "User": "FIRMA\\max.mustermann", + "IPAddress": "192.168.178.51", + "MacAddress": "00-11-22-33-44-55", + "LastSeen": "2026-05-18 10:15:00", + "Software": [ + { + "Name": "JTL-Wawi", + "Version": "2.0.3" + }, + { + "Name": "Slack", + "Version": "4.44.60" + } + ] +} diff --git a/config.toml b/config.toml new file mode 100644 index 0000000..2739645 --- /dev/null +++ b/config.toml @@ -0,0 +1,3 @@ +bind_address = "0.0.0.0:8080" +clients_dir = "clients" +wol_broadcast = "255.255.255.255:9" diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..f5d38f6 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,613 @@ +use std::{ + net::SocketAddr, + path::{Path, PathBuf}, + sync::Arc, +}; + +use anyhow::{Context, Result, bail}; +use axum::{ + Form, Router, + extract::State, + http::StatusCode, + response::{Html, IntoResponse}, + routing::{get, post}, +}; +use serde::{Deserialize, Serialize}; +use tokio::{fs, net::UdpSocket}; + +#[derive(Clone, Debug, Deserialize)] +struct Config { + #[serde(default = "default_bind_address")] + bind_address: SocketAddr, + #[serde(default = "default_clients_dir")] + clients_dir: PathBuf, + #[serde(default = "default_wol_broadcast")] + wol_broadcast: SocketAddr, +} + +#[derive(Clone)] +struct AppState { + config: Config, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +struct ClientInventory { + computer_name: String, + user: Option, + #[serde(rename = "IPAddress")] + ip_address: Option, + mac_address: Option, + last_seen: Option, + #[serde(default)] + software: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +struct SoftwareEntry { + name: String, + version: Option, +} + +#[derive(Debug)] +struct InventoryLoadError { + path: PathBuf, + message: String, +} + +#[derive(Debug, Deserialize)] +struct WakeForm { + computer_name: String, +} + +#[tokio::main] +async fn main() -> Result<()> { + let config = load_config("config.toml").await?; + let bind_address = config.bind_address; + + // Ensure clients directory exists + if !config.clients_dir.exists() { + fs::create_dir_all(&config.clients_dir).await?; + println!("Created clients directory: {}", config.clients_dir.display()); + } + + let state = Arc::new(AppState { config }); + + let app = Router::new() + .route("/", get(index)) + .route("/wake", post(wake)) + .route("/inventory", post(receive_inventory)) + .route("/styles.css", get(styles)) + .with_state(state); + + println!("mini-inventory listening on http://{bind_address}"); + let listener = tokio::net::TcpListener::bind(bind_address) + .await + .with_context(|| format!("failed to bind to {bind_address}"))?; + axum::serve(listener, app).await?; + + Ok(()) +} + +async fn load_config(path: impl AsRef) -> Result { + let path = path.as_ref(); + let content = fs::read_to_string(path) + .await + .with_context(|| format!("failed to read {}", path.display()))?; + toml::from_str(&content).with_context(|| format!("failed to parse {}", path.display())) +} + +async fn index(State(state): State>) -> impl IntoResponse { + match render_inventory_page(&state.config, None).await { + Ok(html) => Html(html).into_response(), + Err(error) => ( + StatusCode::INTERNAL_SERVER_ERROR, + Html(render_error_page( + "Inventar konnte nicht geladen werden", + &error.to_string(), + )), + ) + .into_response(), + } +} + +async fn wake(State(state): State>, Form(form): Form) -> impl IntoResponse { + let inventories = match load_inventories(&state.config.clients_dir).await { + Ok((inventories, _errors)) => inventories, + Err(error) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Html(render_error_page( + "Wake-on-LAN konnte nicht vorbereitet werden", + &error.to_string(), + )), + ) + .into_response(); + } + }; + + let result = inventories + .iter() + .find(|client| client.computer_name == form.computer_name) + .and_then(|client| client.mac_address.as_deref().map(|mac| (client, mac))); + + let message = match result { + Some((client, mac)) => match send_wake_on_lan(mac, state.config.wol_broadcast).await { + Ok(()) => format!( + "Wake-on-LAN-Paket fuer {} wurde gesendet.", + client.computer_name + ), + Err(error) => format!( + "Wake-on-LAN fuer {} fehlgeschlagen: {error}", + client.computer_name + ), + }, + None => format!( + "Kein Computer mit MAC-Adresse fuer {} gefunden.", + form.computer_name + ), + }; + + match render_inventory_page(&state.config, Some(&message)).await { + Ok(html) => Html(html).into_response(), + Err(error) => ( + StatusCode::INTERNAL_SERVER_ERROR, + Html(render_error_page( + "Inventar konnte nicht geladen werden", + &error.to_string(), + )), + ) + .into_response(), + } +} + +async fn receive_inventory( + State(state): State>, + axum::Json(inventory): axum::Json, +) -> impl IntoResponse { + let file_name = format!("{}.json", inventory.computer_name); + let path = state.config.clients_dir.join(file_name); + + match serde_json::to_string_pretty(&inventory) { + Ok(json) => match fs::write(&path, json).await { + Ok(()) => StatusCode::OK, + Err(error) => { + eprintln!("Failed to write inventory to {}: {}", path.display(), error); + StatusCode::INTERNAL_SERVER_ERROR + } + }, + Err(error) => { + eprintln!("Failed to serialize inventory: {}", error); + StatusCode::INTERNAL_SERVER_ERROR + } + } +} + +async fn styles() -> impl IntoResponse { + ( + [("content-type", "text/css; charset=utf-8")], + r#" +:root { + color-scheme: light; + font-family: "Segoe UI", Arial, sans-serif; + background: #f5f7fa; + color: #1c2530; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; +} + +header { + background: #182535; + color: #fff; + padding: 24px clamp(16px, 4vw, 48px); +} + +header h1 { + margin: 0; + font-size: clamp(1.5rem, 3vw, 2.1rem); + letter-spacing: 0; +} + +header p { + margin: 8px 0 0; + color: #c8d3df; +} + +main { + width: min(1180px, calc(100% - 32px)); + margin: 24px auto 48px; +} + +.flash { + border-left: 4px solid #1f7a4d; + background: #eaf6ef; + padding: 12px 14px; + margin-bottom: 16px; +} + +.error-list { + border-left: 4px solid #b42318; + background: #fff1f0; + padding: 12px 14px; + margin-bottom: 16px; +} + +.summary { + display: flex; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 16px; +} + +.summary div { + background: #fff; + border: 1px solid #d8e0e8; + border-radius: 8px; + padding: 12px 14px; + min-width: 160px; +} + +.summary strong { + display: block; + font-size: 1.4rem; +} + +.client { + background: #fff; + border: 1px solid #d8e0e8; + border-radius: 8px; + margin-bottom: 14px; + overflow: hidden; +} + +.client-head { + display: grid; + grid-template-columns: minmax(160px, 1fr) repeat(4, minmax(130px, auto)) auto; + gap: 12px; + align-items: center; + padding: 14px; + border-bottom: 1px solid #e5ebf1; +} + +.computer { + font-weight: 700; + font-size: 1.05rem; +} + +.label { + display: block; + color: #607084; + font-size: .78rem; + margin-bottom: 2px; +} + +.value { + word-break: break-word; +} + +button { + border: 0; + border-radius: 6px; + background: #0f6cbd; + color: #fff; + cursor: pointer; + font: inherit; + font-weight: 600; + padding: 10px 12px; + white-space: nowrap; +} + +button:disabled { + background: #98a6b3; + cursor: not-allowed; +} + +.software { + padding: 0 14px 14px; +} + +.software h2 { + font-size: .95rem; + margin: 14px 0 8px; +} + +table { + border-collapse: collapse; + width: 100%; +} + +th, +td { + border-top: 1px solid #e5ebf1; + padding: 8px; + text-align: left; +} + +th { + color: #607084; + font-weight: 600; +} + +.empty { + color: #607084; + background: #fff; + border: 1px solid #d8e0e8; + border-radius: 8px; + padding: 24px; +} + +@media (max-width: 900px) { + .client-head { + grid-template-columns: 1fr; + } + + button { + width: 100%; + } +} +"#, + ) +} + +async fn render_inventory_page(config: &Config, flash: Option<&str>) -> Result { + let (inventories, errors) = load_inventories(&config.clients_dir).await?; + let total_software: usize = inventories.iter().map(|client| client.software.len()).sum(); + + let mut html = String::new(); + html.push_str(""); + html.push_str(""); + html.push_str("Mini Inventory"); + html.push_str("

Mini Inventory

"); + html.push_str("

Windows-Clients, installierte Software und Wake-on-LAN

"); + html.push_str("
"); + + if let Some(message) = flash { + html.push_str("
"); + html.push_str(&escape_html(message)); + html.push_str("
"); + } + + if !errors.is_empty() { + html.push_str("
Einige Dateien konnten nicht gelesen werden.
    "); + for error in &errors { + html.push_str("
  • "); + html.push_str(&escape_html(&format!( + "{}: {}", + error.path.display(), + error.message + ))); + html.push_str("
  • "); + } + html.push_str("
"); + } + + html.push_str("
"); + html.push_str(&format!( + "
Computer{}
", + inventories.len() + )); + html.push_str(&format!( + "
Software-Eintraege{total_software}
" + )); + html.push_str(&format!( + "
Ordner{}
", + escape_html(&config.clients_dir.display().to_string()) + )); + html.push_str("
"); + + if inventories.is_empty() { + html.push_str("
Keine Client-Inventare gefunden.
"); + } + + for client in inventories { + html.push_str("
"); + html.push_str("
Computer"); + html.push_str(&escape_html(&client.computer_name)); + html.push_str("
"); + append_meta(&mut html, "Benutzer", client.user.as_deref()); + append_meta(&mut html, "IP-Adresse", client.ip_address.as_deref()); + append_meta(&mut html, "MAC-Adresse", client.mac_address.as_deref()); + append_meta(&mut html, "Zuletzt gesehen", client.last_seen.as_deref()); + html.push_str("
"); + html.push_str(""); + if client + .mac_address + .as_deref() + .unwrap_or("") + .trim() + .is_empty() + { + html.push_str(""); + } else { + html.push_str(""); + } + html.push_str("

Installierte Software

"); + + if client.software.is_empty() { + html.push_str("

Keine Software gemeldet.

"); + } else { + html.push_str(""); + for software in client.software { + html.push_str(""); + } + html.push_str("
NameVersion
"); + html.push_str(&escape_html(&software.name)); + html.push_str(""); + html.push_str(&escape_html(software.version.as_deref().unwrap_or("-"))); + html.push_str("
"); + } + + html.push_str("
"); + } + + html.push_str("
"); + Ok(html) +} + +async fn load_inventories( + clients_dir: &Path, +) -> Result<(Vec, Vec)> { + let mut inventories = Vec::new(); + let mut errors = Vec::new(); + + let mut entries = fs::read_dir(clients_dir) + .await + .with_context(|| format!("failed to read clients directory {}", clients_dir.display()))?; + + while let Some(entry) = entries.next_entry().await? { + let path = entry.path(); + if !path + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| extension.eq_ignore_ascii_case("json")) + { + continue; + } + + match load_inventory(&path).await { + Ok(inventory) => inventories.push(inventory), + Err(error) => errors.push(InventoryLoadError { + path, + message: error.to_string(), + }), + } + } + + inventories.sort_by_key(|client| client.computer_name.to_ascii_lowercase()); + Ok((inventories, errors)) +} + +async fn load_inventory(path: &Path) -> Result { + let content = fs::read_to_string(path) + .await + .with_context(|| format!("failed to read {}", path.display()))?; + serde_json::from_str(&content).with_context(|| format!("failed to parse {}", path.display())) +} + +async fn send_wake_on_lan(mac_address: &str, broadcast: SocketAddr) -> Result<()> { + let mac = parse_mac_address(mac_address)?; + let mut packet = [0xff_u8; 102]; + for chunk in packet[6..].chunks_exact_mut(6) { + chunk.copy_from_slice(&mac); + } + + let socket = UdpSocket::bind("0.0.0.0:0").await?; + socket.set_broadcast(true)?; + socket.send_to(&packet, broadcast).await?; + Ok(()) +} + +fn parse_mac_address(mac_address: &str) -> Result<[u8; 6]> { + let hex: String = mac_address + .chars() + .filter(|character| character.is_ascii_hexdigit()) + .collect(); + + if hex.len() != 12 { + bail!("ungueltige MAC-Adresse: {mac_address}"); + } + + let mut bytes = [0_u8; 6]; + for (index, byte) in bytes.iter_mut().enumerate() { + let start = index * 2; + *byte = u8::from_str_radix(&hex[start..start + 2], 16) + .with_context(|| format!("ungueltige MAC-Adresse: {mac_address}"))?; + } + + Ok(bytes) +} + +fn append_meta(html: &mut String, label: &str, value: Option<&str>) { + html.push_str("
"); + html.push_str(&escape_html(label)); + html.push_str(""); + html.push_str(&escape_html(value.unwrap_or("-"))); + html.push_str("
"); +} + +fn render_error_page(title: &str, message: &str) -> String { + format!( + "{}

{}

{}

", + escape_html(title), + escape_html(title), + escape_html(message) + ) +} + +fn escape_html(input: &str) -> String { + input + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} + +fn default_bind_address() -> SocketAddr { + "0.0.0.0:8080".parse().expect("valid default bind address") +} + +fn default_clients_dir() -> PathBuf { + PathBuf::from("clients") +} + +fn default_wol_broadcast() -> SocketAddr { + "255.255.255.255:9" + .parse() + .expect("valid default broadcast address") +} + +#[cfg(test)] +mod tests { + use super::{ClientInventory, parse_mac_address}; + + #[test] + fn deserializes_client_inventory_powershell_field_names() { + let json = r#"{ + "ComputerName": "PC-001", + "User": "FIRMA\\max.mustermann", + "IPAddress": "192.168.178.51", + "MacAddress": "00-11-22-33-44-55", + "LastSeen": "2026-05-18 10:15:00", + "Software": [{"Name": "JTL-Wawi", "Version": "2.0.3"}] + }"#; + + let inventory: ClientInventory = serde_json::from_str(json).unwrap(); + + assert_eq!(inventory.computer_name, "PC-001"); + assert_eq!(inventory.ip_address.as_deref(), Some("192.168.178.51")); + assert_eq!(inventory.mac_address.as_deref(), Some("00-11-22-33-44-55")); + assert_eq!(inventory.software[0].name, "JTL-Wawi"); + } + + #[test] + fn parses_common_mac_address_formats() { + assert_eq!( + parse_mac_address("00-11-22-33-44-55").unwrap(), + [0x00, 0x11, 0x22, 0x33, 0x44, 0x55] + ); + assert_eq!( + parse_mac_address("00:11:22:33:44:55").unwrap(), + [0x00, 0x11, 0x22, 0x33, 0x44, 0x55] + ); + assert_eq!( + parse_mac_address("001122334455").unwrap(), + [0x00, 0x11, 0x22, 0x33, 0x44, 0x55] + ); + } + + #[test] + fn rejects_invalid_mac_addresses() { + assert!(parse_mac_address("00-11-22").is_err()); + assert!(parse_mac_address("not-a-mac").is_err()); + } +}