chiark / gitweb /
config: fix client/server-specific parsing
[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:                        Vec<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         self.sections.entry(sn)
228         .or_default()
229         .extend(
230           vars.into_iter()
231             .map(|(k,raw)| {
232               (k.replace('-',"_"),
233                RawVal { raw, loc: loc.clone() })
234             })
235         );
236     }
237     
238   }
239
240   #[throws(AE)] // AE includes path
241   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
242   {
243     let dir = fs::read_dir(path);
244     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
245     let dir = dir.context("open directory").dcontext(path)?;
246     for ent in dir {
247       let ent = ent.context("read directory").dcontext(path)?;
248       let leaf = ent.file_name();
249       let leaf = leaf.to_str();
250       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
251       if leaf.len() == 0 { continue }
252       if ! leaf.chars().all(
253         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
254       ) { continue }
255
256       // OK we want this one
257       let ent = ent.path();
258       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
259     }
260     None
261   }
262
263   #[throws(AE)] // AE includes everything
264   fn read_toplevel(&mut self, toplevel: &Path) {
265     enum Anyway { None, Dir }
266     match self.read_file(toplevel, &|k| match k {
267       EK::NotFound => Some(Anyway::None),
268       EK::IsADirectory => Some(Anyway::Dir),
269       _ => None,
270     })
271       .dcontext(toplevel).context("top-level config directory (or file)")?
272     {
273       None | Some(Anyway::None) => { },
274
275       Some(Anyway::Dir) => {
276         struct AnywayNone;
277         let anyway_none = |k| match k {
278           EK::NotFound => Some(AnywayNone),
279           _ => None,
280         };
281
282         let mk = |leaf: &str| {
283           [ toplevel, &PathBuf::from(leaf) ]
284             .iter().collect::<PathBuf>()
285         };
286
287         for &(try_main, desc) in &[
288           ("main.cfg", "main config file"),
289           ("master.cfg", "obsolete-named main config file"),
290         ] {
291           let main = mk(try_main);
292
293           match self.read_file(&main, &anyway_none)
294             .dcontext(main).context(desc)?
295           {
296             None => break,
297             Some(AnywayNone) => { },
298           }
299         }
300
301         for &(try_dir, desc) in &[
302           ("config.d", "per-link config directory"),
303           ("secrets.d", "per-link secrets directory"),
304         ] {
305           let dir = mk(try_dir);
306           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
307             None => { },
308             Some(AnywayNone) => { },
309           }
310         }
311       }
312     }
313   }
314
315   #[throws(AE)] // AE includes extra, but does that this is extra
316   fn read_extra(&mut self, extra: &Path) {
317     struct AnywayDir;
318
319     match self.read_file(extra, &|k| match k {
320       EK::IsADirectory => Some(AnywayDir),
321       _ => None,
322     })
323       .dcontext(extra)?
324     {
325       None => return,
326       Some(AnywayDir) => {
327         self.read_dir_d(extra, &|_| None::<Void>)?;
328       }
329     }
330
331   }
332 }
333
334 impl Aggregate {
335   fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
336     let mut links:              BTreeSet<LinkName> = default();
337
338     let mut secrets_anyserver:  BTreeSet<&ClientName> = default();
339     let mut secrets_anyclient:  BTreeSet<&ServerName> = default();
340     let mut secret_global       = false;
341
342     let mut putative_servers   = BTreeSet::new();
343     let mut putative_clients   = BTreeSet::new();
344
345     let mut note_server = |s| {
346       if let Some(only) = only_server { if s != only { return false } }
347       putative_servers.insert(s);
348       true
349     };
350     let mut note_client = |c| {
351       putative_clients.insert(c);
352     };
353
354     for (section, vars) in &self.sections {
355       let has_secret = || vars.contains_key("secret");
356
357       match section {
358         SN::Link(l) => {
359           if ! note_server(&l.server) { continue }
360           note_client(&l.client);
361           if has_secret() { links.insert(l.clone()); }
362         },
363         SN::Server(ref s) => {
364           if ! note_server(s) { continue }
365           if has_secret() { secrets_anyclient.insert(s); }
366         },
367         SN::Client(ref c) => {
368           note_client(c);
369           if has_secret() { secrets_anyserver.insert(c); }
370         },
371         SN::Common => {
372           if has_secret() { secret_global = true; }
373         },
374         _ => { },
375       }
376     }
377
378     // Add links which are justified by blanket secrets
379     for (client, server) in iproduct!(
380       putative_clients.into_iter().filter(
381         |c| secret_global || secrets_anyserver.contains(c)
382       ),
383       putative_servers.iter().cloned().filter(
384         |s| secret_global || secrets_anyclient.contains(s)
385       )
386     ) {
387       links.insert(LinkName {
388         client: client.clone(),
389         server: server.clone(),
390       });
391     }
392
393     links
394   }
395 }
396
397 struct ResolveContext<'c> {
398   agg: &'c Aggregate,
399   link: &'c LinkName,
400   end: LinkEnd,
401   all_sections: Vec<SectionName>,
402 }
403
404 trait Parseable: Sized {
405   fn parse(s: Option<&str>) -> Result<Self, AE>;
406   fn default() -> Result<Self, AE> {
407     Err(anyhow!("setting must be specified"))
408   }
409   #[throws(AE)]
410   fn default_for_key(key: &str) -> Self {
411     Self::default().with_context(|| key.to_string())?
412   }
413 }
414
415 impl Parseable for Duration {
416   #[throws(AE)]
417   fn parse(s: Option<&str>) -> Duration {
418     // todo: would be nice to parse with humantime maybe
419     Duration::from_secs( s.value()?.parse()? )
420   }
421 }
422 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
423   impl Parseable for $t {
424     #[throws(AE)]
425     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
426     $( #[throws(AE)] fn default() -> Self { $def } )?
427   }
428 } }
429 parseable_from_str!{u16, default() }
430 parseable_from_str!{u32, default() }
431 parseable_from_str!{String, default() }
432 parseable_from_str!{IpNet, default() }
433 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
434 parseable_from_str!{Uri, default() }
435
436 impl<T:Parseable> Parseable for Vec<T> {
437   #[throws(AE)]
438   fn parse(s: Option<&str>) -> Vec<T> {
439     s.value()?
440       .split_ascii_whitespace()
441       .map(|s| Parseable::parse(Some(s)))
442       .collect::<Result<Vec<_>,_>>()?
443   }
444   #[throws(AE)]
445   fn default() -> Self { default() }
446 }
447
448
449 #[derive(Debug,Copy,Clone)]
450 enum SectionKindList {
451   Ordinary,
452   Limited,
453   Limits,
454   ClientAgnostic,
455   ServerName,
456 }
457 use SectionKindList as SKL;
458
459 impl SectionName {
460   fn special_server_section() -> Self { SN::Server(ServerName(
461     SPECIAL_SERVER_SECTION.into()
462   )) }
463 }
464
465 impl SectionKindList {
466   fn contains(self, s: &SectionName) -> bool {
467     match self {
468       SKL::Ordinary       => matches!(s, SN::Link(_)
469                                        | SN::Client(_)
470                                        | SN::Server(_)
471                                        | SN::Common),
472
473       SKL::Limits         => matches!(s, SN::ServerLimit(_)
474                                        | SN::GlobalLimit),
475
476       SKL::ClientAgnostic => matches!(s, SN::Common
477                                        | SN::Server(_)),
478
479       SKL::Limited        => SKL::Ordinary.contains(s)
480                            | SKL::Limits  .contains(s),
481
482       SKL::ServerName     => matches!(s, SN::Common)
483                            | matches!(s, SN::Server(ServerName(name))
484                                          if name == SPECIAL_SERVER_SECTION),
485     }
486   }
487 }
488
489 impl Aggregate {
490   fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
491                        -> Option<RawValRef<'a,'a,'s>>
492   where S: Iterator<Item=&'s SectionName>
493   {
494     for section in sections {
495       if let Some(raw) = self.sections
496         .get(section)
497         .and_then(|vars: &SectionMap| vars.get(key))
498       {
499         return Some(RawValRef {
500           raw: raw.raw.as_deref(),
501           loc: &raw.loc,
502           section, key,
503         })
504       }
505     }
506     None
507   }
508
509   #[throws(AE)]
510   pub fn establish_server_name(&self) -> ServerName {
511     let key = "server";
512     let raw = match self.lookup_raw(
513       key,
514       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
515     ) {
516       Some(raw) => raw.try_map(|os| os.value())?,
517       None => SPECIAL_SERVER_SECTION,
518     };
519     ServerName(raw.into())
520   }
521 }
522
523 impl<'c> ResolveContext<'c> {
524   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
525                   -> Option<RawValRef<'c,'c,'c>> {
526     self.agg.lookup_raw(
527       key,
528       self.all_sections.iter()
529         .filter(|s| sections.contains(s))
530     )
531   }
532
533   #[throws(AE)]
534   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
535                  -> Option<T>
536   where T: Parseable
537   {
538     match self.first_of_raw(key, sections) {
539       None => None,
540       Some(raw) => Some(raw.try_map(Parseable::parse)?),
541     }
542   }
543
544   #[throws(AE)]
545   pub fn ordinary<T>(&self, key: &'static str) -> T
546   where T: Parseable
547   {
548     match self.first_of(key, SKL::Ordinary)? {
549       Some(y) => y,
550       None => Parseable::default_for_key(key)?,
551     }
552   }
553
554   #[throws(AE)]
555   pub fn limited<T>(&self, key: &'static str) -> T
556   where T: Parseable + Ord
557   {
558     let val = self.ordinary(key)?;
559     if let Some(limit) = self.first_of(key, SKL::Limits)? {
560       min(val, limit)
561     } else {
562       val
563     }
564   }
565
566   #[throws(AE)]
567   pub fn client<T>(&self, key: &'static str) -> T
568   where T: Parseable + Default {
569     match self.end {
570       LinkEnd::Client => self.ordinary(key)?,
571       LinkEnd::Server => default(),
572     }
573   }
574   #[throws(AE)]
575   pub fn server<T>(&self, key: &'static str) -> T
576   where T: Parseable + Default {
577     match self.end {
578       LinkEnd::Server => self.ordinary(key)?,
579       LinkEnd::Client => default(),
580     }
581   }
582
583   #[throws(AE)]
584   pub fn special_ipif(&self, key: &'static str) -> String {
585     match self.end {
586       LinkEnd::Client => self.ordinary(key)?,
587       LinkEnd::Server => {
588         self.first_of(key, SKL::ClientAgnostic)?
589           .unwrap_or_default()
590       },
591     }
592   }
593
594   #[throws(AE)]
595   pub fn special_server(&self, key: &'static str) -> ServerName {
596     self.link.server.clone()
597   }
598 }
599
600 #[throws(AE)]
601 pub fn read(end: LinkEnd) -> Vec<InstanceConfig> {
602   let opts = config::Opts::from_args();
603
604   let agg = (||{
605     let mut agg = Aggregate::default();
606
607     agg.read_string(DEFAULT_CONFIG.into(),
608                     "<build-in defaults>".as_ref()).unwrap();
609
610     agg.read_toplevel(&opts.config)?;
611     for extra in &opts.extra_config {
612       agg.read_extra(extra).context("extra config")?;
613     }
614
615     eprintln!("GOT {:#?}", agg);
616
617     Ok::<_,AE>(agg)
618   })().context("read configuration")?;
619
620   let server_name = match end {
621     LinkEnd::Server => Some(agg.establish_server_name()?),
622     LinkEnd::Client => None,
623   };
624
625   let instances = agg.instances(server_name.as_ref());
626   let mut ics = vec![];
627
628   for link in instances {
629     let rctx = ResolveContext {
630       agg: &agg,
631       link: &link,
632       end,
633       all_sections: vec![
634         SN::Link(link.clone()),
635         SN::Client(link.client.clone()),
636         SN::Server(link.server.clone()),
637         SN::Common,
638         SN::ServerLimit(link.server.clone()),
639         SN::GlobalLimit,
640       ],
641     };
642
643     let ic = InstanceConfig::resolve_instance(&rctx)
644       .with_context(|| format!(r#"resolve config for "{:?}""#, &link))?;
645
646     ics.push(ic);
647   }
648
649   ics
650 }