chiark / gitweb /
config: Fix error reporting
[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 { raw: Option<String>, loc: Arc<PathBuf> }
99 type SectionMap = HashMap<String, RawVal>;
100
101 struct RawValRef<'v,'l,'s> {
102   raw: Option<&'v str>,
103   key: &'static str,
104   loc: &'l Path,
105   section: &'s SectionName,
106 }
107
108 impl<'v> RawValRef<'v,'_,'_> {
109   #[throws(AE)]
110   fn try_map<F,T>(&self, f: F) -> T
111   where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
112     f(self.raw)
113       .with_context(|| format!(r#"file {:?}, section "{:?}", key "{}"#,
114                                self.loc, self.section, self.key))?
115   }
116 }
117
118 pub struct Config {
119   opts: Opts,
120 }
121
122 static OUTSIDE_SECTION: &str = "[";
123 static SPECIAL_SERVER_SECTION: &str = "SERVER";
124
125 #[derive(Default,Debug)]
126 struct Aggregate {
127   sections: HashMap<SectionName, SectionMap>,
128 }
129
130 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
131 #[ext]
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()?;
135     let k = e.kind();
136     let a = self(k)?;
137     Some(a)
138   }
139 }
140
141 impl FromStr for SectionName {
142   type Err = AE;
143   #[throws(AE)]
144   fn from_str(s: &str) -> Self {
145     match s {
146       "COMMON" => return SN::Common,
147       "DEFAULT" => return SN::Default,
148       "LIMIT" => return SN::GlobalLimit,
149       _ => { }
150     };
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>",
157         s
158       ))?;
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 })
163   }
164 }
165
166 impl Aggregate {
167   #[throws(AE)] // AE does not include path
168   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
169   {
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")?;
173
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) }
177     y.context("read")?;
178
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"));
185     }
186
187     let loc = Arc::new(path.to_owned());
188
189     for (sn, vars) in map {
190       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
191
192       let sn = sn.parse().dcontext(&sn)?;
193         self.sections.entry(sn)
194         .or_default()
195         .extend(
196           vars.into_iter()
197             .map(|(k,raw)| {
198               (k.replace('-',"_"),
199                RawVal { raw, loc: loc.clone() })
200             })
201         );
202     }
203     None
204   }
205
206   #[throws(AE)] // AE includes path
207   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
208   {
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)?;
212     for ent in dir {
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()
220       ) { continue }
221
222       // OK we want this one
223       let ent = ent.path();
224       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
225     }
226     None
227   }
228
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),
235       _ => None,
236     })
237       .dcontext(toplevel).context("top-level config directory (or file)")?
238     {
239       None | Some(Anyway::None) => { },
240
241       Some(Anyway::Dir) => {
242         struct AnywayNone;
243         let anyway_none = |k| match k {
244           EK::NotFound => Some(AnywayNone),
245           _ => None,
246         };
247
248         let mk = |leaf: &str| {
249           [ toplevel, &PathBuf::from(leaf) ]
250             .iter().collect::<PathBuf>()
251         };
252
253         for &(try_main, desc) in &[
254           ("main.cfg", "main config file"),
255           ("master.cfg", "obsolete-named main config file"),
256         ] {
257           let main = mk(try_main);
258
259           match self.read_file(&main, &anyway_none)
260             .dcontext(main).context(desc)?
261           {
262             None => break,
263             Some(AnywayNone) => { },
264           }
265         }
266
267         for &(try_dir, desc) in &[
268           ("config.d", "per-link config directory"),
269           ("secrets.d", "per-link secrets directory"),
270         ] {
271           let dir = mk(try_dir);
272           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
273             None => { },
274             Some(AnywayNone) => { },
275           }
276         }
277       }
278     }
279   }
280
281   #[throws(AE)] // AE includes extra, but does that this is extra
282   fn read_extra(&mut self, extra: &Path) {
283     struct AnywayDir;
284
285     match self.read_file(extra, &|k| match k {
286       EK::IsADirectory => Some(AnywayDir),
287       _ => None,
288     })
289       .dcontext(extra)?
290     {
291       None => return,
292       Some(AnywayDir) => {
293         self.read_dir_d(extra, &|_| None::<Void>)?;
294       }
295     }
296
297   }
298 }
299
300 struct ResolveContext<'c> {
301   agg: &'c Aggregate,
302   link: &'c LinkName,
303   end: LinkEnd,
304   server_name: ServerName,
305   all_sections: Vec<SectionName>,
306 }
307
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"))
312   }
313   #[throws(AE)]
314   fn default_for_key(key: &str) -> Self {
315     Self::default().with_context(|| key.to_string())?
316   }
317 }
318
319 impl Parseable for Duration {
320   #[throws(AE)]
321   fn parse(s: Option<&str>) -> Duration {
322     // todo: would be nice to parse with humantime maybe
323     Duration::from_secs( s.value()?.parse()? )
324   }
325 }
326 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
327   impl Parseable for $t {
328     #[throws(AE)]
329     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
330     $( #[throws(AE)] fn default() -> Self { $def } )?
331   }
332 } }
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() }
339
340 impl<T:Parseable> Parseable for Vec<T> {
341   #[throws(AE)]
342   fn parse(s: Option<&str>) -> Vec<T> {
343     s.value()?
344       .split_ascii_whitespace()
345       .map(|s| Parseable::parse(Some(s)))
346       .collect::<Result<Vec<_>,_>>()?
347   }
348 }
349
350
351 #[derive(Debug,Copy,Clone)]
352 enum SectionKindList {
353   Ordinary,
354   Limited,
355   Limits,
356   ClientAgnostic,
357   ServerName,
358 }
359 use SectionKindList as SKL;
360
361 impl SectionName {
362   fn special_server_section() -> Self { SN::Server(ServerName(
363     SPECIAL_SERVER_SECTION.into()
364   )) }
365 }
366
367 impl SectionKindList {
368   fn contains(self, s: &SectionName) -> bool {
369     match self {
370       SKL::Ordinary       => matches!(s, SN::Link(_)
371                                        | SN::Client(_)
372                                        | SN::Server(_)
373                                        | SN::Common),
374
375       SKL::Limits         => matches!(s, SN::ServerLimit(_)
376                                        | SN::GlobalLimit),
377
378       SKL::ClientAgnostic => matches!(s, SN::Common
379                                        | SN::Server(_)),
380
381       SKL::Limited        => SKL::Ordinary.contains(s)
382                            | SKL::Limits  .contains(s),
383
384       SKL::ServerName     => matches!(s, SN::Common)
385                            | matches!(s, SN::Server(ServerName(name))
386                                          if name == SPECIAL_SERVER_SECTION),
387     }
388   }
389 }
390
391 impl Aggregate {
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>
395   {
396     for section in sections {
397       if let Some(raw) = self.sections
398         .get(section)
399         .and_then(|vars: &SectionMap| vars.get(key))
400       {
401         return Some(RawValRef {
402           raw: raw.raw.as_deref(),
403           loc: &raw.loc,
404           section, key,
405         })
406       }
407     }
408     None
409   }
410
411   #[throws(AE)]
412   pub fn establish_server_name(&self) -> ServerName {
413     let key = "server";
414     let raw = match self.lookup_raw(
415       key,
416       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
417     ) {
418       Some(raw) => raw.try_map(|os| os.value())?,
419       None => SPECIAL_SERVER_SECTION,
420     };
421     ServerName(raw.into())
422   }
423 }
424
425 impl<'c> ResolveContext<'c> {
426   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
427                   -> Option<RawValRef<'c,'c,'c>> {
428     self.agg.lookup_raw(
429       key,
430       self.all_sections.iter()
431         .filter(|s| sections.contains(s))
432     )
433   }
434
435   #[throws(AE)]
436   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
437                  -> Option<T>
438   where T: Parseable
439   {
440     match self.first_of_raw(key, sections) {
441       None => None,
442       Some(raw) => Some(raw.try_map(Parseable::parse)?),
443     }
444   }
445
446   #[throws(AE)]
447   pub fn ordinary<T>(&self, key: &'static str) -> T
448   where T: Parseable
449   {
450     match self.first_of(key, SKL::Ordinary)? {
451       Some(y) => y,
452       None => Parseable::default_for_key(key)?,
453     }
454   }
455
456   #[throws(AE)]
457   pub fn limited<T>(&self, key: &'static str) -> T
458   where T: Parseable + Ord
459   {
460     let val = self.ordinary(key)?;
461     if let Some(limit) = self.first_of(key, SKL::Limits)? {
462       min(val, limit)
463     } else {
464       val
465     }
466   }
467
468   #[throws(AE)]
469   pub fn client<T>(&self, key: &'static str) -> T
470   where T: Parseable {
471     match self.end {
472       LinkEnd::Client => self.ordinary(key)?,
473       LinkEnd::Server => Parseable::default_for_key(key)?,
474     }
475   }
476   #[throws(AE)]
477   pub fn server<T>(&self, key: &'static str) -> T
478   where T: Parseable {
479     match self.end {
480       LinkEnd::Server => self.ordinary(key)?,
481       LinkEnd::Client => Parseable::default_for_key(key)?,
482     }
483   }
484
485   #[throws(AE)]
486   pub fn special_ipif(&self, key: &'static str) -> String {
487     match self.end {
488       LinkEnd::Client => self.ordinary(key)?,
489       LinkEnd::Server => {
490         self.first_of(key, SKL::ClientAgnostic)?
491           .unwrap_or_default()
492       },
493     }
494   }
495
496   #[throws(AE)]
497   pub fn special_server(&self, key: &'static str) -> ServerName {
498     self.server_name.clone()
499   }
500 }
501
502 #[throws(AE)]
503 pub fn read() {
504   let opts = config::Opts::from_args();
505
506   let agg = (||{
507     let mut agg = Aggregate::default();
508
509     agg.read_toplevel(&opts.config)?;
510     for extra in &opts.extra_config {
511       agg.read_extra(extra).context("extra config")?;
512     }
513
514     eprintln!("GOT {:#?}", agg);
515
516     Ok::<_,AE>(agg)
517   })().context("read configuration")?;
518
519   let server_name = agg.establish_server_name()?;
520
521   let link = LinkName {
522     server: "fooxxx".parse().unwrap(),
523     client: "127.0.0.1".parse().unwrap(),
524   };
525
526   let rctx = ResolveContext {
527     agg: &agg,
528     link: &link,
529     end: LinkEnd::Server,
530     server_name,
531     all_sections: vec![
532       SN::Link(link.clone()),
533       SN::Client(link.client.clone()),
534       SN::Server(link.server.clone()),
535       SN::Common,
536       SN::ServerLimit(link.server.clone()),
537       SN::GlobalLimit,
538     ],
539   };
540
541   let ic = InstanceConfig::resolve_instance(&rctx)
542     .context("resolve config xxx for")?;
543
544   eprintln!("{:?}", &ic);
545 }