chiark / gitweb /
config: Break out read_file
[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     self.read_string(s, path)?;
180     None
181   }
182
183   #[throws(AE)] // AE does not include path
184   fn read_string(&mut self, s: String, path_for_loc: &Path) {
185     let mut ini = Ini::new_cs();
186     ini.set_default_section(OUTSIDE_SECTION);
187     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
188     let map = mem::take(ini.get_mut_map());
189     if map.get(OUTSIDE_SECTION).is_some() {
190       throw!(anyhow!("INI file contains settings outside a section"));
191     }
192
193     let loc = Arc::new(path_for_loc.to_owned());
194
195     for (sn, vars) in map {
196       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
197
198       let sn = sn.parse().dcontext(&sn)?;
199         self.sections.entry(sn)
200         .or_default()
201         .extend(
202           vars.into_iter()
203             .map(|(k,raw)| {
204               (k.replace('-',"_"),
205                RawVal { raw, loc: loc.clone() })
206             })
207         );
208     }
209     
210   }
211
212   #[throws(AE)] // AE includes path
213   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
214   {
215     let dir = fs::read_dir(path);
216     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
217     let dir = dir.context("open directory").dcontext(path)?;
218     for ent in dir {
219       let ent = ent.context("read directory").dcontext(path)?;
220       let leaf = ent.file_name();
221       let leaf = leaf.to_str();
222       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
223       if leaf.len() == 0 { continue }
224       if ! leaf.chars().all(
225         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
226       ) { continue }
227
228       // OK we want this one
229       let ent = ent.path();
230       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
231     }
232     None
233   }
234
235   #[throws(AE)] // AE includes everything
236   fn read_toplevel(&mut self, toplevel: &Path) {
237     enum Anyway { None, Dir }
238     match self.read_file(toplevel, &|k| match k {
239       EK::NotFound => Some(Anyway::None),
240       EK::IsADirectory => Some(Anyway::Dir),
241       _ => None,
242     })
243       .dcontext(toplevel).context("top-level config directory (or file)")?
244     {
245       None | Some(Anyway::None) => { },
246
247       Some(Anyway::Dir) => {
248         struct AnywayNone;
249         let anyway_none = |k| match k {
250           EK::NotFound => Some(AnywayNone),
251           _ => None,
252         };
253
254         let mk = |leaf: &str| {
255           [ toplevel, &PathBuf::from(leaf) ]
256             .iter().collect::<PathBuf>()
257         };
258
259         for &(try_main, desc) in &[
260           ("main.cfg", "main config file"),
261           ("master.cfg", "obsolete-named main config file"),
262         ] {
263           let main = mk(try_main);
264
265           match self.read_file(&main, &anyway_none)
266             .dcontext(main).context(desc)?
267           {
268             None => break,
269             Some(AnywayNone) => { },
270           }
271         }
272
273         for &(try_dir, desc) in &[
274           ("config.d", "per-link config directory"),
275           ("secrets.d", "per-link secrets directory"),
276         ] {
277           let dir = mk(try_dir);
278           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
279             None => { },
280             Some(AnywayNone) => { },
281           }
282         }
283       }
284     }
285   }
286
287   #[throws(AE)] // AE includes extra, but does that this is extra
288   fn read_extra(&mut self, extra: &Path) {
289     struct AnywayDir;
290
291     match self.read_file(extra, &|k| match k {
292       EK::IsADirectory => Some(AnywayDir),
293       _ => None,
294     })
295       .dcontext(extra)?
296     {
297       None => return,
298       Some(AnywayDir) => {
299         self.read_dir_d(extra, &|_| None::<Void>)?;
300       }
301     }
302
303   }
304 }
305
306 struct ResolveContext<'c> {
307   agg: &'c Aggregate,
308   link: &'c LinkName,
309   end: LinkEnd,
310   server_name: ServerName,
311   all_sections: Vec<SectionName>,
312 }
313
314 trait Parseable: Sized {
315   fn parse(s: Option<&str>) -> Result<Self, AE>;
316   fn default() -> Result<Self, AE> {
317     Err(anyhow!("setting must be specified"))
318   }
319   #[throws(AE)]
320   fn default_for_key(key: &str) -> Self {
321     Self::default().with_context(|| key.to_string())?
322   }
323 }
324
325 impl Parseable for Duration {
326   #[throws(AE)]
327   fn parse(s: Option<&str>) -> Duration {
328     // todo: would be nice to parse with humantime maybe
329     Duration::from_secs( s.value()?.parse()? )
330   }
331 }
332 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
333   impl Parseable for $t {
334     #[throws(AE)]
335     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
336     $( #[throws(AE)] fn default() -> Self { $def } )?
337   }
338 } }
339 parseable_from_str!{u16, default() }
340 parseable_from_str!{u32, default() }
341 parseable_from_str!{String, default() }
342 parseable_from_str!{IpNet, default() }
343 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
344 parseable_from_str!{Uri, default() }
345
346 impl<T:Parseable> Parseable for Vec<T> {
347   #[throws(AE)]
348   fn parse(s: Option<&str>) -> Vec<T> {
349     s.value()?
350       .split_ascii_whitespace()
351       .map(|s| Parseable::parse(Some(s)))
352       .collect::<Result<Vec<_>,_>>()?
353   }
354 }
355
356
357 #[derive(Debug,Copy,Clone)]
358 enum SectionKindList {
359   Ordinary,
360   Limited,
361   Limits,
362   ClientAgnostic,
363   ServerName,
364 }
365 use SectionKindList as SKL;
366
367 impl SectionName {
368   fn special_server_section() -> Self { SN::Server(ServerName(
369     SPECIAL_SERVER_SECTION.into()
370   )) }
371 }
372
373 impl SectionKindList {
374   fn contains(self, s: &SectionName) -> bool {
375     match self {
376       SKL::Ordinary       => matches!(s, SN::Link(_)
377                                        | SN::Client(_)
378                                        | SN::Server(_)
379                                        | SN::Common),
380
381       SKL::Limits         => matches!(s, SN::ServerLimit(_)
382                                        | SN::GlobalLimit),
383
384       SKL::ClientAgnostic => matches!(s, SN::Common
385                                        | SN::Server(_)),
386
387       SKL::Limited        => SKL::Ordinary.contains(s)
388                            | SKL::Limits  .contains(s),
389
390       SKL::ServerName     => matches!(s, SN::Common)
391                            | matches!(s, SN::Server(ServerName(name))
392                                          if name == SPECIAL_SERVER_SECTION),
393     }
394   }
395 }
396
397 impl Aggregate {
398   fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
399                        -> Option<RawValRef<'a,'a,'s>>
400   where S: Iterator<Item=&'s SectionName>
401   {
402     for section in sections {
403       if let Some(raw) = self.sections
404         .get(section)
405         .and_then(|vars: &SectionMap| vars.get(key))
406       {
407         return Some(RawValRef {
408           raw: raw.raw.as_deref(),
409           loc: &raw.loc,
410           section, key,
411         })
412       }
413     }
414     None
415   }
416
417   #[throws(AE)]
418   pub fn establish_server_name(&self) -> ServerName {
419     let key = "server";
420     let raw = match self.lookup_raw(
421       key,
422       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
423     ) {
424       Some(raw) => raw.try_map(|os| os.value())?,
425       None => SPECIAL_SERVER_SECTION,
426     };
427     ServerName(raw.into())
428   }
429 }
430
431 impl<'c> ResolveContext<'c> {
432   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
433                   -> Option<RawValRef<'c,'c,'c>> {
434     self.agg.lookup_raw(
435       key,
436       self.all_sections.iter()
437         .filter(|s| sections.contains(s))
438     )
439   }
440
441   #[throws(AE)]
442   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
443                  -> Option<T>
444   where T: Parseable
445   {
446     match self.first_of_raw(key, sections) {
447       None => None,
448       Some(raw) => Some(raw.try_map(Parseable::parse)?),
449     }
450   }
451
452   #[throws(AE)]
453   pub fn ordinary<T>(&self, key: &'static str) -> T
454   where T: Parseable
455   {
456     match self.first_of(key, SKL::Ordinary)? {
457       Some(y) => y,
458       None => Parseable::default_for_key(key)?,
459     }
460   }
461
462   #[throws(AE)]
463   pub fn limited<T>(&self, key: &'static str) -> T
464   where T: Parseable + Ord
465   {
466     let val = self.ordinary(key)?;
467     if let Some(limit) = self.first_of(key, SKL::Limits)? {
468       min(val, limit)
469     } else {
470       val
471     }
472   }
473
474   #[throws(AE)]
475   pub fn client<T>(&self, key: &'static str) -> T
476   where T: Parseable {
477     match self.end {
478       LinkEnd::Client => self.ordinary(key)?,
479       LinkEnd::Server => Parseable::default_for_key(key)?,
480     }
481   }
482   #[throws(AE)]
483   pub fn server<T>(&self, key: &'static str) -> T
484   where T: Parseable {
485     match self.end {
486       LinkEnd::Server => self.ordinary(key)?,
487       LinkEnd::Client => Parseable::default_for_key(key)?,
488     }
489   }
490
491   #[throws(AE)]
492   pub fn special_ipif(&self, key: &'static str) -> String {
493     match self.end {
494       LinkEnd::Client => self.ordinary(key)?,
495       LinkEnd::Server => {
496         self.first_of(key, SKL::ClientAgnostic)?
497           .unwrap_or_default()
498       },
499     }
500   }
501
502   #[throws(AE)]
503   pub fn special_server(&self, key: &'static str) -> ServerName {
504     self.server_name.clone()
505   }
506 }
507
508 #[throws(AE)]
509 pub fn read() {
510   let opts = config::Opts::from_args();
511
512   let agg = (||{
513     let mut agg = Aggregate::default();
514
515     agg.read_toplevel(&opts.config)?;
516     for extra in &opts.extra_config {
517       agg.read_extra(extra).context("extra config")?;
518     }
519
520     eprintln!("GOT {:#?}", agg);
521
522     Ok::<_,AE>(agg)
523   })().context("read configuration")?;
524
525   let server_name = agg.establish_server_name()?;
526
527   let link = LinkName {
528     server: "fooxxx".parse().unwrap(),
529     client: "127.0.0.1".parse().unwrap(),
530   };
531
532   let rctx = ResolveContext {
533     agg: &agg,
534     link: &link,
535     end: LinkEnd::Server,
536     server_name,
537     all_sections: vec![
538       SN::Link(link.clone()),
539       SN::Client(link.client.clone()),
540       SN::Server(link.server.clone()),
541       SN::Common,
542       SN::ServerLimit(link.server.clone()),
543       SN::GlobalLimit,
544     ],
545   };
546
547   let ic = InstanceConfig::resolve_instance(&rctx)
548     .context("resolve config xxx for")?;
549
550   eprintln!("{:?}", &ic);
551 }