1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
7 use configparser::ini::Ini;
9 #[derive(StructOpt,Debug)]
11 /// Top-level config file or directory
13 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
15 /// Or if this is a file, just read that file.
16 #[structopt(long, default_value="/etc/hippotat")]
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>,
24 pub struct CidrString(pub String);
26 pub struct InstanceConfig {
27 // Exceptional settings
33 pub max_batch_down: u32,
34 pub max_queue_time: Duration,
35 pub http_timeout: Duration,
38 pub target_requests_outstanding: u32,
39 pub addrs: Vec<IpAddr>,
40 pub vnetwork: Vec<CidrString>,
41 pub vaddr: Vec<IpAddr>,
45 pub ifname_server: String,
46 pub ifname_client: String,
48 // Ordinary settings, used by server only:
49 pub max_clock_skew: Duration,
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,
57 pub vroutes: Vec<CidrString>,
60 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
61 pub enum SectionName {
62 Link { server: ServerName, client: ClientName },
64 Server(ServerName), // includes SERVER, which is slightly special
68 pub use SectionName as SN;
70 type SectionMap = HashMap<String, (Option<String>, Arc<PathBuf>)>;
76 static OUTSIDE_SECTION: &str = "[";
78 #[derive(Default,Debug)]
80 sections: HashMap<SectionName, SectionMap>,
83 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
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()?;
94 impl FromStr for SectionName {
97 fn from_str(s: &str) -> Self {
99 "COMMON" => return SN::Common,
100 "DEFAULT" => return SN::Default,
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>",
111 let server = server.parse().context("server name in link section name")?;
112 let client = client.parse().context("client name in link section name")?;
113 SN::Link { server, client }
118 #[throws(AE)] // AE does not include path
119 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
121 let f = fs::File::open(path);
122 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
123 let mut f = f.context("open")?;
125 let mut s = String::new();
126 let y = f.read_to_string(&mut s);
127 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
130 let mut ini = Ini::new_cs();
131 ini.set_default_section(OUTSIDE_SECTION);
132 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
133 let map = mem::take(ini.get_mut_map());
134 if map.get(OUTSIDE_SECTION).is_some() {
135 throw!(anyhow!("INI file contains settings outside a section"));
138 let loc = Arc::new(path.to_owned());
140 for (sn, vars) in map {
141 let sn = sn.parse().dcontext(&sn)?;
142 self.sections.entry(sn)
146 .map(|(k,v)| (k, (v, loc.clone())))
152 #[throws(AE)] // AE includes path
153 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
155 let dir = fs::read_dir(path);
156 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
157 let dir = dir.context("open directory").dcontext(path)?;
159 let ent = ent.context("read directory").dcontext(path)?;
160 let leaf = ent.file_name();
161 let leaf = leaf.to_str();
162 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
163 if leaf.len() == 0 { continue }
164 if ! leaf.chars().all(
165 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
168 // OK we want this one
169 let ent = ent.path();
170 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
175 #[throws(AE)] // AE includes everything
176 fn read_toplevel(&mut self, toplevel: &Path) {
177 enum Anyway { None, Dir }
178 match self.read_file(toplevel, &|k| match k {
179 EK::NotFound => Some(Anyway::None),
180 EK::IsADirectory => Some(Anyway::Dir),
183 .dcontext(toplevel).context("top-level config directory (or file)")?
185 None | Some(Anyway::None) => { },
187 Some(Anyway::Dir) => {
189 let anyway_none = |k| match k {
190 EK::NotFound => Some(AnywayNone),
194 let mk = |leaf: &str| {
195 [ toplevel, &PathBuf::from(leaf) ]
196 .iter().collect::<PathBuf>()
199 for &(try_main, desc) in &[
200 ("main.cfg", "main config file"),
201 ("master.cfg", "obsolete-named main config file"),
203 let main = mk(try_main);
205 match self.read_file(&main, &anyway_none)
206 .dcontext(main).context(desc)?
209 Some(AnywayNone) => { },
213 for &(try_dir, desc) in &[
214 ("config.d", "per-link config directory"),
215 ("secrets.d", "per-link secrets directory"),
217 let dir = mk(try_dir);
218 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
220 Some(AnywayNone) => { },
227 #[throws(AE)] // AE includes extra, but does that this is extra
228 fn read_extra(&mut self, extra: &Path) {
231 match self.read_file(extra, &|k| match k {
232 EK::IsADirectory => Some(AnywayDir),
239 self.read_dir_d(extra, &|_| None::<Void>)?;
249 let opts = config::Opts::from_args();
252 let mut agg = Aggregate::default();
254 agg.read_toplevel(&opts.config)?;
255 for extra in &opts.extra_config {
256 agg.read_extra(extra).context("extra config")?;
259 eprintln!("GOT {:#?}", agg);
262 })().context("read configuration")?;