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,Hash,Eq,PartialEq)]
73 struct LinkName {
74   server: ServerName,
75   client: ClientName,
76 }
77
78 #[derive(Debug,Clone)]
79 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
80 type SectionMap = HashMap<String, RawVal>;
81
82 pub struct Config {
83   opts: Opts,
84 }
85
86 static OUTSIDE_SECTION: &str = "[";
87
88 #[derive(Default,Debug)]
89 struct Aggregate {
90   sections: HashMap<SectionName, SectionMap>,
91 }
92
93 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
94 #[ext]
95 impl<'f,A> OkAnyway<'f,A> {
96   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
97     let e = r.as_ref().err()?;
98     let k = e.kind();
99     let a = self(k)?;
100     Some(a)
101   }
102 }
103
104 impl FromStr for SectionName {
105   type Err = AE;
106   #[throws(AE)]
107   fn from_str(s: &str) -> Self {
108     match s {
109       "COMMON" => return SN::Common,
110       "DEFAULT" => return SN::Default,
111       "LIMIT" => return SN::GlobalLimit,
112       _ => { }
113     };
114     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
115     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
116     let (server, client) = s.split_ascii_whitespace().collect_tuple()
117       .ok_or_else(|| anyhow!(
118         "bad section name {:?} \
119          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
120         s
121       ))?;
122     let server = server.parse().context("server name in link section name")?;
123     if client == "LIMIT" { return SN::ServerLimit(server) }
124     let client = client.parse().context("client name in link section name")?;
125     SN::Link(LinkName { server, client })
126   }
127 }
128
129 impl Aggregate {
130   #[throws(AE)] // AE does not include path
131   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
132   {
133     let f = fs::File::open(path);
134     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
135     let mut f = f.context("open")?;
136
137     let mut s = String::new();
138     let y = f.read_to_string(&mut s);
139     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
140     y.context("read")?;
141
142     let mut ini = Ini::new_cs();
143     ini.set_default_section(OUTSIDE_SECTION);
144     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
145     let map = mem::take(ini.get_mut_map());
146     if map.get(OUTSIDE_SECTION).is_some() {
147       throw!(anyhow!("INI file contains settings outside a section"));
148     }
149
150     let loc = Arc::new(path.to_owned());
151
152     for (sn, vars) in map {
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 }
268
269 impl<'c> ResolveContext<'c> {
270   fn first_of_raw(&self, key: &str,
271                   sections: &[ &dyn Fn() -> SectionName ])
272                   -> Option<&'c RawVal> {
273     for section in sections {
274       if let Some(raw) = self.agg.sections
275         .get(&section())
276         .and_then(|vars: &SectionMap| vars.get(key))
277       {
278         return Some(raw)
279       }
280     }
281     None
282   }
283
284   #[throws(AE)]
285   fn first_of<T>(&self, key: &str,
286                  sections: &[ &dyn Fn() -> SectionName ])
287                  -> Option<T>
288   where T: FromStr
289   {
290     match self.first_of_raw(key, sections) {
291       None => None,
292       Some(raw) => Some({
293         raw.val.parse()
294           .context(key)
295           .context(r#"in section "{}""#, &raw.section)
296           .dcontext(&raw.loc)?
297       }),
298     }
299   }
300
301   pub fn ordinary<T>(&self, key: &str) -> T where T: FromStr + Default {
302     self.first_of(key, &[
303       || SN::Link(self.link.clone()),
304       || SN::Client(self.link.client.clone()),
305       || SN::Server(self.link.server.clone()),
306       || SN::Common,
307     ])?
308       .unwrap_or_default()
309   }
310
311   pub fn limited<T>(&self, key: &str) -> T
312   where T: FromStr + Default + PartialOrd
313   {
314     let val = self.ordinary(key);
315     if let Some(limit) = self.first_of(key, &[
316       || SN::LimitServer(self.link.server.clone()),
317       || SN::LimitGlobal,
318     ])? {
319       val = min(val, limit)
320     }
321     val
322   }
323
324   pub fn client<T>(&self, key: &str) -> T where T: FromStr + Default {
325     match self.end {
326       LinkEnd::Client => self.ordinary(key)?,
327       LinkEnd::Server => default(),
328     }
329   }
330   pub fn server<T>(&self, key: &str) -> T where T: FromStr + Default {
331     match self.end {
332       LinkEnd::Server => self.ordinary(key)?,
333       LinkEnd::Client => default(),
334     }
335   }
336
337   pub fn special_ipif<T>(&self, key: &str) -> T where T: FromStr + Default {
338     match self.end {
339       LinkEnd::Client => self.ordinary(key)?,
340       LinkEnd::Server => {
341         self.first_of(key, &[
342           || SN::Common,
343           || SN::Server(self.link.server.clone()),
344         ])?
345       },
346     }
347   }
348 }
349
350 /*
351 fn resolve_instance_config() {
352   InstanceConfig {
353     max_batch_down: resolve::limited(&agg, "max_batch_down")
354   }
355 }
356 */
357
358 #[throws(AE)]
359 pub fn read() {
360   let opts = config::Opts::from_args();
361
362   (||{
363     let mut agg = Aggregate::default();
364
365     agg.read_toplevel(&opts.config)?;
366     for extra in &opts.extra_config {
367       agg.read_extra(extra).context("extra config")?;
368     }
369
370     eprintln!("GOT {:#?}", agg);
371
372     Ok::<_,AE>(())
373   })().context("read configuration")?;
374 }