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(StructOpt,Debug)]
11 /// Top-level config file or directory
13 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
15 /// Or if this is a file, just read that file.
16 #[structopt(long, default_value="/etc/hippotat")]
19 /// Additional config files or dirs, which can override the others
20 #[structopt(long, multiple=true, number_of_values=1)]
21 pub extra_config: Vec<PathBuf>,
25 impl<'s> Option<&'s str> {
27 fn value(self) -> &'s str {
28 self.ok_or_else(|| anyhow!("value needed"))?
33 pub struct Secret(pub String);
34 impl Parseable for Secret {
36 fn parse(s: Option<&str>) -> Self {
38 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
42 fn default() -> Self { Secret(default()) }
44 impl Debug for Secret {
46 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
49 #[derive(hippotat_macros::ResolveConfig)]
50 #[derive(Debug,Clone)]
51 pub struct InstanceConfig {
52 // Exceptional settings
53 #[special(special_server, SKL::ServerName)] pub server: ServerName,
55 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
58 #[limited] pub max_batch_down: u32,
59 #[limited] pub max_queue_time: Duration,
60 #[limited] pub http_timeout: Duration,
61 #[limited] pub target_requests_outstanding: u32,
64 pub addrs: Vec<IpAddr>,
65 pub vnetwork: Vec<IpNet>,
66 pub vaddr: Vec<IpAddr>,
70 pub ifname_server: String,
71 pub ifname_client: String,
73 // Ordinary settings, used by server only:
74 #[server] pub max_clock_skew: Duration,
76 // Ordinary settings, used by client only:
77 #[client] pub http_timeout_grace: Duration,
78 #[client] pub max_requests_outstanding: u32,
79 #[client] pub max_batch_up: u32,
80 #[client] pub http_retry: Duration,
81 #[client] pub url: Uri,
82 #[client] pub vroutes: Vec<IpNet>,
85 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
86 pub enum SectionName {
89 Server(ServerName), // includes SERVER, which is slightly special
90 ServerLimit(ServerName),
95 pub use SectionName as SN;
97 #[derive(Debug,Clone)]
98 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
99 type SectionMap = HashMap<String, RawVal>;
101 struct RawValRef<'v,'l,'s> {
102 raw: Option<&'v str>,
105 section: &'s SectionName,
108 impl<'v> RawValRef<'v,'_,'_> {
110 fn try_map<F,T>(&self, f: F) -> T
111 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
113 .with_context(|| format!(r#"file {:?}, section "{:?}", key "{}"#,
114 self.loc, self.section, self.key))?
122 static OUTSIDE_SECTION: &str = "[";
123 static SPECIAL_SERVER_SECTION: &str = "SERVER";
125 #[derive(Default,Debug)]
127 sections: HashMap<SectionName, SectionMap>,
130 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
132 impl<'f,A> OkAnyway<'f,A> {
133 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
134 let e = r.as_ref().err()?;
141 impl FromStr for SectionName {
144 fn from_str(s: &str) -> Self {
146 "COMMON" => return SN::Common,
147 "DEFAULT" => return SN::Default,
148 "LIMIT" => return SN::GlobalLimit,
151 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
152 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
153 let (server, client) = s.split_ascii_whitespace().collect_tuple()
154 .ok_or_else(|| anyhow!(
155 "bad section name {:?} \
156 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
159 let server = server.parse().context("server name in link section name")?;
160 if client == "LIMIT" { return SN::ServerLimit(server) }
161 let client = client.parse().context("client name in link section name")?;
162 SN::Link(LinkName { server, client })
167 #[throws(AE)] // AE does not include path
168 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
170 let f = fs::File::open(path);
171 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
172 let mut f = f.context("open")?;
174 let mut s = String::new();
175 let y = f.read_to_string(&mut s);
176 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
179 self.read_string(s, path)?;
183 #[throws(AE)] // AE does not include path
184 fn read_string(&mut self, s: String, path_for_loc: &Path) {
185 let mut ini = Ini::new_cs();
186 ini.set_default_section(OUTSIDE_SECTION);
187 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
188 let map = mem::take(ini.get_mut_map());
189 if map.get(OUTSIDE_SECTION).is_some() {
190 throw!(anyhow!("INI file contains settings outside a section"));
193 let loc = Arc::new(path_for_loc.to_owned());
195 for (sn, vars) in map {
196 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
198 let sn = sn.parse().dcontext(&sn)?;
199 self.sections.entry(sn)
205 RawVal { raw, loc: loc.clone() })
212 #[throws(AE)] // AE includes path
213 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
215 let dir = fs::read_dir(path);
216 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
217 let dir = dir.context("open directory").dcontext(path)?;
219 let ent = ent.context("read directory").dcontext(path)?;
220 let leaf = ent.file_name();
221 let leaf = leaf.to_str();
222 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
223 if leaf.len() == 0 { continue }
224 if ! leaf.chars().all(
225 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
228 // OK we want this one
229 let ent = ent.path();
230 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
235 #[throws(AE)] // AE includes everything
236 fn read_toplevel(&mut self, toplevel: &Path) {
237 enum Anyway { None, Dir }
238 match self.read_file(toplevel, &|k| match k {
239 EK::NotFound => Some(Anyway::None),
240 EK::IsADirectory => Some(Anyway::Dir),
243 .dcontext(toplevel).context("top-level config directory (or file)")?
245 None | Some(Anyway::None) => { },
247 Some(Anyway::Dir) => {
249 let anyway_none = |k| match k {
250 EK::NotFound => Some(AnywayNone),
254 let mk = |leaf: &str| {
255 [ toplevel, &PathBuf::from(leaf) ]
256 .iter().collect::<PathBuf>()
259 for &(try_main, desc) in &[
260 ("main.cfg", "main config file"),
261 ("master.cfg", "obsolete-named main config file"),
263 let main = mk(try_main);
265 match self.read_file(&main, &anyway_none)
266 .dcontext(main).context(desc)?
269 Some(AnywayNone) => { },
273 for &(try_dir, desc) in &[
274 ("config.d", "per-link config directory"),
275 ("secrets.d", "per-link secrets directory"),
277 let dir = mk(try_dir);
278 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
280 Some(AnywayNone) => { },
287 #[throws(AE)] // AE includes extra, but does that this is extra
288 fn read_extra(&mut self, extra: &Path) {
291 match self.read_file(extra, &|k| match k {
292 EK::IsADirectory => Some(AnywayDir),
299 self.read_dir_d(extra, &|_| None::<Void>)?;
306 struct ResolveContext<'c> {
310 server_name: ServerName,
311 all_sections: Vec<SectionName>,
314 trait Parseable: Sized {
315 fn parse(s: Option<&str>) -> Result<Self, AE>;
316 fn default() -> Result<Self, AE> {
317 Err(anyhow!("setting must be specified"))
320 fn default_for_key(key: &str) -> Self {
321 Self::default().with_context(|| key.to_string())?
325 impl Parseable for Duration {
327 fn parse(s: Option<&str>) -> Duration {
328 // todo: would be nice to parse with humantime maybe
329 Duration::from_secs( s.value()?.parse()? )
332 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
333 impl Parseable for $t {
335 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
336 $( #[throws(AE)] fn default() -> Self { $def } )?
339 parseable_from_str!{u16, default() }
340 parseable_from_str!{u32, default() }
341 parseable_from_str!{String, default() }
342 parseable_from_str!{IpNet, default() }
343 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
344 parseable_from_str!{Uri, default() }
346 impl<T:Parseable> Parseable for Vec<T> {
348 fn parse(s: Option<&str>) -> Vec<T> {
350 .split_ascii_whitespace()
351 .map(|s| Parseable::parse(Some(s)))
352 .collect::<Result<Vec<_>,_>>()?
357 #[derive(Debug,Copy,Clone)]
358 enum SectionKindList {
365 use SectionKindList as SKL;
368 fn special_server_section() -> Self { SN::Server(ServerName(
369 SPECIAL_SERVER_SECTION.into()
373 impl SectionKindList {
374 fn contains(self, s: &SectionName) -> bool {
376 SKL::Ordinary => matches!(s, SN::Link(_)
381 SKL::Limits => matches!(s, SN::ServerLimit(_)
384 SKL::ClientAgnostic => matches!(s, SN::Common
387 SKL::Limited => SKL::Ordinary.contains(s)
388 | SKL::Limits .contains(s),
390 SKL::ServerName => matches!(s, SN::Common)
391 | matches!(s, SN::Server(ServerName(name))
392 if name == SPECIAL_SERVER_SECTION),
398 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
399 -> Option<RawValRef<'a,'a,'s>>
400 where S: Iterator<Item=&'s SectionName>
402 for section in sections {
403 if let Some(raw) = self.sections
405 .and_then(|vars: &SectionMap| vars.get(key))
407 return Some(RawValRef {
408 raw: raw.raw.as_deref(),
418 pub fn establish_server_name(&self) -> ServerName {
420 let raw = match self.lookup_raw(
422 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
424 Some(raw) => raw.try_map(|os| os.value())?,
425 None => SPECIAL_SERVER_SECTION,
427 ServerName(raw.into())
431 impl<'c> ResolveContext<'c> {
432 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
433 -> Option<RawValRef<'c,'c,'c>> {
436 self.all_sections.iter()
437 .filter(|s| sections.contains(s))
442 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
446 match self.first_of_raw(key, sections) {
448 Some(raw) => Some(raw.try_map(Parseable::parse)?),
453 pub fn ordinary<T>(&self, key: &'static str) -> T
456 match self.first_of(key, SKL::Ordinary)? {
458 None => Parseable::default_for_key(key)?,
463 pub fn limited<T>(&self, key: &'static str) -> T
464 where T: Parseable + Ord
466 let val = self.ordinary(key)?;
467 if let Some(limit) = self.first_of(key, SKL::Limits)? {
475 pub fn client<T>(&self, key: &'static str) -> T
478 LinkEnd::Client => self.ordinary(key)?,
479 LinkEnd::Server => Parseable::default_for_key(key)?,
483 pub fn server<T>(&self, key: &'static str) -> T
486 LinkEnd::Server => self.ordinary(key)?,
487 LinkEnd::Client => Parseable::default_for_key(key)?,
492 pub fn special_ipif(&self, key: &'static str) -> String {
494 LinkEnd::Client => self.ordinary(key)?,
496 self.first_of(key, SKL::ClientAgnostic)?
503 pub fn special_server(&self, key: &'static str) -> ServerName {
504 self.server_name.clone()
510 let opts = config::Opts::from_args();
513 let mut agg = Aggregate::default();
515 agg.read_toplevel(&opts.config)?;
516 for extra in &opts.extra_config {
517 agg.read_extra(extra).context("extra config")?;
520 eprintln!("GOT {:#?}", agg);
523 })().context("read configuration")?;
525 let server_name = agg.establish_server_name()?;
527 let link = LinkName {
528 server: "fooxxx".parse().unwrap(),
529 client: "127.0.0.1".parse().unwrap(),
532 let rctx = ResolveContext {
535 end: LinkEnd::Server,
538 SN::Link(link.clone()),
539 SN::Client(link.client.clone()),
540 SN::Server(link.server.clone()),
542 SN::ServerLimit(link.server.clone()),
547 let ic = InstanceConfig::resolve_instance(&rctx)
548 .context("resolve config xxx for")?;
550 eprintln!("{:?}", &ic);