1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::Result;
use thiserror::Error;
use super::{prelude::*, recipients::Recipients, util, ContextPool, Key, Proto};
use crate::Store;
const STORE_GPG_IDS_FILE: &str = ".gpg-id";
const STORE_PUB_KEY_DIR: &str = ".public-keys/";
pub fn store_gpg_ids_file(store: &Store) -> PathBuf {
store.root.join(STORE_GPG_IDS_FILE)
}
pub fn store_public_keys_dir(store: &Store) -> PathBuf {
store.root.join(STORE_PUB_KEY_DIR)
}
pub fn store_read_gpg_fingerprints(store: &Store) -> Result<Vec<String>> {
let path = store_gpg_ids_file(store);
if path.is_file() {
read_fingerprints(path)
} else {
Ok(vec![])
}
}
pub fn store_write_gpg_fingerprints<S: AsRef<str>>(
store: &Store,
fingerprints: &[S],
) -> Result<()> {
write_fingerprints(store_gpg_ids_file(store), fingerprints)
}
fn read_fingerprints<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
Ok(fs::read_to_string(path)
.map_err(Err::ReadFile)?
.lines()
.filter(|fp| !fp.trim().is_empty())
.map(|fp| fp.into())
.collect())
}
fn write_fingerprints<P: AsRef<Path>, S: AsRef<str>>(path: P, fingerprints: &[S]) -> Result<()> {
fs::write(
path,
fingerprints
.into_iter()
.map(|k| k.as_ref())
.collect::<Vec<_>>()
.join("\n"),
)
.map_err(|err| Err::WriteFile(err).into())
}
pub fn store_load_keys(store: &Store) -> Result<Vec<Key>> {
let mut keys = Vec::new();
let fingerprints = store_read_gpg_fingerprints(store)?;
if !fingerprints.is_empty() {
let mut context = super::context(Proto::Gpg)?;
let fingerprints: Vec<_> = fingerprints.iter().map(|fp| fp.as_str()).collect();
keys.extend(context.find_public_keys(&fingerprints)?);
}
Ok(keys)
}
pub fn store_load_recipients(store: &Store) -> Result<Recipients> {
Ok(Recipients::from(store_load_keys(store)?))
}
pub fn store_save_keys(store: &Store, keys: &[Key]) -> Result<()> {
let gpg_fingerprints: Vec<_> = keys
.iter()
.filter(|key| key.proto() == Proto::Gpg)
.map(|key| key.fingerprint(false))
.collect();
store_write_gpg_fingerprints(store, &gpg_fingerprints)?;
store_sync_public_key_files(store, keys)?;
Ok(())
}
pub fn store_save_recipients(store: &Store, recipients: &Recipients) -> Result<()> {
store_save_keys(store, recipients.keys())
}
pub fn store_sync_public_key_files(store: &Store, keys: &[Key]) -> Result<()> {
let dir = store_public_keys_dir(store);
fs::create_dir_all(&dir).map_err(Err::SyncKeyFiles)?;
let files: Vec<(PathBuf, String)> = dir
.read_dir()
.map_err(Err::SyncKeyFiles)?
.filter_map(|e| e.ok())
.filter(|e| e.file_type().map(|f| f.is_file()).unwrap_or(false))
.filter_map(|e| {
e.file_name()
.to_str()
.map(|fp| (e.path(), util::format_fingerprint(fp)))
})
.collect();
for (path, _) in files
.iter()
.filter(|(_, fp)| !util::keys_contain_fingerprint(keys, fp))
{
fs::remove_file(path).map_err(Err::SyncKeyFiles)?;
}
let mut contexts = ContextPool::empty();
for (key, fp) in keys
.into_iter()
.map(|k| (k, k.fingerprint(false)))
.filter(|(_, fp)| !files.iter().any(|(_, other)| fp == other))
{
let proto = key.proto();
let context = contexts.get_mut(proto)?;
let path = dir.join(&fp);
context.export_key_file(key.clone(), &path)?;
}
Ok(())
}
pub fn import_missing_keys_from_store(store: &Store) -> Result<Vec<ImportResult>> {
let dir = store_public_keys_dir(store);
if !dir.is_dir() {
return Ok(vec![]);
}
let mut contexts = ContextPool::empty();
let mut results = Vec::new();
let gpg_fingerprints = store_read_gpg_fingerprints(store)?;
for fingerprint in gpg_fingerprints {
let context = contexts.get_mut(Proto::Gpg)?;
if let Err(_) = context.get_public_key(&fingerprint) {
let path = &store_public_keys_dir(store).join(&fingerprint);
if path.is_file() {
context.import_key_file(path)?;
results.push(ImportResult::Imported(fingerprint));
} else {
results.push(ImportResult::Unavailable(fingerprint));
}
}
}
Ok(results)
}
pub enum ImportResult {
Imported(String),
Unavailable(String),
}
pub trait StoreRecipients {
fn load(store: &Store) -> Result<Recipients>;
fn save(&self, store: &Store) -> Result<()>;
}
impl StoreRecipients for Recipients {
fn load(store: &Store) -> Result<Recipients> {
store_load_recipients(store)
}
fn save(&self, store: &Store) -> Result<()> {
store_save_recipients(store, self)
}
}
#[derive(Debug, Error)]
pub enum Err {
#[error("failed to write to file")]
WriteFile(#[source] std::io::Error),
#[error("failed to read from file")]
ReadFile(#[source] std::io::Error),
#[error("failed to sync public key files")]
SyncKeyFiles(#[source] std::io::Error),
}