chiark / gitweb /
config: wip defaulting
[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 static DEFAULT_CONFIG: &str = r#"
10 [COMMON]
11 max_batch_down = 65536
12 max_queue_time = 10
13 target_requests_outstanding = 3
14 http_timeout = 30
15 http_timeout_grace = 5
16 max_requests_outstanding = 6
17 max_batch_up = 4000
18 http_retry = 5
19 port = 80
20 vroutes = ''
21 ifname_client = hippo%%d
22 ifname_server = shippo%%d
23 max_clock_skew = 300
24
25 ipif = userv root ipif %(local)s,%(peer)s,%(mtu)s,slip,%(ifname)s %(rnets)s
26
27 mtu = 1500
28
29 vvnetwork = 172.24.230.192
30
31 [LIMIT]
32 max_batch_down = 262144
33 max_queue_time = 121
34 http_timeout = 121
35 target_requests_outstanding = 10
36 "#;
37
38 #[derive(StructOpt,Debug)]
39 pub struct Opts {
40   /// Top-level config file or directory
41   ///
42   /// Look for `main.cfg`, `config.d` and `secrets.d` here.
43   ///
44   /// Or if this is a file, just read that file.
45   #[structopt(long, default_value="/etc/hippotat")]
46   pub config: PathBuf,
47   
48   /// Additional config files or dirs, which can override the others
49   #[structopt(long, multiple=true, number_of_values=1)]
50   pub extra_config: Vec<PathBuf>,
51 }
52
53 #[ext]
54 impl<'s> Option<&'s str> {
55   #[throws(AE)]
56   fn value(self) -> &'s str {
57     self.ok_or_else(|| anyhow!("value needed"))?
58   }
59 }
60
61 #[derive(Clone)]
62 pub struct Secret(pub String);
63 impl Parseable for Secret {
64   #[throws(AE)]
65   fn parse(s: Option<&str>) -> Self {
66     let s = s.value()?;
67     if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
68     Secret(s.into())
69   }
70   #[throws(AE)]
71   fn default() -> Self { Secret(default()) }
72 }
73 impl Debug for Secret {
74   #[throws(fmt::Error)]
75   fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
76 }
77
78 #[derive(hippotat_macros::ResolveConfig)]
79 #[derive(Debug,Clone)]
80 pub struct InstanceConfig {
81   // Exceptional settings
82   #[special(special_server, SKL::ServerName)] pub server: ServerName,
83   pub                                             secret: Secret,
84   #[special(special_ipif, SKL::Ordinary)]     pub ipif:   String,
85
86   // Capped settings:
87   #[limited]    pub max_batch_down:               u32,
88   #[limited]    pub max_queue_time:               Duration,
89   #[limited]    pub http_timeout:                 Duration,
90   #[limited]    pub target_requests_outstanding:  u32,
91
92   // Ordinary settings:
93   pub addrs:                        Vec<IpAddr>,
94   pub vnetwork:                     Vec<IpNet>,
95   pub vaddr:                        IpAddr,
96   pub vrelay:                       IpAddr,
97   pub port:                         u16,
98   pub mtu:                          u32,
99   pub ifname_server:                String,
100   pub ifname_client:                String,
101
102   // Ordinary settings, used by server only:
103   #[server]  pub max_clock_skew:               Duration,
104
105   // Ordinary settings, used by client only:
106   #[client]  pub http_timeout_grace:           Duration,
107   #[client]  pub max_requests_outstanding:     u32,
108   #[client]  pub max_batch_up:                 u32,
109   #[client]  pub http_retry:                   Duration,
110   #[client]  pub url:                          Uri,
111   #[client]  pub vroutes:                      Vec<IpNet>,
112 }
113
114 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
115 pub enum SectionName {
116   Link(LinkName),
117   Client(ClientName),
118   Server(ServerName), // includes SERVER, which is slightly special
119   ServerLimit(ServerName),
120   GlobalLimit,
121   Common,
122 }
123 pub use SectionName as SN;
124
125 #[derive(Debug,Clone)]
126 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
127 type SectionMap = HashMap<String, RawVal>;
128
129 #[derive(Debug)]
130 struct RawValRef<'v,'l,'s> {
131   raw: Option<&'v str>,
132   key: &'static str,
133   loc: &'l Path,
134   section: &'s SectionName,
135 }
136
137 impl<'v> RawValRef<'v,'_,'_> {
138   #[throws(AE)]
139   fn try_map<F,T>(&self, f: F) -> T
140   where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
141     f(self.raw)
142       .with_context(|| format!(r#"file {:?}, section "{:?}", key "{}""#,
143                                self.loc, self.section, self.key))?
144   }
145 }
146
147 pub struct Config {
148   opts: Opts,
149 }
150
151 static OUTSIDE_SECTION: &str = "[";
152 static SPECIAL_SERVER_SECTION: &str = "SERVER";
153
154 #[derive(Default,Debug)]
155 struct Aggregate {
156   sections: HashMap<SectionName, SectionMap>,
157 }
158
159 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
160 #[ext]
161 impl<'f,A> OkAnyway<'f,A> {
162   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
163     let e = r.as_ref().err()?;
164     let k = e.kind();
165     let a = self(k)?;
166     Some(a)
167   }
168 }
169
170 impl FromStr for SectionName {
171   type Err = AE;
172   #[throws(AE)]
173   fn from_str(s: &str) -> Self {
174     match s {
175       "COMMON" => return SN::Common,
176       "LIMIT" => return SN::GlobalLimit,
177       _ => { }
178     };
179     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
180     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
181     let (server, client) = s.split_ascii_whitespace().collect_tuple()
182       .ok_or_else(|| anyhow!(
183         "bad section name {:?} \
184          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
185         s
186       ))?;
187     let server = server.parse().context("server name in link section name")?;
188     if client == "LIMIT" { return SN::ServerLimit(server) }
189     let client = client.parse().context("client name in link section name")?;
190     SN::Link(LinkName { server, client })
191   }
192 }
193
194 impl Aggregate {
195   #[throws(AE)] // AE does not include path
196   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
197   {
198     let f = fs::File::open(path);
199     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
200     let mut f = f.context("open")?;
201
202     let mut s = String::new();
203     let y = f.read_to_string(&mut s);
204     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
205     y.context("read")?;
206
207     self.read_string(s, path)?;
208     None
209   }
210
211   #[throws(AE)] // AE does not include path
212   fn read_string(&mut self, s: String, path_for_loc: &Path) {
213     let mut ini = Ini::new_cs();
214     ini.set_default_section(OUTSIDE_SECTION);
215     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
216     let map = mem::take(ini.get_mut_map());
217     if map.get(OUTSIDE_SECTION).is_some() {
218       throw!(anyhow!("INI file contains settings outside a section"));
219     }
220
221     let loc = Arc::new(path_for_loc.to_owned());
222
223     for (sn, vars) in map {
224       //dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
225
226       let sn = sn.parse().dcontext(&sn)?;
227       let ent = self.sections.entry(sn).or_default();
228       for (key, raw) in vars {
229         let raw = match raw {
230           Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
231             (||{
232               if raw.contains('\\') {
233                 throw!(
234                   anyhow!("quoted value contains backslash, not supported")
235                 );
236               }
237               let unq = raw[1..].strip_suffix(&raw[0..1])
238                 .ok_or_else(
239                   || anyhow!("mismatched quotes around quoted value")
240                 )?
241                 .to_owned();
242               Ok::<_,AE>(unq)
243             })()
244               .with_context(|| format!("key {:?}", key))
245               .dcontext(path_for_loc)?
246           ),
247           x => x,
248         };
249         let key = key.replace('-',"_");
250         ent.insert(key, RawVal { raw, loc: loc.clone() });
251       }
252     }
253   }
254
255   #[throws(AE)] // AE includes path
256   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
257   {
258     let dir = fs::read_dir(path);
259     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
260     let dir = dir.context("open directory").dcontext(path)?;
261     for ent in dir {
262       let ent = ent.context("read directory").dcontext(path)?;
263       let leaf = ent.file_name();
264       let leaf = leaf.to_str();
265       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
266       if leaf.len() == 0 { continue }
267       if ! leaf.chars().all(
268         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
269       ) { continue }
270
271       // OK we want this one
272       let ent = ent.path();
273       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
274     }
275     None
276   }
277
278   #[throws(AE)] // AE includes everything
279   fn read_toplevel(&mut self, toplevel: &Path) {
280     enum Anyway { None, Dir }
281     match self.read_file(toplevel, &|k| match k {
282       EK::NotFound => Some(Anyway::None),
283       EK::IsADirectory => Some(Anyway::Dir),
284       _ => None,
285     })
286       .dcontext(toplevel).context("top-level config directory (or file)")?
287     {
288       None | Some(Anyway::None) => { },
289
290       Some(Anyway::Dir) => {
291         struct AnywayNone;
292         let anyway_none = |k| match k {
293           EK::NotFound => Some(AnywayNone),
294           _ => None,
295         };
296
297         let mk = |leaf: &str| {
298           [ toplevel, &PathBuf::from(leaf) ]
299             .iter().collect::<PathBuf>()
300         };
301
302         for &(try_main, desc) in &[
303           ("main.cfg", "main config file"),
304           ("master.cfg", "obsolete-named main config file"),
305         ] {
306           let main = mk(try_main);
307
308           match self.read_file(&main, &anyway_none)
309             .dcontext(main).context(desc)?
310           {
311             None => break,
312             Some(AnywayNone) => { },
313           }
314         }
315
316         for &(try_dir, desc) in &[
317           ("config.d", "per-link config directory"),
318           ("secrets.d", "per-link secrets directory"),
319         ] {
320           let dir = mk(try_dir);
321           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
322             None => { },
323             Some(AnywayNone) => { },
324           }
325         }
326       }
327     }
328   }
329
330   #[throws(AE)] // AE includes extra, but does that this is extra
331   fn read_extra(&mut self, extra: &Path) {
332     struct AnywayDir;
333
334     match self.read_file(extra, &|k| match k {
335       EK::IsADirectory => Some(AnywayDir),
336       _ => None,
337     })
338       .dcontext(extra)?
339     {
340       None => return,
341       Some(AnywayDir) => {
342         self.read_dir_d(extra, &|_| None::<Void>)?;
343       }
344     }
345
346   }
347 }
348
349 impl Aggregate {
350   fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
351     let mut links:              BTreeSet<LinkName> = default();
352
353     let mut secrets_anyserver:  BTreeSet<&ClientName> = default();
354     let mut secrets_anyclient:  BTreeSet<&ServerName> = default();
355     let mut secret_global       = false;
356
357     let mut putative_servers   = BTreeSet::new();
358     let mut putative_clients   = BTreeSet::new();
359
360     let mut note_server = |s| {
361       if let Some(only) = only_server { if s != only { return false } }
362       putative_servers.insert(s);
363       true
364     };
365     let mut note_client = |c| {
366       putative_clients.insert(c);
367     };
368
369     for (section, vars) in &self.sections {
370       let has_secret = || vars.contains_key("secret");
371
372       match section {
373         SN::Link(l) => {
374           if ! note_server(&l.server) { continue }
375           note_client(&l.client);
376           if has_secret() { links.insert(l.clone()); }
377         },
378         SN::Server(ref s) => {
379           if ! note_server(s) { continue }
380           if has_secret() { secrets_anyclient.insert(s); }
381         },
382         SN::Client(ref c) => {
383           note_client(c);
384           if has_secret() { secrets_anyserver.insert(c); }
385         },
386         SN::Common => {
387           if has_secret() { secret_global = true; }
388         },
389         _ => { },
390       }
391     }
392
393     // Add links which are justified by blanket secrets
394     for (client, server) in iproduct!(
395       putative_clients.into_iter().filter(
396         |c| secret_global || secrets_anyserver.contains(c)
397       ),
398       putative_servers.iter().cloned().filter(
399         |s| secret_global || secrets_anyclient.contains(s)
400       )
401     ) {
402       links.insert(LinkName {
403         client: client.clone(),
404         server: server.clone(),
405       });
406     }
407
408     links
409   }
410 }
411
412 struct ResolveContext<'c> {
413   agg: &'c Aggregate,
414   link: &'c LinkName,
415   end: LinkEnd,
416   all_sections: Vec<SectionName>,
417 }
418
419 trait Parseable: Sized {
420   fn parse(s: Option<&str>) -> Result<Self, AE>;
421   fn default() -> Result<Self, AE> {
422     Err(anyhow!("setting must be specified"))
423   }
424   #[throws(AE)]
425   fn default_for_key(key: &str) -> Self {
426     Self::default().with_context(|| key.to_string())?
427   }
428 }
429
430 impl Parseable for Duration {
431   #[throws(AE)]
432   fn parse(s: Option<&str>) -> Duration {
433     // todo: would be nice to parse with humantime maybe
434     Duration::from_secs( s.value()?.parse()? )
435   }
436 }
437 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
438   impl Parseable for $t {
439     #[throws(AE)]
440     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
441     $( #[throws(AE)] fn default() -> Self { $def } )?
442   }
443 } }
444 parseable_from_str!{u16, default() }
445 parseable_from_str!{u32, default() }
446 parseable_from_str!{String, default() }
447 parseable_from_str!{IpNet, default() }
448 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
449 parseable_from_str!{Uri, default() }
450
451 impl<T:Parseable> Parseable for Vec<T> {
452   #[throws(AE)]
453   fn parse(s: Option<&str>) -> Vec<T> {
454     s.value()?
455       .split_ascii_whitespace()
456       .map(|s| Parseable::parse(Some(s)))
457       .collect::<Result<Vec<_>,_>>()?
458   }
459   #[throws(AE)]
460   fn default() -> Self { default() }
461 }
462
463
464 #[derive(Debug,Copy,Clone)]
465 enum SectionKindList {
466   Ordinary,
467   Limited,
468   Limits,
469   ClientAgnostic,
470   ServerName,
471 }
472 use SectionKindList as SKL;
473
474 impl SectionName {
475   fn special_server_section() -> Self { SN::Server(ServerName(
476     SPECIAL_SERVER_SECTION.into()
477   )) }
478 }
479
480 impl SectionKindList {
481   fn contains(self, s: &SectionName) -> bool {
482     match self {
483       SKL::Ordinary       => matches!(s, SN::Link(_)
484                                        | SN::Client(_)
485                                        | SN::Server(_)
486                                        | SN::Common),
487
488       SKL::Limits         => matches!(s, SN::ServerLimit(_)
489                                        | SN::GlobalLimit),
490
491       SKL::ClientAgnostic => matches!(s, SN::Common
492                                        | SN::Server(_)),
493
494       SKL::Limited        => SKL::Ordinary.contains(s)
495                            | SKL::Limits  .contains(s),
496
497       SKL::ServerName     => matches!(s, SN::Common)
498                            | matches!(s, SN::Server(ServerName(name))
499                                          if name == SPECIAL_SERVER_SECTION),
500     }
501   }
502 }
503
504 impl Aggregate {
505   fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
506                        -> Option<RawValRef<'a,'a,'s>>
507   where S: Iterator<Item=&'s SectionName>
508   {
509     for section in sections {
510       if let Some(raw) = self.sections
511         .get(section)
512         .and_then(|vars: &SectionMap| vars.get(key))
513       {
514         return Some(RawValRef {
515           raw: raw.raw.as_deref(),
516           loc: &raw.loc,
517           section, key,
518         })
519       }
520     }
521     None
522   }
523
524   #[throws(AE)]
525   pub fn establish_server_name(&self) -> ServerName {
526     let key = "server";
527     let raw = match self.lookup_raw(
528       key,
529       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
530     ) {
531       Some(raw) => raw.try_map(|os| os.value())?,
532       None => SPECIAL_SERVER_SECTION,
533     };
534     ServerName(raw.into())
535   }
536 }
537
538 impl<'c> ResolveContext<'c> {
539   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
540                   -> Option<RawValRef<'c,'c,'c>> {
541     self.agg.lookup_raw(
542       key,
543       self.all_sections.iter()
544         .filter(|s| sections.contains(s))
545     )
546   }
547
548   #[throws(AE)]
549   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
550                  -> Option<T>
551   where T: Parseable
552   {
553     match self.first_of_raw(key, sections) {
554       None => None,
555       Some(raw) => Some(raw.try_map(Parseable::parse)?),
556     }
557   }
558
559   #[throws(AE)]
560   pub fn ordinary<T>(&self, key: &'static str) -> T
561   where T: Parseable
562   {
563     match self.first_of(key, SKL::Ordinary)? {
564       Some(y) => y,
565       None => Parseable::default_for_key(key)?,
566     }
567   }
568
569   #[throws(AE)]
570   pub fn limited<T>(&self, key: &'static str) -> T
571   where T: Parseable + Ord
572   {
573     let val = self.ordinary(key)?;
574     if let Some(limit) = self.first_of(key, SKL::Limits)? {
575       min(val, limit)
576     } else {
577       val
578     }
579   }
580
581   #[throws(AE)]
582   pub fn client<T>(&self, key: &'static str) -> T
583   where T: Parseable + Default {
584     match self.end {
585       LinkEnd::Client => self.ordinary(key)?,
586       LinkEnd::Server => default(),
587     }
588   }
589   #[throws(AE)]
590   pub fn server<T>(&self, key: &'static str) -> T
591   where T: Parseable + Default {
592     match self.end {
593       LinkEnd::Server => self.ordinary(key)?,
594       LinkEnd::Client => default(),
595     }
596   }
597
598   #[throws(AE)]
599   pub fn special_ipif(&self, key: &'static str) -> String {
600     match self.end {
601       LinkEnd::Client => self.ordinary(key)?,
602       LinkEnd::Server => {
603         self.first_of(key, SKL::ClientAgnostic)?
604           .unwrap_or_default()
605       },
606     }
607   }
608
609   #[throws(AE)]
610   pub fn special_server(&self, key: &'static str) -> ServerName {
611     self.link.server.clone()
612   }
613 }
614
615 impl InstanceConfig {
616   #[throws(AE)]
617   fn complete(&mut self, end: LinkEnd) {
618     let mut vhosts = self.vnetwork.iter()
619       .map(|n| n.hosts()).flatten()
620       .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
621
622     if self.vaddr.is_unspecified() {
623       self.vaddr = vhosts.next().ok_or_else(
624         || anyhow!("vnetwork too small to generate vaddrr")
625       )?;
626     }
627     if self.vrelay.is_unspecified() {
628       self.vrelay = vhosts.next().ok_or_else(
629         || anyhow!("vnetwork too small to generate vrelay")
630       )?;
631     }
632
633     match end {
634       LinkEnd::Client => {
635         if &self.url == &default::<Uri>() {
636           let addr = self.addrs.get(0).ok_or_else(
637             || anyhow!("client needs addrs or url set")
638           )?;
639           self.url = format!(
640             "http://{}{}/",
641             match addr {
642               IpAddr::V4(a) => format!("{}", a),
643               IpAddr::V6(a) => format!("[{}]", a),
644             },
645             match self.port {
646               80 => format!(""),
647               p => format!(":{}", p),
648             })
649             .parse().unwrap()
650         }
651       },
652
653       LinkEnd::Server => {
654         if self.addrs.is_empty() {
655           throw!(anyhow!("missing 'addrs' setting"))
656         }
657       },
658     }
659   }
660 }
661
662 #[throws(AE)]
663 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
664   let opts = config::Opts::from_args();
665
666   let agg = (||{
667     let mut agg = Aggregate::default();
668
669     agg.read_string(DEFAULT_CONFIG.into(),
670                     "<build-in defaults>".as_ref()).unwrap();
671
672     agg.read_toplevel(&opts.config)?;
673     for extra in &opts.extra_config {
674       agg.read_extra(extra).context("extra config")?;
675     }
676
677     eprintln!("GOT {:#?}", agg);
678
679     Ok::<_,AE>(agg)
680   })().context("read configuration")?;
681
682   let server_name = match end {
683     LinkEnd::Server => Some(agg.establish_server_name()?),
684     LinkEnd::Client => None,
685   };
686
687   let instances = agg.instances(server_name.as_ref());
688   let mut ics = vec![];
689
690   for link in instances {
691     let rctx = ResolveContext {
692       agg: &agg,
693       link: &link,
694       end,
695       all_sections: vec![
696         SN::Link(link.clone()),
697         SN::Client(link.client.clone()),
698         SN::Server(link.server.clone()),
699         SN::Common,
700         SN::ServerLimit(link.server.clone()),
701         SN::GlobalLimit,
702       ],
703     };
704
705     let mut ic = InstanceConfig::resolve_instance(&rctx)
706       .with_context(|| format!(r#"resolve config for "{:?}""#, &link))?;
707
708     ic.complete(end)
709       .with_context(|| format!(r#"complete config for "{:?}""#, &link))?;
710
711     ics.push(ic);
712   }
713
714   ics
715 }