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