1 // Copyright 2021-2022 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(&io::Error) -> 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()?;
176 impl FromStr for SectionName {
179 fn from_str(s: &str) -> Self {
181 "COMMON" => return SN::Common,
182 "LIMIT" => return SN::GlobalLimit,
185 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
186 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
187 let (server, client) = s.split_ascii_whitespace().collect_tuple()
188 .ok_or_else(|| anyhow!(
189 "bad section name {:?} \
190 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
193 let server = server.parse().context("server name in link section name")?;
194 if client == "LIMIT" { return SN::ServerLimit(server) }
195 let client = client.parse().context("client name in link section name")?;
196 SN::Link(LinkName { server, client })
199 impl Display for InstanceConfig {
200 #[throws(fmt::Error)]
201 fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.link, f)? }
204 impl Display for SectionName {
205 #[throws(fmt::Error)]
206 fn fmt(&self, f: &mut fmt::Formatter) {
208 SN::Link (ref l) => Display::fmt(l, f)?,
209 SN::Client(ref c) => write!(f, "[{}]" , c)?,
210 SN::Server(ref s) => write!(f, "[{}]" , s)?,
211 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
212 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
213 SN::Common => write!(f, "[COMMON]" )?,
221 keys_allowed: HashMap<&'static str, SectionKindList>
222 ) -> Self { Aggregate {
227 #[throws(AE)] // AE does not include path
228 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
230 let f = fs::File::open(path);
231 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
232 let mut f = f.context("open")?;
234 let mut s = String::new();
235 let y = f.read_to_string(&mut s);
236 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
239 self.read_string(s, path)?;
243 #[throws(AE)] // AE does not include path
244 fn read_string(&mut self, s: String, path_for_loc: &Path) {
245 let mut map: ini::Parsed = default();
246 ini::read(&mut map, &mut s.as_bytes(), path_for_loc)
247 .context("parse as INI")?;
248 if map.get(OUTSIDE_SECTION).is_some() {
249 throw!(anyhow!("INI file contains settings outside a section"));
252 for (sn, section) in map {
253 let sn = sn.parse().dcontext(&sn)?;
254 let vars = §ion.values;
256 for (key, val) in vars {
258 let skl = if key == "server" {
261 *self.keys_allowed.get(key.as_str()).ok_or_else(
262 || anyhow!("unknown configuration key")
265 if ! skl.contains(&sn, self.end) {
266 throw!(anyhow!("key not applicable in this kind of section"))
270 .with_context(|| format!("key {:?}", key))
271 .with_context(|| val.loc.to_string())?
274 let ent = self.sections.entry(sn)
275 .or_insert_with(|| ini::Section {
276 loc: section.loc.clone(),
280 for (key, ini::Val { val: raw, loc }) in vars {
281 let val = if raw.starts_with('\'') || raw.starts_with('"') {
283 if raw.contains('\\') {
285 anyhow!("quoted value contains backslash, not supported")
288 let quote = &raw[0..1];
290 let unq = raw[1..].strip_suffix(quote)
292 || anyhow!("mismatched quotes around quoted value")
295 if unq.contains(quote) {
297 "quoted value contains quote (escaping not supported)"
303 .with_context(|| format!("key {:?}", key))
304 .with_context(|| loc.to_string())?
308 let key = key.replace('-',"_");
309 ent.values.insert(key, ini::Val { val, loc: loc.clone() });
314 #[throws(AE)] // AE includes path
315 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
317 let dir = fs::read_dir(path);
318 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
319 let dir = dir.context("open directory").dcontext(path)?;
321 let ent = ent.context("read directory").dcontext(path)?;
322 let leaf = ent.file_name();
323 let leaf = leaf.to_str();
324 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
325 if leaf.len() == 0 { continue }
326 if ! leaf.chars().all(
327 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
330 // OK we want this one
331 let ent = ent.path();
332 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
337 #[throws(AE)] // AE includes everything
338 fn read_toplevel(&mut self, toplevel: &Path) {
339 enum Anyway { None, Dir }
340 match self.read_file(toplevel, &|e| match e {
341 e if e.kind() == EK::NotFound => Some(Anyway::None),
342 e if e.is_is_a_directory() => Some(Anyway::Dir),
345 .dcontext(toplevel).context("top-level config directory (or file)")?
347 None | Some(Anyway::None) => { },
349 Some(Anyway::Dir) => {
351 let anyway_none = |e: &io::Error| match e {
352 e if e.kind() == EK::NotFound => Some(AnywayNone),
356 let mk = |leaf: &str| {
357 [ toplevel, &PathBuf::from(leaf) ]
358 .iter().collect::<PathBuf>()
361 for &(try_main, desc) in &[
362 ("main.cfg", "main config file"),
363 ("master.cfg", "obsolete-named main config file"),
365 let main = mk(try_main);
367 match self.read_file(&main, &anyway_none)
368 .dcontext(main).context(desc)?
371 Some(AnywayNone) => { },
375 for &(try_dir, desc) in &[
376 ("config.d", "per-link config directory"),
377 ("secrets.d", "per-link secrets directory"),
379 let dir = mk(try_dir);
380 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
382 Some(AnywayNone) => { },
389 #[throws(AE)] // AE includes extra, but does that this is extra
390 fn read_extra(&mut self, extra: &Path) {
393 match self.read_file(extra, &|e| match e {
394 e if e.is_is_a_directory() => Some(AnywayDir),
401 self.read_dir_d(extra, &|_| None::<Void>)?;
409 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
410 let mut links: BTreeSet<LinkName> = default();
412 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
413 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
414 let mut secret_global = false;
416 let mut putative_servers = BTreeSet::new();
417 let mut putative_clients = BTreeSet::new();
419 let mut note_server = |s| {
420 if let Some(only) = only_server { if s != only { return false } }
421 putative_servers.insert(s);
424 let mut note_client = |c| {
425 putative_clients.insert(c);
428 for (section, vars) in &self.sections {
429 let has_secret = || vars.values.contains_key("secret");
430 //dbg!(§ion, has_secret());
434 if ! note_server(&l.server) { continue }
435 note_client(&l.client);
436 if has_secret() { links.insert(l.clone()); }
438 SN::Server(ref s) => {
439 if ! note_server(s) { continue }
440 if has_secret() { secrets_anyclient.insert(s); }
442 SN::Client(ref c) => {
444 if has_secret() { secrets_anyserver.insert(c); }
447 if has_secret() { secret_global = true; }
453 //dbg!(&putative_servers, &putative_clients);
454 //dbg!(&secrets_anyserver, &secrets_anyclient, &secret_global);
456 // Add links which are justified by blanket secrets
457 for (client, server) in iproduct!(
458 putative_clients.into_iter().filter(
460 || secrets_anyserver.contains(c)
461 || ! secrets_anyclient.is_empty()
463 putative_servers.iter().cloned().filter(
465 || secrets_anyclient.contains(s)
466 || ! secrets_anyserver.is_empty()
469 links.insert(LinkName {
470 client: client.clone(),
471 server: server.clone(),
479 struct ResolveContext<'c> {
483 all_sections: Vec<SectionName>,
486 trait Parseable: Sized {
487 fn parse(s: Option<&str>) -> Result<Self, AE>;
488 fn default() -> Result<Self, AE> {
489 Err(anyhow!("setting must be specified"))
492 fn default_for_key(key: &str) -> Self {
493 Self::default().with_context(|| key.to_string())?
497 impl Parseable for Duration {
499 fn parse(s: Option<&str>) -> Duration {
500 // todo: would be nice to parse with humantime maybe
501 Duration::from_secs( s.value()?.parse()? )
504 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
505 impl Parseable for $t {
507 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
508 $( #[throws(AE)] fn default() -> Self { $def } )?
511 parseable_from_str!{u16, default() }
512 parseable_from_str!{u32, default() }
513 parseable_from_str!{String, default() }
514 parseable_from_str!{IpNet, default() }
515 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
516 parseable_from_str!{Uri, default() }
518 impl<T:Parseable> Parseable for Vec<T> {
520 fn parse(s: Option<&str>) -> Vec<T> {
522 .split_ascii_whitespace()
523 .map(|s| Parseable::parse(Some(s)))
524 .collect::<Result<Vec<_>,_>>()?
527 fn default() -> Self { default() }
531 #[derive(Debug,Copy,Clone,Eq,PartialEq)]
532 enum SectionKindList {
540 use SectionKindList as SKL;
543 fn special_server_section() -> Self { SN::Server(ServerName(
544 SPECIAL_SERVER_SECTION.into()
548 impl SectionKindList {
549 fn contains(self, s: &SectionName, end: LinkEnd) -> bool {
552 (SKL::Global, LinkEnd::Client) => matches!(s, SN::Link(_)
557 (SKL::Limits,_) => matches!(s, SN::ServerLimit(_)
560 (SKL::Global, LinkEnd::Server) => matches!(s, SN::Common
563 (SKL::Limited,_) => SKL::PerClient.contains(s, end)
564 | SKL::Limits .contains(s, end),
566 (SKL::ServerName,_) => matches!(s, SN::Common)
567 | matches!(s, SN::Server(ServerName(name))
568 if name == SPECIAL_SERVER_SECTION),
569 (SKL::None,_) => false,
575 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
576 -> Option<RawValRef<'a,'a,'s>>
577 where S: Iterator<Item=&'s SectionName>
579 for section in sections {
580 if let Some(val) = self.sections
582 .and_then(|s: &ini::Section| s.values.get(key))
584 return Some(RawValRef {
595 pub fn establish_server_name(&self) -> ServerName {
597 let raw = match self.lookup_raw(
599 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
601 Some(raw) => raw.try_map(|os| os.value())?,
602 None => SPECIAL_SERVER_SECTION,
604 ServerName(raw.into())
608 impl<'c> ResolveContext<'c> {
609 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
610 -> Option<RawValRef<'c,'c,'c>> {
613 self.all_sections.iter()
614 .filter(|s| sections.contains(s, self.end))
619 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
623 match self.first_of_raw(key, sections) {
625 Some(raw) => Some(raw.try_map(Parseable::parse)?),
630 pub fn ordinary<T>(&self, key: &'static str, skl: SKL) -> T
633 match self.first_of(key, skl)? {
635 None => Parseable::default_for_key(key)?,
640 pub fn limited<T>(&self, key: &'static str, skl: SKL) -> T
641 where T: Parseable + Ord
643 assert_eq!(skl, SKL::Limited);
644 let val = self.ordinary(key, SKL::PerClient)?;
645 if let Some(limit) = self.first_of(key, SKL::Limits)? {
653 pub fn client<T>(&self, key: &'static str, skl: SKL) -> T
654 where T: Parseable + Default {
656 LinkEnd::Client => self.ordinary(key, skl)?,
657 LinkEnd::Server => default(),
661 pub fn server<T>(&self, key: &'static str, skl: SKL) -> T
662 where T: Parseable + Default {
664 LinkEnd::Server => self.ordinary(key, skl)?,
665 LinkEnd::Client => default(),
670 pub fn computed<T>(&self, _key: &'static str, skl: SKL) -> T
673 assert_eq!(skl, SKL::None);
678 pub fn special_ipif(&self, key: &'static str, skl: SKL) -> String {
679 assert_eq!(skl, SKL::PerClient); // we tolerate it in per-client sections
681 LinkEnd::Client => self.ordinary(key, SKL::PerClient)?,
682 LinkEnd::Server => self.ordinary(key, SKL::Global)?,
687 pub fn special_link(&self, _key: &'static str, skl: SKL) -> LinkName {
688 assert_eq!(skl, SKL::None);
693 pub fn special_max_up(&self, key: &'static str, skl: SKL) -> u32 {
694 assert_eq!(skl, SKL::Limited);
696 LinkEnd::Client => self.ordinary(key, SKL::Limited)?,
697 LinkEnd::Server => self.ordinary(key, SKL::Limits)?,
702 impl InstanceConfig {
704 fn complete(&mut self, end: LinkEnd) {
705 let mut vhosts = self.vnetwork.iter()
706 .map(|n| n.hosts()).flatten()
707 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
709 if self.vaddr.is_unspecified() {
710 self.vaddr = vhosts.next().ok_or_else(
711 || anyhow!("vnetwork too small to generate vaddrr")
714 if self.vrelay.is_unspecified() {
715 self.vrelay = vhosts.next().ok_or_else(
716 || anyhow!("vnetwork too small to generate vrelay")
722 move |max_batch, key| {
723 if max_batch/2 < mtu {
724 throw!(anyhow!("max batch {:?} ({}) must be >= 2 x mtu ({}) \
725 (to allow for SLIP ESC-encoding)",
726 key, max_batch, mtu))
734 if &self.url == &default::<Uri>() {
735 let addr = self.addrs.get(0).ok_or_else(
736 || anyhow!("client needs addrs or url set")
741 IpAddr::V4(a) => format!("{}", a),
742 IpAddr::V6(a) => format!("[{}]", a),
746 p => format!(":{}", p),
751 self.effective_http_timeout = {
752 let a = self.http_timeout;
753 let b = self.http_timeout_grace;
754 a.checked_add(b).ok_or_else(
755 || anyhow!("calculate effective http timeout ({:?} + {:?})", a, b)
760 let t = self.target_requests_outstanding;
761 let m = self.max_requests_outstanding;
762 if t > m { throw!(anyhow!(
763 "target_requests_outstanding ({}) > max_requests_outstanding ({})",
768 check_batch(self.max_batch_up, "max_batch_up")?;
772 if self.addrs.is_empty() {
773 throw!(anyhow!("missing 'addrs' setting"))
775 check_batch(self.max_batch_down, "max_batch_down")?;
780 fn subst(var: &mut String,
781 kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
784 .map(|(k,v)| (k.to_string(), v.to_string()))
785 .collect::<HashMap<String, String>>();
786 let bad = parking_lot::Mutex::new(vec![]);
787 *var = regex_replace_all!(
788 r#"%(?:%|\((\w+)\)s|\{(\w+)\}|.)"#,
790 |whole, k1, k2| (|| Ok::<_,String>({
791 if whole == "%%" { "%" }
792 else if let Some(&k) = [k1,k2].iter().find(|&&s| s != "") {
793 substs.get(k).ok_or_else(
794 || format!("unknown key %({})s", k)
797 throw!(format!("bad percent escape {:?}", &whole));
799 }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
801 let bad = bad.into_inner();
802 if ! bad.is_empty() {
803 throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
809 type DD<'d> = &'d dyn Display;
810 fn dv<T:Display>(v: &[T]) -> String {
811 format!("{}", v.iter().format(" "))
813 let mut ipif = mem::take(&mut self.ipif); // lets us borrow all of self
814 let s = &self; // just for abbreviation, below
815 let vnetwork = dv(&s.vnetwork);
816 let vroutes = dv(&s.vroutes);
818 let keys = &["local", "peer", "rnets", "ifname"];
819 let values = match end {
820 Server => [&s.vaddr as DD , &s.vrelay, &vnetwork, &s.ifname_server],
821 Client => [&s.link.client as DD, &s.vaddr, &vroutes, &s.ifname_client],
824 ( "mtu", &s.mtu as DD ),
829 &mut keys.iter().cloned()
831 .chain(always.iter().cloned()),
838 trait ResolveGlobal<'i> where Self: 'i {
839 fn resolve<I>(it: I) -> Self
840 where I: Iterator<Item=&'i Self>;
842 impl<'i,T> ResolveGlobal<'i> for T where T: Eq + Clone + Debug + 'i {
843 fn resolve<I>(mut it: I) -> Self
844 where I: Iterator<Item=&'i Self>
846 let first = it.next().expect("empty instances no global!");
847 for x in it { assert_eq!(x, first); }
853 pub fn read(opts: &Opts, end: LinkEnd) -> Vec<InstanceConfig> {
855 let mut agg = Aggregate::new(
857 InstanceConfig::FIELDS.iter().cloned().collect(),
860 agg.read_string(DEFAULT_CONFIG.into(),
861 "<build-in defaults>".as_ref())
862 .expect("builtin configuration is broken");
864 agg.read_toplevel(&opts.config)?;
865 for extra in &opts.extra_config {
866 agg.read_extra(extra).context("extra config")?;
869 //eprintln!("GOT {:#?}", agg);
872 })().context("read configuration")?;
874 let server_name = match end {
875 LinkEnd::Server => Some(agg.establish_server_name()?),
876 LinkEnd::Client => None,
879 let instances = agg.instances(server_name.as_ref());
880 let mut ics = vec![];
883 for link in instances {
884 let rctx = ResolveContext {
889 SN::Link(link.clone()),
890 SN::Client(link.client.clone()),
891 SN::Server(link.server.clone()),
893 SN::ServerLimit(link.server.clone()),
898 if rctx.first_of_raw("secret", SKL::PerClient).is_none() { continue }
900 let mut ic = InstanceConfig::resolve_instance(&rctx)
901 .with_context(|| format!("resolve config for {}", &link))?;
904 .with_context(|| format!("complete config for {}", &link))?;
912 pub fn startup<F,T>(progname: &str, end: LinkEnd,
913 opts: &Opts, logopts: &LogOpts,
915 where F: FnOnce(Vec<InstanceConfig>) -> Result<T,AE>
919 let ics = config::read(opts, end)?;
920 if ics.is_empty() { throw!(anyhow!("no associations, quitting")); }
926 })().unwrap_or_else(|e| {
927 eprintln!("{}: startup error: {}", progname, &e);