aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/config/mod.rs24
-rw-r--r--src/federation/party.rs170
2 files changed, 187 insertions, 7 deletions
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 0ed22a2..87f53ba 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -2150,11 +2150,25 @@ pub(crate) fn merged(
matches: &ArgMatches,
options: &'static [OptionSpec],
) -> Result<(Layer, Vec<PathBuf>)> {
- let files: Vec<PathBuf> = matches
- .get_many::<String>(CONFIG)
- .into_iter()
- .flatten()
- .map(PathBuf::from)
+ merged_with(matches, options, &[])
+}
+
+/// As `merged`, the files `first` read before those `matches` names, which win over them.
+pub(crate) fn merged_with(
+ matches: &ArgMatches,
+ options: &'static [OptionSpec],
+ first: &[PathBuf],
+) -> Result<(Layer, Vec<PathBuf>)> {
+ let files: Vec<PathBuf> = first
+ .iter()
+ .cloned()
+ .chain(
+ matches
+ .get_many::<String>(CONFIG)
+ .into_iter()
+ .flatten()
+ .map(PathBuf::from),
+ )
.collect();
let mut merged = Layer::new();
for path in &files {
diff --git a/src/federation/party.rs b/src/federation/party.rs
index 78c31e2..bacca3d 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -85,6 +85,16 @@ fn command() -> Command {
.long_version(crate::release::described())
.about("A party's client of a federation: signs its events, and votes by its record");
config::with_options(command, config::PARTY_OPTIONS)
+ .arg(
+ Arg::new("federation")
+ .long("federation")
+ .value_name("NAME")
+ .help(
+ "The federation to work with, by the name of its directory in \
+ ~/.config/continuum/federations: its party.toml, record and key. Where \
+ there is one, and no --config, that one",
+ ),
+ )
.subcommand_required(true)
.subcommand(
Command::new("init")
@@ -252,12 +262,130 @@ fn changes() -> ArgGroup {
.multiple(true)
}
+/// Where the client keeps a directory for each federation, by its name: `continuum/
+/// federations` in `$XDG_CONFIG_HOME`, else in `~/.config`.
+fn federations() -> Option<PathBuf> {
+ let base = std::env::var_os("XDG_CONFIG_HOME")
+ .filter(|dir| !dir.is_empty())
+ .map(PathBuf::from)
+ .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
+ Some(base.join("continuum").join("federations"))
+}
+
+/// The directory of the federation the client works with: the one `--federation` names;
+/// else, without `--config`, the only one in `all` (`federations`). None where there is
+/// none, and an error where there are several.
+fn federation(matches: &ArgMatches, all: Option<&Path>) -> Result<Option<PathBuf>> {
+ if let Some(name) = matches.get_one::<String>("federation") {
+ if name.is_empty() || name.contains('/') || name == "." || name == ".." {
+ bail!("--federation {name:?}: a federation is named by one segment of a path");
+ }
+ let all = all.context("no directory for federations: set HOME or XDG_CONFIG_HOME")?;
+ return Ok(Some(all.join(name)));
+ }
+ let Some(all) = all else {
+ return Ok(None);
+ };
+ if matches.get_many::<String>("config").is_some() || !all.is_dir() {
+ return Ok(None);
+ }
+ let mut names: Vec<String> = std::fs::read_dir(all)
+ .with_context(|| format!("Reading {}", all.display()))?
+ .filter_map(|entry| entry.ok())
+ .filter(|entry| entry.path().is_dir())
+ .filter_map(|entry| entry.file_name().into_string().ok())
+ .collect();
+ names.sort();
+ match names.as_slice() {
+ [] => Ok(None),
+ [one] => Ok(Some(all.join(one))),
+ several => bail!(
+ "{} federations in {} ({}): choose one with --federation",
+ several.len(),
+ all.display(),
+ several.join(", ")
+ ),
+ }
+}
+
+/// A federation's directory begun by `init`: made, only its owner reading it, with a
+/// `party.toml` holding the options given on the command line, `node`, `token` and `key`,
+/// the key's path made absolute.
+fn begin_federation(dir: &Path, matches: &ArgMatches) -> Result<()> {
+ use clap::parser::ValueSource;
+ use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(dir)
+ .with_context(|| format!("Making {}", dir.display()))?;
+ let mut given = toml::Table::new();
+ for name in ["node", "token", "key"] {
+ if matches.value_source(name) != Some(ValueSource::CommandLine) {
+ continue;
+ }
+ let Some(value) = matches.get_one::<String>(name) else {
+ continue;
+ };
+ let value = if name == "key" && Path::new(value).exists() {
+ std::path::absolute(value)?.display().to_string()
+ } else {
+ value.clone()
+ };
+ given.insert(name.to_owned(), toml::Value::String(value));
+ }
+ let file = dir.join("party.toml");
+ if given.is_empty() || file.exists() {
+ return Ok(());
+ }
+ let mut out = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&file)
+ .with_context(|| format!("Writing {}", file.display()))?;
+ std::io::Write::write_all(&mut out, toml::to_string(&given)?.as_bytes())?;
+ println!("wrote {}", file.display());
+ Ok(())
+}
+
/// Runs the client, as its arguments say.
pub(crate) async fn main() -> Result<()> {
let matches = command().get_matches();
let (name, sub) = matches.subcommand().expect("a subcommand is required");
- let (merged, _) = config::merged(&matches, config::PARTY_OPTIONS)?;
- let options: Options = config::read(&merged)?;
+ // Those that use no options read no federation's.
+ let dir = if matches!(name, "twice" | "root" | "judge") {
+ None
+ } else {
+ federation(&matches, federations().as_deref())?
+ };
+ if let Some(dir) = &dir {
+ if name == "init" {
+ begin_federation(dir, &matches)?;
+ } else if !dir.is_dir() {
+ bail!(
+ "no federation {}: {} isn't there; `init` begins one",
+ dir.file_name().unwrap_or_default().to_string_lossy(),
+ dir.display()
+ );
+ }
+ }
+ let first: Vec<PathBuf> = dir
+ .iter()
+ .map(|dir| dir.join("party.toml"))
+ .filter(|file| file.exists())
+ .collect();
+ let (merged, _) = config::merged_with(&matches, config::PARTY_OPTIONS, &first)?;
+ let mut options: Options = config::read(&merged)?;
+ // In a federation's directory, its record and key, where none other is named.
+ if let Some(dir) = &dir {
+ if options.record.is_none() {
+ options.record = Some(dir.join("record").display().to_string());
+ }
+ if options.key.is_none() && dir.join("key").exists() {
+ options.key = Some(dir.join("key").display().to_string());
+ }
+ }
if name == "twice" {
let records = sub
.get_many::<String>("records")
@@ -1298,6 +1426,44 @@ mod tests {
assert_eq!(changed_by(Some(&[]), &[], &[], true).unwrap(), list(&[]));
}
+ /// The federation the client works with: the one `--federation` names; else, without
+ /// `--config`, the only one there is; none where there is none; and an error where
+ /// there are several. `init` begins one, with the options given on the command line.
+ #[test]
+ fn the_federation_is_the_one_there_is_or_the_one_named() {
+ let all = crate::files::scratch_dir("party-federations");
+ let matches = |args: &[&str]| {
+ super::command()
+ .try_get_matches_from(["continuum-party"].iter().chain(args).chain(&["proposals"]))
+ .unwrap()
+ };
+ let chosen = |args: &[&str]| super::federation(&matches(args), Some(&all));
+ assert_eq!(chosen(&[]).unwrap(), None);
+ std::fs::create_dir(all.join("krebs")).unwrap();
+ assert_eq!(chosen(&[]).unwrap(), Some(all.join("krebs")));
+ assert_eq!(chosen(&["--config", "x.toml"]).unwrap(), None);
+ std::fs::create_dir(all.join("test")).unwrap();
+ let several = chosen(&[]).unwrap_err().to_string();
+ assert!(several.contains("krebs, test"), "{several}");
+ assert_eq!(
+ chosen(&["--federation", "test"]).unwrap(),
+ Some(all.join("test"))
+ );
+ assert!(chosen(&["--federation", "../x"]).is_err());
+ assert_eq!(super::federation(&matches(&[]), None).unwrap(), None);
+ // Begun with the options given on the command line, the default node left out.
+ let begun = all.join("new");
+ super::begin_federation(&begun, &matches(&["--token", "t"])).unwrap();
+ let written = std::fs::read_to_string(begun.join("party.toml")).unwrap();
+ assert_eq!(written.trim(), r#"token = "t""#);
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(begun.join("party.toml"))
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+
/// Votes, proposals, key sets and node lists are signed with a key the current version
/// names for their party; another key, or a party the version doesn't have, is refused
/// before signing.