chiark / gitweb /
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 pub struct InstanceConfig {
27   // Exceptional settings
28   pub server:                       String,
29   pub secret:                       String,
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
37   // Ordinary settings:
38   pub target_requests_outstanding:  u32,
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)]
61 pub enum SectionName {
62   Link { server: ServerName, client: ClientName },
63   Client(ClientName),
64   Server(ServerName), // includes SERVER, which is slightly special
65   Common,
66   Default,
67 }
68 pub use SectionName as SN;
69
70 type SectionMap = HashMap<SectionName, Option<String>>;
71
72 pub struct Config {
73   opts: Opts,
74 }
75
76 static OUTSIDE_SECTION: &str = "[";
77
78 #[derive(Default,Debug)]
79 struct Aggregate {
80   sections: HashMap<String, SectionMap>,
81 }
82
83 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
84 #[ext]
85 impl<'f,A> OkAnyway<'f,A> {
86   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
87     let e = r.as_ref().err()?;
88     let k = e.kind();
89     let a = self(k)?;
90     Some(a)
91   }
92 }
93
94 impl FromStr for SectionName {
95   type Err = AE;
96   #[throws(AE)]
97   fn from_str(s: &str) -> Self {
98     match s {
99       "COMMON" => return SN::Common,
100       "DEFAULT" => return SN::Default,
101       _ => { }
102     };
103     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
104     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
105     let (server, client) = s.split_ascii_whitespace().collect_tuple()
106       .ok_or_else(|| anyhow!(
107         "bad section name \
108          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>"
109       ))?;
110     let server = server.parse().context("server name in link section name")?;
111     let client = client.parse().context("client name in link section name")?;
112     SN::Link { server, client }
113   }
114 }
115
116 impl Aggregate {
117   #[throws(AE)] // AE does not include path
118   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
119   {
120     let f = fs::File::open(path);
121     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
122     let mut f = f.context("open")?;
123
124     let mut s = String::new();
125     let y = f.read_to_string(&mut s);
126     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
127     y.context("read")?;
128
129     let mut ini = Ini::new_cs();
130     ini.set_default_section(OUTSIDE_SECTION);
131     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
132     let mut map = mem::take(ini.get_mut_map());
133     if map.get(OUTSIDE_SECTION).is_some() {
134       throw!(anyhow!("INI file contains settings outside a section"));
135     }
136
137     // xxx parse section names here
138     // xxx save Arc<PathBuf> where we found each item
139
140     for (sn, vars) in map.drain() {
141       let sn = sn.parse().dcontext(&sn)?;
142       self.sections.entry(sn)
143         .or_default()
144         .extend(vars);
145     }
146     None
147   }
148
149   #[throws(AE)] // AE includes path
150   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
151   {
152     let dir = fs::read_dir(path);
153     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
154     let dir = dir.context("open directory").dcontext(path)?;
155     for ent in dir {
156       let ent = ent.context("read directory").dcontext(path)?;
157       let leaf = ent.file_name();
158       let leaf = leaf.to_str();
159       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
160       if leaf.len() == 0 { continue }
161       if ! leaf.chars().all(
162         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
163       ) { continue }
164
165       // OK we want this one
166       let ent = ent.path();
167       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
168     }
169     None
170   }
171
172   #[throws(AE)] // AE includes everything
173   fn read_toplevel(&mut self, toplevel: &Path) {
174     enum Anyway { None, Dir }
175     match self.read_file(toplevel, &|k| match k {
176       EK::NotFound => Some(Anyway::None),
177       EK::IsADirectory => Some(Anyway::Dir),
178       _ => None,
179     })
180       .dcontext(toplevel).context("top-level config directory (or file)")?
181     {
182       None | Some(Anyway::None) => { },
183
184       Some(Anyway::Dir) => {
185         struct AnywayNone;
186         let anyway_none = |k| match k {
187           EK::NotFound => Some(AnywayNone),
188           _ => None,
189         };
190
191         let mk = |leaf: &str| {
192           [ toplevel, &PathBuf::from(leaf) ]
193             .iter().collect::<PathBuf>()
194         };
195
196         for &(try_main, desc) in &[
197           ("main.cfg", "main config file"),
198           ("master.cfg", "obsolete-named main config file"),
199         ] {
200           let main = mk(try_main);
201
202           match self.read_file(&main, &anyway_none)
203             .dcontext(main).context(desc)?
204           {
205             None => break,
206             Some(AnywayNone) => { },
207           }
208         }
209
210         for &(try_dir, desc) in &[
211           ("config.d", "per-link config directory"),
212           ("secrets.d", "per-link secrets directory"),
213         ] {
214           let dir = mk(try_dir);
215           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
216             None => { },
217             Some(AnywayNone) => { },
218           }
219         }
220       }
221     }
222   }
223
224   #[throws(AE)] // AE includes extra, but does that this is extra
225   fn read_extra(&mut self, extra: &Path) {
226     struct AnywayDir;
227
228     match self.read_file(extra, &|k| match k {
229       EK::IsADirectory => Some(AnywayDir),
230       _ => None,
231     })
232       .dcontext(extra)?
233     {
234       None => return,
235       Some(AnywayDir) => {
236         self.read_dir_d(extra, &|_| None::<Void>)?;
237       }
238     }
239
240   }
241 }
242
243
244 #[throws(AE)]
245 pub fn read() {
246   let opts = config::Opts::from_args();
247
248   (||{
249     let mut agg = Aggregate::default();
250
251     agg.read_toplevel(&opts.config)?;
252     for extra in &opts.extra_config {
253       agg.read_extra(extra).context("extra config")?;
254     }
255
256     eprintln!("GOT {:?}", agg);
257
258     Ok::<_,AE>(())
259   })().context("read configuration")?;
260 }