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 //xxx  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 //xxx  #[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<&str>) -> Result<Self, AE>;
271   fn default() -> Result<Self, AE> {
272     Err(anyhow!("setting must be specified"))
273   }
274   #[throws(AE)]
275   fn default_for_key(key: &str) -> Self {
276     Self::default().with_context(|| key.to_string())?
277   }
278 }
279
280 impl Parseable for Duration {
281   #[throws(AE)]
282   fn parse(s: Option<&str>) -> Duration {
283     let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
284     if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
285     throw!(anyhow!("xxx parse with humantime"))
286   }
287 }
288 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
289   impl Parseable for $t {
290     #[throws(AE)]
291     fn parse(s: Option<&str>) -> $t {
292       let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
293       s.parse()?
294     }
295     $(
296       #[throws(AE)] fn default() -> Self { $def }
297     )?
298   }
299 } }
300 parseable_from_str!{u16, default() }
301 parseable_from_str!{u32, default() }
302 parseable_from_str!{String, default() }
303 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
304 parseable_from_str!{Uri, default() }
305
306 impl<T:Parseable> Parseable for Vec<T> {
307   #[throws(AE)]
308   fn parse(s: Option<&str>) -> Vec<T> {
309     let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
310     s.split_ascii_whitespace()
311       .map(|s| Parseable::parse(Some(s)))
312       .collect::<Result<Vec<_>,_>>()?
313   }
314 }
315
316
317 #[derive(Debug,Copy,Clone)]
318 enum SectionKindList {
319   Ordinary,
320   Limited,
321   Limits,
322   ClientAgnostic,
323   ServerName,
324 }
325 use SectionKindList as SKL;
326
327 impl SectionKindList {
328   fn contains(self, s: &SectionName) -> bool {
329     match self {
330       SKL::Ordinary       => matches!(s, SN::Link(_)
331                                        | SN::Client(_)
332                                        | SN::Server(_)
333                                        | SN::Common),
334
335       SKL::Limits         => matches!(s, SN::ServerLimit(_)
336                                        | SN::GlobalLimit),
337
338       SKL::ClientAgnostic => matches!(s, SN::Common
339                                        | SN::Server(_)),
340
341       SKL::Limited        => SKL::Ordinary.contains(s)
342                            | SKL::Limits  .contains(s),
343
344       SKL::ServerName     => matches!(s, SN::Common)
345                            | matches!(s, SN::Server(ServerName(name))
346                                          if name == "SERVER"),
347     }
348   }
349 }
350
351 impl<'c> ResolveContext<'c> {
352   fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
353                   -> Option<&'c RawVal> {
354     for section in self.all_sections.iter()
355       .filter(|s| sections.contains(s))
356     {
357       if let Some(raw) = self.agg.sections
358         .get(section)
359         .and_then(|vars: &SectionMap| vars.get(key))
360       {
361         return Some(raw)
362       }
363     }
364     None
365   }
366
367   #[throws(AE)]
368   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
369                  -> Option<T>
370   where T: Parseable
371   {
372     match self.first_of_raw(key, sections) {
373       None => None,
374       Some(raw) => Some({
375         Parseable::parse(raw.val.as_deref())
376           .context(key)
377 //          .with_context(|| format!(r#"in section "{}""#, &section))
378           .dcontext(&raw.loc)?
379       }),
380     }
381   }
382
383   #[throws(AE)]
384   pub fn ordinary<T>(&self, key: &'static str) -> T
385   where T: Parseable
386   {
387     match self.first_of(key, SKL::Ordinary)? {
388       Some(y) => y,
389       None => Parseable::default_for_key(key)?,
390     }
391   }
392
393   #[throws(AE)]
394   pub fn limited<T>(&self, key: &'static str) -> T
395   where T: Parseable + Ord
396   {
397     let val = self.ordinary(key)?;
398     if let Some(limit) = self.first_of(key, SKL::Limits)? {
399       min(val, limit)
400     } else {
401       val
402     }
403   }
404
405   #[throws(AE)]
406   pub fn client<T>(&self, key: &'static str) -> T
407   where T: Parseable {
408     match self.end {
409       LinkEnd::Client => self.ordinary(key)?,
410       LinkEnd::Server => Parseable::default_for_key(key)?,
411     }
412   }
413   #[throws(AE)]
414   pub fn server<T>(&self, key: &'static str) -> T
415   where T: Parseable {
416     match self.end {
417       LinkEnd::Server => self.ordinary(key)?,
418       LinkEnd::Client => Parseable::default_for_key(key)?,
419     }
420   }
421
422   #[throws(AE)]
423   pub fn special_ipif<T>(&self, key: &'static str) -> T
424   where T: Parseable + Default
425   {
426     match self.end {
427       LinkEnd::Client => self.ordinary(key)?,
428       LinkEnd::Server => {
429         self.first_of(key, SKL::ClientAgnostic)?
430           .unwrap_or_default()
431       },
432     }
433   }
434 }
435
436 /*
437 impl<'c> ResolveContext<'c> {
438   #[throws(AE)]
439   fn resolve_instance(&self) -> InstanceConfig {
440     InstanceConfig {
441       max_batch_down: self.limited::<u32>("max_batch_down")?,
442     }
443   }
444 }
445 */
446
447 #[throws(AE)]
448 pub fn read() {
449   let opts = config::Opts::from_args();
450
451   let agg = (||{
452     let mut agg = Aggregate::default();
453
454     agg.read_toplevel(&opts.config)?;
455     for extra in &opts.extra_config {
456       agg.read_extra(extra).context("extra config")?;
457     }
458
459     eprintln!("GOT {:#?}", agg);
460
461     Ok::<_,AE>(agg)
462   })().context("read configuration")?;
463
464   let link = LinkName {
465     server: "fooxxx".parse().unwrap(),
466     client: "127.0.0.1".parse().unwrap(),
467   };
468
469   let rctx = ResolveContext {
470     agg: &agg,
471     link: &link,
472     end: LinkEnd::Server,
473     all_sections: vec![
474       SN::Link(link.clone()),
475       SN::Client(link.client.clone()),
476       SN::Server(link.server.clone()),
477       SN::Common,
478       SN::ServerLimit(link.server.clone()),
479       SN::GlobalLimit,
480     ],
481   };
482 }