chiark / gitweb /
config, wip 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 #[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 pub struct CidrString(pub String);
25
26 #[derive(hippotat_macros::ResolveConfig)]
27 pub struct InstanceConfig {
28 /*
29   // Exceptional settings
30   #[special(special_name, SKL::ServerName)] pub server: String,
31   pub                                           secret: String, // xxx newytpe
32   #[special(special_ipif, SKL::Ordinary)]   pub ipif:   String,
33
34   // Capped settings:
35 */
36   #[limited]    pub max_batch_down:               u32,
37   #[limited]    pub max_queue_time:               Duration,
38   #[limited]    pub http_timeout:                 Duration,
39   #[limited]    pub target_requests_outstanding:  u32,
40
41   // Ordinary settings:
42   pub addrs:                        Vec<IpAddr>,
43   pub vnetwork:                     Vec<CidrString>,
44   pub vaddr:                        Vec<IpAddr>,
45   pub vrelay:                       IpAddr,
46   pub port:                         u16,
47   pub mtu:                          u32,
48   pub ifname_server:                String,
49   pub ifname_client:                String,
50
51   // Ordinary settings, used by server only:
52   #[server]  pub max_clock_skew:               Duration,
53
54   // Ordinary settings, used by client only:
55   #[client]  pub http_timeout_grace:           Duration,
56   #[client]  pub max_requests_outstanding:     u32,
57   #[client]  pub max_batch_up:                 u32,
58   #[client]  pub http_retry:                   Duration,
59   #[client]  pub url:                          Uri,
60   #[client]  pub vroutes:                      Vec<CidrString>,
61 }
62
63 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
64 pub enum SectionName {
65   Link(LinkName),
66   Client(ClientName),
67   Server(ServerName), // includes SERVER, which is slightly special
68   ServerLimit(ServerName),
69   GlobalLimit,
70   Common,
71   Default,
72 }
73 pub use SectionName as SN;
74
75 #[derive(Debug,Clone)]
76 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
77 type SectionMap = HashMap<String, RawVal>;
78
79 pub struct Config {
80   opts: Opts,
81 }
82
83 static OUTSIDE_SECTION: &str = "[";
84
85 #[derive(Default,Debug)]
86 struct Aggregate {
87   sections: HashMap<SectionName, SectionMap>,
88 }
89
90 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
91 #[ext]
92 impl<'f,A> OkAnyway<'f,A> {
93   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
94     let e = r.as_ref().err()?;
95     let k = e.kind();
96     let a = self(k)?;
97     Some(a)
98   }
99 }
100
101 impl FromStr for SectionName {
102   type Err = AE;
103   #[throws(AE)]
104   fn from_str(s: &str) -> Self {
105     match s {
106       "COMMON" => return SN::Common,
107       "DEFAULT" => return SN::Default,
108       "LIMIT" => return SN::GlobalLimit,
109       _ => { }
110     };
111     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
112     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
113     let (server, client) = s.split_ascii_whitespace().collect_tuple()
114       .ok_or_else(|| anyhow!(
115         "bad section name {:?} \
116          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
117         s
118       ))?;
119     let server = server.parse().context("server name in link section name")?;
120     if client == "LIMIT" { return SN::ServerLimit(server) }
121     let client = client.parse().context("client name in link section name")?;
122     SN::Link(LinkName { server, client })
123   }
124 }
125
126 impl Aggregate {
127   #[throws(AE)] // AE does not include path
128   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
129   {
130     let f = fs::File::open(path);
131     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
132     let mut f = f.context("open")?;
133
134     let mut s = String::new();
135     let y = f.read_to_string(&mut s);
136     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
137     y.context("read")?;
138
139     let mut ini = Ini::new_cs();
140     ini.set_default_section(OUTSIDE_SECTION);
141     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
142     let map = mem::take(ini.get_mut_map());
143     if map.get(OUTSIDE_SECTION).is_some() {
144       throw!(anyhow!("INI file contains settings outside a section"));
145     }
146
147     let loc = Arc::new(path.to_owned());
148
149     for (sn, vars) in map {
150       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
151
152       let sn = sn.parse().dcontext(&sn)?;
153         self.sections.entry(sn)
154         .or_default()
155         .extend(
156           vars.into_iter()
157             .map(|(k,val)| {
158               (k.replace('-',"_"),
159                RawVal { val, loc: loc.clone() })
160             })
161         );
162     }
163     None
164   }
165
166   #[throws(AE)] // AE includes path
167   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
168   {
169     let dir = fs::read_dir(path);
170     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
171     let dir = dir.context("open directory").dcontext(path)?;
172     for ent in dir {
173       let ent = ent.context("read directory").dcontext(path)?;
174       let leaf = ent.file_name();
175       let leaf = leaf.to_str();
176       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
177       if leaf.len() == 0 { continue }
178       if ! leaf.chars().all(
179         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
180       ) { continue }
181
182       // OK we want this one
183       let ent = ent.path();
184       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
185     }
186     None
187   }
188
189   #[throws(AE)] // AE includes everything
190   fn read_toplevel(&mut self, toplevel: &Path) {
191     enum Anyway { None, Dir }
192     match self.read_file(toplevel, &|k| match k {
193       EK::NotFound => Some(Anyway::None),
194       EK::IsADirectory => Some(Anyway::Dir),
195       _ => None,
196     })
197       .dcontext(toplevel).context("top-level config directory (or file)")?
198     {
199       None | Some(Anyway::None) => { },
200
201       Some(Anyway::Dir) => {
202         struct AnywayNone;
203         let anyway_none = |k| match k {
204           EK::NotFound => Some(AnywayNone),
205           _ => None,
206         };
207
208         let mk = |leaf: &str| {
209           [ toplevel, &PathBuf::from(leaf) ]
210             .iter().collect::<PathBuf>()
211         };
212
213         for &(try_main, desc) in &[
214           ("main.cfg", "main config file"),
215           ("master.cfg", "obsolete-named main config file"),
216         ] {
217           let main = mk(try_main);
218
219           match self.read_file(&main, &anyway_none)
220             .dcontext(main).context(desc)?
221           {
222             None => break,
223             Some(AnywayNone) => { },
224           }
225         }
226
227         for &(try_dir, desc) in &[
228           ("config.d", "per-link config directory"),
229           ("secrets.d", "per-link secrets directory"),
230         ] {
231           let dir = mk(try_dir);
232           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
233             None => { },
234             Some(AnywayNone) => { },
235           }
236         }
237       }
238     }
239   }
240
241   #[throws(AE)] // AE includes extra, but does that this is extra
242   fn read_extra(&mut self, extra: &Path) {
243     struct AnywayDir;
244
245     match self.read_file(extra, &|k| match k {
246       EK::IsADirectory => Some(AnywayDir),
247       _ => None,
248     })
249       .dcontext(extra)?
250     {
251       None => return,
252       Some(AnywayDir) => {
253         self.read_dir_d(extra, &|_| None::<Void>)?;
254       }
255     }
256
257   }
258 }
259
260 enum LinkEnd { Server, Client }
261
262 struct ResolveContext<'c> {
263   agg: &'c Aggregate,
264   link: &'c LinkName,
265   end: LinkEnd,
266   all_sections: Vec<SectionName>,
267 }
268
269 trait Parseable: Sized {
270   fn parse(s: &Option<String>) -> Result<Self, AE>;
271 }
272
273 impl Parseable for Duration {
274   #[throws(AE)]
275   fn parse(s: &Option<String>) -> Duration {
276     let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
277     if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
278     throw!(anyhow!("xxx parse with humantime"))
279   }
280 }
281 macro_rules! parseable_from_str { ($t:ty) => {
282   impl Parseable for $t {
283     #[throws(AE)]
284     fn parse(s: &Option<String>) -> $t {
285       let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
286       s.parse()?
287     }
288   }
289 } }
290 parseable_from_str!{u32}
291 parseable_from_str!{IpAddr}
292
293 impl<T:Parseable> Parseable for Vec<T> {
294   #[throws(AE)]
295   fn parse(s: &Option<String>) -> Vec<T> {
296     let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
297     s.split_ascii_whitespace()
298       .map(|s| s.parse())
299       .collect::<Result<Vec<_>>>()?
300   }
301 }
302
303
304 #[derive(Debug,Copy,Clone)]
305 enum SectionKindList {
306   Ordinary,
307   Limited,
308   Limits,
309   ClientAgnostic,
310   ServerName,
311 }
312 use SectionKindList as SKL;
313
314 impl SectionKindList {
315   fn contains(self, s: &SectionName) -> bool {
316     match self {
317       SKL::Ordinary       => matches!(s, SN::Link(_)
318                                        | SN::Client(_)
319                                        | SN::Server(_)
320                                        | SN::Common),
321
322       SKL::Limits         => matches!(s, SN::ServerLimit(_)
323                                        | SN::GlobalLimit),
324
325       SKL::ClientAgnostic => matches!(s, SN::Common
326                                        | SN::Server(_)),
327
328       SKL::Limited        => SKL::Ordinary.contains(s)
329                            | SKL::Limits  .contains(s),
330
331       SKL::ServerName     => matches!(s, SN::Common)
332                            | matches!(s, SN::Server(ServerName(name))
333                                          if name == "SERVER"),
334     }
335   }
336 }
337
338 impl<'c> ResolveContext<'c> {
339   fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
340                   -> Option<&'c RawVal> {
341     for section in self.all_sections.iter()
342       .filter(|s| sections.contains(s))
343     {
344       if let Some(raw) = self.agg.sections
345         .get(section)
346         .and_then(|vars: &SectionMap| vars.get(key))
347       {
348         return Some(raw)
349       }
350     }
351     None
352   }
353
354   #[throws(AE)]
355   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
356                  -> Option<T>
357   where T: Parseable
358   {
359     match self.first_of_raw(key, sections) {
360       None => None,
361       Some(raw) => Some({
362         Parseable::parse(&raw.val)
363           .context(key)
364 //          .with_context(|| format!(r#"in section "{}""#, &section))
365           .dcontext(&raw.loc)?
366       }),
367     }
368   }
369
370   #[throws(AE)]
371   pub fn ordinary<T>(&self, key: &'static str) -> T
372   where T: Parseable + Default
373   {
374     self.first_of(key, SKL::Ordinary)?
375       .unwrap_or_default()
376   }
377
378   #[throws(AE)]
379   pub fn limited<T>(&self, key: &'static str) -> T
380   where T: Parseable + Default + Ord
381   {
382     let val = self.ordinary(key)?;
383     if let Some(limit) = self.first_of(key, SKL::Limits)? {
384       min(val, limit)
385     } else {
386       val
387     }
388   }
389
390   #[throws(AE)]
391   pub fn client<T>(&self, key: &'static str) -> T
392   where T: Parseable + Default {
393     match self.end {
394       LinkEnd::Client => self.ordinary(key)?,
395       LinkEnd::Server => default(),
396     }
397   }
398   #[throws(AE)]
399   pub fn server<T>(&self, key: &'static str) -> T
400   where T: Parseable + Default {
401     match self.end {
402       LinkEnd::Server => self.ordinary(key)?,
403       LinkEnd::Client => default(),
404     }
405   }
406
407   #[throws(AE)]
408   pub fn special_ipif<T>(&self, key: &'static str) -> T
409   where T: Parseable + Default
410   {
411     match self.end {
412       LinkEnd::Client => self.ordinary(key)?,
413       LinkEnd::Server => {
414         self.first_of(key, SKL::ClientAgnostic)?
415           .unwrap_or_default()
416       },
417     }
418   }
419 }
420
421 /*
422 impl<'c> ResolveContext<'c> {
423   #[throws(AE)]
424   fn resolve_instance(&self) -> InstanceConfig {
425     InstanceConfig {
426       max_batch_down: self.limited::<u32>("max_batch_down")?,
427     }
428   }
429 }
430 */
431
432 #[throws(AE)]
433 pub fn read() {
434   let opts = config::Opts::from_args();
435
436   let agg = (||{
437     let mut agg = Aggregate::default();
438
439     agg.read_toplevel(&opts.config)?;
440     for extra in &opts.extra_config {
441       agg.read_extra(extra).context("extra config")?;
442     }
443
444     eprintln!("GOT {:#?}", agg);
445
446     Ok::<_,AE>(agg)
447   })().context("read configuration")?;
448
449   let link = LinkName {
450     server: "fooxxx".parse().unwrap(),
451     client: "127.0.0.1".parse().unwrap(),
452   };
453
454   let rctx = ResolveContext {
455     agg: &agg,
456     link: &link,
457     end: LinkEnd::Server,
458     all_sections: vec![
459       SN::Link(link.clone()),
460       SN::Client(link.client.clone()),
461       SN::Server(link.server.clone()),
462       SN::Common,
463       SN::ServerLimit(link.server.clone()),
464       SN::GlobalLimit,
465     ],
466   };
467 }