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>,
24 pub struct CidrString(pub String);
26 pub struct InstanceConfig {
28 // Exceptional settings
30 pub secret: String, // make a newytpe
34 pub max_batch_down: u32,
36 pub max_queue_time: Duration,
37 pub http_timeout: Duration,
38 pub target_requests_outstanding: u32,
41 pub addrs: Vec<IpAddr>,
42 pub vnetwork: Vec<CidrString>,
43 pub vaddr: Vec<IpAddr>,
47 pub ifname_server: String,
48 pub ifname_client: String,
50 // Ordinary settings, used by server only:
51 pub max_clock_skew: Duration,
53 // Ordinary settings, used by client only:
54 pub http_timeout_grace: Duration,
55 pub max_requests_outstanding: u32,
56 pub max_batch_up: u32,
57 pub http_retry: Duration,
59 pub vroutes: Vec<CidrString>,
63 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
64 pub enum SectionName {
67 Server(ServerName), // includes SERVER, which is slightly special
68 ServerLimit(ServerName),
73 pub use SectionName as SN;
75 #[derive(Debug,Clone)]
76 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
77 type SectionMap = HashMap<String, RawVal>;
83 static OUTSIDE_SECTION: &str = "[";
85 #[derive(Default,Debug)]
87 sections: HashMap<SectionName, SectionMap>,
90 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
92 impl<'f,A> OkAnyway<'f,A> {
93 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
94 let e = r.as_ref().err()?;
101 impl FromStr for SectionName {
104 fn from_str(s: &str) -> Self {
106 "COMMON" => return SN::Common,
107 "DEFAULT" => return SN::Default,
108 "LIMIT" => return SN::GlobalLimit,
111 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
112 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
113 let (server, client) = s.split_ascii_whitespace().collect_tuple()
114 .ok_or_else(|| anyhow!(
115 "bad section name {:?} \
116 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
119 let server = server.parse().context("server name in link section name")?;
120 if client == "LIMIT" { return SN::ServerLimit(server) }
121 let client = client.parse().context("client name in link section name")?;
122 SN::Link(LinkName { server, client })
127 #[throws(AE)] // AE does not include path
128 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
130 let f = fs::File::open(path);
131 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
132 let mut f = f.context("open")?;
134 let mut s = String::new();
135 let y = f.read_to_string(&mut s);
136 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
139 let mut ini = Ini::new_cs();
140 ini.set_default_section(OUTSIDE_SECTION);
141 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
142 let map = mem::take(ini.get_mut_map());
143 if map.get(OUTSIDE_SECTION).is_some() {
144 throw!(anyhow!("INI file contains settings outside a section"));
147 let loc = Arc::new(path.to_owned());
149 for (sn, vars) in map {
150 let sn = sn.parse().dcontext(&sn)?;
151 self.sections.entry(sn)
157 RawVal { val, loc: loc.clone() })
164 #[throws(AE)] // AE includes path
165 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
167 let dir = fs::read_dir(path);
168 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
169 let dir = dir.context("open directory").dcontext(path)?;
171 let ent = ent.context("read directory").dcontext(path)?;
172 let leaf = ent.file_name();
173 let leaf = leaf.to_str();
174 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
175 if leaf.len() == 0 { continue }
176 if ! leaf.chars().all(
177 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
180 // OK we want this one
181 let ent = ent.path();
182 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
187 #[throws(AE)] // AE includes everything
188 fn read_toplevel(&mut self, toplevel: &Path) {
189 enum Anyway { None, Dir }
190 match self.read_file(toplevel, &|k| match k {
191 EK::NotFound => Some(Anyway::None),
192 EK::IsADirectory => Some(Anyway::Dir),
195 .dcontext(toplevel).context("top-level config directory (or file)")?
197 None | Some(Anyway::None) => { },
199 Some(Anyway::Dir) => {
201 let anyway_none = |k| match k {
202 EK::NotFound => Some(AnywayNone),
206 let mk = |leaf: &str| {
207 [ toplevel, &PathBuf::from(leaf) ]
208 .iter().collect::<PathBuf>()
211 for &(try_main, desc) in &[
212 ("main.cfg", "main config file"),
213 ("master.cfg", "obsolete-named main config file"),
215 let main = mk(try_main);
217 match self.read_file(&main, &anyway_none)
218 .dcontext(main).context(desc)?
221 Some(AnywayNone) => { },
225 for &(try_dir, desc) in &[
226 ("config.d", "per-link config directory"),
227 ("secrets.d", "per-link secrets directory"),
229 let dir = mk(try_dir);
230 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
232 Some(AnywayNone) => { },
239 #[throws(AE)] // AE includes extra, but does that this is extra
240 fn read_extra(&mut self, extra: &Path) {
243 match self.read_file(extra, &|k| match k {
244 EK::IsADirectory => Some(AnywayDir),
251 self.read_dir_d(extra, &|_| None::<Void>)?;
258 enum LinkEnd { Server, Client }
260 struct ResolveContext<'c> {
264 lookup_ordinary: Vec<SectionName>,
265 lookup_limit: Vec<SectionName>,
266 lookup_server_sections_only: Vec<SectionName>,
269 trait Parseable: Sized {
270 fn parse(s: &Option<String>) -> Result<Self, AE>;
273 impl Parseable for Duration {
275 fn parse(s: &Option<String>) -> Duration {
276 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
277 if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
278 throw!(anyhow!("xxx parse with humantime"))
281 macro_rules! parseable_from_str { ($t:ty) => {
282 impl Parseable for $t {
284 fn parse(s: &Option<String>) -> $t {
285 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
290 parseable_from_str!{u32}
292 impl<'c> ResolveContext<'c> {
293 fn first_of_raw(&self, key: &'static str, sections: &[SectionName])
294 -> Option<&'c RawVal> {
295 for section in sections {
296 if let Some(raw) = self.agg.sections
298 .and_then(|vars: &SectionMap| vars.get(key))
307 fn first_of<T>(&self, key: &'static str, sections: &[SectionName])
311 match self.first_of_raw(key, sections) {
314 Parseable::parse(&raw.val)
316 // .with_context(|| format!(r#"in section "{}""#, §ion))
323 pub fn ordinary<T>(&self, key: &'static str) -> T
324 where T: Parseable + Default
326 self.first_of(key, &self.lookup_ordinary)?
331 pub fn limited<T>(&self, key: &'static str) -> T
332 where T: Parseable + Default + Ord
334 let val = self.ordinary(key)?;
335 if let Some(limit) = self.first_of(key, &self.lookup_limit)? {
343 pub fn client<T>(&self, key: &'static str) -> T
344 where T: Parseable + Default {
346 LinkEnd::Client => self.ordinary(key)?,
347 LinkEnd::Server => default(),
351 pub fn server<T>(&self, key: &'static str) -> T
352 where T: Parseable + Default {
354 LinkEnd::Server => self.ordinary(key)?,
355 LinkEnd::Client => default(),
360 pub fn special_ipif<T>(&self, key: &'static str) -> T
361 where T: Parseable + Default
364 LinkEnd::Client => self.ordinary(key)?,
366 self.first_of(key, &self.lookup_server_sections_only)?
373 impl<'c> ResolveContext<'c> {
375 fn resolve_instance(&self) -> InstanceConfig {
377 max_batch_down: self.limited::<u32>("max_batch_down")?.into(),
384 let opts = config::Opts::from_args();
387 let mut agg = Aggregate::default();
389 agg.read_toplevel(&opts.config)?;
390 for extra in &opts.extra_config {
391 agg.read_extra(extra).context("extra config")?;
394 eprintln!("GOT {:#?}", agg);
397 })().context("read configuration")?;
399 let link = LinkName {
400 server: "fooxxx".parse().unwrap(),
401 client: "127.0.0.1".parse().unwrap(),
404 let rctx = ResolveContext {
407 end: LinkEnd::Server,
408 lookup_ordinary: vec![
409 SN::Link(link.clone()),
410 SN::Client(link.client.clone()),
411 SN::Server(link.server.clone()),
415 SN::ServerLimit(link.server.clone()),
418 lookup_server_sections_only: vec![
420 SN::Server(link.server.clone()),