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