chiark / gitweb /
identify links before away from trait again?
[hippotat.git] / src / config.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 use configparser::ini::Ini;
8
9 static DEFAULT_CONFIG: &str = r#"
10 [COMMON]
11 max_batch_down = 65536
12 max_queue_time = 10
13 target_requests_outstanding = 3
14 http_timeout = 30
15 http_timeout_grace = 5
16 max_requests_outstanding = 6
17 max_batch_up = 4000
18 http_retry = 5
19 port = 80
20 vroutes = ''
21 ifname_client = hippo%%d
22 ifname_server = shippo%%d
23 max_clock_skew = 300
24
25 ipif = userv root ipif %(local)s,%(peer)s,%(mtu)s,slip,%(ifname)s %(rnets)s
26
27 mtu = 1500
28
29 vvnetwork = 172.24.230.192
30
31 [LIMIT]
32 max_batch_down = 262144
33 max_queue_time = 121
34 http_timeout = 121
35 target_requests_outstanding = 10
36 "#;
37
38 #[derive(StructOpt,Debug)]
39 pub struct Opts {
40   /// Top-level config file or directory
41   ///
42   /// Look for `main.cfg`, `config.d` and `secrets.d` here.
43   ///
44   /// Or if this is a file, just read that file.
45   #[structopt(long, default_value="/etc/hippotat")]
46   pub config: PathBuf,
47   
48   /// Additional config files or dirs, which can override the others
49   #[structopt(long, multiple=true, number_of_values=1)]
50   pub extra_config: Vec<PathBuf>,
51 }
52
53 #[ext]
54 impl<'s> Option<&'s str> {
55   #[throws(AE)]
56   fn value(self) -> &'s str {
57     self.ok_or_else(|| anyhow!("value needed"))?
58   }
59 }
60
61 #[derive(Clone)]
62 pub struct Secret(pub String);
63 impl Parseable for Secret {
64   #[throws(AE)]
65   fn parse(s: Option<&str>) -> Self {
66     let s = s.value()?;
67     if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
68     Secret(s.into())
69   }
70   #[throws(AE)]
71   fn default() -> Self { Secret(default()) }
72 }
73 impl Debug for Secret {
74   #[throws(fmt::Error)]
75   fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
76 }
77
78 #[derive(hippotat_macros::ResolveConfig)]
79 #[derive(Debug,Clone)]
80 pub struct InstanceConfig {
81   // Exceptional settings
82   #[special(special_server, SKL::ServerName)] pub server: ServerName,
83   pub                                             secret: Secret,
84   #[special(special_ipif, SKL::Ordinary)]     pub ipif:   String,
85
86   // Capped settings:
87   #[limited]    pub max_batch_down:               u32,
88   #[limited]    pub max_queue_time:               Duration,
89   #[limited]    pub http_timeout:                 Duration,
90   #[limited]    pub target_requests_outstanding:  u32,
91
92   // Ordinary settings:
93   pub addrs:                        Vec<IpAddr>,
94   pub vnetwork:                     Vec<IpNet>,
95   pub vaddr:                        Vec<IpAddr>,
96   pub vrelay:                       IpAddr,
97   pub port:                         u16,
98   pub mtu:                          u32,
99   pub ifname_server:                String,
100   pub ifname_client:                String,
101
102   // Ordinary settings, used by server only:
103   #[server]  pub max_clock_skew:               Duration,
104
105   // Ordinary settings, used by client only:
106   #[client]  pub http_timeout_grace:           Duration,
107   #[client]  pub max_requests_outstanding:     u32,
108   #[client]  pub max_batch_up:                 u32,
109   #[client]  pub http_retry:                   Duration,
110   #[client]  pub url:                          Uri,
111   #[client]  pub vroutes:                      Vec<IpNet>,
112 }
113
114 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
115 pub enum SectionName {
116   Link(LinkName),
117   Client(ClientName),
118   Server(ServerName), // includes SERVER, which is slightly special
119   ServerLimit(ServerName),
120   GlobalLimit,
121   Common,
122 }
123 pub use SectionName as SN;
124
125 #[derive(Debug,Clone)]
126 struct RawVal { raw: Option<String>, loc: Arc<PathBuf> }
127 type SectionMap = HashMap<String, RawVal>;
128
129 struct RawValRef<'v,'l,'s> {
130   raw: Option<&'v str>,
131   key: &'static str,
132   loc: &'l Path,
133   section: &'s SectionName,
134 }
135
136 impl<'v> RawValRef<'v,'_,'_> {
137   #[throws(AE)]
138   fn try_map<F,T>(&self, f: F) -> T
139   where F: FnOnce(Option<&'v str>) -> Result<T, AE> {
140     f(self.raw)
141       .with_context(|| format!(r#"file {:?}, section "{:?}", key "{}"#,
142                                self.loc, self.section, self.key))?
143   }
144 }
145
146 pub struct Config {
147   opts: Opts,
148 }
149
150 static OUTSIDE_SECTION: &str = "[";
151 static SPECIAL_SERVER_SECTION: &str = "SERVER";
152
153 #[derive(Default,Debug)]
154 struct Aggregate {
155   sections: HashMap<SectionName, SectionMap>,
156 }
157
158 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
159 #[ext]
160 impl<'f,A> OkAnyway<'f,A> {
161   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
162     let e = r.as_ref().err()?;
163     let k = e.kind();
164     let a = self(k)?;
165     Some(a)
166   }
167 }
168
169 impl FromStr for SectionName {
170   type Err = AE;
171   #[throws(AE)]
172   fn from_str(s: &str) -> Self {
173     match s {
174       "COMMON" => return SN::Common,
175       "LIMIT" => return SN::GlobalLimit,
176       _ => { }
177     };
178     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
179     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
180     let (server, client) = s.split_ascii_whitespace().collect_tuple()
181       .ok_or_else(|| anyhow!(
182         "bad section name {:?} \
183          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
184         s
185       ))?;
186     let server = server.parse().context("server name in link section name")?;
187     if client == "LIMIT" { return SN::ServerLimit(server) }
188     let client = client.parse().context("client name in link section name")?;
189     SN::Link(LinkName { server, client })
190   }
191 }
192
193 impl Aggregate {
194   #[throws(AE)] // AE does not include path
195   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
196   {
197     let f = fs::File::open(path);
198     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
199     let mut f = f.context("open")?;
200
201     let mut s = String::new();
202     let y = f.read_to_string(&mut s);
203     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
204     y.context("read")?;
205
206     self.read_string(s, path)?;
207     None
208   }
209
210   #[throws(AE)] // AE does not include path
211   fn read_string(&mut self, s: String, path_for_loc: &Path) {
212     let mut ini = Ini::new_cs();
213     ini.set_default_section(OUTSIDE_SECTION);
214     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
215     let map = mem::take(ini.get_mut_map());
216     if map.get(OUTSIDE_SECTION).is_some() {
217       throw!(anyhow!("INI file contains settings outside a section"));
218     }
219
220     let loc = Arc::new(path_for_loc.to_owned());
221
222     for (sn, vars) in map {
223       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
224
225       let sn = sn.parse().dcontext(&sn)?;
226         self.sections.entry(sn)
227         .or_default()
228         .extend(
229           vars.into_iter()
230             .map(|(k,raw)| {
231               (k.replace('-',"_"),
232                RawVal { raw, loc: loc.clone() })
233             })
234         );
235     }
236     
237   }
238
239   #[throws(AE)] // AE includes path
240   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
241   {
242     let dir = fs::read_dir(path);
243     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
244     let dir = dir.context("open directory").dcontext(path)?;
245     for ent in dir {
246       let ent = ent.context("read directory").dcontext(path)?;
247       let leaf = ent.file_name();
248       let leaf = leaf.to_str();
249       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
250       if leaf.len() == 0 { continue }
251       if ! leaf.chars().all(
252         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
253       ) { continue }
254
255       // OK we want this one
256       let ent = ent.path();
257       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
258     }
259     None
260   }
261
262   #[throws(AE)] // AE includes everything
263   fn read_toplevel(&mut self, toplevel: &Path) {
264     enum Anyway { None, Dir }
265     match self.read_file(toplevel, &|k| match k {
266       EK::NotFound => Some(Anyway::None),
267       EK::IsADirectory => Some(Anyway::Dir),
268       _ => None,
269     })
270       .dcontext(toplevel).context("top-level config directory (or file)")?
271     {
272       None | Some(Anyway::None) => { },
273
274       Some(Anyway::Dir) => {
275         struct AnywayNone;
276         let anyway_none = |k| match k {
277           EK::NotFound => Some(AnywayNone),
278           _ => None,
279         };
280
281         let mk = |leaf: &str| {
282           [ toplevel, &PathBuf::from(leaf) ]
283             .iter().collect::<PathBuf>()
284         };
285
286         for &(try_main, desc) in &[
287           ("main.cfg", "main config file"),
288           ("master.cfg", "obsolete-named main config file"),
289         ] {
290           let main = mk(try_main);
291
292           match self.read_file(&main, &anyway_none)
293             .dcontext(main).context(desc)?
294           {
295             None => break,
296             Some(AnywayNone) => { },
297           }
298         }
299
300         for &(try_dir, desc) in &[
301           ("config.d", "per-link config directory"),
302           ("secrets.d", "per-link secrets directory"),
303         ] {
304           let dir = mk(try_dir);
305           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
306             None => { },
307             Some(AnywayNone) => { },
308           }
309         }
310       }
311     }
312   }
313
314   #[throws(AE)] // AE includes extra, but does that this is extra
315   fn read_extra(&mut self, extra: &Path) {
316     struct AnywayDir;
317
318     match self.read_file(extra, &|k| match k {
319       EK::IsADirectory => Some(AnywayDir),
320       _ => None,
321     })
322       .dcontext(extra)?
323     {
324       None => return,
325       Some(AnywayDir) => {
326         self.read_dir_d(extra, &|_| None::<Void>)?;
327       }
328     }
329
330   }
331 }
332
333 #[derive(Debug)]
334 enum Which<T> {
335   All,
336   These(T),
337 }
338
339 struct MeansForEnd<'m,U,P> {
340   us_spec: Which<&'m U>,
341   peer:    Which<&'m P>,
342 }
343
344 trait InstancesForEnd: Eq {
345   type Peer: Ord + Eq + Hash + Debug;
346   fn section_means<'s>(&self, s: &'s SectionName)
347                        -> MeansForEnd<'s, Self, Peer>
348 }
349
350 impl InstanceForEnd for ServerName {
351   type Peer = ClientName;
352   fn section_means<'s>(&'_ self, s: &'s SectionName)
353                        -> Option<MeansForEnd<'s>> {
354     use Which:*;
355     let (us_spec, peer) = match s {
356       SN::Link(l)            => (These(l.server), These(l.client)),
357       SN::Server(server)     => (These(  server), All),
358       SN::Client(client)     => (All,             These(  client)),
359       SN::Common             => (All,             All),
360       _ => return None,
361     };
362     MeansForEnd { us_spec, peer }
363   }
364 }
365
366 impl Aggregate {
367   fn instances_for<N>(&self, us: N) -> Vec<LinkName>
368   where N: InstancesForEnd,
369   {
370     use Which::*;
371     let mut secrets = Which::These(BTreeSet::new());
372     let mut putative_selves = BTreeSet::new();
373     let mut putative_peers  = BTreeSet::new();
374
375     let matching_means = |section: &SectionName| {
376       let means = us.section_means(section)?;
377       if match means.us_spec {
378         These(u) => if u == us,
379         All      => true,
380       } { Some(means) } else { None }
381     };
382
383     for (section, vars) in &self.agg.sections {
384
385       if let Some(means) = matching_means(section) {
386         
387
388       if ! vars.has_key("secret") { continue }
389
390       let tsecrets = match secrets {
391         These(ref mut s) => s,
392         All => break,
393       };
394
395       if let Some(means) = matching_means(section) {
396         match means.peer {
397           Which::These(ypeer) => tsecrets.insert(ypeer),
398           Which::All          => secrets = Which::All,
399         }
400       }
401
402     }
403
404     let links = vec![];
405
406     for (section, vars) in &self.agg.sections {
407
408       if let Some(means) = matching_means(section) {
409
410         if match secrets {
411           All => true,
412           These(s) => s.contains(means.peer),
413         } {
414
415           links.push( us.
416         
417
418       match section {
419         SN::Link(LinkName { ref client, ref srver })
420           if server == &server_name
421           => tclients.insert(client),
422
423         SN::Client(ref client)
424           => tclients.insert(client),
425
426         SN::Server(ref server) | SN::Common
427           => tclients.
428           
429         }
430         
431
432     let has_secret = .iter().filter_map(|section, vars| {
433
434       
435
436       match section {
437
438       SN::
439         
440       
441
442     let links = self.agg.sections.iter().filter_map(|section| match section {
443
444       SN::Link(LinkName { ref client, .. }) |
445       SN::Client(ref client)                => Some(client.clone()),
446
447       SN::Server(_) | SN::ServerLimit(_) |
448       SN::GlobalLimit : SN::Common => None  => None,
449
450     }).filter(|client| {
451
452       self.lookup_raw("secret", SKL::Ordinary).is_some()
453
454     }).map(|client| {
455
456       
457       
458         
459         |
460   }
461 }
462
463 struct ResolveContext<'c> {
464   agg: &'c Aggregate,
465   link: &'c LinkName,
466   end: LinkEnd,
467   server_name: ServerName,
468   all_sections: Vec<SectionName>,
469 }
470
471 trait Parseable: Sized {
472   fn parse(s: Option<&str>) -> Result<Self, AE>;
473   fn default() -> Result<Self, AE> {
474     Err(anyhow!("setting must be specified"))
475   }
476   #[throws(AE)]
477   fn default_for_key(key: &str) -> Self {
478     Self::default().with_context(|| key.to_string())?
479   }
480 }
481
482 impl Parseable for Duration {
483   #[throws(AE)]
484   fn parse(s: Option<&str>) -> Duration {
485     // todo: would be nice to parse with humantime maybe
486     Duration::from_secs( s.value()?.parse()? )
487   }
488 }
489 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
490   impl Parseable for $t {
491     #[throws(AE)]
492     fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
493     $( #[throws(AE)] fn default() -> Self { $def } )?
494   }
495 } }
496 parseable_from_str!{u16, default() }
497 parseable_from_str!{u32, default() }
498 parseable_from_str!{String, default() }
499 parseable_from_str!{IpNet, default() }
500 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
501 parseable_from_str!{Uri, default() }
502
503 impl<T:Parseable> Parseable for Vec<T> {
504   #[throws(AE)]
505   fn parse(s: Option<&str>) -> Vec<T> {
506     s.value()?
507       .split_ascii_whitespace()
508       .map(|s| Parseable::parse(Some(s)))
509       .collect::<Result<Vec<_>,_>>()?
510   }
511 }
512
513
514 #[derive(Debug,Copy,Clone)]
515 enum SectionKindList {
516   Ordinary,
517   Limited,
518   Limits,
519   ClientAgnostic,
520   ServerName,
521 }
522 use SectionKindList as SKL;
523
524 impl SectionName {
525   fn special_server_section() -> Self { SN::Server(ServerName(
526     SPECIAL_SERVER_SECTION.into()
527   )) }
528 }
529
530 impl SectionKindList {
531   fn contains(self, s: &SectionName) -> bool {
532     match self {
533       SKL::Ordinary       => matches!(s, SN::Link(_)
534                                        | SN::Client(_)
535                                        | SN::Server(_)
536                                        | SN::Common),
537
538       SKL::Limits         => matches!(s, SN::ServerLimit(_)
539                                        | SN::GlobalLimit),
540
541       SKL::ClientAgnostic => matches!(s, SN::Common
542                                        | SN::Server(_)),
543
544       SKL::Limited        => SKL::Ordinary.contains(s)
545                            | SKL::Limits  .contains(s),
546
547       SKL::ServerName     => matches!(s, SN::Common)
548                            | matches!(s, SN::Server(ServerName(name))
549                                          if name == SPECIAL_SERVER_SECTION),
550     }
551   }
552 }
553
554 impl Aggregate {
555   fn lookup_raw<'a,'s,S>(&'a self, key: &'static str, sections: S)
556                        -> Option<RawValRef<'a,'a,'s>>
557   where S: Iterator<Item=&'s SectionName>
558   {
559     for section in sections {
560       if let Some(raw) = self.sections
561         .get(section)
562         .and_then(|vars: &SectionMap| vars.get(key))
563       {
564         return Some(RawValRef {
565           raw: raw.raw.as_deref(),
566           loc: &raw.loc,
567           section, key,
568         })
569       }
570     }
571     None
572   }
573
574   #[throws(AE)]
575   pub fn establish_server_name(&self) -> ServerName {
576     let key = "server";
577     let raw = match self.lookup_raw(
578       key,
579       [ &SectionName::Common, &SN::special_server_section() ].iter().cloned()
580     ) {
581       Some(raw) => raw.try_map(|os| os.value())?,
582       None => SPECIAL_SERVER_SECTION,
583     };
584     ServerName(raw.into())
585   }
586 }
587
588 impl<'c> ResolveContext<'c> {
589   fn first_of_raw(&'c self, key: &'static str, sections: SectionKindList)
590                   -> Option<RawValRef<'c,'c,'c>> {
591     self.agg.lookup_raw(
592       key,
593       self.all_sections.iter()
594         .filter(|s| sections.contains(s))
595     )
596   }
597
598   #[throws(AE)]
599   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
600                  -> Option<T>
601   where T: Parseable
602   {
603     match self.first_of_raw(key, sections) {
604       None => None,
605       Some(raw) => Some(raw.try_map(Parseable::parse)?),
606     }
607   }
608
609   #[throws(AE)]
610   pub fn ordinary<T>(&self, key: &'static str) -> T
611   where T: Parseable
612   {
613     match self.first_of(key, SKL::Ordinary)? {
614       Some(y) => y,
615       None => Parseable::default_for_key(key)?,
616     }
617   }
618
619   #[throws(AE)]
620   pub fn limited<T>(&self, key: &'static str) -> T
621   where T: Parseable + Ord
622   {
623     let val = self.ordinary(key)?;
624     if let Some(limit) = self.first_of(key, SKL::Limits)? {
625       min(val, limit)
626     } else {
627       val
628     }
629   }
630
631   #[throws(AE)]
632   pub fn client<T>(&self, key: &'static str) -> T
633   where T: Parseable {
634     match self.end {
635       LinkEnd::Client => self.ordinary(key)?,
636       LinkEnd::Server => Parseable::default_for_key(key)?,
637     }
638   }
639   #[throws(AE)]
640   pub fn server<T>(&self, key: &'static str) -> T
641   where T: Parseable {
642     match self.end {
643       LinkEnd::Server => self.ordinary(key)?,
644       LinkEnd::Client => Parseable::default_for_key(key)?,
645     }
646   }
647
648   #[throws(AE)]
649   pub fn special_ipif(&self, key: &'static str) -> String {
650     match self.end {
651       LinkEnd::Client => self.ordinary(key)?,
652       LinkEnd::Server => {
653         self.first_of(key, SKL::ClientAgnostic)?
654           .unwrap_or_default()
655       },
656     }
657   }
658
659   #[throws(AE)]
660   pub fn special_server(&self, key: &'static str) -> ServerName {
661     self.server_name.clone()
662   }
663 }
664
665 #[throws(AE)]
666 pub fn read() {
667   let opts = config::Opts::from_args();
668
669   let agg = (||{
670     let mut agg = Aggregate::default();
671
672     agg.read_string(DEFAULT_CONFIG.into(),
673                     "<build-in defaults>".as_ref()).unwrap();
674
675     agg.read_toplevel(&opts.config)?;
676     for extra in &opts.extra_config {
677       agg.read_extra(extra).context("extra config")?;
678     }
679
680     eprintln!("GOT {:#?}", agg);
681
682     Ok::<_,AE>(agg)
683   })().context("read configuration")?;
684
685   let server_name = agg.establish_server_name()?;
686
687   let link = LinkName {
688     server: "fooxxx".parse().unwrap(),
689     client: "127.0.0.1".parse().unwrap(),
690   };
691
692   let rctx = ResolveContext {
693     agg: &agg,
694     link: &link,
695     end: LinkEnd::Server,
696     server_name,
697     all_sections: vec![
698       SN::Link(link.clone()),
699       SN::Client(link.client.clone()),
700       SN::Server(link.server.clone()),
701       SN::Common,
702       SN::ServerLimit(link.server.clone()),
703       SN::GlobalLimit,
704     ],
705   };
706
707     let server_name = self.establish_server_name()
708       .context("establish server name")?;
709
710   let ic = InstanceConfig::resolve_instance(&rctx)
711     .context("resolve config xxx for")?;
712
713   eprintln!("{:?}", &ic);
714 }