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 let mut ini = Ini::new_cs();
180 ini.set_default_section(OUTSIDE_SECTION);
181 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
182 let map = mem::take(ini.get_mut_map());
183 if map.get(OUTSIDE_SECTION).is_some() {
184 throw!(anyhow!("INI file contains settings outside a section"));
187 let loc = Arc::new(path.to_owned());
189 for (sn, vars) in map {
190 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
192 let sn = sn.parse().dcontext(&sn)?;
193 self.sections.entry(sn)
199 RawVal { raw, loc: loc.clone() })
206 #[throws(AE)] // AE includes path
207 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
209 let dir = fs::read_dir(path);
210 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
211 let dir = dir.context("open directory").dcontext(path)?;
213 let ent = ent.context("read directory").dcontext(path)?;
214 let leaf = ent.file_name();
215 let leaf = leaf.to_str();
216 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
217 if leaf.len() == 0 { continue }
218 if ! leaf.chars().all(
219 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
222 // OK we want this one
223 let ent = ent.path();
224 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
229 #[throws(AE)] // AE includes everything
230 fn read_toplevel(&mut self, toplevel: &Path) {
231 enum Anyway { None, Dir }
232 match self.read_file(toplevel, &|k| match k {
233 EK::NotFound => Some(Anyway::None),
234 EK::IsADirectory => Some(Anyway::Dir),
237 .dcontext(toplevel).context("top-level config directory (or file)")?
239 None | Some(Anyway::None) => { },
241 Some(Anyway::Dir) => {
243 let anyway_none = |k| match k {
244 EK::NotFound => Some(AnywayNone),
248 let mk = |leaf: &str| {
249 [ toplevel, &PathBuf::from(leaf) ]
250 .iter().collect::<PathBuf>()
253 for &(try_main, desc) in &[
254 ("main.cfg", "main config file"),
255 ("master.cfg", "obsolete-named main config file"),
257 let main = mk(try_main);
259 match self.read_file(&main, &anyway_none)
260 .dcontext(main).context(desc)?
263 Some(AnywayNone) => { },
267 for &(try_dir, desc) in &[
268 ("config.d", "per-link config directory"),
269 ("secrets.d", "per-link secrets directory"),
271 let dir = mk(try_dir);
272 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
274 Some(AnywayNone) => { },
281 #[throws(AE)] // AE includes extra, but does that this is extra
282 fn read_extra(&mut self, extra: &Path) {
285 match self.read_file(extra, &|k| match k {
286 EK::IsADirectory => Some(AnywayDir),
293 self.read_dir_d(extra, &|_| None::<Void>)?;
300 struct ResolveContext<'c> {
304 server_name: ServerName,
305 all_sections: Vec<SectionName>,
308 trait Parseable: Sized {
309 fn parse(s: Option<&str>) -> Result<Self, AE>;
310 fn default() -> Result<Self, AE> {
311 Err(anyhow!("setting must be specified"))
314 fn default_for_key(key: &str) -> Self {
315 Self::default().with_context(|| key.to_string())?
319 impl Parseable for Duration {
321 fn parse(s: Option<&str>) -> Duration {
322 // todo: would be nice to parse with humantime maybe
323 Duration::from_secs( s.value()?.parse()? )
326 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
327 impl Parseable for $t {
329 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
330 $( #[throws(AE)] fn default() -> Self { $def } )?
333 parseable_from_str!{u16, default() }
334 parseable_from_str!{u32, default() }
335 parseable_from_str!{String, default() }
336 parseable_from_str!{IpNet, default() }
337 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
338 parseable_from_str!{Uri, default() }
340 impl<T:Parseable> Parseable for Vec<T> {
342 fn parse(s: Option<&str>) -> Vec<T> {
344 .split_ascii_whitespace()
345 .map(|s| Parseable::parse(Some(s)))
346 .collect::<Result<Vec<_>,_>>()?
351 #[derive(Debug,Copy,Clone)]
352 enum SectionKindList {
359 use SectionKindList as SKL;
362 fn special_server_section() -> Self { SN::Server(ServerName(
363 SPECIAL_SERVER_SECTION.into()
367 impl SectionKindList {
368 fn contains(self, s: &SectionName) -> bool {
370 SKL::Ordinary => matches!(s, SN::Link(_)
375 SKL::Limits => matches!(s, SN::ServerLimit(_)
378 SKL::ClientAgnostic => matches!(s, SN::Common
381 SKL::Limited => SKL::Ordinary.contains(s)
382 | SKL::Limits .contains(s),
384 SKL::ServerName => matches!(s, SN::Common)
385 | matches!(s, SN::Server(ServerName(name))
386 if name == SPECIAL_SERVER_SECTION),
392 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
393 -> Option<RawValRef<'a,'a,'s>>
394 where S: Iterator<Item=&'s SectionName>
396 for section in sections {
397 if let Some(raw) = self.sections
399 .and_then(|vars: &SectionMap| vars.get(key))
401 return Some(RawValRef {
402 raw: raw.raw.as_deref(),
412 pub fn establish_server_name(&self) -> ServerName {
414 let raw = match self.lookup_raw(
416 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
418 Some(raw) => raw.try_map(|os| os.value())?,
419 None => SPECIAL_SERVER_SECTION,
421 ServerName(raw.into())
425 impl<'c> ResolveContext<'c> {
426 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
427 -> Option<RawValRef<'c,'c,'c>> {
430 self.all_sections.iter()
431 .filter(|s| sections.contains(s))
436 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
440 match self.first_of_raw(key, sections) {
442 Some(raw) => Some(raw.try_map(Parseable::parse)?),
447 pub fn ordinary<T>(&self, key: &'static str) -> T
450 match self.first_of(key, SKL::Ordinary)? {
452 None => Parseable::default_for_key(key)?,
457 pub fn limited<T>(&self, key: &'static str) -> T
458 where T: Parseable + Ord
460 let val = self.ordinary(key)?;
461 if let Some(limit) = self.first_of(key, SKL::Limits)? {
469 pub fn client<T>(&self, key: &'static str) -> T
472 LinkEnd::Client => self.ordinary(key)?,
473 LinkEnd::Server => Parseable::default_for_key(key)?,
477 pub fn server<T>(&self, key: &'static str) -> T
480 LinkEnd::Server => self.ordinary(key)?,
481 LinkEnd::Client => Parseable::default_for_key(key)?,
486 pub fn special_ipif(&self, key: &'static str) -> String {
488 LinkEnd::Client => self.ordinary(key)?,
490 self.first_of(key, SKL::ClientAgnostic)?
497 pub fn special_server(&self, key: &'static str) -> ServerName {
498 self.server_name.clone()
504 let opts = config::Opts::from_args();
507 let mut agg = Aggregate::default();
509 agg.read_toplevel(&opts.config)?;
510 for extra in &opts.extra_config {
511 agg.read_extra(extra).context("extra config")?;
514 eprintln!("GOT {:#?}", agg);
517 })().context("read configuration")?;
519 let server_name = agg.establish_server_name()?;
521 let link = LinkName {
522 server: "fooxxx".parse().unwrap(),
523 client: "127.0.0.1".parse().unwrap(),
526 let rctx = ResolveContext {
529 end: LinkEnd::Server,
532 SN::Link(link.clone()),
533 SN::Client(link.client.clone()),
534 SN::Server(link.server.clone()),
536 SN::ServerLimit(link.server.clone()),
541 let ic = InstanceConfig::resolve_instance(&rctx)
542 .context("resolve config xxx for")?;
544 eprintln!("{:?}", &ic);