1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
7 #[derive(hippotat_macros::ResolveConfig)]
9 pub struct InstanceConfig {
10 // Exceptional settings
11 #[special(special_link, SKL::None)] pub link: LinkName,
12 #[per_client] pub secret: Secret,
13 #[global] #[special(special_ipif, SKL::PerClient)] pub ipif: String,
16 #[limited] pub max_batch_down: u32,
17 #[limited] pub max_queue_time: Duration,
18 #[limited] pub http_timeout: Duration,
19 #[limited] pub target_requests_outstanding: u32,
20 #[special(special_max_up, SKL::Limited)] pub max_batch_up: u32,
22 // Ordinary settings, used by both, not client-specifi:
23 #[global] pub addrs: Vec<IpAddr>,
24 #[global] pub vnetwork: Vec<IpNet>,
25 #[global] pub vaddr: IpAddr,
26 #[global] pub vrelay: IpAddr,
27 #[global] pub port: u16,
28 #[global] pub mtu: u32,
30 // Ordinary settings, used by server only:
31 #[server] #[per_client] pub max_clock_skew: Duration,
32 #[server] #[global] pub ifname_server: String,
34 // Ordinary settings, used by client only:
35 #[client] pub http_timeout_grace: Duration,
36 #[client] pub max_requests_outstanding: u32,
37 #[client] pub http_retry: Duration,
38 #[client] pub success_report_interval: Duration,
39 #[client] pub url: Uri,
40 #[client] pub vroutes: Vec<IpNet>,
41 #[client] pub ifname_client: String,
43 // Computed, rather than looked up. Client only:
44 #[computed] pub effective_http_timeout: Duration,
47 static DEFAULT_CONFIG: &str = r#"
49 max_batch_down = 65536
51 target_requests_outstanding = 3
53 http_timeout_grace = 5
54 max_requests_outstanding = 6
59 ifname_client = hippo%d
60 ifname_server = shippo%d
62 success_report_interval = 3600
64 ipif = userv root ipif %{local},%{peer},%{mtu},slip,%{ifname} '%{rnets}'
68 vnetwork = 172.24.230.192
72 max_batch_down = 262144
75 target_requests_outstanding = 10
78 #[derive(StructOpt,Debug)]
80 /// Top-level config file or directory
82 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
84 /// Or if this is a file, just read that file.
85 #[structopt(long, default_value="/etc/hippotat")]
88 /// Additional config files or dirs, which can override the others
89 #[structopt(long, multiple=true, number_of_values=1)]
90 pub extra_config: Vec<PathBuf>,
95 fn sat(self) -> usize { self.try_into().unwrap_or(usize::MAX) }
99 impl<'s> Option<&'s str> {
101 fn value(self) -> &'s str {
102 self.ok_or_else(|| anyhow!("value needed"))?
107 pub struct Secret(pub String);
108 impl Parseable for Secret {
110 fn parse(s: Option<&str>) -> Self {
112 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
116 fn default() -> Self { Secret(default()) }
118 impl Debug for Secret {
119 #[throws(fmt::Error)]
120 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
123 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
124 pub enum SectionName {
127 Server(ServerName), // includes SERVER, which is slightly special
128 ServerLimit(ServerName),
132 pub use SectionName as SN;
135 struct RawValRef<'v,'l,'s> {
136 raw: Option<&'v str>, // todo: not Option any more
139 section: &'s SectionName,
142 impl<'v> RawValRef<'v,'_,'_> {
144 fn try_map<F,T>(&self, f: F) -> T
145 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
147 .with_context(|| format!(r#"file {:?}, section {}, key "{}""#,
148 self.loc, self.section, self.key))?
156 static OUTSIDE_SECTION: &str = "[";
157 static SPECIAL_SERVER_SECTION: &str = "SERVER";
162 keys_allowed: HashMap<&'static str, SectionKindList>,
163 sections: HashMap<SectionName, ini::Section>,
166 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
168 impl<'f,A> OkAnyway<'f,A> {
169 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
170 let e = r.as_ref().err()?;
177 impl FromStr for SectionName {
180 fn from_str(s: &str) -> Self {
182 "COMMON" => return SN::Common,
183 "LIMIT" => return SN::GlobalLimit,
186 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
187 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
188 let (server, client) = s.split_ascii_whitespace().collect_tuple()
189 .ok_or_else(|| anyhow!(
190 "bad section name {:?} \
191 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
194 let server = server.parse().context("server name in link section name")?;
195 if client == "LIMIT" { return SN::ServerLimit(server) }
196 let client = client.parse().context("client name in link section name")?;
197 SN::Link(LinkName { server, client })
200 impl Display for InstanceConfig {
201 #[throws(fmt::Error)]
202 fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.link, f)? }
205 impl Display for SectionName {
206 #[throws(fmt::Error)]
207 fn fmt(&self, f: &mut fmt::Formatter) {
209 SN::Link (ref l) => Display::fmt(l, f)?,
210 SN::Client(ref c) => write!(f, "[{}]" , c)?,
211 SN::Server(ref s) => write!(f, "[{}]" , s)?,
212 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
213 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
214 SN::Common => write!(f, "[COMMON]" )?,
222 keys_allowed: HashMap<&'static str, SectionKindList>
223 ) -> Self { Aggregate {
228 #[throws(AE)] // AE does not include path
229 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
231 let f = fs::File::open(path);
232 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
233 let mut f = f.context("open")?;
235 let mut s = String::new();
236 let y = f.read_to_string(&mut s);
237 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
240 self.read_string(s, path)?;
244 #[throws(AE)] // AE does not include path
245 fn read_string(&mut self, s: String, path_for_loc: &Path) {
246 let mut map: ini::Parsed = default();
247 ini::read(&mut map, &mut s.as_bytes(), path_for_loc)
248 .context("parse as INI")?;
249 if map.get(OUTSIDE_SECTION).is_some() {
250 throw!(anyhow!("INI file contains settings outside a section"));
253 for (sn, section) in map {
254 let sn = sn.parse().dcontext(&sn)?;
255 let vars = §ion.values;
257 for (key, val) in vars {
259 let skl = if key == "server" {
262 *self.keys_allowed.get(key.as_str()).ok_or_else(
263 || anyhow!("unknown configuration key")
266 if ! skl.contains(&sn, self.end) {
267 throw!(anyhow!("key not applicable in this kind of section"))
271 .with_context(|| format!("key {:?}", key))
272 .with_context(|| val.loc.to_string())?
275 let ent = self.sections.entry(sn)
276 .or_insert_with(|| ini::Section {
277 loc: section.loc.clone(),
281 for (key, ini::Val { val: raw, loc }) in vars {
282 let val = if raw.starts_with('\'') || raw.starts_with('"') {
284 if raw.contains('\\') {
286 anyhow!("quoted value contains backslash, not supported")
289 let quote = &raw[0..1];
291 let unq = raw[1..].strip_suffix(quote)
293 || anyhow!("mismatched quotes around quoted value")
296 if unq.contains(quote) {
298 "quoted value contains quote (escaping not supported)"
304 .with_context(|| format!("key {:?}", key))
305 .with_context(|| loc.to_string())?
309 let key = key.replace('-',"_");
310 ent.values.insert(key, ini::Val { val, loc: loc.clone() });
315 #[throws(AE)] // AE includes path
316 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
318 let dir = fs::read_dir(path);
319 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
320 let dir = dir.context("open directory").dcontext(path)?;
322 let ent = ent.context("read directory").dcontext(path)?;
323 let leaf = ent.file_name();
324 let leaf = leaf.to_str();
325 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
326 if leaf.len() == 0 { continue }
327 if ! leaf.chars().all(
328 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
331 // OK we want this one
332 let ent = ent.path();
333 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
338 #[throws(AE)] // AE includes everything
339 fn read_toplevel(&mut self, toplevel: &Path) {
340 enum Anyway { None, Dir }
341 match self.read_file(toplevel, &|k| match k {
342 EK::NotFound => Some(Anyway::None),
343 EK::IsADirectory => Some(Anyway::Dir),
346 .dcontext(toplevel).context("top-level config directory (or file)")?
348 None | Some(Anyway::None) => { },
350 Some(Anyway::Dir) => {
352 let anyway_none = |k| match k {
353 EK::NotFound => Some(AnywayNone),
357 let mk = |leaf: &str| {
358 [ toplevel, &PathBuf::from(leaf) ]
359 .iter().collect::<PathBuf>()
362 for &(try_main, desc) in &[
363 ("main.cfg", "main config file"),
364 ("master.cfg", "obsolete-named main config file"),
366 let main = mk(try_main);
368 match self.read_file(&main, &anyway_none)
369 .dcontext(main).context(desc)?
372 Some(AnywayNone) => { },
376 for &(try_dir, desc) in &[
377 ("config.d", "per-link config directory"),
378 ("secrets.d", "per-link secrets directory"),
380 let dir = mk(try_dir);
381 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
383 Some(AnywayNone) => { },
390 #[throws(AE)] // AE includes extra, but does that this is extra
391 fn read_extra(&mut self, extra: &Path) {
394 match self.read_file(extra, &|k| match k {
395 EK::IsADirectory => Some(AnywayDir),
402 self.read_dir_d(extra, &|_| None::<Void>)?;
410 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
411 let mut links: BTreeSet<LinkName> = default();
413 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
414 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
415 let mut secret_global = false;
417 let mut putative_servers = BTreeSet::new();
418 let mut putative_clients = BTreeSet::new();
420 let mut note_server = |s| {
421 if let Some(only) = only_server { if s != only { return false } }
422 putative_servers.insert(s);
425 let mut note_client = |c| {
426 putative_clients.insert(c);
429 for (section, vars) in &self.sections {
430 let has_secret = || vars.values.contains_key("secret");
431 //dbg!(§ion, has_secret());
435 if ! note_server(&l.server) { continue }
436 note_client(&l.client);
437 if has_secret() { links.insert(l.clone()); }
439 SN::Server(ref s) => {
440 if ! note_server(s) { continue }
441 if has_secret() { secrets_anyclient.insert(s); }
443 SN::Client(ref c) => {
445 if has_secret() { secrets_anyserver.insert(c); }
448 if has_secret() { secret_global = true; }
454 //dbg!(&putative_servers, &putative_clients);
455 //dbg!(&secrets_anyserver, &secrets_anyclient, &secret_global);
457 // Add links which are justified by blanket secrets
458 for (client, server) in iproduct!(
459 putative_clients.into_iter().filter(
461 || secrets_anyserver.contains(c)
462 || ! secrets_anyclient.is_empty()
464 putative_servers.iter().cloned().filter(
466 || secrets_anyclient.contains(s)
467 || ! secrets_anyserver.is_empty()
470 links.insert(LinkName {
471 client: client.clone(),
472 server: server.clone(),
480 struct ResolveContext<'c> {
484 all_sections: Vec<SectionName>,
487 trait Parseable: Sized {
488 fn parse(s: Option<&str>) -> Result<Self, AE>;
489 fn default() -> Result<Self, AE> {
490 Err(anyhow!("setting must be specified"))
493 fn default_for_key(key: &str) -> Self {
494 Self::default().with_context(|| key.to_string())?
498 impl Parseable for Duration {
500 fn parse(s: Option<&str>) -> Duration {
501 // todo: would be nice to parse with humantime maybe
502 Duration::from_secs( s.value()?.parse()? )
505 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
506 impl Parseable for $t {
508 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
509 $( #[throws(AE)] fn default() -> Self { $def } )?
512 parseable_from_str!{u16, default() }
513 parseable_from_str!{u32, default() }
514 parseable_from_str!{String, default() }
515 parseable_from_str!{IpNet, default() }
516 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
517 parseable_from_str!{Uri, default() }
519 impl<T:Parseable> Parseable for Vec<T> {
521 fn parse(s: Option<&str>) -> Vec<T> {
523 .split_ascii_whitespace()
524 .map(|s| Parseable::parse(Some(s)))
525 .collect::<Result<Vec<_>,_>>()?
528 fn default() -> Self { default() }
532 #[derive(Debug,Copy,Clone,Eq,PartialEq)]
533 enum SectionKindList {
541 use SectionKindList as SKL;
544 fn special_server_section() -> Self { SN::Server(ServerName(
545 SPECIAL_SERVER_SECTION.into()
549 impl SectionKindList {
550 fn contains(self, s: &SectionName, end: LinkEnd) -> bool {
553 (SKL::Global, LinkEnd::Client) => matches!(s, SN::Link(_)
558 (SKL::Limits,_) => matches!(s, SN::ServerLimit(_)
561 (SKL::Global, LinkEnd::Server) => matches!(s, SN::Common
564 (SKL::Limited,_) => SKL::PerClient.contains(s, end)
565 | SKL::Limits .contains(s, end),
567 (SKL::ServerName,_) => matches!(s, SN::Common)
568 | matches!(s, SN::Server(ServerName(name))
569 if name == SPECIAL_SERVER_SECTION),
570 (SKL::None,_) => false,
576 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
577 -> Option<RawValRef<'a,'a,'s>>
578 where S: Iterator<Item=&'s SectionName>
580 for section in sections {
581 if let Some(val) = self.sections
583 .and_then(|s: &ini::Section| s.values.get(key))
585 return Some(RawValRef {
596 pub fn establish_server_name(&self) -> ServerName {
598 let raw = match self.lookup_raw(
600 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
602 Some(raw) => raw.try_map(|os| os.value())?,
603 None => SPECIAL_SERVER_SECTION,
605 ServerName(raw.into())
609 impl<'c> ResolveContext<'c> {
610 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
611 -> Option<RawValRef<'c,'c,'c>> {
614 self.all_sections.iter()
615 .filter(|s| sections.contains(s, self.end))
620 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
624 match self.first_of_raw(key, sections) {
626 Some(raw) => Some(raw.try_map(Parseable::parse)?),
631 pub fn ordinary<T>(&self, key: &'static str, skl: SKL) -> T
634 match self.first_of(key, skl)? {
636 None => Parseable::default_for_key(key)?,
641 pub fn limited<T>(&self, key: &'static str, skl: SKL) -> T
642 where T: Parseable + Ord
644 assert_eq!(skl, SKL::Limited);
645 let val = self.ordinary(key, SKL::PerClient)?;
646 if let Some(limit) = self.first_of(key, SKL::Limits)? {
654 pub fn client<T>(&self, key: &'static str, skl: SKL) -> T
655 where T: Parseable + Default {
657 LinkEnd::Client => self.ordinary(key, skl)?,
658 LinkEnd::Server => default(),
662 pub fn server<T>(&self, key: &'static str, skl: SKL) -> T
663 where T: Parseable + Default {
665 LinkEnd::Server => self.ordinary(key, skl)?,
666 LinkEnd::Client => default(),
671 pub fn computed<T>(&self, _key: &'static str, skl: SKL) -> T
674 assert_eq!(skl, SKL::None);
679 pub fn special_ipif(&self, key: &'static str, skl: SKL) -> String {
680 assert_eq!(skl, SKL::PerClient); // we tolerate it in per-client sections
682 LinkEnd::Client => self.ordinary(key, SKL::PerClient)?,
683 LinkEnd::Server => self.ordinary(key, SKL::Global)?,
688 pub fn special_link(&self, _key: &'static str, skl: SKL) -> LinkName {
689 assert_eq!(skl, SKL::None);
694 pub fn special_max_up(&self, key: &'static str, skl: SKL) -> u32 {
695 assert_eq!(skl, SKL::Limited);
697 LinkEnd::Client => self.ordinary(key, SKL::Limited)?,
698 LinkEnd::Server => self.ordinary(key, SKL::Limits)?,
703 impl InstanceConfig {
705 fn complete(&mut self, end: LinkEnd) {
706 let mut vhosts = self.vnetwork.iter()
707 .map(|n| n.hosts()).flatten()
708 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
710 if self.vaddr.is_unspecified() {
711 self.vaddr = vhosts.next().ok_or_else(
712 || anyhow!("vnetwork too small to generate vaddrr")
715 if self.vrelay.is_unspecified() {
716 self.vrelay = vhosts.next().ok_or_else(
717 || anyhow!("vnetwork too small to generate vrelay")
723 move |max_batch, key| {
724 if max_batch/2 < mtu {
725 throw!(anyhow!("max batch {:?} ({}) must be >= 2 x mtu ({}) \
726 (to allow for SLIP ESC-encoding)",
727 key, max_batch, mtu))
735 if &self.url == &default::<Uri>() {
736 let addr = self.addrs.get(0).ok_or_else(
737 || anyhow!("client needs addrs or url set")
742 IpAddr::V4(a) => format!("{}", a),
743 IpAddr::V6(a) => format!("[{}]", a),
747 p => format!(":{}", p),
752 self.effective_http_timeout = {
753 let a = self.http_timeout;
754 let b = self.http_timeout_grace;
755 a.checked_add(b).ok_or_else(
756 || anyhow!("calculate effective http timeout ({:?} + {:?})", a, b)
761 let t = self.target_requests_outstanding;
762 let m = self.max_requests_outstanding;
763 if t > m { throw!(anyhow!(
764 "target_requests_outstanding ({}) > max_requests_outstanding ({})",
769 check_batch(self.max_batch_up, "max_batch_up")?;
773 if self.addrs.is_empty() {
774 throw!(anyhow!("missing 'addrs' setting"))
776 check_batch(self.max_batch_down, "max_batch_down")?;
781 fn subst(var: &mut String,
782 kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
785 .map(|(k,v)| (k.to_string(), v.to_string()))
786 .collect::<HashMap<String, String>>();
787 let bad = parking_lot::Mutex::new(vec![]);
788 *var = regex_replace_all!(
789 r#"%(?:%|\((\w+)\)s|\{(\w+)\}|.)"#,
791 |whole, k1, k2| (|| Ok::<_,String>({
792 if whole == "%%" { "%" }
793 else if let Some(&k) = [k1,k2].iter().find(|&&s| s != "") {
794 substs.get(k).ok_or_else(
795 || format!("unknown key %({})s", k)
798 throw!(format!("bad percent escape {:?}", &whole));
800 }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
802 let bad = bad.into_inner();
803 if ! bad.is_empty() {
804 throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
810 type DD<'d> = &'d dyn Display;
811 fn dv<T:Display>(v: &[T]) -> String {
812 format!("{}", v.iter().format(" "))
814 let mut ipif = mem::take(&mut self.ipif); // lets us borrow all of self
815 let s = &self; // just for abbreviation, below
816 let vnetwork = dv(&s.vnetwork);
817 let vroutes = dv(&s.vroutes);
819 let keys = &["local", "peer", "rnets", "ifname"];
820 let values = match end {
821 Server => [&s.vaddr as DD , &s.vrelay, &vnetwork, &s.ifname_server],
822 Client => [&s.link.client as DD, &s.vaddr, &vroutes, &s.ifname_client],
825 ( "mtu", &s.mtu as DD ),
830 &mut keys.iter().cloned()
832 .chain(always.iter().cloned()),
839 trait ResolveGlobal<'i> where Self: 'i {
840 fn resolve<I>(it: I) -> Self
841 where I: Iterator<Item=&'i Self>;
843 impl<'i,T> ResolveGlobal<'i> for T where T: Eq + Clone + Debug + 'i {
844 fn resolve<I>(mut it: I) -> Self
845 where I: Iterator<Item=&'i Self>
847 let first = it.next().expect("empty instances no global!");
848 for x in it { assert_eq!(x, first); }
854 pub fn read(opts: &Opts, end: LinkEnd) -> Vec<InstanceConfig> {
856 let mut agg = Aggregate::new(
858 InstanceConfig::FIELDS.iter().cloned().collect(),
861 agg.read_string(DEFAULT_CONFIG.into(),
862 "<build-in defaults>".as_ref())
863 .expect("builtin configuration is broken");
865 agg.read_toplevel(&opts.config)?;
866 for extra in &opts.extra_config {
867 agg.read_extra(extra).context("extra config")?;
870 //eprintln!("GOT {:#?}", agg);
873 })().context("read configuration")?;
875 let server_name = match end {
876 LinkEnd::Server => Some(agg.establish_server_name()?),
877 LinkEnd::Client => None,
880 let instances = agg.instances(server_name.as_ref());
881 let mut ics = vec![];
884 for link in instances {
885 let rctx = ResolveContext {
890 SN::Link(link.clone()),
891 SN::Client(link.client.clone()),
892 SN::Server(link.server.clone()),
894 SN::ServerLimit(link.server.clone()),
899 if rctx.first_of_raw("secret", SKL::PerClient).is_none() { continue }
901 let mut ic = InstanceConfig::resolve_instance(&rctx)
902 .with_context(|| format!("resolve config for {}", &link))?;
905 .with_context(|| format!("complete config for {}", &link))?;
913 pub fn startup<F,T>(progname: &str, end: LinkEnd,
914 opts: &Opts, logopts: &LogOpts,
916 where F: FnOnce(Vec<InstanceConfig>) -> Result<T,AE>
920 let ics = config::read(opts, end)?;
921 if ics.is_empty() { throw!(anyhow!("no associations, quitting")); }
927 })().unwrap_or_else(|e| {
928 eprintln!("{}: startup error: {}", progname, &e);