chiark / gitweb /
wip resolve, comment out for macro work, for revert
[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 /*
28   // Exceptional settings
29   pub server:                       String,
30   pub secret:                       String, // make a newytpe
31   pub ipif:                         String,
32 */
33   // Capped settings:
34   pub max_batch_down:               u32,
35 /*
36   pub max_queue_time:               Duration,
37   pub http_timeout:                 Duration,
38   pub target_requests_outstanding:  u32,
39
40   // Ordinary settings:
41   pub addrs:                        Vec<IpAddr>,
42   pub vnetwork:                     Vec<CidrString>,
43   pub vaddr:                        Vec<IpAddr>,
44   pub vrelay:                       IpAddr,
45   pub port:                         u16,
46   pub mtu:                          u32,
47   pub ifname_server:                String,
48   pub ifname_client:                String,
49
50   // Ordinary settings, used by server only:
51   pub max_clock_skew:               Duration,
52
53   // Ordinary settings, used by client only:
54   pub http_timeout_grace:           Duration,
55   pub max_requests_outstanding:     u32,
56   pub max_batch_up:                 u32,
57   pub http_retry:                   Duration,
58   pub url:                          Uri,
59   pub vroutes:                      Vec<CidrString>,
60 */
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       let sn = sn.parse().dcontext(&sn)?;
151         self.sections.entry(sn)
152         .or_default()
153         .extend(
154           vars.into_iter()
155             .map(|(k,val)| {
156               (k.replace('-',"_"),
157                RawVal { val, loc: loc.clone() })
158             })
159         );
160     }
161     None
162   }
163
164   #[throws(AE)] // AE includes path
165   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
166   {
167     let dir = fs::read_dir(path);
168     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
169     let dir = dir.context("open directory").dcontext(path)?;
170     for ent in dir {
171       let ent = ent.context("read directory").dcontext(path)?;
172       let leaf = ent.file_name();
173       let leaf = leaf.to_str();
174       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
175       if leaf.len() == 0 { continue }
176       if ! leaf.chars().all(
177         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
178       ) { continue }
179
180       // OK we want this one
181       let ent = ent.path();
182       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
183     }
184     None
185   }
186
187   #[throws(AE)] // AE includes everything
188   fn read_toplevel(&mut self, toplevel: &Path) {
189     enum Anyway { None, Dir }
190     match self.read_file(toplevel, &|k| match k {
191       EK::NotFound => Some(Anyway::None),
192       EK::IsADirectory => Some(Anyway::Dir),
193       _ => None,
194     })
195       .dcontext(toplevel).context("top-level config directory (or file)")?
196     {
197       None | Some(Anyway::None) => { },
198
199       Some(Anyway::Dir) => {
200         struct AnywayNone;
201         let anyway_none = |k| match k {
202           EK::NotFound => Some(AnywayNone),
203           _ => None,
204         };
205
206         let mk = |leaf: &str| {
207           [ toplevel, &PathBuf::from(leaf) ]
208             .iter().collect::<PathBuf>()
209         };
210
211         for &(try_main, desc) in &[
212           ("main.cfg", "main config file"),
213           ("master.cfg", "obsolete-named main config file"),
214         ] {
215           let main = mk(try_main);
216
217           match self.read_file(&main, &anyway_none)
218             .dcontext(main).context(desc)?
219           {
220             None => break,
221             Some(AnywayNone) => { },
222           }
223         }
224
225         for &(try_dir, desc) in &[
226           ("config.d", "per-link config directory"),
227           ("secrets.d", "per-link secrets directory"),
228         ] {
229           let dir = mk(try_dir);
230           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
231             None => { },
232             Some(AnywayNone) => { },
233           }
234         }
235       }
236     }
237   }
238
239   #[throws(AE)] // AE includes extra, but does that this is extra
240   fn read_extra(&mut self, extra: &Path) {
241     struct AnywayDir;
242
243     match self.read_file(extra, &|k| match k {
244       EK::IsADirectory => Some(AnywayDir),
245       _ => None,
246     })
247       .dcontext(extra)?
248     {
249       None => return,
250       Some(AnywayDir) => {
251         self.read_dir_d(extra, &|_| None::<Void>)?;
252       }
253     }
254
255   }
256 }
257
258 enum LinkEnd { Server, Client }
259
260 struct ResolveContext<'c> {
261   agg: &'c Aggregate,
262   link: &'c LinkName,
263   end: LinkEnd,
264   lookup_ordinary:             Vec<SectionName>,
265   lookup_limit:                Vec<SectionName>,
266   lookup_server_sections_only: 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
292 impl<'c> ResolveContext<'c> {
293   fn first_of_raw(&self, key: &'static str, sections: &[SectionName])
294                   -> Option<&'c RawVal> {
295     for section in sections {
296       if let Some(raw) = self.agg.sections
297         .get(section)
298         .and_then(|vars: &SectionMap| vars.get(key))
299       {
300         return Some(raw)
301       }
302     }
303     None
304   }
305
306   #[throws(AE)]
307   fn first_of<T>(&self, key: &'static str, sections: &[SectionName])
308                  -> Option<T>
309   where T: Parseable
310   {
311     match self.first_of_raw(key, sections) {
312       None => None,
313       Some(raw) => Some({
314         Parseable::parse(&raw.val)
315           .context(key)
316 //          .with_context(|| format!(r#"in section "{}""#, &section))
317           .dcontext(&raw.loc)?
318       }),
319     }
320   }
321
322   #[throws(AE)]
323   pub fn ordinary<T>(&self, key: &'static str) -> T
324   where T: Parseable + Default
325   {
326     self.first_of(key, &self.lookup_ordinary)?
327       .unwrap_or_default()
328   }
329
330   #[throws(AE)]
331   pub fn limited<T>(&self, key: &'static str) -> T
332   where T: Parseable + Default + Ord
333   {
334     let val = self.ordinary(key)?;
335     if let Some(limit) = self.first_of(key, &self.lookup_limit)? {
336       min(val, limit)
337     } else {
338       val
339     }
340   }
341
342   #[throws(AE)]
343   pub fn client<T>(&self, key: &'static str) -> T
344   where T: Parseable + Default {
345     match self.end {
346       LinkEnd::Client => self.ordinary(key)?,
347       LinkEnd::Server => default(),
348     }
349   }
350   #[throws(AE)]
351   pub fn server<T>(&self, key: &'static str) -> T
352   where T: Parseable + Default {
353     match self.end {
354       LinkEnd::Server => self.ordinary(key)?,
355       LinkEnd::Client => default(),
356     }
357   }
358
359   #[throws(AE)]
360   pub fn special_ipif<T>(&self, key: &'static str) -> T
361   where T: Parseable + Default
362   {
363     match self.end {
364       LinkEnd::Client => self.ordinary(key)?,
365       LinkEnd::Server => {
366         self.first_of(key, &self.lookup_server_sections_only)?
367           .unwrap_or_default()
368       },
369     }
370   }
371 }
372
373 impl<'c> ResolveContext<'c> {
374   #[throws(AE)]
375   fn resolve_instance(&self) -> InstanceConfig {
376     InstanceConfig {
377       max_batch_down: self.limited::<u32>("max_batch_down")?.into(),
378     }
379   }
380 }
381
382 #[throws(AE)]
383 pub fn read() {
384   let opts = config::Opts::from_args();
385
386   let agg = (||{
387     let mut agg = Aggregate::default();
388
389     agg.read_toplevel(&opts.config)?;
390     for extra in &opts.extra_config {
391       agg.read_extra(extra).context("extra config")?;
392     }
393
394     eprintln!("GOT {:#?}", agg);
395
396     Ok::<_,AE>(agg)
397   })().context("read configuration")?;
398
399   let link = LinkName {
400     server: "fooxxx".parse().unwrap(),
401     client: "127.0.0.1".parse().unwrap(),
402   };
403
404   let rctx = ResolveContext {
405     agg: &agg,
406     link: &link,
407     end: LinkEnd::Server,
408     lookup_ordinary: vec![
409       SN::Link(link.clone()),
410       SN::Client(link.client.clone()),
411       SN::Server(link.server.clone()),
412       SN::Common,
413     ],
414     lookup_limit: vec![
415       SN::ServerLimit(link.server.clone()),
416       SN::GlobalLimit,
417     ],
418     lookup_server_sections_only: vec![
419       SN::Common,
420       SN::Server(link.server.clone()),
421     ],
422   };
423 }