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