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