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