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