1 // Copyright 2021-2022 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later WITH LicenseRef-Hippotat-OpenSSL-Exception
3 // There is NO WARRANTY.
7 #[derive(hippotat_macros::ResolveConfig)]
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,
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,
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,
30 // Ordinary settings, used by server only:
31 #[server] #[per_client] pub max_clock_skew: Duration,
32 #[server] #[global] pub ifname_server: String,
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,
43 // Computed, rather than looked up. Client only:
44 #[computed] pub effective_http_timeout: Duration,
47 static DEFAULT_CONFIG: &str = r#"
49 max_batch_down = 65536
51 target_requests_outstanding = 3
53 http_timeout_grace = 5
54 max_requests_outstanding = 6
59 ifname_client = hippo%d
60 ifname_server = shippo%d
62 success_report_interval = 3600
64 ipif = userv root ipif %{local},%{peer},%{mtu},slip,%{ifname} '%{rnets}'
68 vnetwork = 172.24.230.192
72 max_batch_down = 262144
75 target_requests_outstanding = 10
78 #[derive(StructOpt,Debug)]
80 /// Top-level config file or directory
82 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
84 /// Or if this is a file, just read that file.
85 #[structopt(long, default_value="/etc/hippotat")]
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>,
93 pub trait InspectableConfigValue {
94 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result;
97 macro_rules! impl_inspectable_config_value {
98 { $t:ty as $trait:path } => {
99 impl InspectableConfigValue for $t {
100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 <Self as $trait>::fmt(self, f)
107 impl InspectableConfigValue for Vec<$t> {
108 #[throws(fmt::Error)]
109 fn fmt(&self, f: &mut fmt::Formatter) {
110 let mut first = Some(());
111 for v in self.iter() {
112 if first.take().is_none() { write!(f, " ")?; }
113 InspectableConfigValue::fmt(v, f)?;
120 pub struct DisplayInspectable<'i>(pub &'i dyn InspectableConfigValue);
121 impl<'i> Display for DisplayInspectable<'i> {
122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123 InspectableConfigValue::fmt(self.0, f)
127 impl_inspectable_config_value!{ String as Display }
128 impl_inspectable_config_value!{ u16 as Display }
129 impl_inspectable_config_value!{ u32 as Display }
130 impl_inspectable_config_value!{ hyper::Uri as Display }
132 impl_inspectable_config_value!{ IpAddr as Display }
133 impl_inspectable_config_value!{ ipnet::IpNet as Display }
134 impl_inspectable_config_value!{ Vec<IpAddr> }
135 impl_inspectable_config_value!{ Vec<ipnet::IpNet> }
137 impl InspectableConfigValue for Duration {
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139 let v = self.as_secs_f64();
146 fn sat(self) -> usize { self.try_into().unwrap_or(usize::MAX) }
150 impl<'s> Option<&'s str> {
152 fn value(self) -> &'s str {
153 self.ok_or_else(|| anyhow!("value needed"))?
158 pub struct Secret(pub String);
159 impl Parseable for Secret {
161 fn parse(s: Option<&str>) -> Self {
163 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
167 fn default() -> Self { Secret(default()) }
169 impl Debug for Secret {
170 #[throws(fmt::Error)]
171 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
173 impl_inspectable_config_value!{ Secret as Debug }
175 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
176 pub enum SectionName {
179 Server(ServerName), // includes SERVER, which is slightly special
180 ServerLimit(ServerName),
184 pub use SectionName as SN;
187 struct RawValRef<'v,'l,'s> {
188 raw: Option<&'v str>, // todo: not Option any more
191 section: &'s SectionName,
194 impl<'v> RawValRef<'v,'_,'_> {
196 fn try_map<F,T>(&self, f: F) -> T
197 where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
199 .with_context(|| format!(r#"file {:?}, section {}, key "{}""#,
200 self.loc, self.section, self.key))?
208 static OUTSIDE_SECTION: &str = "[";
209 static SPECIAL_SERVER_SECTION: &str = "SERVER";
214 keys_allowed: HashMap<&'static str, SectionKindList>,
215 sections: HashMap<SectionName, ini::Section>,
218 type OkAnyway<'f,A> = &'f dyn Fn(&io::Error) -> Option<A>;
220 impl<'f,A> OkAnyway<'f,A> {
221 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
222 let e = r.as_ref().err()?;
228 impl FromStr for SectionName {
231 fn from_str(s: &str) -> Self {
233 "COMMON" => return SN::Common,
234 "LIMIT" => return SN::GlobalLimit,
237 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
238 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
239 let (server, client) = s.split_ascii_whitespace().collect_tuple()
240 .ok_or_else(|| anyhow!(
241 "bad section name {:?} \
242 (must be COMMON, <server>, <client>, or <server> <client>",
245 let server = server.parse().context("server name in link section name")?;
246 if client == "LIMIT" { return SN::ServerLimit(server) }
247 let client = client.parse().context("client name in link section name")?;
248 SN::Link(LinkName { server, client })
251 impl Display for InstanceConfig {
252 #[throws(fmt::Error)]
253 fn fmt(&self, f: &mut fmt::Formatter) { Display::fmt(&self.link, f)? }
256 impl Display for SectionName {
257 #[throws(fmt::Error)]
258 fn fmt(&self, f: &mut fmt::Formatter) {
260 SN::Link (ref l) => Display::fmt(l, f)?,
261 SN::Client(ref c) => write!(f, "[{}]" , c)?,
262 SN::Server(ref s) => write!(f, "[{}]" , s)?,
263 SN::ServerLimit(ref s) => write!(f, "[{} LIMIT] ", s)?,
264 SN::GlobalLimit => write!(f, "[LIMIT]" )?,
265 SN::Common => write!(f, "[COMMON]" )?,
273 keys_allowed: HashMap<&'static str, SectionKindList>
274 ) -> Self { Aggregate {
279 #[throws(AE)] // AE does not include path
280 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
282 let f = fs::File::open(path);
283 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
284 let mut f = f.context("open")?;
286 let mut s = String::new();
287 let y = f.read_to_string(&mut s);
288 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
291 self.read_string(s, path)?;
295 #[throws(AE)] // AE does not include path
296 fn read_string(&mut self, s: String, path_for_loc: &Path) {
297 let mut map: ini::Parsed = default();
298 ini::read(&mut map, &mut s.as_bytes(), path_for_loc)
299 .context("parse as INI")?;
300 if map.get(OUTSIDE_SECTION).is_some() {
301 throw!(anyhow!("INI file contains settings outside a section"));
304 for (sn, section) in map {
305 let sn = sn.parse().dcontext(&sn)?;
306 let vars = §ion.values;
308 for (key, val) in vars {
310 let skl = if key == "server" {
313 *self.keys_allowed.get(key.as_str()).ok_or_else(
314 || anyhow!("unknown configuration key")
317 if ! skl.contains(&sn, self.end) {
318 throw!(anyhow!("key not applicable in this kind of section"))
322 .with_context(|| format!("key {:?}", key))
323 .with_context(|| val.loc.to_string())?
326 let ent = self.sections.entry(sn)
327 .or_insert_with(|| ini::Section {
328 loc: section.loc.clone(),
332 for (key, ini::Val { val: raw, loc }) in vars {
333 let val = if raw.starts_with('\'') || raw.starts_with('"') {
335 if raw.contains('\\') {
337 anyhow!("quoted value contains backslash, not supported")
340 let quote = &raw[0..1];
342 let unq = raw[1..].strip_suffix(quote)
344 || anyhow!("mismatched quotes around quoted value")
347 if unq.contains(quote) {
349 "quoted value contains quote (escaping not supported)"
355 .with_context(|| format!("key {:?}", key))
356 .with_context(|| loc.to_string())?
360 let key = key.replace('-',"_");
361 ent.values.insert(key, ini::Val { val, loc: loc.clone() });
366 #[throws(AE)] // AE includes path
367 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
369 let dir = fs::read_dir(path);
370 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
371 let dir = dir.context("open directory").dcontext(path)?;
373 let ent = ent.context("read directory").dcontext(path)?;
374 let leaf = ent.file_name();
375 let leaf = leaf.to_str();
376 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
377 if leaf.len() == 0 { continue }
378 if ! leaf.chars().all(
379 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
382 // OK we want this one
383 let ent = ent.path();
384 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
389 #[throws(AE)] // AE includes everything
390 fn read_toplevel(&mut self, toplevel: &Path) {
391 enum Anyway { None, Dir }
392 match self.read_file(toplevel, &|e| match e {
393 e if e.kind() == EK::NotFound => Some(Anyway::None),
394 e if e.is_is_a_directory() => Some(Anyway::Dir),
397 .dcontext(toplevel).context("top-level config directory (or file)")?
399 None | Some(Anyway::None) => { },
401 Some(Anyway::Dir) => {
403 let anyway_none = |e: &io::Error| match e {
404 e if e.kind() == EK::NotFound => Some(AnywayNone),
408 let mk = |leaf: &str| {
409 [ toplevel, &PathBuf::from(leaf) ]
410 .iter().collect::<PathBuf>()
413 for &(try_main, desc) in &[
414 ("main.cfg", "main config file"),
415 ("master.cfg", "obsolete-named main config file"),
417 let main = mk(try_main);
419 match self.read_file(&main, &anyway_none)
420 .dcontext(main).context(desc)?
423 Some(AnywayNone) => { },
427 for &(try_dir, desc) in &[
428 ("config.d", "per-link config directory"),
429 ("secrets.d", "per-link secrets directory"),
431 let dir = mk(try_dir);
432 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
434 Some(AnywayNone) => { },
441 #[throws(AE)] // AE includes extra, but does that this is extra
442 fn read_extra(&mut self, extra: &Path) {
445 match self.read_file(extra, &|e| match e {
446 e if e.is_is_a_directory() => Some(AnywayDir),
453 self.read_dir_d(extra, &|_| None::<Void>)?;
461 fn instances(&self, only_server: Option<&ServerName>) -> BTreeSet<LinkName> {
462 let mut links: BTreeSet<LinkName> = default();
464 let mut secrets_anyserver: BTreeSet<&ClientName> = default();
465 let mut secrets_anyclient: BTreeSet<&ServerName> = default();
466 let mut secret_global = false;
468 let mut putative_servers = BTreeSet::new();
469 let mut putative_clients = BTreeSet::new();
471 let mut note_server = |s| {
472 if let Some(only) = only_server { if s != only { return false } }
473 putative_servers.insert(s);
476 let mut note_client = |c| {
477 putative_clients.insert(c);
480 for (section, vars) in &self.sections {
481 let has_secret = || vars.values.contains_key("secret");
482 //dbg!(§ion, has_secret());
486 if ! note_server(&l.server) { continue }
487 note_client(&l.client);
488 if has_secret() { links.insert(l.clone()); }
490 SN::Server(ref s) => {
491 if ! note_server(s) { continue }
492 if has_secret() { secrets_anyclient.insert(s); }
494 SN::Client(ref c) => {
496 if has_secret() { secrets_anyserver.insert(c); }
499 if has_secret() { secret_global = true; }
505 //dbg!(&putative_servers, &putative_clients);
506 //dbg!(&secrets_anyserver, &secrets_anyclient, &secret_global);
508 // Add links which are justified by blanket secrets
509 for (client, server) in iproduct!(
510 putative_clients.into_iter().filter(
512 || secrets_anyserver.contains(c)
513 || ! secrets_anyclient.is_empty()
515 putative_servers.iter().cloned().filter(
517 || secrets_anyclient.contains(s)
518 || ! secrets_anyserver.is_empty()
521 links.insert(LinkName {
522 client: client.clone(),
523 server: server.clone(),
531 struct ResolveContext<'c> {
535 all_sections: Vec<SectionName>,
538 trait Parseable: Sized {
539 fn parse(s: Option<&str>) -> Result<Self, AE>;
540 fn default() -> Result<Self, AE> {
541 Err(anyhow!("setting must be specified"))
544 fn default_for_key(key: &str) -> Self {
545 Self::default().with_context(|| key.to_string())?
549 impl Parseable for Duration {
551 fn parse(s: Option<&str>) -> Duration {
552 // todo: would be nice to parse with humantime maybe
553 Duration::from_secs( s.value()?.parse()? )
556 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
557 impl Parseable for $t {
559 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
560 $( #[throws(AE)] fn default() -> Self { $def } )?
563 parseable_from_str!{u16, default() }
564 parseable_from_str!{u32, default() }
565 parseable_from_str!{String, default() }
566 parseable_from_str!{IpNet, default() }
567 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
568 parseable_from_str!{Uri, default() }
570 impl<T:Parseable> Parseable for Vec<T> {
572 fn parse(s: Option<&str>) -> Vec<T> {
574 .split_ascii_whitespace()
575 .map(|s| Parseable::parse(Some(s)))
576 .collect::<Result<Vec<_>,_>>()?
579 fn default() -> Self { default() }
583 #[derive(Debug,Copy,Clone,Eq,PartialEq)]
584 enum SectionKindList {
592 use SectionKindList as SKL;
595 fn special_server_section() -> Self { SN::Server(ServerName(
596 SPECIAL_SERVER_SECTION.into()
600 impl SectionKindList {
601 fn contains(self, s: &SectionName, end: LinkEnd) -> bool {
604 (SKL::Global, LinkEnd::Client) => matches!(s, SN::Link(_)
609 (SKL::Limits,_) => matches!(s, SN::ServerLimit(_)
612 (SKL::Global, LinkEnd::Server) => matches!(s, SN::Common
615 (SKL::Limited,_) => SKL::PerClient.contains(s, end)
616 | SKL::Limits .contains(s, end),
618 (SKL::ServerName,_) => matches!(s, SN::Common)
619 | matches!(s, SN::Server(ServerName(name))
620 if name == SPECIAL_SERVER_SECTION),
621 (SKL::None,_) => false,
627 fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
628 -> Option<RawValRef<'a,'a,'s>>
629 where S: Iterator<Item=&'s SectionName>
631 for section in sections {
632 if let Some(val) = self.sections
634 .and_then(|s: &ini::Section| s.values.get(key))
636 return Some(RawValRef {
647 pub fn establish_server_name(&self) -> ServerName {
649 let raw = match self.lookup_raw(
651 [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
653 Some(raw) => raw.try_map(|os| os.value())?,
654 None => SPECIAL_SERVER_SECTION,
656 ServerName(raw.into())
660 impl<'c> ResolveContext<'c> {
661 fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
662 -> Option<RawValRef<'c,'c,'c>> {
665 self.all_sections.iter()
666 .filter(|s| sections.contains(s, self.end))
671 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
675 match self.first_of_raw(key, sections) {
677 Some(raw) => Some(raw.try_map(Parseable::parse)?),
682 pub fn ordinary<T>(&self, key: &'static str, skl: SKL) -> T
685 match self.first_of(key, skl)? {
687 None => Parseable::default_for_key(key)?,
692 pub fn limited<T>(&self, key: &'static str, skl: SKL) -> T
693 where T: Parseable + Ord
695 assert_eq!(skl, SKL::Limited);
696 let val = self.ordinary(key, SKL::PerClient)?;
697 if let Some(limit) = self.first_of(key, SKL::Limits)? {
705 pub fn client<T>(&self, key: &'static str, skl: SKL) -> T
706 where T: Parseable + Default {
708 LinkEnd::Client => self.ordinary(key, skl)?,
709 LinkEnd::Server => default(),
713 pub fn server<T>(&self, key: &'static str, skl: SKL) -> T
714 where T: Parseable + Default {
716 LinkEnd::Server => self.ordinary(key, skl)?,
717 LinkEnd::Client => default(),
722 pub fn computed<T>(&self, _key: &'static str, skl: SKL) -> T
725 assert_eq!(skl, SKL::None);
730 pub fn special_ipif(&self, key: &'static str, skl: SKL) -> String {
731 assert_eq!(skl, SKL::PerClient); // we tolerate it in per-client sections
733 LinkEnd::Client => self.ordinary(key, SKL::PerClient)?,
734 LinkEnd::Server => self.ordinary(key, SKL::Global)?,
739 pub fn special_link(&self, _key: &'static str, skl: SKL) -> LinkName {
740 assert_eq!(skl, SKL::None);
745 pub fn special_max_up(&self, key: &'static str, skl: SKL) -> u32 {
746 assert_eq!(skl, SKL::Limited);
748 LinkEnd::Client => self.ordinary(key, SKL::Limited)?,
749 LinkEnd::Server => self.ordinary(key, SKL::Limits)?,
754 impl InstanceConfig {
756 fn complete(&mut self, end: LinkEnd) {
757 let mut vhosts = self.vnetwork.iter()
758 .map(|n| n.hosts()).flatten()
759 .filter({ let vaddr = self.vaddr; move |v| v != &vaddr });
761 if self.vaddr.is_unspecified() {
762 self.vaddr = vhosts.next().ok_or_else(
763 || anyhow!("vnetwork too small to generate vaddrr")
766 if self.vrelay.is_unspecified() {
767 self.vrelay = vhosts.next().ok_or_else(
768 || anyhow!("vnetwork too small to generate vrelay")
774 move |max_batch, key| {
775 if max_batch/2 < mtu {
776 throw!(anyhow!("max batch {:?} ({}) must be >= 2 x mtu ({}) \
777 (to allow for SLIP ESC-encoding)",
778 key, max_batch, mtu))
786 if &self.url == &default::<Uri>() {
787 let addr = self.addrs.get(0).ok_or_else(
788 || anyhow!("client needs addrs or url set")
793 IpAddr::V4(a) => format!("{}", a),
794 IpAddr::V6(a) => format!("[{}]", a),
798 p => format!(":{}", p),
803 self.effective_http_timeout = {
804 let a = self.http_timeout;
805 let b = self.http_timeout_grace;
806 a.checked_add(b).ok_or_else(
807 || anyhow!("calculate effective http timeout ({:?} + {:?})", a, b)
812 let t = self.target_requests_outstanding;
813 let m = self.max_requests_outstanding;
814 if t > m { throw!(anyhow!(
815 "target_requests_outstanding ({}) > max_requests_outstanding ({})",
820 check_batch(self.max_batch_up, "max_batch_up")?;
824 if self.addrs.is_empty() {
825 throw!(anyhow!("missing 'addrs' setting"))
827 check_batch(self.max_batch_down, "max_batch_down")?;
832 fn subst(var: &mut String,
833 kv: &mut dyn Iterator<Item=(&'static str, &dyn Display)>
836 .map(|(k,v)| (k.to_string(), v.to_string()))
837 .collect::<HashMap<String, String>>();
838 let bad = parking_lot::Mutex::new(vec![]);
839 *var = regex_replace_all!(
840 r#"%(?:%|\((\w+)\)s|\{(\w+)\}|.)"#,
842 |whole, k1, k2| (|| Ok::<_,String>({
843 if whole == "%%" { "%" }
844 else if let Some(&k) = [k1,k2].iter().find(|&&s| s != "") {
845 substs.get(k).ok_or_else(
846 || format!("unknown key %({})s", k)
849 throw!(format!("bad percent escape {:?}", &whole));
851 }))().unwrap_or_else(|e| { bad.lock().push(e); "" })
853 let bad = bad.into_inner();
854 if ! bad.is_empty() {
855 throw!(anyhow!("substitution failed: {}", bad.iter().format("; ")));
861 type DD<'d> = &'d dyn Display;
862 fn dv<T:Display>(v: &[T]) -> String {
863 format!("{}", v.iter().format(" "))
865 let mut ipif = mem::take(&mut self.ipif); // lets us borrow all of self
866 let s = &self; // just for abbreviation, below
867 let vnetwork = dv(&s.vnetwork);
868 let vroutes = dv(&s.vroutes);
870 let keys = &["local", "peer", "rnets", "ifname"];
871 let values = match end {
872 Server => [&s.vaddr as DD , &s.vrelay, &vnetwork, &s.ifname_server],
873 Client => [&s.link.client as DD, &s.vaddr, &vroutes, &s.ifname_client],
876 ( "mtu", &s.mtu as DD ),
881 &mut keys.iter().cloned()
883 .chain(always.iter().cloned()),
890 trait ResolveGlobal<'i> where Self: 'i {
891 fn resolve<I>(it: I) -> Self
892 where I: Iterator<Item=&'i Self>;
894 impl<'i,T> ResolveGlobal<'i> for T where T: Eq + Clone + Debug + 'i {
895 fn resolve<I>(mut it: I) -> Self
896 where I: Iterator<Item=&'i Self>
898 let first = it.next().expect("empty instances no global!");
899 for x in it { assert_eq!(x, first); }
905 pub fn read(opts: &Opts, end: LinkEnd) -> Vec<InstanceConfig> {
907 let mut agg = Aggregate::new(
909 InstanceConfig::FIELDS.iter().cloned().collect(),
912 agg.read_string(DEFAULT_CONFIG.into(),
913 "<build-in defaults>".as_ref())
914 .expect("builtin configuration is broken");
916 agg.read_toplevel(&opts.config)?;
917 for extra in &opts.extra_config {
918 agg.read_extra(extra).context("extra config")?;
921 //eprintln!("GOT {:#?}", agg);
924 })().context("read configuration")?;
926 let server_name = match end {
927 LinkEnd::Server => Some(agg.establish_server_name()?),
928 LinkEnd::Client => None,
931 let instances = agg.instances(server_name.as_ref());
932 let mut ics = vec![];
935 for link in instances {
936 let rctx = ResolveContext {
941 SN::Link(link.clone()),
942 SN::Client(link.client.clone()),
943 SN::Server(link.server.clone()),
945 SN::ServerLimit(link.server.clone()),
950 if rctx.first_of_raw("secret", SKL::PerClient).is_none() { continue }
952 let mut ic = InstanceConfig::resolve_instance(&rctx)
953 .with_context(|| format!("resolve config for {}", &link))?;
956 .with_context(|| format!("complete config for {}", &link))?;
964 pub fn startup<F,T>(progname: &str, end: LinkEnd,
965 opts: &Opts, logopts: &LogOpts,
967 where F: FnOnce(Vec<InstanceConfig>) -> Result<T,AE>
971 let ics = config::read(opts, end)?;
972 if ics.is_empty() { throw!(anyhow!("no associations, quitting")); }
978 })().unwrap_or_else(|e| {
979 eprintln!("{}: startup error: {}", progname, &e);