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>,
95 pub vaddr: Vec<IpAddr>,
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),
124 pub use SectionName as SN;
126 #[derive(Debug,Clone)]
127 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
128 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 "DEFAULT" => return SN::Default,
177 "LIMIT" => return SN::GlobalLimit,
180 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
181 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
182 let (server, client) = s.split_ascii_whitespace().collect_tuple()
183 .ok_or_else(|| anyhow!(
184 "bad section name {:?} \
185 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
188 let server = server.parse().context("server name in link section name")?;
189 if client == "LIMIT" { return SN::ServerLimit(server) }
190 let client = client.parse().context("client name in link section name")?;
191 SN::Link(LinkName { server, client })
196 #[throws(AE)] // AE does not include path
197 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
199 let f = fs::File::open(path);
200 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
201 let mut f = f.context("open")?;
203 let mut s = String::new();
204 let y = f.read_to_string(&mut s);
205 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
208 self.read_string(s, path)?;
212 #[throws(AE)] // AE does not include path
213 fn read_string(&mut self, s: String, path_for_loc: &Path) {
214 let mut ini = Ini::new_cs();
215 ini.set_default_section(OUTSIDE_SECTION);
216 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
217 let map = mem::take(ini.get_mut_map());
218 if map.get(OUTSIDE_SECTION).is_some() {
219 throw!(anyhow!("INI file contains settings outside a section"));
222 let loc = Arc::new(path_for_loc.to_owned());
224 for (sn, vars) in map {
225 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
227 let sn = sn.parse().dcontext(&sn)?;
228 self.sections.entry(sn)
234 RawVal { raw, loc: loc.clone() })
241 #[throws(AE)] // AE includes path
242 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
244 let dir = fs::read_dir(path);
245 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
246 let dir = dir.context("open directory").dcontext(path)?;
248 let ent = ent.context("read directory").dcontext(path)?;
249 let leaf = ent.file_name();
250 let leaf = leaf.to_str();
251 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
252 if leaf.len() == 0 { continue }
253 if ! leaf.chars().all(
254 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
257 // OK we want this one
258 let ent = ent.path();
259 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
264 #[throws(AE)] // AE includes everything
265 fn read_toplevel(&mut self, toplevel: &Path) {
266 enum Anyway { None, Dir }
267 match self.read_file(toplevel, &|k| match k {
268 EK::NotFound => Some(Anyway::None),
269 EK::IsADirectory => Some(Anyway::Dir),
272 .dcontext(toplevel).context("top-level config directory (or file)")?
274 None | Some(Anyway::None) => { },
276 Some(Anyway::Dir) => {
278 let anyway_none = |k| match k {
279 EK::NotFound => Some(AnywayNone),
283 let mk = |leaf: &str| {
284 [ toplevel, &PathBuf::from(leaf) ]
285 .iter().collect::<PathBuf>()
288 for &(try_main, desc) in &[
289 ("main.cfg", "main config file"),
290 ("master.cfg", "obsolete-named main config file"),
292 let main = mk(try_main);
294 match self.read_file(&main, &anyway_none)
295 .dcontext(main).context(desc)?
298 Some(AnywayNone) => { },
302 for &(try_dir, desc) in &[
303 ("config.d", "per-link config directory"),
304 ("secrets.d", "per-link secrets directory"),
306 let dir = mk(try_dir);
307 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
309 Some(AnywayNone) => { },
316 #[throws(AE)] // AE includes extra, but does that this is extra
317 fn read_extra(&mut self, extra: &Path) {
320 match self.read_file(extra, &|k| match k {
321 EK::IsADirectory => Some(AnywayDir),
328 self.read_dir_d(extra, &|_| None::<Void>)?;
335 struct ResolveContext<'c> {
339 server_name: ServerName,
340 all_sections: Vec<SectionName>,
343 trait Parseable: Sized {
344 fn parse(s: Option<&str>) -> Result<Self, AE>;
345 fn default() -> Result<Self, AE> {
346 Err(anyhow!("setting must be specified"))
349 fn default_for_key(key: &str) -> Self {
350 Self::default().with_context(|| key.to_string())?
354 impl Parseable for Duration {
356 fn parse(s: Option<&str>) -> Duration {
357 // todo: would be nice to parse with humantime maybe
358 Duration::from_secs( s.value()?.parse()? )
361 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
362 impl Parseable for $t {
364 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
365 $( #[throws(AE)] fn default() -> Self { $def } )?
368 parseable_from_str!{u16, default() }
369 parseable_from_str!{u32, default() }
370 parseable_from_str!{String, default() }
371 parseable_from_str!{IpNet, default() }
372 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
373 parseable_from_str!{Uri, default() }
375 impl<T:Parseable> Parseable for Vec<T> {
377 fn parse(s: Option<&str>) -> Vec<T> {
379 .split_ascii_whitespace()
380 .map(|s| Parseable::parse(Some(s)))
381 .collect::<Result<Vec<_>,_>>()?
386 #[derive(Debug,Copy,Clone)]
387 enum SectionKindList {
394 use SectionKindList as SKL;
397 fn special_server_section() -> Self { SN::Server(ServerName(
398 SPECIAL_SERVER_SECTION.into()
402 impl SectionKindList {
403 fn contains(self, s: &SectionName) -> bool {
405 SKL::Ordinary => matches!(s, SN::Link(_)
410 SKL::Limits => matches!(s, SN::ServerLimit(_)
413 SKL::ClientAgnostic => matches!(s, SN::Common
416 SKL::Limited => SKL::Ordinary.contains(s)
417 | SKL::Limits .contains(s),
419 SKL::ServerName => matches!(s, SN::Common)
420 | matches!(s, SN::Server(ServerName(name))
421 if name == SPECIAL_SERVER_SECTION),
427 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
428 -> Option<RawValRef<'a,'a,'s>>
429 where S: Iterator<Item=&'s SectionName>
431 for section in sections {
432 if let Some(raw) = self.sections
434 .and_then(|vars: &SectionMap| vars.get(key))
436 return Some(RawValRef {
437 raw: raw.raw.as_deref(),
447 pub fn establish_server_name(&self) -> ServerName {
449 let raw = match self.lookup_raw(
451 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
453 Some(raw) => raw.try_map(|os| os.value())?,
454 None => SPECIAL_SERVER_SECTION,
456 ServerName(raw.into())
460 impl<'c> ResolveContext<'c> {
461 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
462 -> Option<RawValRef<'c,'c,'c>> {
465 self.all_sections.iter()
466 .filter(|s| sections.contains(s))
471 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
475 match self.first_of_raw(key, sections) {
477 Some(raw) => Some(raw.try_map(Parseable::parse)?),
482 pub fn ordinary<T>(&self, key: &'static str) -> T
485 match self.first_of(key, SKL::Ordinary)? {
487 None => Parseable::default_for_key(key)?,
492 pub fn limited<T>(&self, key: &'static str) -> T
493 where T: Parseable + Ord
495 let val = self.ordinary(key)?;
496 if let Some(limit) = self.first_of(key, SKL::Limits)? {
504 pub fn client<T>(&self, key: &'static str) -> T
507 LinkEnd::Client => self.ordinary(key)?,
508 LinkEnd::Server => Parseable::default_for_key(key)?,
512 pub fn server<T>(&self, key: &'static str) -> T
515 LinkEnd::Server => self.ordinary(key)?,
516 LinkEnd::Client => Parseable::default_for_key(key)?,
521 pub fn special_ipif(&self, key: &'static str) -> String {
523 LinkEnd::Client => self.ordinary(key)?,
525 self.first_of(key, SKL::ClientAgnostic)?
532 pub fn special_server(&self, key: &'static str) -> ServerName {
533 self.server_name.clone()
539 let opts = config::Opts::from_args();
542 let mut agg = Aggregate::default();
544 agg.read_toplevel(&opts.config)?;
545 for extra in &opts.extra_config {
546 agg.read_extra(extra).context("extra config")?;
549 eprintln!("GOT {:#?}", agg);
552 })().context("read configuration")?;
554 let server_name = agg.establish_server_name()?;
556 let link = LinkName {
557 server: "fooxxx".parse().unwrap(),
558 client: "127.0.0.1".parse().unwrap(),
561 let rctx = ResolveContext {
564 end: LinkEnd::Server,
567 SN::Link(link.clone()),
568 SN::Client(link.client.clone()),
569 SN::Server(link.server.clone()),
571 SN::ServerLimit(link.server.clone()),
576 let ic = InstanceConfig::resolve_instance(&rctx)
577 .context("resolve config xxx for")?;
579 eprintln!("{:?}", &ic);