First dispatcher

- Create (sub)command structure.
- First experimental dispatcher to start the daemon.
This commit is contained in:
Malte Meiboom
2026-02-22 12:51:05 +01:00
parent 2d072bf10b
commit c33feb1ee7
14 changed files with 323 additions and 35 deletions
Generated
+121
View File
@@ -26,6 +26,56 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.101" version = "1.0.101"
@@ -254,6 +304,52 @@ dependencies = [
"libloading", "libloading",
] ]
[[package]]
name = "clap"
version = "4.5.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6899ea499e3fb9305a65d5ebf6e3d2248c5fab291f300ad0a704fbe142eae31a"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.5.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b12c8b680195a62a8364d16b8447b01b6c2c8f9aaf68bee653be34d4245e238"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32"
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]] [[package]]
name = "core-foundation" name = "core-foundation"
version = "0.9.4" version = "0.9.4"
@@ -893,6 +989,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
"clap",
"indymilter", "indymilter",
"log", "log",
"log4rs", "log4rs",
@@ -1164,6 +1261,12 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]] [[package]]
name = "itertools" name = "itertools"
version = "0.13.0" version = "0.13.0"
@@ -1506,6 +1609,12 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]] [[package]]
name = "openpgp-cert-d" name = "openpgp-cert-d"
version = "0.3.4" version = "0.3.4"
@@ -2354,6 +2463,12 @@ dependencies = [
"precomputed-hash", "precomputed-hash",
] ]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.6.1" version = "2.6.1"
@@ -2762,6 +2877,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
+2 -1
View File
@@ -8,11 +8,12 @@ authors = [ "Malte Meiboom <malte@netropol.de>" ]
readme = "README.md" readme = "README.md"
keywords = ["cryptography", "openpgp", "pgp", "encryption", "email"] keywords = ["cryptography", "openpgp", "pgp", "encryption", "email"]
categories = ["cryptography", "email"] categories = ["cryptography", "email"]
rust-version = "1.79" rust-version = "1.85"
[dependencies] [dependencies]
anyhow = "1.0.100" anyhow = "1.0.100"
bytes = "1.11.1" bytes = "1.11.1"
clap = { version = "4", features = ["derive"] }
indymilter = "0.3.0" indymilter = "0.3.0"
log = "0.4.27" log = "0.4.27"
log4rs = "1.3.0" log4rs = "1.3.0"
+107
View File
@@ -0,0 +1,107 @@
use clap::Parser;
use clap::Subcommand;
#[derive(Parser, Debug)]
#[clap(
name = "Husk milter",
about = "Encrypting milter.",
arg_required_else_help = true,
)]
pub struct CliArgs {
#[clap(
long, short,
help = "Configuration file.",
)]
pub config: Option<String>,
#[clap(subcommand)]
pub subcommand: HuskSubcommands,
}
// Subcommands Level 1
#[derive(Debug, Subcommand)]
pub enum HuskSubcommands {
Daemon(DaemonCommand),
Introducer(IntroducerCommand),
Local,
}
// Daemon subcommands
#[derive(Parser, Debug)]
#[clap(
name = "daemon",
about = "Manage milter daemon.",
subcommand_required = true,
arg_required_else_help = true,
disable_colored_help = true,
disable_version_flag = true,
)]
pub struct DaemonCommand {
#[clap(subcommand)]
pub subcommand: DaemonSubcommand,
}
#[derive(Debug, Subcommand)]
pub enum DaemonSubcommand {
Start,
Stop,
Status
}
// Introducer subcommands
#[derive(Parser, Debug)]
#[clap(
name = "introducer",
about = "Manage introducers.",
subcommand_required = true,
arg_required_else_help = true,
disable_colored_help = true,
disable_version_flag = true,
)]
pub struct IntroducerCommand {
#[clap(subcommand)]
pub subcommand: IntroducerSubcommands,
}
#[derive(Debug, Subcommand)]
pub enum IntroducerSubcommands {
Add(IntroducerAddCommand),
Remove(IntroducerRemoveCommand),
List
}
#[derive(Parser, Debug)]
#[clap(
name = "introducer",
about = "Add introducers.",
)]
pub struct IntroducerAddCommand {
#[clap(
long = "cert",
help = "Certificate to declare as introducer."
)]
pub cert: String,
#[clap(
long = "domains",
help = "Domains this certificate introduces.",
required = true,
num_args = 1..,
value_delimiter = ' '
)]
pub domains: Vec<String>,
}
#[derive(Parser, Debug)]
#[clap(
name = "introducer",
about = "Remove introducers.",
)]
pub struct IntroducerRemoveCommand {
#[clap(
long = "cert",
help = "Certificate to be removed as introducer."
)]
pub cert: String,
}
+1
View File
@@ -0,0 +1 @@
pub mod cli_args;
+19
View File
@@ -0,0 +1,19 @@
use anyhow::Result;
use crate::commands;
use crate::cli::cli_args::{CliArgs, HuskSubcommands};
use crate::config::HuskConfigContainer;
pub mod daemon;
pub async fn dispatch(cli: CliArgs, config: HuskConfigContainer) -> Result<()> {
match cli.subcommand {
HuskSubcommands::Daemon(subcmd) => {
commands::daemon::dispatch(subcmd, config).await?;
},
_ => { println!("something else"); }
}
Ok(())
}
+21
View File
@@ -0,0 +1,21 @@
use anyhow::Result;
use crate::cli::cli_args::{DaemonCommand, DaemonSubcommand};
use crate::config::HuskConfigContainer;
use crate::Daemon;
pub async fn dispatch(cmd: DaemonCommand, config: HuskConfigContainer) -> Result<()> {
match cmd.subcommand {
DaemonSubcommand::Start => {
Daemon::run(config).await?;
},
DaemonSubcommand::Stop => {
println!("stop");
},
DaemonSubcommand::Status => {
println!("status");
}
}
Ok(())
}
+1 -1
View File
@@ -19,7 +19,7 @@ pub struct HuskConfig {
impl HuskConfig { impl HuskConfig {
pub fn load(path: &String) -> anyhow::Result<Self> { pub fn load(path: &str) -> anyhow::Result<Self> {
match fs::read_to_string(path) { match fs::read_to_string(path) {
Ok(data) => { Ok(data) => {
match toml::from_str(data.as_str()) { match toml::from_str(data.as_str()) {
+24 -24
View File
@@ -26,7 +26,7 @@ use wot::{Depth, Path};
use crate::types::errors::HuskError; use crate::types::errors::HuskError;
use crate::types::husk_context::HuskContext; use crate::types::husk_context::HuskContext;
use crate::types::introducer::{self, Introducer}; use crate::types::introducer::Introducer;
use crate::types::recipient::Recipient; use crate::types::recipient::Recipient;
/// Returns the local trust root from the cert_store. If the trust root /// Returns the local trust root from the cert_store. If the trust root
@@ -72,7 +72,7 @@ pub fn get_local_trust_root(cert_store: &CertStore) -> anyhow::Result<Cert> {
pub fn get_local_certificates<'hc>(context: &HuskContext<'hc>, email: &str) pub fn get_local_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
-> Vec<Arc<LazyCert<'hc>>> { -> Vec<Arc<LazyCert<'hc>>> {
log::debug!("local lookup for {}", email); log::debug!("local lookup for {}", email);
let cert_store = &context.cert_store; let cert_store = &context.cert_store;
let trust_roots = vec![(context.local_trust_root.fingerprint(), wot::FULLY_TRUSTED)]; let trust_roots = vec![(context.local_trust_root.fingerprint(), wot::FULLY_TRUSTED)];
@@ -107,14 +107,14 @@ const USER_AGENT: &'static str = concat!("husk/", env!("CARGO_PKG_VERSION"));
const CONNECT_TIMEOUT: Duration = Duration::new(5, 0); const CONNECT_TIMEOUT: Duration = Duration::new(5, 0);
const REQUEST_TIMEOUT: Duration = Duration::new(5, 0); const REQUEST_TIMEOUT: Duration = Duration::new(5, 0);
/// Try to fetch certificates for `email` from online sources (keyservers, wkd, /// Try to fetch certificates for `email` from online sources (keyservers, wkd,
/// dane). /// dane).
pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str) pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
-> anyhow::Result<Vec<Cert>> { -> anyhow::Result<Vec<Cert>> {
log::debug!("remote lookup for {}", email); log::debug!("remote lookup for {}", email);
let mut jobs = JoinSet::new(); let mut jobs = JoinSet::new();
let http_client = sequoia_net::reqwest::Client::builder() let http_client = sequoia_net::reqwest::Client::builder()
.user_agent(USER_AGENT) .user_agent(USER_AGENT)
.connect_timeout(CONNECT_TIMEOUT) .connect_timeout(CONNECT_TIMEOUT)
@@ -128,8 +128,8 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
for cert in certs { for cert in certs {
if let Ok(c) = cert { if let Ok(c) = cert {
if let Ok(vc) = c.with_policy(policy, None) { if let Ok(vc) = c.with_policy(policy, None) {
// check if the returned certificate contains a userid with the // check if the returned certificate contains a userid with the
// email address in question. // email address in question.
let mut userid_found = false; let mut userid_found = false;
for userid in vc.userids() { for userid in vc.userids() {
@@ -139,7 +139,7 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
} }
} }
} }
if userid_found { if userid_found {
// check if the certificate can be used (for encryption). // check if the certificate can be used (for encryption).
vc.keys() vc.keys()
@@ -147,10 +147,10 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
.alive() .alive()
.revoked(false) .revoked(false)
.for_transport_encryption() .for_transport_encryption()
.for_each(|_| { .for_each(|_| {
// XXX: cert gets returned for each transport key // XXX: cert gets returned for each transport key
// once would be enough // once would be enough
result.push(c.clone()); result.push(c.clone());
}); });
} }
} }
@@ -158,22 +158,22 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
} }
result result
}; };
// Keyservers // Keyservers
for keyserver in &context.keyservers { for keyserver in &context.keyservers {
log::debug!("querying {}", keyserver); log::debug!("querying {}", keyserver);
if let Ok(ks) = KeyServer::with_client(keyserver.as_str(), http_client.clone()) { if let Ok(ks) = KeyServer::with_client(keyserver.as_str(), http_client.clone()) {
let e = email.to_string(); let e = email.to_string();
let p = StandardPolicy::new(); let p = StandardPolicy::new();
jobs.spawn(async move { jobs.spawn(async move {
let mut partial_result = Vec::new(); let mut partial_result = Vec::new();
if let Ok(certs) = ks.search(e.as_str()).await { if let Ok(certs) = ks.search(e.as_str()).await {
partial_result = collect_certs(certs, e, &p); partial_result = collect_certs(certs, e, &p);
} }
partial_result partial_result
}); });
@@ -191,8 +191,8 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
} }
partial_result partial_result
}); });
// DANE // DANE
let e = email.to_string(); let e = email.to_string();
let p = StandardPolicy::new(); let p = StandardPolicy::new();
jobs.spawn(async move { jobs.spawn(async move {
@@ -215,13 +215,13 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
log::debug!("found cert {}", fpr); log::debug!("found cert {}", fpr);
match set.entry(fpr.clone()) { match set.entry(fpr.clone()) {
Occupied(entry) => { Occupied(entry) => {
let existing_cert = entry.into_mut(); let existing_cert = entry.into_mut();
if let Ok(merged_cert) = existing_cert.clone().merge_public(c) { if let Ok(merged_cert) = existing_cert.clone().merge_public(c) {
*existing_cert = merged_cert; *existing_cert = merged_cert;
} }
}, },
Vacant(_entry) => { Vacant(_entry) => {
set.insert(fpr.clone(), c); set.insert(fpr.clone(), c);
}, },
} }
@@ -231,7 +231,7 @@ pub async fn lookup_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
Ok(result) Ok(result)
} }
pub async fn get_certificates<'hc>(context: &HuskContext<'hc>, email: &str) pub async fn get_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
-> Vec<Arc<LazyCert<'hc>>> { -> Vec<Arc<LazyCert<'hc>>> {
@@ -239,14 +239,14 @@ pub async fn get_certificates<'hc>(context: &HuskContext<'hc>, email: &str)
log::debug!("get certificate for {}", email); log::debug!("get certificate for {}", email);
let locals = get_local_certificates(context, email); let locals = get_local_certificates(context, email);
if locals.len() > 0 { if locals.len() > 0 {
return locals; return locals;
} }
let mut result = Vec::new(); let mut result = Vec::new();
for introducer in &context.introducers { for introducer in &context.introducers {
log::debug!("consider introducer {:?}", log::debug!("consider introducer {:?}",
introducer.cert.userids().map(|u| u.userid()).collect::<Vec<_>>()); introducer.cert.userids().map(|u| u.userid()).collect::<Vec<_>>());
if introducer.can_introduce(format!("<{}>", email).as_str()) { if introducer.can_introduce(format!("<{}>", email).as_str()) {
log::debug!(" introducer regex matches!"); log::debug!(" introducer regex matches!");
-1
View File
@@ -20,7 +20,6 @@ use indymilter::{
ProtoOpts, ProtoOpts,
SocketInfo, SocketInfo,
Status, Status,
Config,
ContextActions, ContextActions,
}; };
+15 -4
View File
@@ -2,9 +2,15 @@
// Husk milter // Husk milter
// //
use std::{env, process}; use std::process;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use clap::Parser;
use types::defaults;
pub mod cli;
use cli::cli_args::CliArgs;
pub mod commands;
pub mod config; pub mod config;
use config::{HuskConfig, HuskConfigContainer}; use config::{HuskConfig, HuskConfigContainer};
pub mod types; pub mod types;
@@ -15,9 +21,14 @@ use daemon::Daemon;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let args = CliArgs::parse();
let config_file = env::args().nth(1).expect("config file missing"); let config_file = match &args.config {
let husk_config = match HuskConfig::load(&config_file) { Some(c) => c.as_str(),
None => defaults::CONFIG_FILE_LOCATION
};
let husk_config = match HuskConfig::load(config_file) {
Ok(config) => config, Ok(config) => config,
Err(e) => { Err(e) => {
eprintln!("{:?}", e); eprintln!("{:?}", e);
@@ -31,7 +42,7 @@ async fn main() {
let config_container: HuskConfigContainer = Arc::new(Mutex::new(husk_config)); let config_container: HuskConfigContainer = Arc::new(Mutex::new(husk_config));
match Daemon::run(config_container).await { match commands::dispatch(args, config_container).await {
Ok(_) => { Ok(_) => {
println!("exiting..."); println!("exiting...");
}, },
+5
View File
@@ -0,0 +1,5 @@
//
// Some defaults
//
pub const CONFIG_FILE_LOCATION: &'static str = "/etc/husk/config.toml";
+2 -2
View File
@@ -8,7 +8,7 @@ use anyhow;
use sequoia_openpgp::policy::StandardPolicy; use sequoia_openpgp::policy::StandardPolicy;
use std::path::PathBuf; use std::path::PathBuf;
use sequoia_openpgp::Cert; use sequoia_openpgp::Cert;
use sequoia_cert_store::{CertStore, StoreUpdate}; use sequoia_cert_store::CertStore;
use sequoia_directories::Home; use sequoia_directories::Home;
use crate::{config::HuskConfig, crypto}; use crate::{config::HuskConfig, crypto};
@@ -58,7 +58,7 @@ impl<'hc> HuskContext<'hc> {
} }
pub async fn add_recipient(&mut self, rcpt: String) { pub async fn add_recipient(&mut self, rcpt: String) {
let certs = crypto::get_certificates(&self, rcpt.as_str()).await; let certs = crypto::get_certificates(&self, rcpt.as_str()).await;
self.mail.add_recipient(rcpt, certs) self.mail.add_recipient(rcpt, certs)
+3 -2
View File
@@ -6,7 +6,8 @@
use sequoia_wot as wot; use sequoia_wot as wot;
use wot::{CertSynopsis, Certification}; use wot::{CertSynopsis, Certification};
use sequoia_openpgp::{policy::StandardPolicy, Cert, KeyID}; use sequoia_openpgp::policy::StandardPolicy;
use sequoia_openpgp::Cert;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Introducer { pub struct Introducer {
@@ -44,7 +45,7 @@ impl Introducer {
u.certifications().for_each(|s| { u.certifications().for_each(|s| {
if s.signature_alive(None, None).is_ok() { if s.signature_alive(None, None).is_ok() {
s.issuers().for_each(|i| { s.issuers().for_each(|i| {
if i == &my_keyid { result = true; } if i == &my_keyid { result = true; }
}); });
} }
}) })
+2
View File
@@ -1,5 +1,7 @@
pub mod defaults;
pub mod husk_context; pub mod husk_context;
pub mod mail_context; pub mod mail_context;
pub mod errors; pub mod errors;
pub mod recipient; pub mod recipient;
pub mod introducer; pub mod introducer;