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 sections: HashMap<SectionName, SectionMap>,
159 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
161 impl<'f,A> OkAnyway<'f,A> {
162 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
163 let e = r.as_ref().err()?;
170 impl FromStr for SectionName {
173 fn from_str(s: &str) -> Self {
175 "COMMON" => return SN::Common,
176 "LIMIT" => return SN::GlobalLimit,
179 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
180 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
181 let (server, client) = s.split_ascii_whitespace().collect_tuple()
182 .ok_or_else(|| anyhow!(
183 "bad section name {:?} \
184 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
187 let server = server.parse().context("server name in link section name")?;
188 if client == "LIMIT" { return SN::ServerLimit(server) }
189 let client = client.parse().context("client name in link section name")?;
190 SN::Link(LinkName { server, client })
193 impl Display for SectionName {
194 #[throws(fmt::Error)]
195 fn fmt(&self, f: &mut fmt::Formatter) {
197 SN::Link (ref l) => Display::fmt(l, f)?,
198 SN::Client(ref c) => write!(f, "[{}]" , c)?,
199 SN::Server(ref s) => write!(f, "[{}]" , s)?,
200 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
201 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
202 SN::Common => write!(f, "[COMMON]" )?,
208 #[throws(AE)] // AE does not include path
209 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
211 let f = fs::File::open(path);
212 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
213 let mut f = f.context("open")?;
215 let mut s = String::new();
216 let y = f.read_to_string(&mut s);
217 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
220 self.read_string(s, path)?;
224 #[throws(AE)] // AE does not include path
225 fn read_string(&mut self, s: String, path_for_loc: &Path) {
226 let mut ini = Ini::new_cs();
227 ini.set_default_section(OUTSIDE_SECTION);
228 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
229 let map = mem::take(ini.get_mut_map());
230 if map.get(OUTSIDE_SECTION).is_some() {
231 throw!(anyhow!("INI file contains settings outside a section"));
234 let loc = Arc::new(path_for_loc.to_owned());
236 for (sn, vars) in map {
237 //dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
239 let sn = sn.parse().dcontext(&sn)?;
240 let ent = self.sections.entry(sn).or_default();
241 for (key, raw) in vars {
242 let raw = match raw {
243 Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
245 if raw.contains('\\') {
247 anyhow!("quoted value contains backslash, not supported")
250 let unq = raw[1..].strip_suffix(&raw[0..1])
252 || anyhow!("mismatched quotes around quoted value")
257 .with_context(|| format!("key {:?}", key))
258 .dcontext(path_for_loc)?
262 let key = key.replace('-',"_");
263 ent.insert(key, RawVal { raw, loc: loc.clone() });
268 #[throws(AE)] // AE includes path
269 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
271 let dir = fs::read_dir(path);
272 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
273 let dir = dir.context("open directory").dcontext(path)?;
275 let ent = ent.context("read directory").dcontext(path)?;
276 let leaf = ent.file_name();
277 let leaf = leaf.to_str();
278 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
279 if leaf.len() == 0 { continue }
280 if ! leaf.chars().all(
281 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
284 // OK we want this one
285 let ent = ent.path();
286 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
291 #[throws(AE)] // AE includes everything
292 fn read_toplevel(&mut self, toplevel: &Path) {
293 enum Anyway { None, Dir }
294 match self.read_file(toplevel, &|k| match k {
295 EK::NotFound => Some(Anyway::None),
296 EK::IsADirectory => Some(Anyway::Dir),
299 .dcontext(toplevel).context("top-level config directory (or file)")?
301 None | Some(Anyway::None) => { },
303 Some(Anyway::Dir) => {
305 let anyway_none = |k| match k {
306 EK::NotFound => Some(AnywayNone),
310 let mk = |leaf: &str| {
311 [ toplevel, &PathBuf::from(leaf) ]
312 .iter().collect::<PathBuf>()
315 for &(try_main, desc) in &[
316 ("main.cfg", "main config file"),
317 ("master.cfg", "obsolete-named main config file"),
319 let main = mk(try_main);
321 match self.read_file(&main, &anyway_none)
322 .dcontext(main).context(desc)?
325 Some(AnywayNone) => { },
329 for &(try_dir, desc) in &[
330 ("config.d", "per-link config directory"),
331 ("secrets.d", "per-link secrets directory"),
333 let dir = mk(try_dir);
334 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
336 Some(AnywayNone) => { },
343 #[throws(AE)] // AE includes extra, but does that this is extra
344 fn read_extra(&mut self, extra: &Path) {
347 match self.read_file(extra, &|k| match k {
348 EK::IsADirectory => Some(AnywayDir),
355 self.read_dir_d(extra, &|_| None::<Void>)?;
363 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
364 let mut links: BTreeSet<LinkName> = default();
366 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
367 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
368 let mut secret_global = false;
370 let mut putative_servers = BTreeSet::new();
371 let mut putative_clients = BTreeSet::new();
373 let mut note_server = |s| {
374 if let Some(only) = only_server { if s != only { return false } }
375 putative_servers.insert(s);
378 let mut note_client = |c| {
379 putative_clients.insert(c);
382 for (section, vars) in &self.sections {
383 let has_secret = || vars.contains_key("secret");
387 if ! note_server(&l.server) { continue }
388 note_client(&l.client);
389 if has_secret() { links.insert(l.clone()); }
391 SN::Server(ref s) => {
392 if ! note_server(s) { continue }
393 if has_secret() { secrets_anyclient.insert(s); }
395 SN::Client(ref c) => {
397 if has_secret() { secrets_anyserver.insert(c); }
400 if has_secret() { secret_global = true; }
406 // Add links which are justified by blanket secrets
407 for (client, server) in iproduct!(
408 putative_clients.into_iter().filter(
409 |c| secret_global || secrets_anyserver.contains(c)
411 putative_servers.iter().cloned().filter(
412 |s| secret_global || secrets_anyclient.contains(s)
415 links.insert(LinkName {
416 client: client.clone(),
417 server: server.clone(),
425 struct ResolveContext<'c> {
429 all_sections: Vec<SectionName>,
432 trait Parseable: Sized {
433 fn parse(s: Option<&str>) -> Result<Self, AE>;
434 fn default() -> Result<Self, AE> {
435 Err(anyhow!("setting must be specified"))
438 fn default_for_key(key: &str) -> Self {
439 Self::default().with_context(|| key.to_string())?
443 impl Parseable for Duration {
445 fn parse(s: Option<&str>) -> Duration {
446 // todo: would be nice to parse with humantime maybe
447 Duration::from_secs( s.value()?.parse()? )
450 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
451 impl Parseable for $t {
453 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
454 $( #[throws(AE)] fn default() -> Self { $def } )?
457 parseable_from_str!{u16, default() }
458 parseable_from_str!{u32, default() }
459 parseable_from_str!{String, default() }
460 parseable_from_str!{IpNet, default() }
461 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
462 parseable_from_str!{Uri, default() }
464 impl<T:Parseable> Parseable for Vec<T> {
466 fn parse(s: Option<&str>) -> Vec<T> {
468 .split_ascii_whitespace()
469 .map(|s| Parseable::parse(Some(s)))
470 .collect::<Result<Vec<_>,_>>()?
473 fn default() -> Self { default() }
477 #[derive(Debug,Copy,Clone)]
478 enum SectionKindList {
485 use SectionKindList as SKL;
488 fn special_server_section() -> Self { SN::Server(ServerName(
489 SPECIAL_SERVER_SECTION.into()
493 impl SectionKindList {
494 fn contains(self, s: &SectionName) -> bool {
496 SKL::Ordinary => matches!(s, SN::Link(_)
501 SKL::Limits => matches!(s, SN::ServerLimit(_)
504 SKL::ClientAgnostic => matches!(s, SN::Common
507 SKL::Limited => SKL::Ordinary.contains(s)
508 | SKL::Limits .contains(s),
510 SKL::ServerName => matches!(s, SN::Common)
511 | matches!(s, SN::Server(ServerName(name))
512 if name == SPECIAL_SERVER_SECTION),
518 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
519 -> Option<RawValRef<'a,'a,'s>>
520 where S: Iterator<Item=&'s SectionName>
522 for section in sections {
523 if let Some(raw) = self.sections
525 .and_then(|vars: &SectionMap| vars.get(key))
527 return Some(RawValRef {
528 raw: raw.raw.as_deref(),
538 pub fn establish_server_name(&self) -> ServerName {
540 let raw = match self.lookup_raw(
542 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
544 Some(raw) => raw.try_map(|os| os.value())?,
545 None => SPECIAL_SERVER_SECTION,
547 ServerName(raw.into())
551 impl<'c> ResolveContext<'c> {
552 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
553 -> Option<RawValRef<'c,'c,'c>> {
556 self.all_sections.iter()
557 .filter(|s| sections.contains(s))
562 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
566 match self.first_of_raw(key, sections) {
568 Some(raw) => Some(raw.try_map(Parseable::parse)?),
573 pub fn ordinary<T>(&self, key: &'static str) -> T
576 match self.first_of(key, SKL::Ordinary)? {
578 None => Parseable::default_for_key(key)?,
583 pub fn limited<T>(&self, key: &'static str) -> T
584 where T: Parseable + Ord
586 let val = self.ordinary(key)?;
587 if let Some(limit) = self.first_of(key, SKL::Limits)? {
595 pub fn client<T>(&self, key: &'static str) -> T
596 where T: Parseable + Default {
598 LinkEnd::Client => self.ordinary(key)?,
599 LinkEnd::Server => default(),
603 pub fn server<T>(&self, key: &'static str) -> T
604 where T: Parseable + Default {
606 LinkEnd::Server => self.ordinary(key)?,
607 LinkEnd::Client => default(),
612 pub fn special_ipif(&self, key: &'static str) -> String {
614 LinkEnd::Client => self.ordinary(key)?,
616 self.first_of(key, SKL::ClientAgnostic)?
623 pub fn special_server(&self, key: &'static str) -> ServerName {
624 self.link.server.clone()
628 impl InstanceConfig {
630 fn complete(&mut self, end: LinkEnd) {
631 let mut vhosts = self.vnetwork.iter()
632 .map(|n| n.hosts()).flatten()
633 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
635 if self.vaddr.is_unspecified() {
636 self.vaddr = vhosts.next().ok_or_else(
637 || anyhow!("vnetwork too small to generate vaddrr")
640 if self.vrelay.is_unspecified() {
641 self.vrelay = vhosts.next().ok_or_else(
642 || anyhow!("vnetwork too small to generate vrelay")
648 if &self.url == &default::<Uri>() {
649 let addr = self.addrs.get(0).ok_or_else(
650 || anyhow!("client needs addrs or url set")
655 IpAddr::V4(a) => format!("{}", a),
656 IpAddr::V6(a) => format!("[{}]", a),
660 p => format!(":{}", p),
667 if self.addrs.is_empty() {
668 throw!(anyhow!("missing 'addrs' setting"))
676 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
677 let opts = config::Opts::from_args();
680 let mut agg = Aggregate::default();
682 agg.read_string(DEFAULT_CONFIG.into(),
683 "<build-in defaults>".as_ref()).unwrap();
685 agg.read_toplevel(&opts.config)?;
686 for extra in &opts.extra_config {
687 agg.read_extra(extra).context("extra config")?;
690 eprintln!("GOT {:#?}", agg);
693 })().context("read configuration")?;
695 let server_name = match end {
696 LinkEnd::Server => Some(agg.establish_server_name()?),
697 LinkEnd::Client => None,
700 let instances = agg.instances(server_name.as_ref());
701 let mut ics = vec![];
703 for link in instances {
704 let rctx = ResolveContext {
709 SN::Link(link.clone()),
710 SN::Client(link.client.clone()),
711 SN::Server(link.server.clone()),
713 SN::ServerLimit(link.server.clone()),
718 let mut ic = InstanceConfig::resolve_instance(&rctx)
719 .with_context(|| format!("resolve config for {}", &link))?;
722 .with_context(|| format!("complete config for {}", &link))?;