chiark / gitweb /
enforce tx queue expiry
[hippotat.git] / src / config.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 use configparser::ini::Ini;
8
9 #[derive(hippotat_macros::ResolveConfig)]
10 #[derive(Debug,Clone)]
11 pub struct InstanceConfig {
12   // Exceptional settings
13   #[special(special_link, SKL::ServerName)] pub   link:   LinkName,
14   pub                                             secret: Secret,
15   #[special(special_ipif, SKL::Ordinary)] pub     ipif:   String,
16
17   // Capped settings:
18   #[limited]    pub max_batch_down:               u32,
19   #[limited]    pub max_queue_time:               Duration, // xxx client unlimited
20   #[limited]    pub http_timeout:                 Duration,
21   #[limited]    pub target_requests_outstanding:  u32,
22
23   // Ordinary settings:
24   pub addrs:                        Vec<IpAddr>,
25   pub vnetwork:                     Vec<IpNet>,
26   pub vaddr:                        IpAddr,
27   pub vrelay:                       IpAddr,
28   pub port:                         u16,
29   pub mtu:                          u32,
30   pub ifname_server:                String,
31   pub ifname_client:                String,
32
33   // Ordinary settings, used by server only:
34   #[server]  pub max_clock_skew:               Duration,
35
36   // Ordinary settings, used by client only:
37   #[client]  pub http_timeout_grace:           Duration,
38   #[client]  pub max_requests_outstanding:     u32,
39   #[client]  pub max_batch_up:                 u32,
40   #[client]  pub http_retry:                   Duration,
41   #[client]  pub success_report_interval:      Duration,
42   #[client]  pub url:                          Uri,
43   #[client]  pub vroutes:                      Vec<IpNet>,
44
45   // Computed, rather than looked up.  Client only:
46   #[computed]  pub effective_http_timeout:     Duration,
47 }
48
49 static DEFAULT_CONFIG: &str = r#"
50 [COMMON]
51 max_batch_down = 65536
52 max_queue_time = 10
53 target_requests_outstanding = 3
54 http_timeout = 30
55 http_timeout_grace = 5
56 max_requests_outstanding = 6
57 max_batch_up = 4000
58 http_retry = 5
59 port = 80
60 vroutes = ''
61 ifname_client = hippo%d
62 ifname_server = shippo%d
63 max_clock_skew = 300
64 success_report_interval = 3600
65
66 ipif = userv root ipif %{local},%{peer},%{mtu},slip,%{ifname} '%{rnets}'
67
68 mtu = 1500
69
70 vnetwork = 172.24.230.192
71
72 [LIMIT]
73 max_batch_down = 262144
74 max_queue_time = 121
75 http_timeout = 121
76 target_requests_outstanding = 10
77 "#;
78
79 #[derive(StructOpt,Debug)]
80 pub struct Opts {
81   /// Top-level config file or directory
82   ///
83   /// Look for `main.cfg`, `config.d` and `secrets.d` here.
84   ///
85   /// Or if this is a file, just read that file.
86   #[structopt(long, default_value="/etc/hippotat")]
87   pub config: PathBuf,
88   
89   /// Additional config files or dirs, which can override the others
90   #[structopt(long, multiple=true, number_of_values=1)]
91   pub extra_config: Vec<PathBuf>,
92 }
93
94 #[ext(pub)]
95 impl u32 {
96   fn sat(self) -> usize { self.try_into().unwrap_or(usize::MAX) }
97 }
98
99 #[ext]
100 impl<'s> Option<&'s str> {
101   #[throws(AE)]
102   fn value(self) -> &'s str {
103     self.ok_or_else(|| anyhow!("value needed"))?
104   }
105 }
106
107 #[derive(Clone)]
108 pub struct Secret(pub String);
109 impl Parseable for Secret {
110   #[throws(AE)]
111   fn parse(s: Option<&str>) -> Self {
112     let s = s.value()?;
113     if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
114     Secret(s.into())
115   }
116   #[throws(AE)]
117   fn default() -> Self { Secret(default()) }
118 }
119 impl Debug for Secret {
120   #[throws(fmt::Error)]
121   fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
122 }
123
124 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
125 pub enum SectionName {
126   Link(LinkName),
127   Client(ClientName),
128   Server(ServerName), // includes SERVER, which is slightly special
129   ServerLimit(ServerName),
130   GlobalLimit,
131   Common,
132 }
133 pub use SectionName as SN;
134
135 #[derive(Debug,Clone)]
136 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
137 type SectionMap = HashMap<String, RawVal>;
138
139 #[derive(Debug)]
140 struct RawValRef<'v,'l,'s> {
141   raw: Option<&'v str>,
142   key: &'static str,
143   loc: &'l Path,
144   section: &'s SectionName,
145 }
146
147 impl<'v> RawValRef<'v,'_,'_> {
148   #[throws(AE)]
149   fn try_map<F,T>(&self, f: F) -> T
150   where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
151     f(self.raw)
152       .with_context(|| format!(r#"file {:?}, section {}, key "{}""#,
153                                self.loc, self.section, self.key))?
154   }
155 }
156
157 pub struct Config {
158   pub opts: Opts,
159 }
160
161 static OUTSIDE_SECTION: &str = "[";
162 static SPECIAL_SERVER_SECTION: &str = "SERVER";
163
164 #[derive(Default,Debug)]
165 struct Aggregate {
166   keys_allowed: HashMap<&'static str, SectionKindList>,
167   sections: HashMap<SectionName, SectionMap>,
168 }
169
170 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
171 #[ext]
172 impl<'f,A> OkAnyway<'f,A> {
173   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
174     let e = r.as_ref().err()?;
175     let k = e.kind();
176     let a = self(k)?;
177     Some(a)
178   }
179 }
180
181 impl FromStr for SectionName {
182   type Err = AE;
183   #[throws(AE)]
184   fn from_str(s: &str) -> Self {
185     match s {
186       "COMMON" => return SN::Common,
187       "LIMIT" => return SN::GlobalLimit,
188       _ => { }
189     };
190     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
191     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
192     let (server, client) = s.split_ascii_whitespace().collect_tuple()
193       .ok_or_else(|| anyhow!(
194         "bad section name {:?} \
195          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
196         s
197       ))?;
198     let server = server.parse().context("server name in link section name")?;
199     if client == "LIMIT" { return SN::ServerLimit(server) }
200     let client = client.parse().context("client name in link section name")?;
201     SN::Link(LinkName { server, client })
202   }
203 }
204 impl Display for InstanceConfig {
205   #[throws(fmt::Error)]
206   fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.link, f)? }
207 }
208
209 impl Display for SectionName {
210   #[throws(fmt::Error)]
211   fn fmt(&self, f: &mut fmt::Formatter) {
212     match self {
213       SN::Link  (ref l)      => Display::fmt(l, f)?,
214       SN::Client(ref c)      => write!(f, "[{}]"       , c)?,
215       SN::Server(ref s)      => write!(f, "[{}]"       , s)?,
216       SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
217       SN::GlobalLimit        => write!(f, "[LIMIT]"       )?,
218       SN::Common             => write!(f, "[COMMON]"      )?,
219     }
220   }
221 }
222
223 impl Aggregate {
224   #[throws(AE)] // AE does not include path
225   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
226   {
227     let f = fs::File::open(path);
228     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
229     let mut f = f.context("open")?;
230
231     let mut s = String::new();
232     let y = f.read_to_string(&mut s);
233     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
234     y.context("read")?;
235
236     self.read_string(s, path)?;
237     None
238   }
239
240   #[throws(AE)] // AE does not include path
241   fn read_string(&mut self, s: String, path_for_loc: &Path) {
242     let mut ini = Ini::new_cs();
243     ini.set_default_section(OUTSIDE_SECTION);
244     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
245     let map = mem::take(ini.get_mut_map());
246     if map.get(OUTSIDE_SECTION).is_some() {
247       throw!(anyhow!("INI file contains settings outside a section"));
248     }
249
250     let loc = Arc::new(path_for_loc.to_owned());
251
252     for (sn, vars) in map {
253       let sn = sn.parse().dcontext(&sn)?;
254
255       for key in vars.keys() {
256         let skl = self.keys_allowed.get(key.as_str()).ok_or_else(
257           || anyhow!("unknown configuration key {:?}", key)
258         )?;
259         if ! skl.contains(&sn) {
260           throw!(anyhow!("configuration key {:?} not applicable \
261                           in this kind of section {:?}", key, &sn))
262         }
263       }
264
265       let ent = self.sections.entry(sn).or_default();
266       for (key, raw) in vars {
267         let raw = match raw {
268           Some(raw) if raw.starts_with('\'') || raw.starts_with('"') => Some(
269             (||{
270               if raw.contains('\\') {
271                 throw!(
272                   anyhow!("quoted value contains backslash, not supported")
273                 );
274               }
275               let unq = raw[1..].strip_suffix(&raw[0..1])
276                 .ok_or_else(
277                   || anyhow!("mismatched quotes around quoted value")
278                 )?
279                 .to_owned();
280               Ok::<_,AE>(unq)
281             })()
282               .with_context(|| format!("key {:?}", key))
283               .dcontext(path_for_loc)?
284           ),
285           x => x,
286         };
287         let key = key.replace('-',"_");
288         ent.insert(key, RawVal { raw, loc: loc.clone() });
289       }
290     }
291   }
292
293   #[throws(AE)] // AE includes path
294   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
295   {
296     let dir = fs::read_dir(path);
297     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
298     let dir = dir.context("open directory").dcontext(path)?;
299     for ent in dir {
300       let ent = ent.context("read directory").dcontext(path)?;
301       let leaf = ent.file_name();
302       let leaf = leaf.to_str();
303       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
304       if leaf.len() == 0 { continue }
305       if ! leaf.chars().all(
306         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
307       ) { continue }
308
309       // OK we want this one
310       let ent = ent.path();
311       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
312     }
313     None
314   }
315
316   #[throws(AE)] // AE includes everything
317   fn read_toplevel(&mut self, toplevel: &Path) {
318     enum Anyway { None, Dir }
319     match self.read_file(toplevel, &|k| match k {
320       EK::NotFound => Some(Anyway::None),
321       EK::IsADirectory => Some(Anyway::Dir),
322       _ => None,
323     })
324       .dcontext(toplevel).context("top-level config directory (or file)")?
325     {
326       None | Some(Anyway::None) => { },
327
328       Some(Anyway::Dir) => {
329         struct AnywayNone;
330         let anyway_none = |k| match k {
331           EK::NotFound => Some(AnywayNone),
332           _ => None,
333         };
334
335         let mk = |leaf: &str| {
336           [ toplevel, &PathBuf::from(leaf) ]
337             .iter().collect::<PathBuf>()
338         };
339
340         for &(try_main, desc) in &[
341           ("main.cfg", "main config file"),
342           ("master.cfg", "obsolete-named main config file"),
343         ] {
344           let main = mk(try_main);
345
346           match self.read_file(&main, &anyway_none)
347             .dcontext(main).context(desc)?
348           {
349             None => break,
350             Some(AnywayNone) => { },
351           }
352         }
353
354         for &(try_dir, desc) in &[
355           ("config.d", "per-link config directory"),
356           ("secrets.d", "per-link secrets directory"),
357         ] {
358           let dir = mk(try_dir);
359           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
360             None => { },
361             Some(AnywayNone) => { },
362           }
363         }
364       }
365     }
366   }
367
368   #[throws(AE)] // AE includes extra, but does that this is extra
369   fn read_extra(&mut self, extra: &Path) {
370     struct AnywayDir;
371
372     match self.read_file(extra, &|k| match k {
373       EK::IsADirectory => Some(AnywayDir),
374       _ => None,
375     })
376       .dcontext(extra)?
377     {
378       None => return,
379       Some(AnywayDir) => {
380         self.read_dir_d(extra, &|_| None::<Void>)?;
381       }
382     }
383
384   }
385 }
386
387 impl Aggregate {
388   fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
389     let mut links:              BTreeSet<LinkName> = default();
390
391     let mut secrets_anyserver:  BTreeSet<&ClientName> = default();
392     let mut secrets_anyclient:  BTreeSet<&ServerName> = default();
393     let mut secret_global       = false;
394
395     let mut putative_servers   = BTreeSet::new();
396     let mut putative_clients   = BTreeSet::new();
397
398     let mut note_server = |s| {
399       if let Some(only) = only_server { if s != only { return false } }
400       putative_servers.insert(s);
401       true
402     };
403     let mut note_client = |c| {
404       putative_clients.insert(c);
405     };
406
407     for (section, vars) in &self.sections {
408       let has_secret = || vars.contains_key("secret");
409
410       match section {
411         SN::Link(l) => {
412           if ! note_server(&l.server) { continue }
413           note_client(&l.client);
414           if has_secret() { links.insert(l.clone()); }
415         },
416         SN::Server(ref s) => {
417           if ! note_server(s) { continue }
418           if has_secret() { secrets_anyclient.insert(s); }
419         },
420         SN::Client(ref c) => {
421           note_client(c);
422           if has_secret() { secrets_anyserver.insert(c); }
423         },
424         SN::Common => {
425           if has_secret() { secret_global = true; }
426         },
427         _ => { },
428       }
429     }
430
431     // Add links which are justified by blanket secrets
432     for (client, server) in iproduct!(
433       putative_clients.into_iter().filter(
434         |c| secret_global || secrets_anyserver.contains(c)
435       ),
436       putative_servers.iter().cloned().filter(
437         |s| secret_global || secrets_anyclient.contains(s)
438       )
439     ) {
440       links.insert(LinkName {
441         client: client.clone(),
442         server: server.clone(),
443       });
444     }
445
446     links
447   }
448 }
449
450 struct ResolveContext<'c> {
451   agg: &'c Aggregate,
452   link: &'c LinkName,
453   end: LinkEnd,
454   all_sections: Vec<SectionName>,
455 }
456
457 trait Parseable: Sized {
458   fn parse(s: Option<&str>) -> Result<Self, AE>;
459   fn default() -> Result<Self, AE> {
460     Err(anyhow!("setting must be specified"))
461   }
462   #[throws(AE)]
463   fn default_for_key(key: &str) -> Self {
464     Self::default().with_context(|| key.to_string())?
465   }
466 }
467
468 impl Parseable for Duration {
469   #[throws(AE)]
470   fn parse(s: Option<&str>) -> Duration {
471     // todo: would be nice to parse with humantime maybe
472     Duration::from_secs( s.value()?.parse()? )
473   }
474 }
475 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
476   impl Parseable for $t {
477     #[throws(AE)]
478     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
479     $( #[throws(AE)] fn default() -> Self { $def } )?
480   }
481 } }
482 parseable_from_str!{u16, default() }
483 parseable_from_str!{u32, default() }
484 parseable_from_str!{String, default() }
485 parseable_from_str!{IpNet, default() }
486 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
487 parseable_from_str!{Uri, default() }
488
489 impl<T:Parseable> Parseable for Vec<T> {
490   #[throws(AE)]
491   fn parse(s: Option<&str>) -> Vec<T> {
492     s.value()?
493       .split_ascii_whitespace()
494       .map(|s| Parseable::parse(Some(s)))
495       .collect::<Result<Vec<_>,_>>()?
496   }
497   #[throws(AE)]
498   fn default() -> Self { default() }
499 }
500
501
502 #[derive(Debug,Copy,Clone)]
503 enum SectionKindList {
504   Ordinary,
505   Limited,
506   Limits,
507   ClientAgnostic,
508   ServerName,
509 }
510 use SectionKindList as SKL;
511
512 impl SectionName {
513   fn special_server_section() -> Self { SN::Server(ServerName(
514     SPECIAL_SERVER_SECTION.into()
515   )) }
516 }
517
518 impl SectionKindList {
519   fn contains(self, s: &SectionName) -> bool {
520     match self {
521       SKL::Ordinary       => matches!(s, SN::Link(_)
522                                        | SN::Client(_)
523                                        | SN::Server(_)
524                                        | SN::Common),
525
526       SKL::Limits         => matches!(s, SN::ServerLimit(_)
527                                        | SN::GlobalLimit),
528
529       SKL::ClientAgnostic => matches!(s, SN::Common
530                                        | SN::Server(_)),
531
532       SKL::Limited        => SKL::Ordinary.contains(s)
533                            | SKL::Limits  .contains(s),
534
535       SKL::ServerName     => matches!(s, SN::Common)
536                            | matches!(s, SN::Server(ServerName(name))
537                                          if name == SPECIAL_SERVER_SECTION),
538     }
539   }
540 }
541
542 impl Aggregate {
543   fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
544                        -> Option<RawValRef<'a,'a,'s>>
545   where S: Iterator<Item=&'s SectionName>
546   {
547     for section in sections {
548       if let Some(raw) = self.sections
549         .get(section)
550         .and_then(|vars: &SectionMap| vars.get(key))
551       {
552         return Some(RawValRef {
553           raw: raw.raw.as_deref(),
554           loc: &raw.loc,
555           section, key,
556         })
557       }
558     }
559     None
560   }
561
562   #[throws(AE)]
563   pub fn establish_server_name(&self) -> ServerName {
564     let key = "server";
565     let raw = match self.lookup_raw(
566       key,
567       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
568     ) {
569       Some(raw) => raw.try_map(|os| os.value())?,
570       None => SPECIAL_SERVER_SECTION,
571     };
572     ServerName(raw.into())
573   }
574 }
575
576 impl<'c> ResolveContext<'c> {
577   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
578                   -> Option<RawValRef<'c,'c,'c>> {
579     self.agg.lookup_raw(
580       key,
581       self.all_sections.iter()
582         .filter(|s| sections.contains(s))
583     )
584   }
585
586   #[throws(AE)]
587   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
588                  -> Option<T>
589   where T: Parseable
590   {
591     match self.first_of_raw(key, sections) {
592       None => None,
593       Some(raw) => Some(raw.try_map(Parseable::parse)?),
594     }
595   }
596
597   #[throws(AE)]
598   pub fn ordinary<T>(&self, key: &'static str) -> T
599   where T: Parseable
600   {
601     match self.first_of(key, SKL::Ordinary)? {
602       Some(y) => y,
603       None => Parseable::default_for_key(key)?,
604     }
605   }
606
607   #[throws(AE)]
608   pub fn limited<T>(&self, key: &'static str) -> T
609   where T: Parseable + Ord
610   {
611     let val = self.ordinary(key)?;
612     if let Some(limit) = self.first_of(key, SKL::Limits)? {
613       min(val, limit)
614     } else {
615       val
616     }
617   }
618
619   #[throws(AE)]
620   pub fn client<T>(&self, key: &'static str) -> T
621   where T: Parseable + Default {
622     match self.end {
623       LinkEnd::Client => self.ordinary(key)?,
624       LinkEnd::Server => default(),
625     }
626   }
627   #[throws(AE)]
628   pub fn server<T>(&self, key: &'static str) -> T
629   where T: Parseable + Default {
630     match self.end {
631       LinkEnd::Server => self.ordinary(key)?,
632       LinkEnd::Client => default(),
633     }
634   }
635
636   #[throws(AE)]
637   pub fn computed<T>(&self, _key: &'static str) -> T
638   where T: Default
639   {
640     default()
641   }
642
643   #[throws(AE)]
644   pub fn special_ipif(&self, key: &'static str) -> String {
645     match self.end {
646       LinkEnd::Client => self.ordinary(key)?,
647       LinkEnd::Server => {
648         self.first_of(key, SKL::ClientAgnostic)?
649           .unwrap_or_default()
650       },
651     }
652   }
653
654   #[throws(AE)]
655   pub fn special_link(&self, _key: &'static str) -> LinkName {
656     self.link.clone()
657   }
658 }
659
660 impl InstanceConfig {
661   #[throws(AE)]
662   fn complete(&mut self, end: LinkEnd) {
663     let mut vhosts = self.vnetwork.iter()
664       .map(|n| n.hosts()).flatten()
665       .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
666
667     if self.vaddr.is_unspecified() {
668       self.vaddr = vhosts.next().ok_or_else(
669         || anyhow!("vnetwork too small to generate vaddrr")
670       )?;
671     }
672     if self.vrelay.is_unspecified() {
673       self.vrelay = vhosts.next().ok_or_else(
674         || anyhow!("vnetwork too small to generate vrelay")
675       )?;
676     }
677
678     let check_batch = {
679       let mtu = self.mtu;
680       move |max_batch, key| {
681         if max_batch/2 < mtu {
682           throw!(anyhow!("max batch {:?} ({}) must be >= 2 x mtu ({}) \
683                           (to allow for SLIP ESC-encoding)",
684                          key, max_batch, mtu))
685         }
686         Ok::<_,AE>(())
687       }
688     };
689
690     match end {
691       LinkEnd::Client => {
692         if &self.url == &default::<Uri>() {
693           let addr = self.addrs.get(0).ok_or_else(
694             || anyhow!("client needs addrs or url set")
695           )?;
696           self.url = format!(
697             "http://{}{}/",
698             match addr {
699               IpAddr::V4(a) => format!("{}", a),
700               IpAddr::V6(a) => format!("[{}]", a),
701             },
702             match self.port {
703               80 => format!(""),
704               p => format!(":{}", p),
705             })
706             .parse().unwrap()
707         }
708
709         self.effective_http_timeout = {
710           let a = self.http_timeout;
711           let b = self.http_timeout_grace;
712           a.checked_add(b).ok_or_else(
713             || anyhow!("calculate effective http timeout ({:?} + {:?})", a, b)
714           )?
715         };
716
717         check_batch(self.max_batch_up, "max_batch_up")?;
718       },
719
720       LinkEnd::Server => {
721         if self.addrs.is_empty() {
722           throw!(anyhow!("missing 'addrs' setting"))
723         }
724         check_batch(self.max_batch_down, "max_batch_down")?;
725       },
726
727       // xxx check target vs max req outstanding
728     }
729
730     #[throws(AE)]
731     fn subst(var: &mut String,
732              kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
733     ) {
734       let substs = kv
735         .map(|(k,v)| (k.to_string(), v.to_string()))
736         .collect::<HashMap<String, String>>();
737       let bad = parking_lot::Mutex::new(vec![]);
738       *var = regex_replace_all!(
739         r#"%(?:%|\((\w+)\)s|\{(\w+)\}|.)"#,
740         &var,
741         |whole, k1, k2| (|| Ok::<_,String>({
742           if whole == "%%" { "%" }
743           else if let Some(&k) = [k1,k2].iter().find(|&&s| s != "") {
744             substs.get(k).ok_or_else(
745               || format!("unknown key %({})s", k)
746             )?
747           } else {
748             throw!(format!("bad percent escape {:?}", &whole));
749           }
750         }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
751       ).into_owned();
752       let bad = bad.into_inner();
753       if ! bad.is_empty() {
754         throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
755       }
756     }
757
758     {
759       use LinkEnd::*;
760       type DD<'d> = &'d dyn Display;
761       fn dv<T:Display>(v: &[T]) -> String {
762         format!("{}", v.iter().format(" "))
763       }
764       let mut ipif = mem::take(&mut self.ipif); // lets us borrow all of self
765       let s = &self; // just for abbreviation, below
766       let vnetwork = dv(&s.vnetwork);
767       let vroutes  = dv(&s.vroutes);
768
769       let keys = &["local",       "peer",    "rnets",   "ifname"];
770       let values = match end {
771  Server => [&s.vaddr as DD      , &s.vrelay, &vnetwork, &s.ifname_server],
772  Client => [&s.link.client as DD, &s.vaddr,  &vroutes,  &s.ifname_client],
773       };
774       let always = [
775         ( "mtu",     &s.mtu as DD ),
776       ];
777
778       subst(
779         &mut ipif,
780         &mut keys.iter().cloned()
781           .zip_eq(values)
782           .chain(always.iter().cloned()),
783       ).context("ipif")?;
784       self.ipif = ipif;
785     }
786   }
787 }
788
789 #[throws(AE)]
790 pub fn read(opts: &Opts, end: LinkEnd) -> Vec<InstanceConfig> {
791   let agg = (||{
792     let mut agg = Aggregate::default();
793     agg.keys_allowed.extend(
794       InstanceConfig::FIELDS.iter().cloned()
795     );
796
797     agg.read_string(DEFAULT_CONFIG.into(),
798                     "<build-in defaults>".as_ref()).unwrap();
799
800     agg.read_toplevel(&opts.config)?;
801     for extra in &opts.extra_config {
802       agg.read_extra(extra).context("extra config")?;
803     }
804
805     //eprintln!("GOT {:#?}", agg);
806
807     Ok::<_,AE>(agg)
808   })().context("read configuration")?;
809
810   let server_name = match end {
811     LinkEnd::Server => Some(agg.establish_server_name()?),
812     LinkEnd::Client => None,
813   };
814
815   let instances = agg.instances(server_name.as_ref());
816   let mut ics = vec![];
817
818   for link in instances {
819     let rctx = ResolveContext {
820       agg: &agg,
821       link: &link,
822       end,
823       all_sections: vec![
824         SN::Link(link.clone()),
825         SN::Client(link.client.clone()),
826         SN::Server(link.server.clone()),
827         SN::Common,
828         SN::ServerLimit(link.server.clone()),
829         SN::GlobalLimit,
830       ],
831     };
832
833     let mut ic = InstanceConfig::resolve_instance(&rctx)
834       .with_context(|| format!("resolve config for {}", &link))?;
835
836     ic.complete(end)
837       .with_context(|| format!("complete config for {}", &link))?;
838
839     ics.push(ic);
840   }
841
842   ics
843 }