chiark / gitweb /
config
[hippotat.git] / src / config.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 use configparser::ini::Ini;
8
9 #[derive(StructOpt,Debug)]
10 pub struct Opts {
11   /// Top-level config file or directory
12   ///
13   /// Look for `main.cfg`, `config.d` and `secrets.d` here.
14   ///
15   /// Or if this is a file, just read that file.
16   #[structopt(long, default_value="/etc/hippotat")]
17   pub config: PathBuf,
18   
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>,
22 }
23
24 #[ext]
25 impl<'s> Option<&'s str> {
26   #[throws(AE)]
27   fn value(self) -> &'s str {
28     self.ok_or_else(|| anyhow!("value needed"))?
29   }
30 }
31
32 #[derive(Clone)]
33 pub struct Secret(pub String);
34 impl Parseable for Secret {
35   #[throws(AE)]
36   fn parse(s: Option<&str>) -> Self {
37     let s = s.value()?;
38     if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
39     Secret(s.into())
40   }
41   #[throws(AE)]
42   fn default() -> Self { Secret(default()) }
43 }
44 impl Debug for Secret {
45   #[throws(fmt::Error)]
46   fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
47 }
48
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,
54   pub                                             secret: Secret,
55   #[special(special_ipif, SKL::Ordinary)]     pub ipif:   String,
56
57   // Capped settings:
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,
62
63   // Ordinary settings:
64   pub addrs:                        Vec<IpAddr>,
65   pub vnetwork:                     Vec<IpNet>,
66   pub vaddr:                        Vec<IpAddr>,
67   pub vrelay:                       IpAddr,
68   pub port:                         u16,
69   pub mtu:                          u32,
70   pub ifname_server:                String,
71   pub ifname_client:                String,
72
73   // Ordinary settings, used by server only:
74   #[server]  pub max_clock_skew:               Duration,
75
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>,
83 }
84
85 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
86 pub enum SectionName {
87   Link(LinkName),
88   Client(ClientName),
89   Server(ServerName), // includes SERVER, which is slightly special
90   ServerLimit(ServerName),
91   GlobalLimit,
92   Common,
93   Default,
94 }
95 pub use SectionName as SN;
96
97 #[derive(Debug,Clone)]
98 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
99 type SectionMap = HashMap<String, RawVal>;
100
101 pub struct Config {
102   opts: Opts,
103 }
104
105 static OUTSIDE_SECTION: &str = "[";
106 static SPECIAL_SERVER_SECTION: &str = "SERVER";
107
108 #[derive(Default,Debug)]
109 struct Aggregate {
110   sections: HashMap<SectionName, SectionMap>,
111 }
112
113 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
114 #[ext]
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()?;
118     let k = e.kind();
119     let a = self(k)?;
120     Some(a)
121   }
122 }
123
124 impl FromStr for SectionName {
125   type Err = AE;
126   #[throws(AE)]
127   fn from_str(s: &str) -> Self {
128     match s {
129       "COMMON" => return SN::Common,
130       "DEFAULT" => return SN::Default,
131       "LIMIT" => return SN::GlobalLimit,
132       _ => { }
133     };
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>",
140         s
141       ))?;
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 })
146   }
147 }
148
149 impl Aggregate {
150   #[throws(AE)] // AE does not include path
151   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
152   {
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")?;
156
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) }
160     y.context("read")?;
161
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"));
168     }
169
170     let loc = Arc::new(path.to_owned());
171
172     for (sn, vars) in map {
173       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
174
175       let sn = sn.parse().dcontext(&sn)?;
176         self.sections.entry(sn)
177         .or_default()
178         .extend(
179           vars.into_iter()
180             .map(|(k,val)| {
181               (k.replace('-',"_"),
182                RawVal { val, loc: loc.clone() })
183             })
184         );
185     }
186     None
187   }
188
189   #[throws(AE)] // AE includes path
190   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
191   {
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)?;
195     for ent in dir {
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()
203       ) { continue }
204
205       // OK we want this one
206       let ent = ent.path();
207       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
208     }
209     None
210   }
211
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),
218       _ => None,
219     })
220       .dcontext(toplevel).context("top-level config directory (or file)")?
221     {
222       None | Some(Anyway::None) => { },
223
224       Some(Anyway::Dir) => {
225         struct AnywayNone;
226         let anyway_none = |k| match k {
227           EK::NotFound => Some(AnywayNone),
228           _ => None,
229         };
230
231         let mk = |leaf: &str| {
232           [ toplevel, &PathBuf::from(leaf) ]
233             .iter().collect::<PathBuf>()
234         };
235
236         for &(try_main, desc) in &[
237           ("main.cfg", "main config file"),
238           ("master.cfg", "obsolete-named main config file"),
239         ] {
240           let main = mk(try_main);
241
242           match self.read_file(&main, &anyway_none)
243             .dcontext(main).context(desc)?
244           {
245             None => break,
246             Some(AnywayNone) => { },
247           }
248         }
249
250         for &(try_dir, desc) in &[
251           ("config.d", "per-link config directory"),
252           ("secrets.d", "per-link secrets directory"),
253         ] {
254           let dir = mk(try_dir);
255           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
256             None => { },
257             Some(AnywayNone) => { },
258           }
259         }
260       }
261     }
262   }
263
264   #[throws(AE)] // AE includes extra, but does that this is extra
265   fn read_extra(&mut self, extra: &Path) {
266     struct AnywayDir;
267
268     match self.read_file(extra, &|k| match k {
269       EK::IsADirectory => Some(AnywayDir),
270       _ => None,
271     })
272       .dcontext(extra)?
273     {
274       None => return,
275       Some(AnywayDir) => {
276         self.read_dir_d(extra, &|_| None::<Void>)?;
277       }
278     }
279
280   }
281 }
282
283 enum LinkEnd { Server, Client }
284
285 struct ResolveContext<'c> {
286   agg: &'c Aggregate,
287   link: &'c LinkName,
288   end: LinkEnd,
289   all_sections: Vec<SectionName>,
290   special_server_section: SectionName,
291 }
292
293 trait Parseable: Sized {
294   fn parse(s: Option<&str>) -> Result<Self, AE>;
295   fn default() -> Result<Self, AE> {
296     Err(anyhow!("setting must be specified"))
297   }
298   #[throws(AE)]
299   fn default_for_key(key: &str) -> Self {
300     Self::default().with_context(|| key.to_string())?
301   }
302 }
303
304 impl Parseable for Duration {
305   #[throws(AE)]
306   fn parse(s: Option<&str>) -> Duration {
307     // todo: would be nice to parse with humantime maybe
308     Duration::from_secs( s.value()?.parse()? )
309   }
310 }
311 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
312   impl Parseable for $t {
313     #[throws(AE)]
314     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
315     $( #[throws(AE)] fn default() -> Self { $def } )?
316   }
317 } }
318 parseable_from_str!{u16, default() }
319 parseable_from_str!{u32, default() }
320 parseable_from_str!{String, default() }
321 parseable_from_str!{IpNet, default() }
322 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
323 parseable_from_str!{Uri, default() }
324
325 impl<T:Parseable> Parseable for Vec<T> {
326   #[throws(AE)]
327   fn parse(s: Option<&str>) -> Vec<T> {
328     s.value()?
329       .split_ascii_whitespace()
330       .map(|s| Parseable::parse(Some(s)))
331       .collect::<Result<Vec<_>,_>>()?
332   }
333 }
334
335
336 #[derive(Debug,Copy,Clone)]
337 enum SectionKindList {
338   Ordinary,
339   Limited,
340   Limits,
341   ClientAgnostic,
342   ServerName,
343 }
344 use SectionKindList as SKL;
345
346 impl SectionName {
347   fn special_server_section() -> Self { SN::Server(ServerName(
348     SPECIAL_SERVER_SECTION.into()
349   )) }
350 }
351
352 impl SectionKindList {
353   fn contains(self, s: &SectionName) -> bool {
354     match self {
355       SKL::Ordinary       => matches!(s, SN::Link(_)
356                                        | SN::Client(_)
357                                        | SN::Server(_)
358                                        | SN::Common),
359
360       SKL::Limits         => matches!(s, SN::ServerLimit(_)
361                                        | SN::GlobalLimit),
362
363       SKL::ClientAgnostic => matches!(s, SN::Common
364                                        | SN::Server(_)),
365
366       SKL::Limited        => SKL::Ordinary.contains(s)
367                            | SKL::Limits  .contains(s),
368
369       SKL::ServerName     => matches!(s, SN::Common)
370                            | matches!(s, SN::Server(ServerName(name))
371                                          if name == SPECIAL_SERVER_SECTION),
372     }
373   }
374 }
375
376 impl<'c> ResolveContext<'c> {
377   fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
378                        -> Option<&'c RawVal>
379   where S: Iterator<Item=&'n SectionName>
380   {
381     for section in sections {
382       if let Some(raw) = self.agg.sections
383         .get(section)
384         .and_then(|vars: &SectionMap| vars.get(key))
385       {
386         return Some(raw)
387       }
388     }
389     None
390   }
391
392   fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
393                   -> Option<&'c RawVal> {
394     self.lookup_raw(
395       key,
396       self.all_sections.iter()
397         .filter(|s| sections.contains(s))
398     )
399   }
400
401   #[throws(AE)]
402   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
403                  -> Option<T>
404   where T: Parseable
405   {
406     match self.first_of_raw(key, sections) {
407       None => None,
408       Some(raw) => Some({
409         Parseable::parse(raw.val.as_deref())
410           .context(key)
411 //          .with_context(|| format!(r#"in section "{}""#, &section))
412           .dcontext(&raw.loc)?
413       }),
414     }
415   }
416
417   #[throws(AE)]
418   pub fn ordinary<T>(&self, key: &'static str) -> T
419   where T: Parseable
420   {
421     match self.first_of(key, SKL::Ordinary)? {
422       Some(y) => y,
423       None => Parseable::default_for_key(key)?,
424     }
425   }
426
427   #[throws(AE)]
428   pub fn limited<T>(&self, key: &'static str) -> T
429   where T: Parseable + Ord
430   {
431     let val = self.ordinary(key)?;
432     if let Some(limit) = self.first_of(key, SKL::Limits)? {
433       min(val, limit)
434     } else {
435       val
436     }
437   }
438
439   #[throws(AE)]
440   pub fn client<T>(&self, key: &'static str) -> T
441   where T: Parseable {
442     match self.end {
443       LinkEnd::Client => self.ordinary(key)?,
444       LinkEnd::Server => Parseable::default_for_key(key)?,
445     }
446   }
447   #[throws(AE)]
448   pub fn server<T>(&self, key: &'static str) -> T
449   where T: Parseable {
450     match self.end {
451       LinkEnd::Server => self.ordinary(key)?,
452       LinkEnd::Client => Parseable::default_for_key(key)?,
453     }
454   }
455
456   #[throws(AE)]
457   pub fn special_ipif(&self, key: &'static str) -> String {
458     match self.end {
459       LinkEnd::Client => self.ordinary(key)?,
460       LinkEnd::Server => {
461         self.first_of(key, SKL::ClientAgnostic)?
462           .unwrap_or_default()
463       },
464     }
465   }
466
467   #[throws(AE)]
468   pub fn special_server(&self, key: &'static str) -> ServerName {
469     let raw = match self.lookup_raw(
470       "server",
471       [ &SectionName::Common, &self.special_server_section ].iter().cloned()
472     ) {
473       Some(raw) => raw.val.as_deref().value()?,
474       None => SPECIAL_SERVER_SECTION,
475     };
476     ServerName(raw.into())
477   }
478 }
479
480 #[throws(AE)]
481 pub fn read() {
482   let opts = config::Opts::from_args();
483
484   let agg = (||{
485     let mut agg = Aggregate::default();
486
487     agg.read_toplevel(&opts.config)?;
488     for extra in &opts.extra_config {
489       agg.read_extra(extra).context("extra config")?;
490     }
491
492     eprintln!("GOT {:#?}", agg);
493
494     Ok::<_,AE>(agg)
495   })().context("read configuration")?;
496
497   let link = LinkName {
498     server: "fooxxx".parse().unwrap(),
499     client: "127.0.0.1".parse().unwrap(),
500   };
501
502   let rctx = ResolveContext {
503     agg: &agg,
504     link: &link,
505     end: LinkEnd::Server,
506     all_sections: vec![
507       SN::Link(link.clone()),
508       SN::Client(link.client.clone()),
509       SN::Server(link.server.clone()),
510       SN::Common,
511       SN::ServerLimit(link.server.clone()),
512       SN::GlobalLimit,
513     ],
514     special_server_section: SN::special_server_section(),
515   };
516
517   let ic = InstanceConfig::resolve_instance(&rctx)
518     .context("resolve config xxx for")?;
519
520   eprintln!("{:?}", &ic);
521 }