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