chiark / gitweb /
config: Move server_name
[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 { val: Option<String>, loc: Arc<PathBuf> }
99 type SectionMap = HashMap<String, RawVal>;
100
101 pub struct Config {
102   opts: Opts,
103 }
104
105 static OUTSIDE_SECTION: &str = "[";
106 static SPECIAL_SERVER_SECTION: &str = "SERVER";
107
108 #[derive(Default,Debug)]
109 struct Aggregate {
110   sections: HashMap<SectionName, SectionMap>,
111 }
112
113 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
114 #[ext]
115 impl<'f,A> OkAnyway<'f,A> {
116   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
117     let e = r.as_ref().err()?;
118     let k = e.kind();
119     let a = self(k)?;
120     Some(a)
121   }
122 }
123
124 impl FromStr for SectionName {
125   type Err = AE;
126   #[throws(AE)]
127   fn from_str(s: &str) -> Self {
128     match s {
129       "COMMON" => return SN::Common,
130       "DEFAULT" => return SN::Default,
131       "LIMIT" => return SN::GlobalLimit,
132       _ => { }
133     };
134     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
135     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
136     let (server, client) = s.split_ascii_whitespace().collect_tuple()
137       .ok_or_else(|| anyhow!(
138         "bad section name {:?} \
139          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
140         s
141       ))?;
142     let server = server.parse().context("server name in link section name")?;
143     if client == "LIMIT" { return SN::ServerLimit(server) }
144     let client = client.parse().context("client name in link section name")?;
145     SN::Link(LinkName { server, client })
146   }
147 }
148
149 impl Aggregate {
150   #[throws(AE)] // AE does not include path
151   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
152   {
153     let f = fs::File::open(path);
154     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
155     let mut f = f.context("open")?;
156
157     let mut s = String::new();
158     let y = f.read_to_string(&mut s);
159     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
160     y.context("read")?;
161
162     let mut ini = Ini::new_cs();
163     ini.set_default_section(OUTSIDE_SECTION);
164     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
165     let map = mem::take(ini.get_mut_map());
166     if map.get(OUTSIDE_SECTION).is_some() {
167       throw!(anyhow!("INI file contains settings outside a section"));
168     }
169
170     let loc = Arc::new(path.to_owned());
171
172     for (sn, vars) in map {
173       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
174
175       let sn = sn.parse().dcontext(&sn)?;
176         self.sections.entry(sn)
177         .or_default()
178         .extend(
179           vars.into_iter()
180             .map(|(k,val)| {
181               (k.replace('-',"_"),
182                RawVal { val, loc: loc.clone() })
183             })
184         );
185     }
186     None
187   }
188
189   #[throws(AE)] // AE includes path
190   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
191   {
192     let dir = fs::read_dir(path);
193     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
194     let dir = dir.context("open directory").dcontext(path)?;
195     for ent in dir {
196       let ent = ent.context("read directory").dcontext(path)?;
197       let leaf = ent.file_name();
198       let leaf = leaf.to_str();
199       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
200       if leaf.len() == 0 { continue }
201       if ! leaf.chars().all(
202         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
203       ) { continue }
204
205       // OK we want this one
206       let ent = ent.path();
207       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
208     }
209     None
210   }
211
212   #[throws(AE)] // AE includes everything
213   fn read_toplevel(&mut self, toplevel: &Path) {
214     enum Anyway { None, Dir }
215     match self.read_file(toplevel, &|k| match k {
216       EK::NotFound => Some(Anyway::None),
217       EK::IsADirectory => Some(Anyway::Dir),
218       _ => None,
219     })
220       .dcontext(toplevel).context("top-level config directory (or file)")?
221     {
222       None | Some(Anyway::None) => { },
223
224       Some(Anyway::Dir) => {
225         struct AnywayNone;
226         let anyway_none = |k| match k {
227           EK::NotFound => Some(AnywayNone),
228           _ => None,
229         };
230
231         let mk = |leaf: &str| {
232           [ toplevel, &PathBuf::from(leaf) ]
233             .iter().collect::<PathBuf>()
234         };
235
236         for &(try_main, desc) in &[
237           ("main.cfg", "main config file"),
238           ("master.cfg", "obsolete-named main config file"),
239         ] {
240           let main = mk(try_main);
241
242           match self.read_file(&main, &anyway_none)
243             .dcontext(main).context(desc)?
244           {
245             None => break,
246             Some(AnywayNone) => { },
247           }
248         }
249
250         for &(try_dir, desc) in &[
251           ("config.d", "per-link config directory"),
252           ("secrets.d", "per-link secrets directory"),
253         ] {
254           let dir = mk(try_dir);
255           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
256             None => { },
257             Some(AnywayNone) => { },
258           }
259         }
260       }
261     }
262   }
263
264   #[throws(AE)] // AE includes extra, but does that this is extra
265   fn read_extra(&mut self, extra: &Path) {
266     struct AnywayDir;
267
268     match self.read_file(extra, &|k| match k {
269       EK::IsADirectory => Some(AnywayDir),
270       _ => None,
271     })
272       .dcontext(extra)?
273     {
274       None => return,
275       Some(AnywayDir) => {
276         self.read_dir_d(extra, &|_| None::<Void>)?;
277       }
278     }
279
280   }
281 }
282
283 struct ResolveContext<'c> {
284   agg: &'c Aggregate,
285   link: &'c LinkName,
286   end: LinkEnd,
287   server_name: ServerName,
288   all_sections: Vec<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 Aggregate {
375   fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
376                        -> Option<&RawVal>
377   where S: Iterator<Item=&'n SectionName>
378   {
379     for section in sections {
380       if let Some(raw) = self.sections
381         .get(section)
382         .and_then(|vars: &SectionMap| vars.get(key))
383       {
384         return Some(raw)
385       }
386     }
387     None
388   }
389
390   #[throws(AE)]
391   pub fn establish_server_name(&self) -> ServerName {
392     let raw = match self.lookup_raw(
393       "server",
394       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
395     ) {
396       Some(raw) => raw.val.as_deref().value()?,
397       None => SPECIAL_SERVER_SECTION,
398     };
399     ServerName(raw.into())
400   }
401 }
402
403 impl<'c> ResolveContext<'c> {
404   fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
405                   -> Option<&'c RawVal> {
406     self.agg.lookup_raw(
407       key,
408       self.all_sections.iter()
409         .filter(|s| sections.contains(s))
410     )
411   }
412
413   #[throws(AE)]
414   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
415                  -> Option<T>
416   where T: Parseable
417   {
418     match self.first_of_raw(key, sections) {
419       None => None,
420       Some(raw) => Some({
421         Parseable::parse(raw.val.as_deref())
422           .context(key)
423 //          .with_context(|| format!(r#"in section "{}""#, &section))
424           .dcontext(&raw.loc)?
425       }),
426     }
427   }
428
429   #[throws(AE)]
430   pub fn ordinary<T>(&self, key: &'static str) -> T
431   where T: Parseable
432   {
433     match self.first_of(key, SKL::Ordinary)? {
434       Some(y) => y,
435       None => Parseable::default_for_key(key)?,
436     }
437   }
438
439   #[throws(AE)]
440   pub fn limited<T>(&self, key: &'static str) -> T
441   where T: Parseable + Ord
442   {
443     let val = self.ordinary(key)?;
444     if let Some(limit) = self.first_of(key, SKL::Limits)? {
445       min(val, limit)
446     } else {
447       val
448     }
449   }
450
451   #[throws(AE)]
452   pub fn client<T>(&self, key: &'static str) -> T
453   where T: Parseable {
454     match self.end {
455       LinkEnd::Client => self.ordinary(key)?,
456       LinkEnd::Server => Parseable::default_for_key(key)?,
457     }
458   }
459   #[throws(AE)]
460   pub fn server<T>(&self, key: &'static str) -> T
461   where T: Parseable {
462     match self.end {
463       LinkEnd::Server => self.ordinary(key)?,
464       LinkEnd::Client => Parseable::default_for_key(key)?,
465     }
466   }
467
468   #[throws(AE)]
469   pub fn special_ipif(&self, key: &'static str) -> String {
470     match self.end {
471       LinkEnd::Client => self.ordinary(key)?,
472       LinkEnd::Server => {
473         self.first_of(key, SKL::ClientAgnostic)?
474           .unwrap_or_default()
475       },
476     }
477   }
478
479   #[throws(AE)]
480   pub fn special_server(&self, key: &'static str) -> ServerName {
481     self.server_name.clone()
482   }
483 }
484
485 #[throws(AE)]
486 pub fn read() {
487   let opts = config::Opts::from_args();
488
489   let agg = (||{
490     let mut agg = Aggregate::default();
491
492     agg.read_toplevel(&opts.config)?;
493     for extra in &opts.extra_config {
494       agg.read_extra(extra).context("extra config")?;
495     }
496
497     eprintln!("GOT {:#?}", agg);
498
499     Ok::<_,AE>(agg)
500   })().context("read configuration")?;
501
502   let server_name = agg.establish_server_name()?;
503
504   let link = LinkName {
505     server: "fooxxx".parse().unwrap(),
506     client: "127.0.0.1".parse().unwrap(),
507   };
508
509   let rctx = ResolveContext {
510     agg: &agg,
511     link: &link,
512     end: LinkEnd::Server,
513     server_name,
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   };
523
524   let ic = InstanceConfig::resolve_instance(&rctx)
525     .context("resolve config xxx for")?;
526
527   eprintln!("{:?}", &ic);
528 }