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 static DEFAULT_CONFIG: &str = r#"
11 max_batch_down = 65536
13 target_requests_outstanding = 3
15 http_timeout_grace = 5
16 max_requests_outstanding = 6
21 ifname_client = hippo%%d
22 ifname_server = shippo%%d
25 ipif = userv root ipif %(local)s,%(peer)s,%(mtu)s,slip,%(ifname)s %(rnets)s
29 vvnetwork = 172.24.230.192
32 max_batch_down = 262144
35 target_requests_outstanding = 10
38 #[derive(StructOpt,Debug)]
40 /// Top-level config file or directory
42 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
44 /// Or if this is a file, just read that file.
45 #[structopt(long, default_value="/etc/hippotat")]
48 /// Additional config files or dirs, which can override the others
49 #[structopt(long, multiple=true, number_of_values=1)]
50 pub extra_config: Vec<PathBuf>,
54 impl<'s> Option<&'s str> {
56 fn value(self) -> &'s str {
57 self.ok_or_else(|| anyhow!("value needed"))?
62 pub struct Secret(pub String);
63 impl Parseable for Secret {
65 fn parse(s: Option<&str>) -> Self {
67 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
71 fn default() -> Self { Secret(default()) }
73 impl Debug for Secret {
75 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
78 #[derive(hippotat_macros::ResolveConfig)]
79 #[derive(Debug,Clone)]
80 pub struct InstanceConfig {
81 // Exceptional settings
82 #[special(special_server, SKL::ServerName)] pub server: ServerName,
84 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
87 #[limited] pub max_batch_down: u32,
88 #[limited] pub max_queue_time: Duration,
89 #[limited] pub http_timeout: Duration,
90 #[limited] pub target_requests_outstanding: u32,
93 pub addrs: Vec<IpAddr>,
94 pub vnetwork: Vec<IpNet>,
95 pub vaddr: Vec<IpAddr>,
99 pub ifname_server: String,
100 pub ifname_client: String,
102 // Ordinary settings, used by server only:
103 #[server] pub max_clock_skew: Duration,
105 // Ordinary settings, used by client only:
106 #[client] pub http_timeout_grace: Duration,
107 #[client] pub max_requests_outstanding: u32,
108 #[client] pub max_batch_up: u32,
109 #[client] pub http_retry: Duration,
110 #[client] pub url: Uri,
111 #[client] pub vroutes: Vec<IpNet>,
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>;
129 struct RawValRef<'v,'l,'s> {
130 raw: Option<&'v str>,
133 section: &'s SectionName,
136 impl<'v> RawValRef<'v,'_,'_> {
138 fn try_map<F,T>(&self, f: F) -> T
139 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
141 .with_context(|| format!(r#"file {:?}, section "{:?}", key "{}"#,
142 self.loc, self.section, self.key))?
150 static OUTSIDE_SECTION: &str = "[";
151 static SPECIAL_SERVER_SECTION: &str = "SERVER";
153 #[derive(Default,Debug)]
155 sections: HashMap<SectionName, SectionMap>,
158 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
160 impl<'f,A> OkAnyway<'f,A> {
161 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
162 let e = r.as_ref().err()?;
169 impl FromStr for SectionName {
172 fn from_str(s: &str) -> Self {
174 "COMMON" => return SN::Common,
175 "LIMIT" => return SN::GlobalLimit,
178 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
179 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
180 let (server, client) = s.split_ascii_whitespace().collect_tuple()
181 .ok_or_else(|| anyhow!(
182 "bad section name {:?} \
183 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
186 let server = server.parse().context("server name in link section name")?;
187 if client == "LIMIT" { return SN::ServerLimit(server) }
188 let client = client.parse().context("client name in link section name")?;
189 SN::Link(LinkName { server, client })
194 #[throws(AE)] // AE does not include path
195 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
197 let f = fs::File::open(path);
198 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
199 let mut f = f.context("open")?;
201 let mut s = String::new();
202 let y = f.read_to_string(&mut s);
203 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
206 self.read_string(s, path)?;
210 #[throws(AE)] // AE does not include path
211 fn read_string(&mut self, s: String, path_for_loc: &Path) {
212 let mut ini = Ini::new_cs();
213 ini.set_default_section(OUTSIDE_SECTION);
214 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
215 let map = mem::take(ini.get_mut_map());
216 if map.get(OUTSIDE_SECTION).is_some() {
217 throw!(anyhow!("INI file contains settings outside a section"));
220 let loc = Arc::new(path_for_loc.to_owned());
222 for (sn, vars) in map {
223 //dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
225 let sn = sn.parse().dcontext(&sn)?;
226 self.sections.entry(sn)
232 RawVal { raw, loc: loc.clone() })
239 #[throws(AE)] // AE includes path
240 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
242 let dir = fs::read_dir(path);
243 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
244 let dir = dir.context("open directory").dcontext(path)?;
246 let ent = ent.context("read directory").dcontext(path)?;
247 let leaf = ent.file_name();
248 let leaf = leaf.to_str();
249 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
250 if leaf.len() == 0 { continue }
251 if ! leaf.chars().all(
252 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
255 // OK we want this one
256 let ent = ent.path();
257 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
262 #[throws(AE)] // AE includes everything
263 fn read_toplevel(&mut self, toplevel: &Path) {
264 enum Anyway { None, Dir }
265 match self.read_file(toplevel, &|k| match k {
266 EK::NotFound => Some(Anyway::None),
267 EK::IsADirectory => Some(Anyway::Dir),
270 .dcontext(toplevel).context("top-level config directory (or file)")?
272 None | Some(Anyway::None) => { },
274 Some(Anyway::Dir) => {
276 let anyway_none = |k| match k {
277 EK::NotFound => Some(AnywayNone),
281 let mk = |leaf: &str| {
282 [ toplevel, &PathBuf::from(leaf) ]
283 .iter().collect::<PathBuf>()
286 for &(try_main, desc) in &[
287 ("main.cfg", "main config file"),
288 ("master.cfg", "obsolete-named main config file"),
290 let main = mk(try_main);
292 match self.read_file(&main, &anyway_none)
293 .dcontext(main).context(desc)?
296 Some(AnywayNone) => { },
300 for &(try_dir, desc) in &[
301 ("config.d", "per-link config directory"),
302 ("secrets.d", "per-link secrets directory"),
304 let dir = mk(try_dir);
305 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
307 Some(AnywayNone) => { },
314 #[throws(AE)] // AE includes extra, but does that this is extra
315 fn read_extra(&mut self, extra: &Path) {
318 match self.read_file(extra, &|k| match k {
319 EK::IsADirectory => Some(AnywayDir),
326 self.read_dir_d(extra, &|_| None::<Void>)?;
334 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
335 let mut links: BTreeSet<LinkName> = default();
337 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
338 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
339 let mut secret_global = false;
341 let mut putative_servers = BTreeSet::new();
342 let mut putative_clients = BTreeSet::new();
344 let mut note_server = |s| {
345 if let Some(only) = only_server { if s != only { return false } }
346 putative_servers.insert(s);
349 let mut note_client = |c| {
350 putative_clients.insert(c);
353 for (section, vars) in &self.sections {
354 let has_secret = || vars.contains_key("secret");
358 if ! note_server(&l.server) { continue }
359 note_client(&l.client);
360 if has_secret() { links.insert(l.clone()); }
362 SN::Server(ref s) => {
363 if ! note_server(s) { continue }
364 if has_secret() { secrets_anyclient.insert(s); }
366 SN::Client(ref c) => {
368 if has_secret() { secrets_anyserver.insert(c); }
371 if has_secret() { secret_global = true; }
377 // Add links which are justified by blanket secrets
378 for (client, server) in iproduct!(
379 putative_clients.into_iter().filter(
380 |c| secret_global || secrets_anyserver.contains(c)
382 putative_servers.iter().cloned().filter(
383 |s| secret_global || secrets_anyclient.contains(s)
386 links.insert(LinkName {
387 client: client.clone(),
388 server: server.clone(),
396 struct ResolveContext<'c> {
400 all_sections: Vec<SectionName>,
403 trait Parseable: Sized {
404 fn parse(s: Option<&str>) -> Result<Self, AE>;
405 fn default() -> Result<Self, AE> {
406 Err(anyhow!("setting must be specified"))
409 fn default_for_key(key: &str) -> Self {
410 Self::default().with_context(|| key.to_string())?
414 impl Parseable for Duration {
416 fn parse(s: Option<&str>) -> Duration {
417 // todo: would be nice to parse with humantime maybe
418 Duration::from_secs( s.value()?.parse()? )
421 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
422 impl Parseable for $t {
424 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
425 $( #[throws(AE)] fn default() -> Self { $def } )?
428 parseable_from_str!{u16, default() }
429 parseable_from_str!{u32, default() }
430 parseable_from_str!{String, default() }
431 parseable_from_str!{IpNet, default() }
432 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
433 parseable_from_str!{Uri, default() }
435 impl<T:Parseable> Parseable for Vec<T> {
437 fn parse(s: Option<&str>) -> Vec<T> {
439 .split_ascii_whitespace()
440 .map(|s| Parseable::parse(Some(s)))
441 .collect::<Result<Vec<_>,_>>()?
444 fn default() -> Self { default() }
448 #[derive(Debug,Copy,Clone)]
449 enum SectionKindList {
456 use SectionKindList as SKL;
459 fn special_server_section() -> Self { SN::Server(ServerName(
460 SPECIAL_SERVER_SECTION.into()
464 impl SectionKindList {
465 fn contains(self, s: &SectionName) -> bool {
467 SKL::Ordinary => matches!(s, SN::Link(_)
472 SKL::Limits => matches!(s, SN::ServerLimit(_)
475 SKL::ClientAgnostic => matches!(s, SN::Common
478 SKL::Limited => SKL::Ordinary.contains(s)
479 | SKL::Limits .contains(s),
481 SKL::ServerName => matches!(s, SN::Common)
482 | matches!(s, SN::Server(ServerName(name))
483 if name == SPECIAL_SERVER_SECTION),
489 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
490 -> Option<RawValRef<'a,'a,'s>>
491 where S: Iterator<Item=&'s SectionName>
493 for section in sections {
494 if let Some(raw) = self.sections
496 .and_then(|vars: &SectionMap| vars.get(key))
498 return Some(RawValRef {
499 raw: raw.raw.as_deref(),
509 pub fn establish_server_name(&self) -> ServerName {
511 let raw = match self.lookup_raw(
513 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
515 Some(raw) => raw.try_map(|os| os.value())?,
516 None => SPECIAL_SERVER_SECTION,
518 ServerName(raw.into())
522 impl<'c> ResolveContext<'c> {
523 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
524 -> Option<RawValRef<'c,'c,'c>> {
527 self.all_sections.iter()
528 .filter(|s| sections.contains(s))
533 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
537 match self.first_of_raw(key, sections) {
539 Some(raw) => Some(raw.try_map(Parseable::parse)?),
544 pub fn ordinary<T>(&self, key: &'static str) -> T
547 match self.first_of(key, SKL::Ordinary)? {
549 None => Parseable::default_for_key(key)?,
554 pub fn limited<T>(&self, key: &'static str) -> T
555 where T: Parseable + Ord
557 let val = self.ordinary(key)?;
558 if let Some(limit) = self.first_of(key, SKL::Limits)? {
566 pub fn client<T>(&self, key: &'static str) -> T
569 LinkEnd::Client => self.ordinary(key)?,
570 LinkEnd::Server => Parseable::default_for_key(key)?,
574 pub fn server<T>(&self, key: &'static str) -> T
577 LinkEnd::Server => self.ordinary(key)?,
578 LinkEnd::Client => Parseable::default_for_key(key)?,
583 pub fn special_ipif(&self, key: &'static str) -> String {
585 LinkEnd::Client => self.ordinary(key)?,
587 self.first_of(key, SKL::ClientAgnostic)?
594 pub fn special_server(&self, key: &'static str) -> ServerName {
595 self.link.server.clone()
600 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
601 let opts = config::Opts::from_args();
604 let mut agg = Aggregate::default();
606 agg.read_string(DEFAULT_CONFIG.into(),
607 "<build-in defaults>".as_ref()).unwrap();
609 agg.read_toplevel(&opts.config)?;
610 for extra in &opts.extra_config {
611 agg.read_extra(extra).context("extra config")?;
614 eprintln!("GOT {:#?}", agg);
617 })().context("read configuration")?;
619 let server_name = match end {
620 LinkEnd::Server => Some(agg.establish_server_name()?),
621 LinkEnd::Client => None,
624 let instances = agg.instances(server_name.as_ref());
625 let mut ics = vec![];
627 for link in instances {
628 let rctx = ResolveContext {
633 SN::Link(link.clone()),
634 SN::Client(link.client.clone()),
635 SN::Server(link.server.clone()),
637 SN::ServerLimit(link.server.clone()),
642 let ic = InstanceConfig::resolve_instance(&rctx)
643 .with_context(|| format!(r#"resolve config for "{:?}""#, &link))?;