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