chiark / gitweb /
config: better display
[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 impl Display for SectionName {
194   #[throws(fmt::Error)]
195   fn fmt(&self, f: &mut fmt::Formatter) {
196     match self {
197       SN::Link  (ref l)      => Display::fmt(l, f)?,
198       SN::Client(ref c)      => write!(f, "[{}]"       , c)?,
199       SN::Server(ref s)      => write!(f, "[{}]"       , s)?,
200       SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
201       SN::GlobalLimit        => write!(f, "[LIMIT]"       )?,
202       SN::Common             => write!(f, "[COMMON]"      )?,
203     }
204   }
205 }
206
207 impl Aggregate {
208   #[throws(AE)] // AE does not include path
209   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
210   {
211     let f = fs::File::open(path);
212     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
213     let mut f = f.context("open")?;
214
215     let mut s = String::new();
216     let y = f.read_to_string(&mut s);
217     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
218     y.context("read")?;
219
220     self.read_string(s, path)?;
221     None
222   }
223
224   #[throws(AE)] // AE does not include path
225   fn read_string(&mut self, s: String, path_for_loc: &Path) {
226     let mut ini = Ini::new_cs();
227     ini.set_default_section(OUTSIDE_SECTION);
228     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
229     let map = mem::take(ini.get_mut_map());
230     if map.get(OUTSIDE_SECTION).is_some() {
231       throw!(anyhow!("INI file contains settings outside a section"));
232     }
233
234     let loc = Arc::new(path_for_loc.to_owned());
235
236     for (sn, vars) in map {
237       //dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
238
239       let sn = sn.parse().dcontext(&sn)?;
240       let ent = self.sections.entry(sn).or_default();
241       for (key, raw) in vars {
242         let raw = match raw {
243           Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
244             (||{
245               if raw.contains('\\') {
246                 throw!(
247                   anyhow!("quoted value contains backslash, not supported")
248                 );
249               }
250               let unq = raw[1..].strip_suffix(&raw[0..1])
251                 .ok_or_else(
252                   || anyhow!("mismatched quotes around quoted value")
253                 )?
254                 .to_owned();
255               Ok::<_,AE>(unq)
256             })()
257               .with_context(|| format!("key {:?}", key))
258               .dcontext(path_for_loc)?
259           ),
260           x => x,
261         };
262         let key = key.replace('-',"_");
263         ent.insert(key, RawVal { raw, loc: loc.clone() });
264       }
265     }
266   }
267
268   #[throws(AE)] // AE includes path
269   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
270   {
271     let dir = fs::read_dir(path);
272     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
273     let dir = dir.context("open directory").dcontext(path)?;
274     for ent in dir {
275       let ent = ent.context("read directory").dcontext(path)?;
276       let leaf = ent.file_name();
277       let leaf = leaf.to_str();
278       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
279       if leaf.len() == 0 { continue }
280       if ! leaf.chars().all(
281         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
282       ) { continue }
283
284       // OK we want this one
285       let ent = ent.path();
286       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
287     }
288     None
289   }
290
291   #[throws(AE)] // AE includes everything
292   fn read_toplevel(&mut self, toplevel: &Path) {
293     enum Anyway { None, Dir }
294     match self.read_file(toplevel, &|k| match k {
295       EK::NotFound => Some(Anyway::None),
296       EK::IsADirectory => Some(Anyway::Dir),
297       _ => None,
298     })
299       .dcontext(toplevel).context("top-level config directory (or file)")?
300     {
301       None | Some(Anyway::None) => { },
302
303       Some(Anyway::Dir) => {
304         struct AnywayNone;
305         let anyway_none = |k| match k {
306           EK::NotFound => Some(AnywayNone),
307           _ => None,
308         };
309
310         let mk = |leaf: &str| {
311           [ toplevel, &PathBuf::from(leaf) ]
312             .iter().collect::<PathBuf>()
313         };
314
315         for &(try_main, desc) in &[
316           ("main.cfg", "main config file"),
317           ("master.cfg", "obsolete-named main config file"),
318         ] {
319           let main = mk(try_main);
320
321           match self.read_file(&main, &anyway_none)
322             .dcontext(main).context(desc)?
323           {
324             None => break,
325             Some(AnywayNone) => { },
326           }
327         }
328
329         for &(try_dir, desc) in &[
330           ("config.d", "per-link config directory"),
331           ("secrets.d", "per-link secrets directory"),
332         ] {
333           let dir = mk(try_dir);
334           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
335             None => { },
336             Some(AnywayNone) => { },
337           }
338         }
339       }
340     }
341   }
342
343   #[throws(AE)] // AE includes extra, but does that this is extra
344   fn read_extra(&mut self, extra: &Path) {
345     struct AnywayDir;
346
347     match self.read_file(extra, &|k| match k {
348       EK::IsADirectory => Some(AnywayDir),
349       _ => None,
350     })
351       .dcontext(extra)?
352     {
353       None => return,
354       Some(AnywayDir) => {
355         self.read_dir_d(extra, &|_| None::<Void>)?;
356       }
357     }
358
359   }
360 }
361
362 impl Aggregate {
363   fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
364     let mut links:              BTreeSet<LinkName> = default();
365
366     let mut secrets_anyserver:  BTreeSet<&ClientName> = default();
367     let mut secrets_anyclient:  BTreeSet<&ServerName> = default();
368     let mut secret_global       = false;
369
370     let mut putative_servers   = BTreeSet::new();
371     let mut putative_clients   = BTreeSet::new();
372
373     let mut note_server = |s| {
374       if let Some(only) = only_server { if s != only { return false } }
375       putative_servers.insert(s);
376       true
377     };
378     let mut note_client = |c| {
379       putative_clients.insert(c);
380     };
381
382     for (section, vars) in &self.sections {
383       let has_secret = || vars.contains_key("secret");
384
385       match section {
386         SN::Link(l) => {
387           if ! note_server(&l.server) { continue }
388           note_client(&l.client);
389           if has_secret() { links.insert(l.clone()); }
390         },
391         SN::Server(ref s) => {
392           if ! note_server(s) { continue }
393           if has_secret() { secrets_anyclient.insert(s); }
394         },
395         SN::Client(ref c) => {
396           note_client(c);
397           if has_secret() { secrets_anyserver.insert(c); }
398         },
399         SN::Common => {
400           if has_secret() { secret_global = true; }
401         },
402         _ => { },
403       }
404     }
405
406     // Add links which are justified by blanket secrets
407     for (client, server) in iproduct!(
408       putative_clients.into_iter().filter(
409         |c| secret_global || secrets_anyserver.contains(c)
410       ),
411       putative_servers.iter().cloned().filter(
412         |s| secret_global || secrets_anyclient.contains(s)
413       )
414     ) {
415       links.insert(LinkName {
416         client: client.clone(),
417         server: server.clone(),
418       });
419     }
420
421     links
422   }
423 }
424
425 struct ResolveContext<'c> {
426   agg: &'c Aggregate,
427   link: &'c LinkName,
428   end: LinkEnd,
429   all_sections: Vec<SectionName>,
430 }
431
432 trait Parseable: Sized {
433   fn parse(s: Option<&str>) -> Result<Self, AE>;
434   fn default() -> Result<Self, AE> {
435     Err(anyhow!("setting must be specified"))
436   }
437   #[throws(AE)]
438   fn default_for_key(key: &str) -> Self {
439     Self::default().with_context(|| key.to_string())?
440   }
441 }
442
443 impl Parseable for Duration {
444   #[throws(AE)]
445   fn parse(s: Option<&str>) -> Duration {
446     // todo: would be nice to parse with humantime maybe
447     Duration::from_secs( s.value()?.parse()? )
448   }
449 }
450 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
451   impl Parseable for $t {
452     #[throws(AE)]
453     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
454     $( #[throws(AE)] fn default() -> Self { $def } )?
455   }
456 } }
457 parseable_from_str!{u16, default() }
458 parseable_from_str!{u32, default() }
459 parseable_from_str!{String, default() }
460 parseable_from_str!{IpNet, default() }
461 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
462 parseable_from_str!{Uri, default() }
463
464 impl<T:Parseable> Parseable for Vec<T> {
465   #[throws(AE)]
466   fn parse(s: Option<&str>) -> Vec<T> {
467     s.value()?
468       .split_ascii_whitespace()
469       .map(|s| Parseable::parse(Some(s)))
470       .collect::<Result<Vec<_>,_>>()?
471   }
472   #[throws(AE)]
473   fn default() -> Self { default() }
474 }
475
476
477 #[derive(Debug,Copy,Clone)]
478 enum SectionKindList {
479   Ordinary,
480   Limited,
481   Limits,
482   ClientAgnostic,
483   ServerName,
484 }
485 use SectionKindList as SKL;
486
487 impl SectionName {
488   fn special_server_section() -> Self { SN::Server(ServerName(
489     SPECIAL_SERVER_SECTION.into()
490   )) }
491 }
492
493 impl SectionKindList {
494   fn contains(self, s: &SectionName) -> bool {
495     match self {
496       SKL::Ordinary       => matches!(s, SN::Link(_)
497                                        | SN::Client(_)
498                                        | SN::Server(_)
499                                        | SN::Common),
500
501       SKL::Limits         => matches!(s, SN::ServerLimit(_)
502                                        | SN::GlobalLimit),
503
504       SKL::ClientAgnostic => matches!(s, SN::Common
505                                        | SN::Server(_)),
506
507       SKL::Limited        => SKL::Ordinary.contains(s)
508                            | SKL::Limits  .contains(s),
509
510       SKL::ServerName     => matches!(s, SN::Common)
511                            | matches!(s, SN::Server(ServerName(name))
512                                          if name == SPECIAL_SERVER_SECTION),
513     }
514   }
515 }
516
517 impl Aggregate {
518   fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
519                        -> Option<RawValRef<'a,'a,'s>>
520   where S: Iterator<Item=&'s SectionName>
521   {
522     for section in sections {
523       if let Some(raw) = self.sections
524         .get(section)
525         .and_then(|vars: &SectionMap| vars.get(key))
526       {
527         return Some(RawValRef {
528           raw: raw.raw.as_deref(),
529           loc: &raw.loc,
530           section, key,
531         })
532       }
533     }
534     None
535   }
536
537   #[throws(AE)]
538   pub fn establish_server_name(&self) -> ServerName {
539     let key = "server";
540     let raw = match self.lookup_raw(
541       key,
542       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
543     ) {
544       Some(raw) => raw.try_map(|os| os.value())?,
545       None => SPECIAL_SERVER_SECTION,
546     };
547     ServerName(raw.into())
548   }
549 }
550
551 impl<'c> ResolveContext<'c> {
552   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
553                   -> Option<RawValRef<'c,'c,'c>> {
554     self.agg.lookup_raw(
555       key,
556       self.all_sections.iter()
557         .filter(|s| sections.contains(s))
558     )
559   }
560
561   #[throws(AE)]
562   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
563                  -> Option<T>
564   where T: Parseable
565   {
566     match self.first_of_raw(key, sections) {
567       None => None,
568       Some(raw) => Some(raw.try_map(Parseable::parse)?),
569     }
570   }
571
572   #[throws(AE)]
573   pub fn ordinary<T>(&self, key: &'static str) -> T
574   where T: Parseable
575   {
576     match self.first_of(key, SKL::Ordinary)? {
577       Some(y) => y,
578       None => Parseable::default_for_key(key)?,
579     }
580   }
581
582   #[throws(AE)]
583   pub fn limited<T>(&self, key: &'static str) -> T
584   where T: Parseable + Ord
585   {
586     let val = self.ordinary(key)?;
587     if let Some(limit) = self.first_of(key, SKL::Limits)? {
588       min(val, limit)
589     } else {
590       val
591     }
592   }
593
594   #[throws(AE)]
595   pub fn client<T>(&self, key: &'static str) -> T
596   where T: Parseable + Default {
597     match self.end {
598       LinkEnd::Client => self.ordinary(key)?,
599       LinkEnd::Server => default(),
600     }
601   }
602   #[throws(AE)]
603   pub fn server<T>(&self, key: &'static str) -> T
604   where T: Parseable + Default {
605     match self.end {
606       LinkEnd::Server => self.ordinary(key)?,
607       LinkEnd::Client => default(),
608     }
609   }
610
611   #[throws(AE)]
612   pub fn special_ipif(&self, key: &'static str) -> String {
613     match self.end {
614       LinkEnd::Client => self.ordinary(key)?,
615       LinkEnd::Server => {
616         self.first_of(key, SKL::ClientAgnostic)?
617           .unwrap_or_default()
618       },
619     }
620   }
621
622   #[throws(AE)]
623   pub fn special_server(&self, key: &'static str) -> ServerName {
624     self.link.server.clone()
625   }
626 }
627
628 impl InstanceConfig {
629   #[throws(AE)]
630   fn complete(&mut self, end: LinkEnd) {
631     let mut vhosts = self.vnetwork.iter()
632       .map(|n| n.hosts()).flatten()
633       .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
634
635     if self.vaddr.is_unspecified() {
636       self.vaddr = vhosts.next().ok_or_else(
637         || anyhow!("vnetwork too small to generate vaddrr")
638       )?;
639     }
640     if self.vrelay.is_unspecified() {
641       self.vrelay = vhosts.next().ok_or_else(
642         || anyhow!("vnetwork too small to generate vrelay")
643       )?;
644     }
645
646     match end {
647       LinkEnd::Client => {
648         if &self.url == &default::<Uri>() {
649           let addr = self.addrs.get(0).ok_or_else(
650             || anyhow!("client needs addrs or url set")
651           )?;
652           self.url = format!(
653             "http://{}{}/",
654             match addr {
655               IpAddr::V4(a) => format!("{}", a),
656               IpAddr::V6(a) => format!("[{}]", a),
657             },
658             match self.port {
659               80 => format!(""),
660               p => format!(":{}", p),
661             })
662             .parse().unwrap()
663         }
664       },
665
666       LinkEnd::Server => {
667         if self.addrs.is_empty() {
668           throw!(anyhow!("missing 'addrs' setting"))
669         }
670       },
671     }
672   }
673 }
674
675 #[throws(AE)]
676 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
677   let opts = config::Opts::from_args();
678
679   let agg = (||{
680     let mut agg = Aggregate::default();
681
682     agg.read_string(DEFAULT_CONFIG.into(),
683                     "<build-in defaults>".as_ref()).unwrap();
684
685     agg.read_toplevel(&opts.config)?;
686     for extra in &opts.extra_config {
687       agg.read_extra(extra).context("extra config")?;
688     }
689
690     eprintln!("GOT {:#?}", agg);
691
692     Ok::<_,AE>(agg)
693   })().context("read configuration")?;
694
695   let server_name = match end {
696     LinkEnd::Server => Some(agg.establish_server_name()?),
697     LinkEnd::Client => None,
698   };
699
700   let instances = agg.instances(server_name.as_ref());
701   let mut ics = vec![];
702
703   for link in instances {
704     let rctx = ResolveContext {
705       agg: &agg,
706       link: &link,
707       end,
708       all_sections: vec![
709         SN::Link(link.clone()),
710         SN::Client(link.client.clone()),
711         SN::Server(link.server.clone()),
712         SN::Common,
713         SN::ServerLimit(link.server.clone()),
714         SN::GlobalLimit,
715       ],
716     };
717
718     let mut ic = InstanceConfig::resolve_instance(&rctx)
719       .with_context(|| format!("resolve config for {}", &link))?;
720
721     ic.complete(end)
722       .with_context(|| format!("complete config for {}", &link))?;
723
724     ics.push(ic);
725   }
726
727   ics
728 }