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