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 { val: Option<String>, loc: Arc<PathBuf> }
99 type SectionMap = HashMap<String, RawVal>;
105 static OUTSIDE_SECTION: &str = "[";
106 static SPECIAL_SERVER_SECTION: &str = "SERVER";
108 #[derive(Default,Debug)]
110 sections: HashMap<SectionName, SectionMap>,
113 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
115 impl<'f,A> OkAnyway<'f,A> {
116 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
117 let e = r.as_ref().err()?;
124 impl FromStr for SectionName {
127 fn from_str(s: &str) -> Self {
129 "COMMON" => return SN::Common,
130 "DEFAULT" => return SN::Default,
131 "LIMIT" => return SN::GlobalLimit,
134 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
135 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
136 let (server, client) = s.split_ascii_whitespace().collect_tuple()
137 .ok_or_else(|| anyhow!(
138 "bad section name {:?} \
139 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
142 let server = server.parse().context("server name in link section name")?;
143 if client == "LIMIT" { return SN::ServerLimit(server) }
144 let client = client.parse().context("client name in link section name")?;
145 SN::Link(LinkName { server, client })
150 #[throws(AE)] // AE does not include path
151 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
153 let f = fs::File::open(path);
154 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
155 let mut f = f.context("open")?;
157 let mut s = String::new();
158 let y = f.read_to_string(&mut s);
159 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
162 let mut ini = Ini::new_cs();
163 ini.set_default_section(OUTSIDE_SECTION);
164 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
165 let map = mem::take(ini.get_mut_map());
166 if map.get(OUTSIDE_SECTION).is_some() {
167 throw!(anyhow!("INI file contains settings outside a section"));
170 let loc = Arc::new(path.to_owned());
172 for (sn, vars) in map {
173 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
175 let sn = sn.parse().dcontext(&sn)?;
176 self.sections.entry(sn)
182 RawVal { val, loc: loc.clone() })
189 #[throws(AE)] // AE includes path
190 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
192 let dir = fs::read_dir(path);
193 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
194 let dir = dir.context("open directory").dcontext(path)?;
196 let ent = ent.context("read directory").dcontext(path)?;
197 let leaf = ent.file_name();
198 let leaf = leaf.to_str();
199 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
200 if leaf.len() == 0 { continue }
201 if ! leaf.chars().all(
202 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
205 // OK we want this one
206 let ent = ent.path();
207 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
212 #[throws(AE)] // AE includes everything
213 fn read_toplevel(&mut self, toplevel: &Path) {
214 enum Anyway { None, Dir }
215 match self.read_file(toplevel, &|k| match k {
216 EK::NotFound => Some(Anyway::None),
217 EK::IsADirectory => Some(Anyway::Dir),
220 .dcontext(toplevel).context("top-level config directory (or file)")?
222 None | Some(Anyway::None) => { },
224 Some(Anyway::Dir) => {
226 let anyway_none = |k| match k {
227 EK::NotFound => Some(AnywayNone),
231 let mk = |leaf: &str| {
232 [ toplevel, &PathBuf::from(leaf) ]
233 .iter().collect::<PathBuf>()
236 for &(try_main, desc) in &[
237 ("main.cfg", "main config file"),
238 ("master.cfg", "obsolete-named main config file"),
240 let main = mk(try_main);
242 match self.read_file(&main, &anyway_none)
243 .dcontext(main).context(desc)?
246 Some(AnywayNone) => { },
250 for &(try_dir, desc) in &[
251 ("config.d", "per-link config directory"),
252 ("secrets.d", "per-link secrets directory"),
254 let dir = mk(try_dir);
255 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
257 Some(AnywayNone) => { },
264 #[throws(AE)] // AE includes extra, but does that this is extra
265 fn read_extra(&mut self, extra: &Path) {
268 match self.read_file(extra, &|k| match k {
269 EK::IsADirectory => Some(AnywayDir),
276 self.read_dir_d(extra, &|_| None::<Void>)?;
283 struct ResolveContext<'c> {
287 all_sections: Vec<SectionName>,
288 special_server_section: SectionName,
291 trait Parseable: Sized {
292 fn parse(s: Option<&str>) -> Result<Self, AE>;
293 fn default() -> Result<Self, AE> {
294 Err(anyhow!("setting must be specified"))
297 fn default_for_key(key: &str) -> Self {
298 Self::default().with_context(|| key.to_string())?
302 impl Parseable for Duration {
304 fn parse(s: Option<&str>) -> Duration {
305 // todo: would be nice to parse with humantime maybe
306 Duration::from_secs( s.value()?.parse()? )
309 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
310 impl Parseable for $t {
312 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
313 $( #[throws(AE)] fn default() -> Self { $def } )?
316 parseable_from_str!{u16, default() }
317 parseable_from_str!{u32, default() }
318 parseable_from_str!{String, default() }
319 parseable_from_str!{IpNet, default() }
320 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
321 parseable_from_str!{Uri, default() }
323 impl<T:Parseable> Parseable for Vec<T> {
325 fn parse(s: Option<&str>) -> Vec<T> {
327 .split_ascii_whitespace()
328 .map(|s| Parseable::parse(Some(s)))
329 .collect::<Result<Vec<_>,_>>()?
334 #[derive(Debug,Copy,Clone)]
335 enum SectionKindList {
342 use SectionKindList as SKL;
345 fn special_server_section() -> Self { SN::Server(ServerName(
346 SPECIAL_SERVER_SECTION.into()
350 impl SectionKindList {
351 fn contains(self, s: &SectionName) -> bool {
353 SKL::Ordinary => matches!(s, SN::Link(_)
358 SKL::Limits => matches!(s, SN::ServerLimit(_)
361 SKL::ClientAgnostic => matches!(s, SN::Common
364 SKL::Limited => SKL::Ordinary.contains(s)
365 | SKL::Limits .contains(s),
367 SKL::ServerName => matches!(s, SN::Common)
368 | matches!(s, SN::Server(ServerName(name))
369 if name == SPECIAL_SERVER_SECTION),
374 impl<'c> ResolveContext<'c> {
375 fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
376 -> Option<&'c RawVal>
377 where S: Iterator<Item=&'n SectionName>
379 for section in sections {
380 if let Some(raw) = self.agg.sections
382 .and_then(|vars: &SectionMap| vars.get(key))
390 fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
391 -> Option<&'c RawVal> {
394 self.all_sections.iter()
395 .filter(|s| sections.contains(s))
400 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
404 match self.first_of_raw(key, sections) {
407 Parseable::parse(raw.val.as_deref())
409 // .with_context(|| format!(r#"in section "{}""#, §ion))
416 pub fn ordinary<T>(&self, key: &'static str) -> T
419 match self.first_of(key, SKL::Ordinary)? {
421 None => Parseable::default_for_key(key)?,
426 pub fn limited<T>(&self, key: &'static str) -> T
427 where T: Parseable + Ord
429 let val = self.ordinary(key)?;
430 if let Some(limit) = self.first_of(key, SKL::Limits)? {
438 pub fn client<T>(&self, key: &'static str) -> T
441 LinkEnd::Client => self.ordinary(key)?,
442 LinkEnd::Server => Parseable::default_for_key(key)?,
446 pub fn server<T>(&self, key: &'static str) -> T
449 LinkEnd::Server => self.ordinary(key)?,
450 LinkEnd::Client => Parseable::default_for_key(key)?,
455 pub fn special_ipif(&self, key: &'static str) -> String {
457 LinkEnd::Client => self.ordinary(key)?,
459 self.first_of(key, SKL::ClientAgnostic)?
466 pub fn special_server(&self, key: &'static str) -> ServerName {
467 let raw = match self.lookup_raw(
469 [ &SectionName::Common, &self.special_server_section ].iter().cloned()
471 Some(raw) => raw.val.as_deref().value()?,
472 None => SPECIAL_SERVER_SECTION,
474 ServerName(raw.into())
480 let opts = config::Opts::from_args();
483 let mut agg = Aggregate::default();
485 agg.read_toplevel(&opts.config)?;
486 for extra in &opts.extra_config {
487 agg.read_extra(extra).context("extra config")?;
490 eprintln!("GOT {:#?}", agg);
493 })().context("read configuration")?;
495 let link = LinkName {
496 server: "fooxxx".parse().unwrap(),
497 client: "127.0.0.1".parse().unwrap(),
500 let rctx = ResolveContext {
503 end: LinkEnd::Server,
505 SN::Link(link.clone()),
506 SN::Client(link.client.clone()),
507 SN::Server(link.server.clone()),
509 SN::ServerLimit(link.server.clone()),
512 special_server_section: SN::special_server_section(),
515 let ic = InstanceConfig::resolve_instance(&rctx)
516 .context("resolve config xxx for")?;
518 eprintln!("{:?}", &ic);