1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-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, // xxx client unlimited
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 success_report_interval: Duration,
42 #[client] pub url: Uri,
43 #[client] pub vroutes: Vec<IpNet>,
45 // Computed, rather than looked up. Client only:
46 #[computed] pub effective_http_timeout: Duration,
49 static DEFAULT_CONFIG: &str = r#"
51 max_batch_down = 65536
53 target_requests_outstanding = 3
55 http_timeout_grace = 5
56 max_requests_outstanding = 6
61 ifname_client = hippo%d
62 ifname_server = shippo%d
64 success_report_interval = 3600
66 ipif = userv root ipif %{local},%{peer},%{mtu},slip,%{ifname} '%{rnets}'
70 vnetwork = 172.24.230.192
73 max_batch_down = 262144
76 target_requests_outstanding = 10
79 #[derive(StructOpt,Debug)]
81 /// Top-level config file or directory
83 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
85 /// Or if this is a file, just read that file.
86 #[structopt(long, default_value="/etc/hippotat")]
89 /// Additional config files or dirs, which can override the others
90 #[structopt(long, multiple=true, number_of_values=1)]
91 pub extra_config: Vec<PathBuf>,
96 fn sat(self) -> usize { self.try_into().unwrap_or(usize::MAX) }
100 impl<'s> Option<&'s str> {
102 fn value(self) -> &'s str {
103 self.ok_or_else(|| anyhow!("value needed"))?
108 pub struct Secret(pub String);
109 impl Parseable for Secret {
111 fn parse(s: Option<&str>) -> Self {
113 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
117 fn default() -> Self { Secret(default()) }
119 impl Debug for Secret {
120 #[throws(fmt::Error)]
121 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
124 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
125 pub enum SectionName {
128 Server(ServerName), // includes SERVER, which is slightly special
129 ServerLimit(ServerName),
133 pub use SectionName as SN;
135 #[derive(Debug,Clone)]
136 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
137 type SectionMap = HashMap<String, RawVal>;
140 struct RawValRef<'v,'l,'s> {
141 raw: Option<&'v str>,
144 section: &'s SectionName,
147 impl<'v> RawValRef<'v,'_,'_> {
149 fn try_map<F,T>(&self, f: F) -> T
150 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
152 .with_context(|| format!(r#"file {:?}, section {}, key "{}""#,
153 self.loc, self.section, self.key))?
161 static OUTSIDE_SECTION: &str = "[";
162 static SPECIAL_SERVER_SECTION: &str = "SERVER";
164 #[derive(Default,Debug)]
166 keys_allowed: HashMap<&'static str, SectionKindList>,
167 sections: HashMap<SectionName, SectionMap>,
170 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
172 impl<'f,A> OkAnyway<'f,A> {
173 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
174 let e = r.as_ref().err()?;
181 impl FromStr for SectionName {
184 fn from_str(s: &str) -> Self {
186 "COMMON" => return SN::Common,
187 "LIMIT" => return SN::GlobalLimit,
190 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
191 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
192 let (server, client) = s.split_ascii_whitespace().collect_tuple()
193 .ok_or_else(|| anyhow!(
194 "bad section name {:?} \
195 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
198 let server = server.parse().context("server name in link section name")?;
199 if client == "LIMIT" { return SN::ServerLimit(server) }
200 let client = client.parse().context("client name in link section name")?;
201 SN::Link(LinkName { server, client })
204 impl Display for InstanceConfig {
205 #[throws(fmt::Error)]
206 fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.link, f)? }
209 impl Display for SectionName {
210 #[throws(fmt::Error)]
211 fn fmt(&self, f: &mut fmt::Formatter) {
213 SN::Link (ref l) => Display::fmt(l, f)?,
214 SN::Client(ref c) => write!(f, "[{}]" , c)?,
215 SN::Server(ref s) => write!(f, "[{}]" , s)?,
216 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
217 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
218 SN::Common => write!(f, "[COMMON]" )?,
224 #[throws(AE)] // AE does not include path
225 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
227 let f = fs::File::open(path);
228 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
229 let mut f = f.context("open")?;
231 let mut s = String::new();
232 let y = f.read_to_string(&mut s);
233 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
236 self.read_string(s, path)?;
240 #[throws(AE)] // AE does not include path
241 fn read_string(&mut self, s: String, path_for_loc: &Path) {
242 let mut ini = Ini::new_cs();
243 ini.set_default_section(OUTSIDE_SECTION);
244 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
245 let map = mem::take(ini.get_mut_map());
246 if map.get(OUTSIDE_SECTION).is_some() {
247 throw!(anyhow!("INI file contains settings outside a section"));
250 let loc = Arc::new(path_for_loc.to_owned());
252 for (sn, vars) in map {
253 let sn = sn.parse().dcontext(&sn)?;
255 for key in vars.keys() {
256 let skl = self.keys_allowed.get(key.as_str()).ok_or_else(
257 || anyhow!("unknown configuration key {:?}", key)
259 if ! skl.contains(&sn) {
260 throw!(anyhow!("configuration key {:?} not applicable \
261 in this kind of section {:?}", key, &sn))
265 let ent = self.sections.entry(sn).or_default();
266 for (key, raw) in vars {
267 let raw = match raw {
268 Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
270 if raw.contains('\\') {
272 anyhow!("quoted value contains backslash, not supported")
275 let unq = raw[1..].strip_suffix(&raw[0..1])
277 || anyhow!("mismatched quotes around quoted value")
282 .with_context(|| format!("key {:?}", key))
283 .dcontext(path_for_loc)?
287 let key = key.replace('-',"_");
288 ent.insert(key, RawVal { raw, loc: loc.clone() });
293 #[throws(AE)] // AE includes path
294 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
296 let dir = fs::read_dir(path);
297 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
298 let dir = dir.context("open directory").dcontext(path)?;
300 let ent = ent.context("read directory").dcontext(path)?;
301 let leaf = ent.file_name();
302 let leaf = leaf.to_str();
303 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
304 if leaf.len() == 0 { continue }
305 if ! leaf.chars().all(
306 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
309 // OK we want this one
310 let ent = ent.path();
311 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
316 #[throws(AE)] // AE includes everything
317 fn read_toplevel(&mut self, toplevel: &Path) {
318 enum Anyway { None, Dir }
319 match self.read_file(toplevel, &|k| match k {
320 EK::NotFound => Some(Anyway::None),
321 EK::IsADirectory => Some(Anyway::Dir),
324 .dcontext(toplevel).context("top-level config directory (or file)")?
326 None | Some(Anyway::None) => { },
328 Some(Anyway::Dir) => {
330 let anyway_none = |k| match k {
331 EK::NotFound => Some(AnywayNone),
335 let mk = |leaf: &str| {
336 [ toplevel, &PathBuf::from(leaf) ]
337 .iter().collect::<PathBuf>()
340 for &(try_main, desc) in &[
341 ("main.cfg", "main config file"),
342 ("master.cfg", "obsolete-named main config file"),
344 let main = mk(try_main);
346 match self.read_file(&main, &anyway_none)
347 .dcontext(main).context(desc)?
350 Some(AnywayNone) => { },
354 for &(try_dir, desc) in &[
355 ("config.d", "per-link config directory"),
356 ("secrets.d", "per-link secrets directory"),
358 let dir = mk(try_dir);
359 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
361 Some(AnywayNone) => { },
368 #[throws(AE)] // AE includes extra, but does that this is extra
369 fn read_extra(&mut self, extra: &Path) {
372 match self.read_file(extra, &|k| match k {
373 EK::IsADirectory => Some(AnywayDir),
380 self.read_dir_d(extra, &|_| None::<Void>)?;
388 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
389 let mut links: BTreeSet<LinkName> = default();
391 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
392 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
393 let mut secret_global = false;
395 let mut putative_servers = BTreeSet::new();
396 let mut putative_clients = BTreeSet::new();
398 let mut note_server = |s| {
399 if let Some(only) = only_server { if s != only { return false } }
400 putative_servers.insert(s);
403 let mut note_client = |c| {
404 putative_clients.insert(c);
407 for (section, vars) in &self.sections {
408 let has_secret = || vars.contains_key("secret");
412 if ! note_server(&l.server) { continue }
413 note_client(&l.client);
414 if has_secret() { links.insert(l.clone()); }
416 SN::Server(ref s) => {
417 if ! note_server(s) { continue }
418 if has_secret() { secrets_anyclient.insert(s); }
420 SN::Client(ref c) => {
422 if has_secret() { secrets_anyserver.insert(c); }
425 if has_secret() { secret_global = true; }
431 // Add links which are justified by blanket secrets
432 for (client, server) in iproduct!(
433 putative_clients.into_iter().filter(
434 |c| secret_global || secrets_anyserver.contains(c)
436 putative_servers.iter().cloned().filter(
437 |s| secret_global || secrets_anyclient.contains(s)
440 links.insert(LinkName {
441 client: client.clone(),
442 server: server.clone(),
450 struct ResolveContext<'c> {
454 all_sections: Vec<SectionName>,
457 trait Parseable: Sized {
458 fn parse(s: Option<&str>) -> Result<Self, AE>;
459 fn default() -> Result<Self, AE> {
460 Err(anyhow!("setting must be specified"))
463 fn default_for_key(key: &str) -> Self {
464 Self::default().with_context(|| key.to_string())?
468 impl Parseable for Duration {
470 fn parse(s: Option<&str>) -> Duration {
471 // todo: would be nice to parse with humantime maybe
472 Duration::from_secs( s.value()?.parse()? )
475 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
476 impl Parseable for $t {
478 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
479 $( #[throws(AE)] fn default() -> Self { $def } )?
482 parseable_from_str!{u16, default() }
483 parseable_from_str!{u32, default() }
484 parseable_from_str!{String, default() }
485 parseable_from_str!{IpNet, default() }
486 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
487 parseable_from_str!{Uri, default() }
489 impl<T:Parseable> Parseable for Vec<T> {
491 fn parse(s: Option<&str>) -> Vec<T> {
493 .split_ascii_whitespace()
494 .map(|s| Parseable::parse(Some(s)))
495 .collect::<Result<Vec<_>,_>>()?
498 fn default() -> Self { default() }
502 #[derive(Debug,Copy,Clone)]
503 enum SectionKindList {
510 use SectionKindList as SKL;
513 fn special_server_section() -> Self { SN::Server(ServerName(
514 SPECIAL_SERVER_SECTION.into()
518 impl SectionKindList {
519 fn contains(self, s: &SectionName) -> bool {
521 SKL::Ordinary => matches!(s, SN::Link(_)
526 SKL::Limits => matches!(s, SN::ServerLimit(_)
529 SKL::ClientAgnostic => matches!(s, SN::Common
532 SKL::Limited => SKL::Ordinary.contains(s)
533 | SKL::Limits .contains(s),
535 SKL::ServerName => matches!(s, SN::Common)
536 | matches!(s, SN::Server(ServerName(name))
537 if name == SPECIAL_SERVER_SECTION),
543 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
544 -> Option<RawValRef<'a,'a,'s>>
545 where S: Iterator<Item=&'s SectionName>
547 for section in sections {
548 if let Some(raw) = self.sections
550 .and_then(|vars: &SectionMap| vars.get(key))
552 return Some(RawValRef {
553 raw: raw.raw.as_deref(),
563 pub fn establish_server_name(&self) -> ServerName {
565 let raw = match self.lookup_raw(
567 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
569 Some(raw) => raw.try_map(|os| os.value())?,
570 None => SPECIAL_SERVER_SECTION,
572 ServerName(raw.into())
576 impl<'c> ResolveContext<'c> {
577 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
578 -> Option<RawValRef<'c,'c,'c>> {
581 self.all_sections.iter()
582 .filter(|s| sections.contains(s))
587 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
591 match self.first_of_raw(key, sections) {
593 Some(raw) => Some(raw.try_map(Parseable::parse)?),
598 pub fn ordinary<T>(&self, key: &'static str) -> T
601 match self.first_of(key, SKL::Ordinary)? {
603 None => Parseable::default_for_key(key)?,
608 pub fn limited<T>(&self, key: &'static str) -> T
609 where T: Parseable + Ord
611 let val = self.ordinary(key)?;
612 if let Some(limit) = self.first_of(key, SKL::Limits)? {
620 pub fn client<T>(&self, key: &'static str) -> T
621 where T: Parseable + Default {
623 LinkEnd::Client => self.ordinary(key)?,
624 LinkEnd::Server => default(),
628 pub fn server<T>(&self, key: &'static str) -> T
629 where T: Parseable + Default {
631 LinkEnd::Server => self.ordinary(key)?,
632 LinkEnd::Client => default(),
637 pub fn computed<T>(&self, _key: &'static str) -> T
644 pub fn special_ipif(&self, key: &'static str) -> String {
646 LinkEnd::Client => self.ordinary(key)?,
648 self.first_of(key, SKL::ClientAgnostic)?
655 pub fn special_link(&self, _key: &'static str) -> LinkName {
660 impl InstanceConfig {
662 fn complete(&mut self, end: LinkEnd) {
663 let mut vhosts = self.vnetwork.iter()
664 .map(|n| n.hosts()).flatten()
665 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
667 if self.vaddr.is_unspecified() {
668 self.vaddr = vhosts.next().ok_or_else(
669 || anyhow!("vnetwork too small to generate vaddrr")
672 if self.vrelay.is_unspecified() {
673 self.vrelay = vhosts.next().ok_or_else(
674 || anyhow!("vnetwork too small to generate vrelay")
680 move |max_batch, key| {
681 if max_batch/2 < mtu {
682 throw!(anyhow!("max batch {:?} ({}) must be >= 2 x mtu ({}) \
683 (to allow for SLIP ESC-encoding)",
684 key, max_batch, mtu))
692 if &self.url == &default::<Uri>() {
693 let addr = self.addrs.get(0).ok_or_else(
694 || anyhow!("client needs addrs or url set")
699 IpAddr::V4(a) => format!("{}", a),
700 IpAddr::V6(a) => format!("[{}]", a),
704 p => format!(":{}", p),
709 self.effective_http_timeout = {
710 let a = self.http_timeout;
711 let b = self.http_timeout_grace;
712 a.checked_add(b).ok_or_else(
713 || anyhow!("calculate effective http timeout ({:?} + {:?})", a, b)
717 check_batch(self.max_batch_up, "max_batch_up")?;
721 if self.addrs.is_empty() {
722 throw!(anyhow!("missing 'addrs' setting"))
724 check_batch(self.max_batch_down, "max_batch_down")?;
727 // xxx check target vs max req outstanding
731 fn subst(var: &mut String,
732 kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
735 .map(|(k,v)| (k.to_string(), v.to_string()))
736 .collect::<HashMap<String, String>>();
737 let bad = parking_lot::Mutex::new(vec![]);
738 *var = regex_replace_all!(
739 r#"%(?:%|\((\w+)\)s|\{(\w+)\}|.)"#,
741 |whole, k1, k2| (|| Ok::<_,String>({
742 if whole == "%%" { "%" }
743 else if let Some(&k) = [k1,k2].iter().find(|&&s| s != "") {
744 substs.get(k).ok_or_else(
745 || format!("unknown key %({})s", k)
748 throw!(format!("bad percent escape {:?}", &whole));
750 }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
752 let bad = bad.into_inner();
753 if ! bad.is_empty() {
754 throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
760 type DD<'d> = &'d dyn Display;
761 fn dv<T:Display>(v: &[T]) -> String {
762 format!("{}", v.iter().format(" "))
764 let mut ipif = mem::take(&mut self.ipif); // lets us borrow all of self
765 let s = &self; // just for abbreviation, below
766 let vnetwork = dv(&s.vnetwork);
767 let vroutes = dv(&s.vroutes);
769 let keys = &["local", "peer", "rnets", "ifname"];
770 let values = match end {
771 Server => [&s.vaddr as DD , &s.vrelay, &vnetwork, &s.ifname_server],
772 Client => [&s.link.client as DD, &s.vaddr, &vroutes, &s.ifname_client],
775 ( "mtu", &s.mtu as DD ),
780 &mut keys.iter().cloned()
782 .chain(always.iter().cloned()),
790 pub fn read(opts: &Opts, end: LinkEnd) -> Vec<InstanceConfig> {
792 let mut agg = Aggregate::default();
793 agg.keys_allowed.extend(
794 InstanceConfig::FIELDS.iter().cloned()
797 agg.read_string(DEFAULT_CONFIG.into(),
798 "<build-in defaults>".as_ref()).unwrap();
800 agg.read_toplevel(&opts.config)?;
801 for extra in &opts.extra_config {
802 agg.read_extra(extra).context("extra config")?;
805 //eprintln!("GOT {:#?}", agg);
808 })().context("read configuration")?;
810 let server_name = match end {
811 LinkEnd::Server => Some(agg.establish_server_name()?),
812 LinkEnd::Client => None,
815 let instances = agg.instances(server_name.as_ref());
816 let mut ics = vec![];
818 for link in instances {
819 let rctx = ResolveContext {
824 SN::Link(link.clone()),
825 SN::Client(link.client.clone()),
826 SN::Server(link.server.clone()),
828 SN::ServerLimit(link.server.clone()),
833 let mut ic = InstanceConfig::resolve_instance(&rctx)
834 .with_context(|| format!("resolve config for {}", &link))?;
837 .with_context(|| format!("complete config for {}", &link))?;