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>,
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 })
195 #[throws(AE)] // AE does not include path
196 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
198 let f = fs::File::open(path);
199 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
200 let mut f = f.context("open")?;
202 let mut s = String::new();
203 let y = f.read_to_string(&mut s);
204 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
207 self.read_string(s, path)?;
211 #[throws(AE)] // AE does not include path
212 fn read_string(&mut self, s: String, path_for_loc: &Path) {
213 let mut ini = Ini::new_cs();
214 ini.set_default_section(OUTSIDE_SECTION);
215 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
216 let map = mem::take(ini.get_mut_map());
217 if map.get(OUTSIDE_SECTION).is_some() {
218 throw!(anyhow!("INI file contains settings outside a section"));
221 let loc = Arc::new(path_for_loc.to_owned());
223 for (sn, vars) in map {
224 //dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
226 let sn = sn.parse().dcontext(&sn)?;
227 let ent = self.sections.entry(sn).or_default();
228 for (key, raw) in vars {
229 let raw = match raw {
230 Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
232 if raw.contains('\\') {
234 anyhow!("quoted value contains backslash, not supported")
237 let unq = raw[1..].strip_suffix(&raw[0..1])
239 || anyhow!("mismatched quotes around quoted value")
244 .with_context(|| format!("key {:?}", key))
245 .dcontext(path_for_loc)?
249 let key = key.replace('-',"_");
250 ent.insert(key, RawVal { raw, loc: loc.clone() });
255 #[throws(AE)] // AE includes path
256 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
258 let dir = fs::read_dir(path);
259 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
260 let dir = dir.context("open directory").dcontext(path)?;
262 let ent = ent.context("read directory").dcontext(path)?;
263 let leaf = ent.file_name();
264 let leaf = leaf.to_str();
265 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
266 if leaf.len() == 0 { continue }
267 if ! leaf.chars().all(
268 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
271 // OK we want this one
272 let ent = ent.path();
273 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
278 #[throws(AE)] // AE includes everything
279 fn read_toplevel(&mut self, toplevel: &Path) {
280 enum Anyway { None, Dir }
281 match self.read_file(toplevel, &|k| match k {
282 EK::NotFound => Some(Anyway::None),
283 EK::IsADirectory => Some(Anyway::Dir),
286 .dcontext(toplevel).context("top-level config directory (or file)")?
288 None | Some(Anyway::None) => { },
290 Some(Anyway::Dir) => {
292 let anyway_none = |k| match k {
293 EK::NotFound => Some(AnywayNone),
297 let mk = |leaf: &str| {
298 [ toplevel, &PathBuf::from(leaf) ]
299 .iter().collect::<PathBuf>()
302 for &(try_main, desc) in &[
303 ("main.cfg", "main config file"),
304 ("master.cfg", "obsolete-named main config file"),
306 let main = mk(try_main);
308 match self.read_file(&main, &anyway_none)
309 .dcontext(main).context(desc)?
312 Some(AnywayNone) => { },
316 for &(try_dir, desc) in &[
317 ("config.d", "per-link config directory"),
318 ("secrets.d", "per-link secrets directory"),
320 let dir = mk(try_dir);
321 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
323 Some(AnywayNone) => { },
330 #[throws(AE)] // AE includes extra, but does that this is extra
331 fn read_extra(&mut self, extra: &Path) {
334 match self.read_file(extra, &|k| match k {
335 EK::IsADirectory => Some(AnywayDir),
342 self.read_dir_d(extra, &|_| None::<Void>)?;
350 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
351 let mut links: BTreeSet<LinkName> = default();
353 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
354 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
355 let mut secret_global = false;
357 let mut putative_servers = BTreeSet::new();
358 let mut putative_clients = BTreeSet::new();
360 let mut note_server = |s| {
361 if let Some(only) = only_server { if s != only { return false } }
362 putative_servers.insert(s);
365 let mut note_client = |c| {
366 putative_clients.insert(c);
369 for (section, vars) in &self.sections {
370 let has_secret = || vars.contains_key("secret");
374 if ! note_server(&l.server) { continue }
375 note_client(&l.client);
376 if has_secret() { links.insert(l.clone()); }
378 SN::Server(ref s) => {
379 if ! note_server(s) { continue }
380 if has_secret() { secrets_anyclient.insert(s); }
382 SN::Client(ref c) => {
384 if has_secret() { secrets_anyserver.insert(c); }
387 if has_secret() { secret_global = true; }
393 // Add links which are justified by blanket secrets
394 for (client, server) in iproduct!(
395 putative_clients.into_iter().filter(
396 |c| secret_global || secrets_anyserver.contains(c)
398 putative_servers.iter().cloned().filter(
399 |s| secret_global || secrets_anyclient.contains(s)
402 links.insert(LinkName {
403 client: client.clone(),
404 server: server.clone(),
412 struct ResolveContext<'c> {
416 all_sections: Vec<SectionName>,
419 trait Parseable: Sized {
420 fn parse(s: Option<&str>) -> Result<Self, AE>;
421 fn default() -> Result<Self, AE> {
422 Err(anyhow!("setting must be specified"))
425 fn default_for_key(key: &str) -> Self {
426 Self::default().with_context(|| key.to_string())?
430 impl Parseable for Duration {
432 fn parse(s: Option<&str>) -> Duration {
433 // todo: would be nice to parse with humantime maybe
434 Duration::from_secs( s.value()?.parse()? )
437 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
438 impl Parseable for $t {
440 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
441 $( #[throws(AE)] fn default() -> Self { $def } )?
444 parseable_from_str!{u16, default() }
445 parseable_from_str!{u32, default() }
446 parseable_from_str!{String, default() }
447 parseable_from_str!{IpNet, default() }
448 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
449 parseable_from_str!{Uri, default() }
451 impl<T:Parseable> Parseable for Vec<T> {
453 fn parse(s: Option<&str>) -> Vec<T> {
455 .split_ascii_whitespace()
456 .map(|s| Parseable::parse(Some(s)))
457 .collect::<Result<Vec<_>,_>>()?
460 fn default() -> Self { default() }
464 #[derive(Debug,Copy,Clone)]
465 enum SectionKindList {
472 use SectionKindList as SKL;
475 fn special_server_section() -> Self { SN::Server(ServerName(
476 SPECIAL_SERVER_SECTION.into()
480 impl SectionKindList {
481 fn contains(self, s: &SectionName) -> bool {
483 SKL::Ordinary => matches!(s, SN::Link(_)
488 SKL::Limits => matches!(s, SN::ServerLimit(_)
491 SKL::ClientAgnostic => matches!(s, SN::Common
494 SKL::Limited => SKL::Ordinary.contains(s)
495 | SKL::Limits .contains(s),
497 SKL::ServerName => matches!(s, SN::Common)
498 | matches!(s, SN::Server(ServerName(name))
499 if name == SPECIAL_SERVER_SECTION),
505 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
506 -> Option<RawValRef<'a,'a,'s>>
507 where S: Iterator<Item=&'s SectionName>
509 for section in sections {
510 if let Some(raw) = self.sections
512 .and_then(|vars: &SectionMap| vars.get(key))
514 return Some(RawValRef {
515 raw: raw.raw.as_deref(),
525 pub fn establish_server_name(&self) -> ServerName {
527 let raw = match self.lookup_raw(
529 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
531 Some(raw) => raw.try_map(|os| os.value())?,
532 None => SPECIAL_SERVER_SECTION,
534 ServerName(raw.into())
538 impl<'c> ResolveContext<'c> {
539 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
540 -> Option<RawValRef<'c,'c,'c>> {
543 self.all_sections.iter()
544 .filter(|s| sections.contains(s))
549 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
553 match self.first_of_raw(key, sections) {
555 Some(raw) => Some(raw.try_map(Parseable::parse)?),
560 pub fn ordinary<T>(&self, key: &'static str) -> T
563 match self.first_of(key, SKL::Ordinary)? {
565 None => Parseable::default_for_key(key)?,
570 pub fn limited<T>(&self, key: &'static str) -> T
571 where T: Parseable + Ord
573 let val = self.ordinary(key)?;
574 if let Some(limit) = self.first_of(key, SKL::Limits)? {
582 pub fn client<T>(&self, key: &'static str) -> T
583 where T: Parseable + Default {
585 LinkEnd::Client => self.ordinary(key)?,
586 LinkEnd::Server => default(),
590 pub fn server<T>(&self, key: &'static str) -> T
591 where T: Parseable + Default {
593 LinkEnd::Server => self.ordinary(key)?,
594 LinkEnd::Client => default(),
599 pub fn special_ipif(&self, key: &'static str) -> String {
601 LinkEnd::Client => self.ordinary(key)?,
603 self.first_of(key, SKL::ClientAgnostic)?
610 pub fn special_server(&self, key: &'static str) -> ServerName {
611 self.link.server.clone()
615 impl InstanceConfig {
617 fn complete(&mut self, end: LinkEnd) {
618 let mut vhosts = self.vnetwork.iter()
619 .map(|n| n.hosts()).flatten()
620 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
622 if self.vaddr.is_unspecified() {
623 self.vaddr = vhosts.next().ok_or_else(
624 || anyhow!("vnetwork too small to generate vaddrr")
627 if self.vrelay.is_unspecified() {
628 self.vrelay = vhosts.next().ok_or_else(
629 || anyhow!("vnetwork too small to generate vrelay")
635 if &self.url == &default::<Uri>() {
636 let addr = self.addrs.get(0).ok_or_else(
637 || anyhow!("client needs addrs or url set")
642 IpAddr::V4(a) => format!("{}", a),
643 IpAddr::V6(a) => format!("[{}]", a),
647 p => format!(":{}", p),
654 if self.addrs.is_empty() {
655 throw!(anyhow!("missing 'addrs' setting"))
663 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
664 let opts = config::Opts::from_args();
667 let mut agg = Aggregate::default();
669 agg.read_string(DEFAULT_CONFIG.into(),
670 "<build-in defaults>".as_ref()).unwrap();
672 agg.read_toplevel(&opts.config)?;
673 for extra in &opts.extra_config {
674 agg.read_extra(extra).context("extra config")?;
677 eprintln!("GOT {:#?}", agg);
680 })().context("read configuration")?;
682 let server_name = match end {
683 LinkEnd::Server => Some(agg.establish_server_name()?),
684 LinkEnd::Client => None,
687 let instances = agg.instances(server_name.as_ref());
688 let mut ics = vec![];
690 for link in instances {
691 let rctx = ResolveContext {
696 SN::Link(link.clone()),
697 SN::Client(link.client.clone()),
698 SN::Server(link.server.clone()),
700 SN::ServerLimit(link.server.clone()),
705 let mut ic = InstanceConfig::resolve_instance(&rctx)
706 .with_context(|| format!(r#"resolve config for "{:?}""#, &link))?;
709 .with_context(|| format!(r#"complete config for "{:?}""#, &link))?;