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},%{peer},%{mtu},slip,%{ifname} '%{rnets}'
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>,
91 fn sat(self) -> usize { self.try_into().unwrap_or(usize::MAX) }
95 impl<'s> Option<&'s str> {
97 fn value(self) -> &'s str {
98 self.ok_or_else(|| anyhow!("value needed"))?
103 pub struct Secret(pub String);
104 impl Parseable for Secret {
106 fn parse(s: Option<&str>) -> Self {
108 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
112 fn default() -> Self { Secret(default()) }
114 impl Debug for Secret {
115 #[throws(fmt::Error)]
116 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
119 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
120 pub enum SectionName {
123 Server(ServerName), // includes SERVER, which is slightly special
124 ServerLimit(ServerName),
128 pub use SectionName as SN;
130 #[derive(Debug,Clone)]
131 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
132 type SectionMap = HashMap<String, RawVal>;
135 struct RawValRef<'v,'l,'s> {
136 raw: Option<&'v str>,
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";
159 #[derive(Default,Debug)]
161 keys_allowed: HashMap<&'static str, SectionKindList>,
162 sections: HashMap<SectionName, SectionMap>,
165 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
167 impl<'f,A> OkAnyway<'f,A> {
168 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
169 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]" )?,
219 #[throws(AE)] // AE does not include path
220 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
222 let f = fs::File::open(path);
223 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
224 let mut f = f.context("open")?;
226 let mut s = String::new();
227 let y = f.read_to_string(&mut s);
228 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
231 self.read_string(s, path)?;
235 #[throws(AE)] // AE does not include path
236 fn read_string(&mut self, s: String, path_for_loc: &Path) {
237 let mut ini = Ini::new_cs();
238 ini.set_default_section(OUTSIDE_SECTION);
239 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
240 let map = mem::take(ini.get_mut_map());
241 if map.get(OUTSIDE_SECTION).is_some() {
242 throw!(anyhow!("INI file contains settings outside a section"));
245 let loc = Arc::new(path_for_loc.to_owned());
247 for (sn, vars) in map {
248 let sn = sn.parse().dcontext(&sn)?;
250 for key in vars.keys() {
251 let skl = self.keys_allowed.get(key.as_str()).ok_or_else(
252 || anyhow!("unknown configuration key {:?}", key)
254 if ! skl.contains(&sn) {
255 throw!(anyhow!("configuration key {:?} not applicable \
256 in this kind of section {:?}", key, &sn))
260 let ent = self.sections.entry(sn).or_default();
261 for (key, raw) in vars {
262 let raw = match raw {
263 Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
265 if raw.contains('\\') {
267 anyhow!("quoted value contains backslash, not supported")
270 let unq = raw[1..].strip_suffix(&raw[0..1])
272 || anyhow!("mismatched quotes around quoted value")
277 .with_context(|| format!("key {:?}", key))
278 .dcontext(path_for_loc)?
282 let key = key.replace('-',"_");
283 ent.insert(key, RawVal { raw, loc: loc.clone() });
288 #[throws(AE)] // AE includes path
289 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
291 let dir = fs::read_dir(path);
292 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
293 let dir = dir.context("open directory").dcontext(path)?;
295 let ent = ent.context("read directory").dcontext(path)?;
296 let leaf = ent.file_name();
297 let leaf = leaf.to_str();
298 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
299 if leaf.len() == 0 { continue }
300 if ! leaf.chars().all(
301 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
304 // OK we want this one
305 let ent = ent.path();
306 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
311 #[throws(AE)] // AE includes everything
312 fn read_toplevel(&mut self, toplevel: &Path) {
313 enum Anyway { None, Dir }
314 match self.read_file(toplevel, &|k| match k {
315 EK::NotFound => Some(Anyway::None),
316 EK::IsADirectory => Some(Anyway::Dir),
319 .dcontext(toplevel).context("top-level config directory (or file)")?
321 None | Some(Anyway::None) => { },
323 Some(Anyway::Dir) => {
325 let anyway_none = |k| match k {
326 EK::NotFound => Some(AnywayNone),
330 let mk = |leaf: &str| {
331 [ toplevel, &PathBuf::from(leaf) ]
332 .iter().collect::<PathBuf>()
335 for &(try_main, desc) in &[
336 ("main.cfg", "main config file"),
337 ("master.cfg", "obsolete-named main config file"),
339 let main = mk(try_main);
341 match self.read_file(&main, &anyway_none)
342 .dcontext(main).context(desc)?
345 Some(AnywayNone) => { },
349 for &(try_dir, desc) in &[
350 ("config.d", "per-link config directory"),
351 ("secrets.d", "per-link secrets directory"),
353 let dir = mk(try_dir);
354 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
356 Some(AnywayNone) => { },
363 #[throws(AE)] // AE includes extra, but does that this is extra
364 fn read_extra(&mut self, extra: &Path) {
367 match self.read_file(extra, &|k| match k {
368 EK::IsADirectory => Some(AnywayDir),
375 self.read_dir_d(extra, &|_| None::<Void>)?;
383 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
384 let mut links: BTreeSet<LinkName> = default();
386 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
387 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
388 let mut secret_global = false;
390 let mut putative_servers = BTreeSet::new();
391 let mut putative_clients = BTreeSet::new();
393 let mut note_server = |s| {
394 if let Some(only) = only_server { if s != only { return false } }
395 putative_servers.insert(s);
398 let mut note_client = |c| {
399 putative_clients.insert(c);
402 for (section, vars) in &self.sections {
403 let has_secret = || vars.contains_key("secret");
407 if ! note_server(&l.server) { continue }
408 note_client(&l.client);
409 if has_secret() { links.insert(l.clone()); }
411 SN::Server(ref s) => {
412 if ! note_server(s) { continue }
413 if has_secret() { secrets_anyclient.insert(s); }
415 SN::Client(ref c) => {
417 if has_secret() { secrets_anyserver.insert(c); }
420 if has_secret() { secret_global = true; }
426 // Add links which are justified by blanket secrets
427 for (client, server) in iproduct!(
428 putative_clients.into_iter().filter(
429 |c| secret_global || secrets_anyserver.contains(c)
431 putative_servers.iter().cloned().filter(
432 |s| secret_global || secrets_anyclient.contains(s)
435 links.insert(LinkName {
436 client: client.clone(),
437 server: server.clone(),
445 struct ResolveContext<'c> {
449 all_sections: Vec<SectionName>,
452 trait Parseable: Sized {
453 fn parse(s: Option<&str>) -> Result<Self, AE>;
454 fn default() -> Result<Self, AE> {
455 Err(anyhow!("setting must be specified"))
458 fn default_for_key(key: &str) -> Self {
459 Self::default().with_context(|| key.to_string())?
463 impl Parseable for Duration {
465 fn parse(s: Option<&str>) -> Duration {
466 // todo: would be nice to parse with humantime maybe
467 Duration::from_secs( s.value()?.parse()? )
470 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
471 impl Parseable for $t {
473 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
474 $( #[throws(AE)] fn default() -> Self { $def } )?
477 parseable_from_str!{u16, default() }
478 parseable_from_str!{u32, default() }
479 parseable_from_str!{String, default() }
480 parseable_from_str!{IpNet, default() }
481 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
482 parseable_from_str!{Uri, default() }
484 impl<T:Parseable> Parseable for Vec<T> {
486 fn parse(s: Option<&str>) -> Vec<T> {
488 .split_ascii_whitespace()
489 .map(|s| Parseable::parse(Some(s)))
490 .collect::<Result<Vec<_>,_>>()?
493 fn default() -> Self { default() }
497 #[derive(Debug,Copy,Clone)]
498 enum SectionKindList {
505 use SectionKindList as SKL;
508 fn special_server_section() -> Self { SN::Server(ServerName(
509 SPECIAL_SERVER_SECTION.into()
513 impl SectionKindList {
514 fn contains(self, s: &SectionName) -> bool {
516 SKL::Ordinary => matches!(s, SN::Link(_)
521 SKL::Limits => matches!(s, SN::ServerLimit(_)
524 SKL::ClientAgnostic => matches!(s, SN::Common
527 SKL::Limited => SKL::Ordinary.contains(s)
528 | SKL::Limits .contains(s),
530 SKL::ServerName => matches!(s, SN::Common)
531 | matches!(s, SN::Server(ServerName(name))
532 if name == SPECIAL_SERVER_SECTION),
538 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
539 -> Option<RawValRef<'a,'a,'s>>
540 where S: Iterator<Item=&'s SectionName>
542 for section in sections {
543 if let Some(raw) = self.sections
545 .and_then(|vars: &SectionMap| vars.get(key))
547 return Some(RawValRef {
548 raw: raw.raw.as_deref(),
558 pub fn establish_server_name(&self) -> ServerName {
560 let raw = match self.lookup_raw(
562 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
564 Some(raw) => raw.try_map(|os| os.value())?,
565 None => SPECIAL_SERVER_SECTION,
567 ServerName(raw.into())
571 impl<'c> ResolveContext<'c> {
572 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
573 -> Option<RawValRef<'c,'c,'c>> {
576 self.all_sections.iter()
577 .filter(|s| sections.contains(s))
582 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
586 match self.first_of_raw(key, sections) {
588 Some(raw) => Some(raw.try_map(Parseable::parse)?),
593 pub fn ordinary<T>(&self, key: &'static str) -> T
596 match self.first_of(key, SKL::Ordinary)? {
598 None => Parseable::default_for_key(key)?,
603 pub fn limited<T>(&self, key: &'static str) -> T
604 where T: Parseable + Ord
606 let val = self.ordinary(key)?;
607 if let Some(limit) = self.first_of(key, SKL::Limits)? {
615 pub fn client<T>(&self, key: &'static str) -> T
616 where T: Parseable + Default {
618 LinkEnd::Client => self.ordinary(key)?,
619 LinkEnd::Server => default(),
623 pub fn server<T>(&self, key: &'static str) -> T
624 where T: Parseable + Default {
626 LinkEnd::Server => self.ordinary(key)?,
627 LinkEnd::Client => default(),
632 pub fn special_ipif(&self, key: &'static str) -> String {
634 LinkEnd::Client => self.ordinary(key)?,
636 self.first_of(key, SKL::ClientAgnostic)?
643 pub fn special_link(&self, _key: &'static str) -> LinkName {
648 impl InstanceConfig {
650 fn complete(&mut self, end: LinkEnd) {
651 let mut vhosts = self.vnetwork.iter()
652 .map(|n| n.hosts()).flatten()
653 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
655 if self.vaddr.is_unspecified() {
656 self.vaddr = vhosts.next().ok_or_else(
657 || anyhow!("vnetwork too small to generate vaddrr")
660 if self.vrelay.is_unspecified() {
661 self.vrelay = vhosts.next().ok_or_else(
662 || anyhow!("vnetwork too small to generate vrelay")
668 move |max_batch, key| {
669 if max_batch/2 < mtu {
670 throw!(anyhow!("max batch {:?} ({}) must be >= 2 x mtu ({}) \
671 (to allow for SLIP ESC-encoding)",
672 key, max_batch, mtu))
680 if &self.url == &default::<Uri>() {
681 let addr = self.addrs.get(0).ok_or_else(
682 || anyhow!("client needs addrs or url set")
687 IpAddr::V4(a) => format!("{}", a),
688 IpAddr::V6(a) => format!("[{}]", a),
692 p => format!(":{}", p),
697 check_batch(self.max_batch_up, "max_batch_up")?;
701 if self.addrs.is_empty() {
702 throw!(anyhow!("missing 'addrs' setting"))
704 check_batch(self.max_batch_down, "max_batch_down")?;
707 // xxx check target vs max req outstanding
711 fn subst(var: &mut String,
712 kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
715 .map(|(k,v)| (k.to_string(), v.to_string()))
716 .collect::<HashMap<String, String>>();
717 let bad = parking_lot::Mutex::new(vec![]);
718 *var = regex_replace_all!(
719 r#"%(?:%|\((\w+)\)s|\{(\w+)\}|.)"#,
721 |whole, k1, k2| (|| Ok::<_,String>({
722 if whole == "%%" { "%" }
723 else if let Some(&k) = [k1,k2].iter().find(|&&s| s != "") {
724 substs.get(k).ok_or_else(
725 || format!("unknown key %({})s", k)
728 throw!(format!("bad percent escape {:?}", &whole));
730 }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
732 let bad = bad.into_inner();
733 if ! bad.is_empty() {
734 throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
740 type DD<'d> = &'d dyn Display;
741 fn dv<T:Display>(v: &[T]) -> String {
742 format!("{}", v.iter().format(" "))
744 let mut ipif = mem::take(&mut self.ipif); // lets us borrow all of self
745 let s = &self; // just for abbreviation, below
746 let vnetwork = dv(&s.vnetwork);
747 let vroutes = dv(&s.vroutes);
749 let keys = &["local", "peer", "rnets", "ifname"];
750 let values = match end {
751 Server => [&s.vaddr as DD , &s.vrelay, &vnetwork, &s.ifname_server],
752 Client => [&s.link.client as DD, &s.vaddr, &vroutes, &s.ifname_client],
755 ( "mtu", &s.mtu as DD ),
760 &mut keys.iter().cloned()
762 .chain(always.iter().cloned()),
770 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
771 let opts = config::Opts::from_args();
774 let mut agg = Aggregate::default();
775 agg.keys_allowed.extend(
776 InstanceConfig::FIELDS.iter().cloned()
779 agg.read_string(DEFAULT_CONFIG.into(),
780 "<build-in defaults>".as_ref()).unwrap();
782 agg.read_toplevel(&opts.config)?;
783 for extra in &opts.extra_config {
784 agg.read_extra(extra).context("extra config")?;
787 //eprintln!("GOT {:#?}", agg);
790 })().context("read configuration")?;
792 let server_name = match end {
793 LinkEnd::Server => Some(agg.establish_server_name()?),
794 LinkEnd::Client => None,
797 let instances = agg.instances(server_name.as_ref());
798 let mut ics = vec![];
800 for link in instances {
801 let rctx = ResolveContext {
806 SN::Link(link.clone()),
807 SN::Client(link.client.clone()),
808 SN::Server(link.server.clone()),
810 SN::ServerLimit(link.server.clone()),
815 let mut ic = InstanceConfig::resolve_instance(&rctx)
816 .with_context(|| format!("resolve config for {}", &link))?;
819 .with_context(|| format!("complete config for {}", &link))?;