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