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