1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
7 use configparser::ini::Ini;
9 #[derive(hippotat_macros::ResolveConfig)]
10 #[derive(Debug,Clone)]
11 pub struct InstanceConfig {
12 // Exceptional settings
13 #[special(special_link, SKL::ServerName)] pub link: LinkName,
15 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
18 #[limited] pub max_batch_down: u32,
19 #[limited] pub max_queue_time: Duration,
20 #[limited] pub http_timeout: Duration,
21 #[limited] pub target_requests_outstanding: u32,
24 pub addrs: Vec<IpAddr>,
25 pub vnetwork: Vec<IpNet>,
30 pub ifname_server: String,
31 pub ifname_client: String,
33 // Ordinary settings, used by server only:
34 #[server] pub max_clock_skew: Duration,
36 // Ordinary settings, used by client only:
37 #[client] pub http_timeout_grace: Duration,
38 #[client] pub max_requests_outstanding: u32,
39 #[client] pub max_batch_up: u32,
40 #[client] pub http_retry: Duration,
41 #[client] pub url: Uri,
42 #[client] pub vroutes: Vec<IpNet>,
45 static DEFAULT_CONFIG: &str = r#"
47 max_batch_down = 65536
49 target_requests_outstanding = 3
51 http_timeout_grace = 5
52 max_requests_outstanding = 6
57 ifname_client = hippo%%d
58 ifname_server = shippo%%d
61 ipif = userv root ipif %(local)s,%(peer)s,%(mtu)s,slip,%(ifname)s '%(rnets)s'
65 vnetwork = 172.24.230.192
68 max_batch_down = 262144
71 target_requests_outstanding = 10
74 #[derive(StructOpt,Debug)]
76 /// Top-level config file or directory
78 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
80 /// Or if this is a file, just read that file.
81 #[structopt(long, default_value="/etc/hippotat")]
84 /// Additional config files or dirs, which can override the others
85 #[structopt(long, multiple=true, number_of_values=1)]
86 pub extra_config: Vec<PathBuf>,
90 impl<'s> Option<&'s str> {
92 fn value(self) -> &'s str {
93 self.ok_or_else(|| anyhow!("value needed"))?
98 pub struct Secret(pub String);
99 impl Parseable for Secret {
101 fn parse(s: Option<&str>) -> Self {
103 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
107 fn default() -> Self { Secret(default()) }
109 impl Debug for Secret {
110 #[throws(fmt::Error)]
111 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
114 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
115 pub enum SectionName {
118 Server(ServerName), // includes SERVER, which is slightly special
119 ServerLimit(ServerName),
123 pub use SectionName as SN;
125 #[derive(Debug,Clone)]
126 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
127 type SectionMap = HashMap<String, RawVal>;
130 struct RawValRef<'v,'l,'s> {
131 raw: Option<&'v str>,
134 section: &'s SectionName,
137 impl<'v> RawValRef<'v,'_,'_> {
139 fn try_map<F,T>(&self, f: F) -> T
140 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
142 .with_context(|| format!(r#"file {:?}, section {}, key "{}""#,
143 self.loc, self.section, self.key))?
151 static OUTSIDE_SECTION: &str = "[";
152 static SPECIAL_SERVER_SECTION: &str = "SERVER";
154 #[derive(Default,Debug)]
156 keys_allowed: HashMap<&'static str, SectionKindList>,
157 sections: HashMap<SectionName, SectionMap>,
160 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
162 impl<'f,A> OkAnyway<'f,A> {
163 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
164 let e = r.as_ref().err()?;
171 impl FromStr for SectionName {
174 fn from_str(s: &str) -> Self {
176 "COMMON" => return SN::Common,
177 "LIMIT" => return SN::GlobalLimit,
180 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
181 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
182 let (server, client) = s.split_ascii_whitespace().collect_tuple()
183 .ok_or_else(|| anyhow!(
184 "bad section name {:?} \
185 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
188 let server = server.parse().context("server name in link section name")?;
189 if client == "LIMIT" { return SN::ServerLimit(server) }
190 let client = client.parse().context("client name in link section name")?;
191 SN::Link(LinkName { server, client })
194 impl Display for InstanceConfig {
195 #[throws(fmt::Error)]
196 fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.link, f)? }
199 impl Display for SectionName {
200 #[throws(fmt::Error)]
201 fn fmt(&self, f: &mut fmt::Formatter) {
203 SN::Link (ref l) => Display::fmt(l, f)?,
204 SN::Client(ref c) => write!(f, "[{}]" , c)?,
205 SN::Server(ref s) => write!(f, "[{}]" , s)?,
206 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
207 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
208 SN::Common => write!(f, "[COMMON]" )?,
214 #[throws(AE)] // AE does not include path
215 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
217 let f = fs::File::open(path);
218 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
219 let mut f = f.context("open")?;
221 let mut s = String::new();
222 let y = f.read_to_string(&mut s);
223 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
226 self.read_string(s, path)?;
230 #[throws(AE)] // AE does not include path
231 fn read_string(&mut self, s: String, path_for_loc: &Path) {
232 let mut ini = Ini::new_cs();
233 ini.set_default_section(OUTSIDE_SECTION);
234 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
235 let map = mem::take(ini.get_mut_map());
236 if map.get(OUTSIDE_SECTION).is_some() {
237 throw!(anyhow!("INI file contains settings outside a section"));
240 let loc = Arc::new(path_for_loc.to_owned());
242 for (sn, vars) in map {
243 let sn = sn.parse().dcontext(&sn)?;
245 for key in vars.keys() {
246 let skl = self.keys_allowed.get(key.as_str()).ok_or_else(
247 || anyhow!("unknown configuration key {:?}", key)
249 if ! skl.contains(&sn) {
250 throw!(anyhow!("configuration key {:?} not applicable \
251 in this kind of section {:?}", key, &sn))
255 let ent = self.sections.entry(sn).or_default();
256 for (key, raw) in vars {
257 let raw = match raw {
258 Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
260 if raw.contains('\\') {
262 anyhow!("quoted value contains backslash, not supported")
265 let unq = raw[1..].strip_suffix(&raw[0..1])
267 || anyhow!("mismatched quotes around quoted value")
272 .with_context(|| format!("key {:?}", key))
273 .dcontext(path_for_loc)?
277 let key = key.replace('-',"_");
278 ent.insert(key, RawVal { raw, loc: loc.clone() });
283 #[throws(AE)] // AE includes path
284 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
286 let dir = fs::read_dir(path);
287 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
288 let dir = dir.context("open directory").dcontext(path)?;
290 let ent = ent.context("read directory").dcontext(path)?;
291 let leaf = ent.file_name();
292 let leaf = leaf.to_str();
293 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
294 if leaf.len() == 0 { continue }
295 if ! leaf.chars().all(
296 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
299 // OK we want this one
300 let ent = ent.path();
301 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
306 #[throws(AE)] // AE includes everything
307 fn read_toplevel(&mut self, toplevel: &Path) {
308 enum Anyway { None, Dir }
309 match self.read_file(toplevel, &|k| match k {
310 EK::NotFound => Some(Anyway::None),
311 EK::IsADirectory => Some(Anyway::Dir),
314 .dcontext(toplevel).context("top-level config directory (or file)")?
316 None | Some(Anyway::None) => { },
318 Some(Anyway::Dir) => {
320 let anyway_none = |k| match k {
321 EK::NotFound => Some(AnywayNone),
325 let mk = |leaf: &str| {
326 [ toplevel, &PathBuf::from(leaf) ]
327 .iter().collect::<PathBuf>()
330 for &(try_main, desc) in &[
331 ("main.cfg", "main config file"),
332 ("master.cfg", "obsolete-named main config file"),
334 let main = mk(try_main);
336 match self.read_file(&main, &anyway_none)
337 .dcontext(main).context(desc)?
340 Some(AnywayNone) => { },
344 for &(try_dir, desc) in &[
345 ("config.d", "per-link config directory"),
346 ("secrets.d", "per-link secrets directory"),
348 let dir = mk(try_dir);
349 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
351 Some(AnywayNone) => { },
358 #[throws(AE)] // AE includes extra, but does that this is extra
359 fn read_extra(&mut self, extra: &Path) {
362 match self.read_file(extra, &|k| match k {
363 EK::IsADirectory => Some(AnywayDir),
370 self.read_dir_d(extra, &|_| None::<Void>)?;
378 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
379 let mut links: BTreeSet<LinkName> = default();
381 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
382 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
383 let mut secret_global = false;
385 let mut putative_servers = BTreeSet::new();
386 let mut putative_clients = BTreeSet::new();
388 let mut note_server = |s| {
389 if let Some(only) = only_server { if s != only { return false } }
390 putative_servers.insert(s);
393 let mut note_client = |c| {
394 putative_clients.insert(c);
397 for (section, vars) in &self.sections {
398 let has_secret = || vars.contains_key("secret");
402 if ! note_server(&l.server) { continue }
403 note_client(&l.client);
404 if has_secret() { links.insert(l.clone()); }
406 SN::Server(ref s) => {
407 if ! note_server(s) { continue }
408 if has_secret() { secrets_anyclient.insert(s); }
410 SN::Client(ref c) => {
412 if has_secret() { secrets_anyserver.insert(c); }
415 if has_secret() { secret_global = true; }
421 // Add links which are justified by blanket secrets
422 for (client, server) in iproduct!(
423 putative_clients.into_iter().filter(
424 |c| secret_global || secrets_anyserver.contains(c)
426 putative_servers.iter().cloned().filter(
427 |s| secret_global || secrets_anyclient.contains(s)
430 links.insert(LinkName {
431 client: client.clone(),
432 server: server.clone(),
440 struct ResolveContext<'c> {
444 all_sections: Vec<SectionName>,
447 trait Parseable: Sized {
448 fn parse(s: Option<&str>) -> Result<Self, AE>;
449 fn default() -> Result<Self, AE> {
450 Err(anyhow!("setting must be specified"))
453 fn default_for_key(key: &str) -> Self {
454 Self::default().with_context(|| key.to_string())?
458 impl Parseable for Duration {
460 fn parse(s: Option<&str>) -> Duration {
461 // todo: would be nice to parse with humantime maybe
462 Duration::from_secs( s.value()?.parse()? )
465 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
466 impl Parseable for $t {
468 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
469 $( #[throws(AE)] fn default() -> Self { $def } )?
472 parseable_from_str!{u16, default() }
473 parseable_from_str!{u32, default() }
474 parseable_from_str!{String, default() }
475 parseable_from_str!{IpNet, default() }
476 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
477 parseable_from_str!{Uri, default() }
479 impl<T:Parseable> Parseable for Vec<T> {
481 fn parse(s: Option<&str>) -> Vec<T> {
483 .split_ascii_whitespace()
484 .map(|s| Parseable::parse(Some(s)))
485 .collect::<Result<Vec<_>,_>>()?
488 fn default() -> Self { default() }
492 #[derive(Debug,Copy,Clone)]
493 enum SectionKindList {
500 use SectionKindList as SKL;
503 fn special_server_section() -> Self { SN::Server(ServerName(
504 SPECIAL_SERVER_SECTION.into()
508 impl SectionKindList {
509 fn contains(self, s: &SectionName) -> bool {
511 SKL::Ordinary => matches!(s, SN::Link(_)
516 SKL::Limits => matches!(s, SN::ServerLimit(_)
519 SKL::ClientAgnostic => matches!(s, SN::Common
522 SKL::Limited => SKL::Ordinary.contains(s)
523 | SKL::Limits .contains(s),
525 SKL::ServerName => matches!(s, SN::Common)
526 | matches!(s, SN::Server(ServerName(name))
527 if name == SPECIAL_SERVER_SECTION),
533 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
534 -> Option<RawValRef<'a,'a,'s>>
535 where S: Iterator<Item=&'s SectionName>
537 for section in sections {
538 if let Some(raw) = self.sections
540 .and_then(|vars: &SectionMap| vars.get(key))
542 return Some(RawValRef {
543 raw: raw.raw.as_deref(),
553 pub fn establish_server_name(&self) -> ServerName {
555 let raw = match self.lookup_raw(
557 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
559 Some(raw) => raw.try_map(|os| os.value())?,
560 None => SPECIAL_SERVER_SECTION,
562 ServerName(raw.into())
566 impl<'c> ResolveContext<'c> {
567 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
568 -> Option<RawValRef<'c,'c,'c>> {
571 self.all_sections.iter()
572 .filter(|s| sections.contains(s))
577 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
581 match self.first_of_raw(key, sections) {
583 Some(raw) => Some(raw.try_map(Parseable::parse)?),
588 pub fn ordinary<T>(&self, key: &'static str) -> T
591 match self.first_of(key, SKL::Ordinary)? {
593 None => Parseable::default_for_key(key)?,
598 pub fn limited<T>(&self, key: &'static str) -> T
599 where T: Parseable + Ord
601 let val = self.ordinary(key)?;
602 if let Some(limit) = self.first_of(key, SKL::Limits)? {
610 pub fn client<T>(&self, key: &'static str) -> T
611 where T: Parseable + Default {
613 LinkEnd::Client => self.ordinary(key)?,
614 LinkEnd::Server => default(),
618 pub fn server<T>(&self, key: &'static str) -> T
619 where T: Parseable + Default {
621 LinkEnd::Server => self.ordinary(key)?,
622 LinkEnd::Client => default(),
627 pub fn special_ipif(&self, key: &'static str) -> String {
629 LinkEnd::Client => self.ordinary(key)?,
631 self.first_of(key, SKL::ClientAgnostic)?
638 pub fn special_link(&self, _key: &'static str) -> LinkName {
643 impl InstanceConfig {
645 fn complete(&mut self, end: LinkEnd) {
646 let mut vhosts = self.vnetwork.iter()
647 .map(|n| n.hosts()).flatten()
648 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
650 if self.vaddr.is_unspecified() {
651 self.vaddr = vhosts.next().ok_or_else(
652 || anyhow!("vnetwork too small to generate vaddrr")
655 if self.vrelay.is_unspecified() {
656 self.vrelay = vhosts.next().ok_or_else(
657 || anyhow!("vnetwork too small to generate vrelay")
663 if &self.url == &default::<Uri>() {
664 let addr = self.addrs.get(0).ok_or_else(
665 || anyhow!("client needs addrs or url set")
670 IpAddr::V4(a) => format!("{}", a),
671 IpAddr::V6(a) => format!("[{}]", a),
675 p => format!(":{}", p),
682 if self.addrs.is_empty() {
683 throw!(anyhow!("missing 'addrs' setting"))
689 fn subst(var: &mut String,
690 kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
693 .map(|(k,v)| (k.to_string(), v.to_string()))
694 .collect::<HashMap<String, String>>();
695 let bad = parking_lot::Mutex::new(vec![]);
696 *var = regex_replace_all!(
697 r#"%(?:%|\((\w+)\)s|.)"#,
699 |whole, k| (|| Ok::<_,String>({
700 if whole == "%%" { "%" }
702 substs.get(k).ok_or_else(
703 || format!("unknown key %({})s", k)
706 throw!(format!("bad percent escape {:?}", &whole));
708 }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
710 let bad = bad.into_inner();
711 if ! bad.is_empty() {
712 throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
716 let ifname = match match end {
717 LinkEnd::Client => (&mut self.ifname_client, "ifname_client"),
718 LinkEnd::Server => (&mut self.ifname_server, "ifname_server"),
720 subst(var, &mut iter::empty()).context(name).context("interface name")?;
726 type DD<'d> = &'d dyn Display;
727 fn dv<T:Display>(v: &[T]) -> String {
728 format!("{}", v.iter().format(" "))
730 let vnetwork = dv(&self.vnetwork);
731 let vroutes = dv(&self.vroutes);
733 let keys = &["local", "peer", "rnets", "ifname"];
734 let values = match end {
735 Server => [&self.vaddr as DD , &self.vrelay, &vnetwork, ifname],
736 Client => [&self.link.client as DD, &self.vaddr, &vroutes, ifname],
740 &mut keys.iter().cloned()
742 .chain([( "mtu", &self.mtu as DD )].iter().cloned()),
749 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
750 let opts = config::Opts::from_args();
753 let mut agg = Aggregate::default();
754 agg.keys_allowed.extend(
755 InstanceConfig::FIELDS.iter().cloned()
758 agg.read_string(DEFAULT_CONFIG.into(),
759 "<build-in defaults>".as_ref()).unwrap();
761 agg.read_toplevel(&opts.config)?;
762 for extra in &opts.extra_config {
763 agg.read_extra(extra).context("extra config")?;
766 //eprintln!("GOT {:#?}", agg);
769 })().context("read configuration")?;
771 let server_name = match end {
772 LinkEnd::Server => Some(agg.establish_server_name()?),
773 LinkEnd::Client => None,
776 let instances = agg.instances(server_name.as_ref());
777 let mut ics = vec![];
779 for link in instances {
780 let rctx = ResolveContext {
785 SN::Link(link.clone()),
786 SN::Client(link.client.clone()),
787 SN::Server(link.server.clone()),
789 SN::ServerLimit(link.server.clone()),
794 let mut ic = InstanceConfig::resolve_instance(&rctx)
795 .with_context(|| format!("resolve config for {}", &link))?;
798 .with_context(|| format!("complete config for {}", &link))?;