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 vnetwork = 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>,
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>;
130 struct RawValRef<'v,'l,'s> {
131 raw: Option<&'v str>,
134 section: &'s SectionName,
137 impl<'v> RawValRef<'v,'_,'_> {
139 fn try_map<F,T>(&self, f: F) -> T
140 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
142 .with_context(|| format!(r#"file {:?}, section {}, key "{}""#,
143 self.loc, self.section, self.key))?
151 static OUTSIDE_SECTION: &str = "[";
152 static SPECIAL_SERVER_SECTION: &str = "SERVER";
154 #[derive(Default,Debug)]
156 keys_allowed: HashMap<&'static str, SectionKindList>,
157 sections: HashMap<SectionName, SectionMap>,
160 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
162 impl<'f,A> OkAnyway<'f,A> {
163 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
164 let e = r.as_ref().err()?;
171 impl FromStr for SectionName {
174 fn from_str(s: &str) -> Self {
176 "COMMON" => return SN::Common,
177 "LIMIT" => return SN::GlobalLimit,
180 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
181 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
182 let (server, client) = s.split_ascii_whitespace().collect_tuple()
183 .ok_or_else(|| anyhow!(
184 "bad section name {:?} \
185 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
188 let server = server.parse().context("server name in link section name")?;
189 if client == "LIMIT" { return SN::ServerLimit(server) }
190 let client = client.parse().context("client name in link section name")?;
191 SN::Link(LinkName { server, client })
194 impl Display for InstanceConfig {
195 #[throws(fmt::Error)]
196 fn fmt(&self, f: &mut fmt::Formatter) {
197 write!(f, "[{} {}]", &self.server, &self.vaddr)?;
201 impl Display for SectionName {
202 #[throws(fmt::Error)]
203 fn fmt(&self, f: &mut fmt::Formatter) {
205 SN::Link (ref l) => Display::fmt(l, f)?,
206 SN::Client(ref c) => write!(f, "[{}]" , c)?,
207 SN::Server(ref s) => write!(f, "[{}]" , s)?,
208 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
209 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
210 SN::Common => write!(f, "[COMMON]" )?,
216 #[throws(AE)] // AE does not include path
217 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
219 let f = fs::File::open(path);
220 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
221 let mut f = f.context("open")?;
223 let mut s = String::new();
224 let y = f.read_to_string(&mut s);
225 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
228 self.read_string(s, path)?;
232 #[throws(AE)] // AE does not include path
233 fn read_string(&mut self, s: String, path_for_loc: &Path) {
234 let mut ini = Ini::new_cs();
235 ini.set_default_section(OUTSIDE_SECTION);
236 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
237 let map = mem::take(ini.get_mut_map());
238 if map.get(OUTSIDE_SECTION).is_some() {
239 throw!(anyhow!("INI file contains settings outside a section"));
242 let loc = Arc::new(path_for_loc.to_owned());
244 for (sn, vars) in map {
245 let sn = sn.parse().dcontext(&sn)?;
247 for key in vars.keys() {
248 let skl = self.keys_allowed.get(key.as_str()).ok_or_else(
249 || anyhow!("unknown configuration key {:?}", key)
251 if ! skl.contains(&sn) {
252 throw!(anyhow!("configuration key {:?} not applicable \
253 in this kind of section {:?}", key, &sn))
257 let ent = self.sections.entry(sn).or_default();
258 for (key, raw) in vars {
259 let raw = match raw {
260 Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
262 if raw.contains('\\') {
264 anyhow!("quoted value contains backslash, not supported")
267 let unq = raw[1..].strip_suffix(&raw[0..1])
269 || anyhow!("mismatched quotes around quoted value")
274 .with_context(|| format!("key {:?}", key))
275 .dcontext(path_for_loc)?
279 let key = key.replace('-',"_");
280 ent.insert(key, RawVal { raw, loc: loc.clone() });
285 #[throws(AE)] // AE includes path
286 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
288 let dir = fs::read_dir(path);
289 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
290 let dir = dir.context("open directory").dcontext(path)?;
292 let ent = ent.context("read directory").dcontext(path)?;
293 let leaf = ent.file_name();
294 let leaf = leaf.to_str();
295 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
296 if leaf.len() == 0 { continue }
297 if ! leaf.chars().all(
298 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
301 // OK we want this one
302 let ent = ent.path();
303 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
308 #[throws(AE)] // AE includes everything
309 fn read_toplevel(&mut self, toplevel: &Path) {
310 enum Anyway { None, Dir }
311 match self.read_file(toplevel, &|k| match k {
312 EK::NotFound => Some(Anyway::None),
313 EK::IsADirectory => Some(Anyway::Dir),
316 .dcontext(toplevel).context("top-level config directory (or file)")?
318 None | Some(Anyway::None) => { },
320 Some(Anyway::Dir) => {
322 let anyway_none = |k| match k {
323 EK::NotFound => Some(AnywayNone),
327 let mk = |leaf: &str| {
328 [ toplevel, &PathBuf::from(leaf) ]
329 .iter().collect::<PathBuf>()
332 for &(try_main, desc) in &[
333 ("main.cfg", "main config file"),
334 ("master.cfg", "obsolete-named main config file"),
336 let main = mk(try_main);
338 match self.read_file(&main, &anyway_none)
339 .dcontext(main).context(desc)?
342 Some(AnywayNone) => { },
346 for &(try_dir, desc) in &[
347 ("config.d", "per-link config directory"),
348 ("secrets.d", "per-link secrets directory"),
350 let dir = mk(try_dir);
351 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
353 Some(AnywayNone) => { },
360 #[throws(AE)] // AE includes extra, but does that this is extra
361 fn read_extra(&mut self, extra: &Path) {
364 match self.read_file(extra, &|k| match k {
365 EK::IsADirectory => Some(AnywayDir),
372 self.read_dir_d(extra, &|_| None::<Void>)?;
380 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
381 let mut links: BTreeSet<LinkName> = default();
383 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
384 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
385 let mut secret_global = false;
387 let mut putative_servers = BTreeSet::new();
388 let mut putative_clients = BTreeSet::new();
390 let mut note_server = |s| {
391 if let Some(only) = only_server { if s != only { return false } }
392 putative_servers.insert(s);
395 let mut note_client = |c| {
396 putative_clients.insert(c);
399 for (section, vars) in &self.sections {
400 let has_secret = || vars.contains_key("secret");
404 if ! note_server(&l.server) { continue }
405 note_client(&l.client);
406 if has_secret() { links.insert(l.clone()); }
408 SN::Server(ref s) => {
409 if ! note_server(s) { continue }
410 if has_secret() { secrets_anyclient.insert(s); }
412 SN::Client(ref c) => {
414 if has_secret() { secrets_anyserver.insert(c); }
417 if has_secret() { secret_global = true; }
423 // Add links which are justified by blanket secrets
424 for (client, server) in iproduct!(
425 putative_clients.into_iter().filter(
426 |c| secret_global || secrets_anyserver.contains(c)
428 putative_servers.iter().cloned().filter(
429 |s| secret_global || secrets_anyclient.contains(s)
432 links.insert(LinkName {
433 client: client.clone(),
434 server: server.clone(),
442 struct ResolveContext<'c> {
446 all_sections: Vec<SectionName>,
449 trait Parseable: Sized {
450 fn parse(s: Option<&str>) -> Result<Self, AE>;
451 fn default() -> Result<Self, AE> {
452 Err(anyhow!("setting must be specified"))
455 fn default_for_key(key: &str) -> Self {
456 Self::default().with_context(|| key.to_string())?
460 impl Parseable for Duration {
462 fn parse(s: Option<&str>) -> Duration {
463 // todo: would be nice to parse with humantime maybe
464 Duration::from_secs( s.value()?.parse()? )
467 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
468 impl Parseable for $t {
470 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
471 $( #[throws(AE)] fn default() -> Self { $def } )?
474 parseable_from_str!{u16, default() }
475 parseable_from_str!{u32, default() }
476 parseable_from_str!{String, default() }
477 parseable_from_str!{IpNet, default() }
478 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
479 parseable_from_str!{Uri, default() }
481 impl<T:Parseable> Parseable for Vec<T> {
483 fn parse(s: Option<&str>) -> Vec<T> {
485 .split_ascii_whitespace()
486 .map(|s| Parseable::parse(Some(s)))
487 .collect::<Result<Vec<_>,_>>()?
490 fn default() -> Self { default() }
494 #[derive(Debug,Copy,Clone)]
495 enum SectionKindList {
502 use SectionKindList as SKL;
505 fn special_server_section() -> Self { SN::Server(ServerName(
506 SPECIAL_SERVER_SECTION.into()
510 impl SectionKindList {
511 fn contains(self, s: &SectionName) -> bool {
513 SKL::Ordinary => matches!(s, SN::Link(_)
518 SKL::Limits => matches!(s, SN::ServerLimit(_)
521 SKL::ClientAgnostic => matches!(s, SN::Common
524 SKL::Limited => SKL::Ordinary.contains(s)
525 | SKL::Limits .contains(s),
527 SKL::ServerName => matches!(s, SN::Common)
528 | matches!(s, SN::Server(ServerName(name))
529 if name == SPECIAL_SERVER_SECTION),
535 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
536 -> Option<RawValRef<'a,'a,'s>>
537 where S: Iterator<Item=&'s SectionName>
539 for section in sections {
540 if let Some(raw) = self.sections
542 .and_then(|vars: &SectionMap| vars.get(key))
544 return Some(RawValRef {
545 raw: raw.raw.as_deref(),
555 pub fn establish_server_name(&self) -> ServerName {
557 let raw = match self.lookup_raw(
559 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
561 Some(raw) => raw.try_map(|os| os.value())?,
562 None => SPECIAL_SERVER_SECTION,
564 ServerName(raw.into())
568 impl<'c> ResolveContext<'c> {
569 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
570 -> Option<RawValRef<'c,'c,'c>> {
573 self.all_sections.iter()
574 .filter(|s| sections.contains(s))
579 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
583 match self.first_of_raw(key, sections) {
585 Some(raw) => Some(raw.try_map(Parseable::parse)?),
590 pub fn ordinary<T>(&self, key: &'static str) -> T
593 match self.first_of(key, SKL::Ordinary)? {
595 None => Parseable::default_for_key(key)?,
600 pub fn limited<T>(&self, key: &'static str) -> T
601 where T: Parseable + Ord
603 let val = self.ordinary(key)?;
604 if let Some(limit) = self.first_of(key, SKL::Limits)? {
612 pub fn client<T>(&self, key: &'static str) -> T
613 where T: Parseable + Default {
615 LinkEnd::Client => self.ordinary(key)?,
616 LinkEnd::Server => default(),
620 pub fn server<T>(&self, key: &'static str) -> T
621 where T: Parseable + Default {
623 LinkEnd::Server => self.ordinary(key)?,
624 LinkEnd::Client => default(),
629 pub fn special_ipif(&self, key: &'static str) -> String {
631 LinkEnd::Client => self.ordinary(key)?,
633 self.first_of(key, SKL::ClientAgnostic)?
640 pub fn special_server(&self, _key: &'static str) -> ServerName {
641 self.link.server.clone()
645 impl InstanceConfig {
647 fn complete(&mut self, end: LinkEnd) {
648 let mut vhosts = self.vnetwork.iter()
649 .map(|n| n.hosts()).flatten()
650 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
652 if self.vaddr.is_unspecified() {
653 self.vaddr = vhosts.next().ok_or_else(
654 || anyhow!("vnetwork too small to generate vaddrr")
657 if self.vrelay.is_unspecified() {
658 self.vrelay = vhosts.next().ok_or_else(
659 || anyhow!("vnetwork too small to generate vrelay")
665 if &self.url == &default::<Uri>() {
666 let addr = self.addrs.get(0).ok_or_else(
667 || anyhow!("client needs addrs or url set")
672 IpAddr::V4(a) => format!("{}", a),
673 IpAddr::V6(a) => format!("[{}]", a),
677 p => format!(":{}", p),
684 if self.addrs.is_empty() {
685 throw!(anyhow!("missing 'addrs' setting"))
693 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
694 let opts = config::Opts::from_args();
697 let mut agg = Aggregate::default();
698 agg.keys_allowed.extend(
699 InstanceConfig::FIELDS.iter().cloned()
702 agg.read_string(DEFAULT_CONFIG.into(),
703 "<build-in defaults>".as_ref()).unwrap();
705 agg.read_toplevel(&opts.config)?;
706 for extra in &opts.extra_config {
707 agg.read_extra(extra).context("extra config")?;
710 //eprintln!("GOT {:#?}", agg);
713 })().context("read configuration")?;
715 let server_name = match end {
716 LinkEnd::Server => Some(agg.establish_server_name()?),
717 LinkEnd::Client => None,
720 let instances = agg.instances(server_name.as_ref());
721 let mut ics = vec![];
723 for link in instances {
724 let rctx = ResolveContext {
729 SN::Link(link.clone()),
730 SN::Client(link.client.clone()),
731 SN::Server(link.server.clone()),
733 SN::ServerLimit(link.server.clone()),
738 let mut ic = InstanceConfig::resolve_instance(&rctx)
739 .with_context(|| format!("resolve config for {}", &link))?;
742 .with_context(|| format!("complete config for {}", &link))?;