1use std::{
4 collections::HashSet,
5 fs,
6 io,
7 path::{Path, PathBuf},
8 sync::Mutex,
9};
10
11use aho_corasick::AhoCorasick;
12use anyhow::Context as _;
13
14use toml_edit::{
15 DocumentMut,
16 Item,
17 Table,
18 Value,
19};
20use crate::toml_edit_tree::Node;
21
22use sequoia_directories::Component;
23use sequoia_directories::Home;
24
25use crate::Result;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Config {
34 modules: Vec<PathBuf>,
36}
37
38impl Default for Config {
39 fn default() -> Self {
40 Config {
41 modules: Vec::new(),
42 }
43 }
44}
45
46impl Config {
47 pub fn modules(&self) -> &[PathBuf] {
49 &self.modules
50 }
51
52 pub fn to_config_file(&self) -> Result<ConfigFile> {
60 let mut doc = DocumentMut::new();
62
63 doc.as_table_mut()
67 .insert("modules", Item::ArrayOfTables(Default::default()));
68
69 let modules = doc
70 .get_mut("modules").expect("created")
71 .as_array_of_tables_mut().expect("invalid type");
72 for file_name in self.modules.iter() {
73 let mut table = Table::new();
74 table.set(
75 &"path".into(),
76 file_name.to_str()
77 .ok_or_else(|| {
78 anyhow::anyhow!("Path ({}) is not valid UTF-8",
79 file_name.display())
80 })?
81 .into())?;
82
83 modules.push(table);
84 }
85
86 let mut config = Config::default();
88 apply_schema(&mut Some(&mut config), None, doc.iter(),
89 TOP_LEVEL_SCHEMA)?;
90
91 Ok(ConfigFile {
92 doc,
93 config: Mutex::new(Some(config.clone())),
94 })
95 }
96
97 pub fn add_module<P>(&mut self, path: P) -> &mut Self
100 where P: Into<PathBuf>
101 {
102 self.modules.push(path.into());
103 self
104 }
105
106 pub fn extend_modules<P>(&mut self, paths: impl Iterator<Item=P>)
109 -> &mut Self
110 where P: Into<PathBuf>
111 {
112 self.modules.extend(paths.map(|p| p.into()));
113 self
114 }
115}
116
117#[derive(Debug, Default)]
131pub struct ConfigFile {
132 doc: DocumentMut,
133 config: Mutex<Option<Config>>,
134}
135
136impl Clone for ConfigFile {
137 fn clone(&self) -> Self {
138 if let Ok(config) = self.config.try_lock() {
139 Self {
140 doc: self.doc.clone(),
141 config: Mutex::new(config.clone()),
142 }
143 } else {
144 Self {
145 doc: self.doc.clone(),
146 config: Mutex::new(None),
147 }
148 }
149 }
150}
151
152impl ConfigFile {
153 const TEMPLATE: &'static str = "\
156# Configuration template for sq-cryptoki <SQ-CRYPTOKI-VERSION>
157<SQ-CRYPTOKI-CONFIG-PATH-HINT>
158
159# [[module]]
160# path = \"/path/to/some/pkcs11/module\"
161#
162# [[module]]
163# path = \"/path/to/another/pkcs11/module\"
164";
165
166 const TEMPLATE_PATTERNS: &'static [&'static str] = &[
169 "<SQ-CRYPTOKI-VERSION>",
170 "<SQ-CRYPTOKI-CONFIG-PATH-HINT>",
171 ];
172
173 fn config_template(path_hint: Option<&Path>) -> Result<String> {
182 let ac = AhoCorasick::new(Self::TEMPLATE_PATTERNS)?;
183
184 let mut path_hint = path_hint;
185 let path_hint_;
186 if let Some(ph) = path_hint.as_ref() {
187 if let Some(home) = dirs::home_dir() {
188 let home = home.display().to_string();
189 if let Ok(rest) = ph.strip_prefix(&home) {
190 path_hint_ = PathBuf::from("$HOME").join(rest);
191 path_hint = Some(path_hint_.as_ref());
192 }
193 }
194 };
195
196 Ok(ac.replace_all(Self::TEMPLATE, &[
197 &env!("CARGO_PKG_VERSION").to_string(),
198 &if let Some(path_hint) = path_hint {
199 format!(
200 "\n\
201 # To use it, edit it to your liking and write it to\n\
202 # {}",
203 &path_hint.display())
204 } else {
205 "".into()
206 }
207 ]))
208 }
209
210 pub fn default_template(home: Option<&Home>) -> Result<Self> {
223 Self::parse_str(&Self::config_template(home.map(Self::file_name).as_deref())?)
224 }
225
226 pub fn file_name(home: &Home) -> PathBuf {
229 home.config_dir(Component::Keystore)
230 .join("cryptoki")
231 .join("config.toml")
232 }
233
234 pub fn parse_default_home() -> Result<Self> {
241 if let Some(home) = sequoia_directories::Home::default() {
242 Self::parse_home(home)
243 } else {
244 Err(anyhow::anyhow!("Platform does not have a default home directory"))
245 }
246 }
247
248 pub fn parse_home(home: &Home) -> Result<Self> {
255 Self::parse_file(&Self::file_name(home))
256 }
257
258 pub fn parse_file(path: &Path) -> Result<Self> {
268 let config = match fs::read_to_string(&path) {
269 Ok(r) => r,
270 Err(e) if e.kind() == io::ErrorKind::NotFound =>
271 Self::config_template(Some(path))?,
272 Err(e) => return Err(anyhow::Error::from(e).context(
273 format!("Reading configuration file {} failed",
274 path.display()))),
275 };
276
277 Self::parse_str(&config)
278 .with_context(|| {
279 format!("Reading configuration file {}", path.display())
280 })
281 }
282
283 pub fn parse_str(config: &str) -> Result<Self> {
288 let doc: DocumentMut = config.parse()
289 .context("Parsing configuration failed")?;
290
291 let mut config = Config::default();
292 apply_schema(&mut Some(&mut config), None, doc.iter(), TOP_LEVEL_SCHEMA)
293 .context("Parsing configuration failed")?;
294
295 Ok(Self {
296 doc,
297 config: Mutex::new(Some(config)),
298 })
299 }
300
301 pub fn persist_to_home(&self, home: &Home) -> Result<()> {
303 let path = Self::file_name(home);
304 self.persist(path)
305 }
306
307 pub fn persist<P>(&self, path: P) -> Result<()>
309 where P: AsRef<Path>
310 {
311 let path = path.as_ref();
312 let dir = path.parent().unwrap();
313
314 fs::create_dir_all(dir)?;
315
316 let mut t = tempfile::NamedTempFile::new_in(dir)?;
317 self.dump(&mut t)?;
318 t.persist(path)?;
319
320 Ok(())
321 }
322
323 pub fn dump(&self, sink: &mut dyn io::Write) -> Result<()> {
325 write!(sink, "{}", self.doc.to_string())?;
326 Ok(())
327 }
328
329 pub fn to_config(&self) -> Result<Config> {
335 let config = self.config.lock().unwrap();
336
337 if let Some(config) = config.as_ref() {
338 Ok(config.clone())
339 } else {
340 let mut c = Default::default();
341 apply_schema(&mut Some(&mut c), None, self.doc.iter(),
342 TOP_LEVEL_SCHEMA)?;
343 Ok(c)
344 }
345 }
346
347 pub fn as_item(&self) -> &Item {
349 self.doc.as_item()
350 }
351
352 pub fn as_item_mut(&mut self) -> &mut Item {
358 *self.config.lock().unwrap() = None;
360 self.doc.as_item_mut()
361 }
362}
363
364fn apply_schema<'toml>(config: &mut Option<&mut Config>,
371 path: Option<&str>,
372 section: toml_edit::Iter<'toml>,
373 schema: Schema) -> Result<()> {
374 let section = section.collect::<Vec<_>>();
375 let known_keys: Vec<_> =
376 schema.iter().map(|(key, _)| *key).collect();
377
378 debug_assert!(known_keys.iter().all(|&s| &s.to_lowercase() == s),
380 "keys in schema must be lowercase");
381
382 debug_assert!(known_keys.windows(2).all(|v| v[0] <= v[1]),
384 "keys in schema must be sorted");
385 let prefix = if let Some(path) = path {
389 format!("{}.", path)
390 } else {
391 "".to_string()
392 };
393
394 let keys: HashSet<&str> = section
395 .iter().map(|(key, _value)| *key)
396 .collect();
397
398 let mut allowed_keys: Vec<&str> = known_keys.to_vec();
401 if let Some(ignore) = section.iter()
402 .find_map(|(k, v)| (*k == "ignore_invalid").then_some(*v))
403 {
404 allowed_keys.push("ignore_invalid");
405 match ignore {
406 Item::Value(Value::String(k)) =>
407 allowed_keys.push(k.value().as_str()),
408 Item::Value(Value::Array(ks)) => {
409 for k in ks {
410 if let Value::String(k) = k {
411 allowed_keys.push(k.value().as_str());
412 } else {
413 Err(Error::ParseError(format!(
414 "'{}ignore_invalid' takes a string \
415 or an array of strings",
416 prefix)))?
417 }
418 }
419 }
420 _ => {
421 return Err(Error::ParseError(format!(
422 "Invalid value for '{}ignore_invalid': {}, \
423 expected a string or an array of strings",
424 prefix, ignore)).into());
425 }
426 }
427 }
428
429 let unknown_keys = keys
431 .difference(&allowed_keys.into_iter().collect())
432 .map(|s| *s)
433 .collect::<Vec<_>>();
434 if ! unknown_keys.is_empty() {
435 return Err(Error::ParseError(format!(
436 "{} has unknown keys: {}, valid keys are: {}",
437 if let Some(path) = path {
438 path
439 } else {
440 "top-level section"
441 },
442 unknown_keys.join(", "),
443 known_keys.join(", "))).into());
445 }
446
447 for (key, value) in §ion {
449 if let Ok(i) = schema.binary_search_by_key(key, |(k, _)| k) {
450 let apply = schema[i].1;
451 (apply)(config, &format!("{}{}", prefix, key), value)
452 .with_context(|| format!("Error validating {:?}", key))?;
453 }
454 }
455
456 Ok(())
457}
458
459#[non_exhaustive]
464#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
465pub enum Error {
466 #[error("Parse error: {0}")]
468 ParseError(String),
469
470 #[error("Configuration item {0:?} is not a {1} but a {2}")]
471 BadType(String, &'static str, &'static str),
472}
473
474impl Error {
475 fn bad_item_type(path: &str, i: &Item, want_type: &'static str)
477 -> anyhow::Error
478 {
479 Error::BadType(path.into(), want_type, i.type_name()).into()
480 }
481
482 #[allow(unused)]
484 fn bad_value_type(path: &str, v: &Value, want_type: &'static str)
485 -> anyhow::Error
486 {
487 Error::BadType(path.into(), want_type, v.type_name()).into()
488 }
489}
490
491type Applicator = fn(&mut Option<&mut Config>, &str, &Item)
494 -> Result<()>;
495
496#[allow(unused)]
498fn apply_nop(_: &mut Option<&mut Config>,
499 _: &str, _: &Item)
500 -> Result<()>
501{
502 Ok(())
503}
504
505type Schema = &'static [(&'static str, Applicator)];
507
508const TOP_LEVEL_SCHEMA: Schema = &[
510 ("modules", apply_modules),
511];
512
513const MODULES_SCHEMA: Schema = &[
515 ("path", apply_modules_path),
516];
517
518fn apply_modules(config: &mut Option<&mut Config>,
520 path: &str, item: &Item)
521 -> Result<()>
522{
523 let tables = item.as_array_of_tables()
524 .ok_or_else(|| Error::bad_item_type(path, item, "array of tables"))?;
525 for (i, table) in tables.iter().enumerate() {
526 let path = format!("{}.{}", path, i);
527 apply_schema(config, Some(&path), table.iter(), MODULES_SCHEMA)?;
528 }
529 Ok(())
530}
531
532fn apply_modules_path(config: &mut Option<&mut Config>,
534 path: &str, item: &Item)
535 -> Result<()>
536{
537 let path = item.as_str()
538 .ok_or_else(|| Error::bad_item_type(path, item, "string"))?;
539
540 if let Some(config) = config {
541 config.modules.push(path.into());
542 }
543
544 Ok(())
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550
551 use toml_edit::Array;
552 use toml_edit::Formatted;
553
554 #[test]
557 fn default_template_is_default() {
558 let default_template
559 = ConfigFile::default_template(None).expect("invalid template")
560 .to_config().expect("invalid template");
561
562 assert_eq!(Config::default(), default_template);
563 }
564
565 #[test]
567 fn config_file() {
568 let modules = [ "/some/pkcs11.dll", "/other/pkcs11.dll" ];
569
570 let base = modules.iter()
572 .map(|module| {
573 format!("\
574[[modules]]
575path = \"{}\"", module)
576 })
577 .collect::<Vec<String>>()
578 .join("\n");
579
580 let config = ConfigFile::parse_str(&base)
581 .expect("invalid template")
582 .to_config()
583 .expect("invalid template");
584
585 let modules = modules
586 .into_iter()
587 .map(PathBuf::from).collect::<Vec<PathBuf>>();
588 assert_eq!(&config.modules(), &modules);
589
590 let invalid = format!("{}
591foo = \"blah\"", base);
592 assert!(ConfigFile::parse_str(&invalid).is_err());
593
594 let ignore_invalid = format!("{}
595ignore_invalid = [ \"foo\", \"nonexistent\" ]", invalid);
596 let config = ConfigFile::parse_str(&ignore_invalid)
597 .expect("invalid template")
598 .to_config()
599 .expect("invalid template");
600
601 assert_eq!(&config.modules(), &modules);
602 }
603
604 #[test]
606 fn modify_config_file() {
607 let modules = [ "/some/pkcs11.dll", "/other/pkcs11.dll" ];
608
609 let base = modules.iter()
611 .map(|module| {
612 format!("\
613[[modules]]
614path = \"{}\"", module)
615 })
616 .collect::<Vec<String>>()
617 .join("\n");
618
619 let mut config_file = ConfigFile::parse_str(&base)
620 .expect("invalid template");
621
622 let config = config_file
623 .to_config()
624 .expect("invalid template");
625
626 let modules = modules
627 .into_iter()
628 .map(PathBuf::from).collect::<Vec<PathBuf>>();
629 assert_eq!(&config.modules(), &modules);
630
631 let doc = config_file.as_item_mut();
634 doc.set(&"foo".into(), Value::String(Formatted::new("bar".to_string())))
635 .expect("couldn't set");
636
637 assert!(config_file.to_config().is_err());
638
639 let doc = config_file.as_item_mut();
641 let mut ignore_invalid = Array::new();
642 ignore_invalid.push("foo");
643 doc.set(&"ignore_invalid".into(), Value::Array(ignore_invalid))
644 .expect("couldn't set");
645
646 let config = config_file
647 .to_config()
648 .expect("invalid template");
649
650 let modules = modules
651 .into_iter()
652 .map(PathBuf::from).collect::<Vec<PathBuf>>();
653 assert_eq!(&config.modules(), &modules);
654 }
655}