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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
use crate::model::{Definitions, Entry, EntryStatus};
use anyhow::{Context, Result, ensure};
use rusqlite::{Connection, OptionalExtension, params};
use std::{
fs,
io::Write,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
};
pub struct Storage {
db: Connection,
pub definitions: Definitions,
config: PathBuf,
}
pub fn private_directory(path: &Path) -> Result<()> {
fs::create_dir_all(path).context("Create Roentgen directory")?;
let metadata = fs::symlink_metadata(path)?;
ensure!(
metadata.is_dir() && !metadata.file_type().is_symlink(),
"Roentgen directory must not be a symlink"
);
ensure!(
metadata.uid() == unsafe { libc::geteuid() },
"Roentgen directory must belong to the service user"
);
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
Ok(())
}
pub fn atomic_private_write(path: &Path, data: &[u8]) -> Result<()> {
let parent = path.parent().context("Missing parent directory")?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
file.as_file()
.set_permissions(fs::Permissions::from_mode(0o600))?;
file.write_all(data)?;
file.as_file().sync_all()?;
file.persist(path).map_err(|e| e.error)?;
fs::File::open(parent)?.sync_all()?;
Ok(())
}
impl Storage {
pub fn open(config_dir: &Path, data_dir: &Path) -> Result<Self> {
private_directory(config_dir)?;
private_directory(data_dir)?;
let config = config_dir.join("config.toml");
let definitions: Definitions = if config.exists() {
ensure!(
fs::symlink_metadata(&config)?.is_file(),
"Editable definitions must be a regular file"
);
toml::from_str(&fs::read_to_string(&config)?)
.context("Invalid Roentgen TOML; repair it before starting")?
} else {
Definitions::default()
};
ensure!(definitions.version == 1, "Unsupported TOML version");
definitions.settings.validate()?;
let mut ids = std::collections::HashSet::new();
let mut names = std::collections::HashSet::new();
for subscription in &definitions.subscriptions {
ensure!(
!subscription.id.is_empty()
&& ids.insert(subscription.id.clone())
&& !subscription.name.is_empty()
&& names.insert(subscription.name.clone()),
"Subscription IDs and names must be unique and nonempty"
);
crate::subscription::subscription_url(&subscription.url)?;
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct GuardInput {
version: u32,
enabled: bool,
}
let guard_path = config_dir.join("guard.toml");
let guard_enabled = if guard_path.exists() {
let guard: GuardInput = toml::from_str(&fs::read_to_string(&guard_path)?)
.context("Corrupt guard state; use explicit recover --disable")?;
ensure!(
guard.version == 1,
"Unsupported guard state; use explicit recover --disable"
);
guard.enabled
} else {
false
};
let path = data_dir.join("state.sqlite3");
let database_existed = path.exists();
ensure!(
database_existed || !guard_enabled,
"Durable state is missing while enabled protection is requested; use explicit recover --disable"
);
if path.exists() {
ensure!(
fs::symlink_metadata(&path)?.is_file(),
"State database must be a regular file"
);
}
let db = Connection::open(&path)?;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
db.busy_timeout(std::time::Duration::from_secs(5))?;
db.execute_batch("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;")?;
let version: u32 = db.query_row("PRAGMA user_version", [], |r| r.get(0))?;
ensure!(version <= 1, "Unsupported database version");
if version == 0 {
ensure!(
!database_existed,
"Existing database has no state schema; use explicit recover --disable"
);
db.execute_batch("BEGIN IMMEDIATE;
CREATE TABLE entries (subscription_id TEXT NOT NULL, ordinal INTEGER NOT NULL, id TEXT PRIMARY KEY, data TEXT NOT NULL);
CREATE TABLE state (singleton INTEGER PRIMARY KEY CHECK(singleton=1), enabled INTEGER NOT NULL CHECK(enabled IN (0,1)), selected TEXT, generation INTEGER NOT NULL);
INSERT INTO state VALUES (1,0,NULL,0);
PRAGMA user_version=1; COMMIT;")?;
}
let store = Self {
db,
definitions,
config,
};
// Removed TOML definitions never authorize retained snapshots or a stale selection.
let known: std::collections::HashSet<_> = store
.definitions
.subscriptions
.iter()
.map(|s| s.id.as_str())
.collect();
for subscription_id in store
.db
.prepare("SELECT DISTINCT subscription_id FROM entries")?
.query_map([], |r| r.get::<_, String>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?
{
if !known.contains(subscription_id.as_str()) {
store.delete_entries(&subscription_id)?;
}
}
if !store.config.exists() {
store.save_definitions(&store.definitions)?;
}
Ok(store)
}
pub fn save_definitions(&self, definitions: &Definitions) -> Result<()> {
atomic_private_write(
&self.config,
toml::to_string_pretty(definitions)?.as_bytes(),
)
}
pub fn state(&self) -> Result<(bool, Option<String>, u64)> {
Ok(self.db.query_row(
"SELECT enabled,selected,generation FROM state WHERE singleton=1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get::<_, i64>(2)? as u64)),
)?)
}
pub fn set_intent(&self, enabled: bool) -> Result<()> {
self.db.execute(
"UPDATE state SET enabled=?1,generation=generation+1 WHERE singleton=1",
[enabled],
)?;
Ok(())
}
pub fn select(&self, id: Option<&str>) -> Result<()> {
self.db.execute(
"UPDATE state SET selected=?1,generation=generation+1 WHERE singleton=1",
[id],
)?;
Ok(())
}
pub fn entries(&self, subscription_id: &str) -> Result<Vec<Entry>> {
let mut query = self
.db
.prepare("SELECT data FROM entries WHERE subscription_id=?1 ORDER BY ordinal")?;
let values = query
.query_map([subscription_id], |r| r.get::<_, String>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
values.iter().map(|v| decode_entry(v)).collect()
}
pub fn find_entry(&self, id: &str) -> Result<Option<Entry>> {
self.db
.query_row("SELECT data FROM entries WHERE id=?1", [id], |r| {
r.get::<_, String>(0)
})
.optional()?
.map(|v| decode_entry(&v))
.transpose()
}
pub fn replace_entries(&mut self, subscription_id: &str, entries: &[Entry]) -> Result<()> {
let transaction = self.db.transaction()?;
let selected: Option<String> =
transaction.query_row("SELECT selected FROM state WHERE singleton=1", [], |r| {
r.get(0)
})?;
let owns_selection = match selected.as_ref() {
Some(id) => contains_id(&transaction, subscription_id, id)?,
None => false,
};
transaction.execute(
"DELETE FROM entries WHERE subscription_id=?1",
[subscription_id],
)?;
for (ordinal, entry) in entries.iter().enumerate() {
transaction.execute(
"INSERT INTO entries VALUES (?1,?2,?3,?4)",
params![
subscription_id,
ordinal as i64,
entry.id,
serde_json::to_string(entry)?
],
)?;
}
if owns_selection
&& !entries
.iter()
.any(|e| Some(&e.id) == selected.as_ref() && e.connection.is_some())
{
transaction.execute("UPDATE state SET selected=NULL WHERE singleton=1", [])?;
}
transaction.execute(
"UPDATE state SET generation=generation+1 WHERE singleton=1",
[],
)?;
transaction.commit()?;
Ok(())
}
pub fn delete_entries(&self, subscription_id: &str) -> Result<()> {
self.db.execute_batch("BEGIN IMMEDIATE")?;
let result = (|| -> Result<()> {
self.db.execute("UPDATE state SET selected=NULL,generation=generation+1 WHERE singleton=1 AND selected IN (SELECT id FROM entries WHERE subscription_id=?1)", [subscription_id])?;
self.db.execute(
"DELETE FROM entries WHERE subscription_id=?1",
[subscription_id],
)?;
self.db.execute_batch("COMMIT")?;
Ok(())
})();
if result.is_err() {
let _ = self.db.execute_batch("ROLLBACK");
}
result
}
}
fn contains_id(db: &Connection, subscription_id: &str, id: &str) -> Result<bool> {
Ok(db.query_row(
"SELECT EXISTS(SELECT 1 FROM entries WHERE subscription_id=?1 AND id=?2)",
params![subscription_id, id],
|r| r.get(0),
)?)
}
/// Recovery deliberately needs no valid editable definitions or imported entries.
pub fn persist_recovery_disabled(data_dir: &Path) -> Result<()> {
private_directory(data_dir)?;
let path = data_dir.join("state.sqlite3");
if path.exists() {
ensure!(
fs::symlink_metadata(&path)?.is_file(),
"Recovery database must be a regular file"
);
}
let db = Connection::open(&path)?;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
db.busy_timeout(std::time::Duration::from_secs(5))?;
db.execute_batch("PRAGMA synchronous=FULL;")?;
let version: u32 = db.query_row("PRAGMA user_version", [], |row| row.get(0))?;
ensure!(
version <= 1,
"Unknown database schema; repair it before explicit recovery"
);
db.execute_batch("BEGIN EXCLUSIVE;
CREATE TABLE IF NOT EXISTS entries (subscription_id TEXT NOT NULL, ordinal INTEGER NOT NULL, id TEXT PRIMARY KEY, data TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS state (singleton INTEGER PRIMARY KEY CHECK(singleton=1), enabled INTEGER NOT NULL CHECK(enabled IN (0,1)), selected TEXT, generation INTEGER NOT NULL);
INSERT OR IGNORE INTO state VALUES (1,0,NULL,0);
PRAGMA user_version=1;")?;
db.execute(
"UPDATE state SET enabled=0,generation=generation+1 WHERE singleton=1",
[],
)?;
db.execute_batch("COMMIT")?;
Ok(())
}
fn decode_entry(value: &str) -> Result<Entry> {
let entry: Entry = serde_json::from_str(value).context("Corrupt saved configuration")?;
ensure!(
entry.status == EntryStatus::Supported
&& entry.connection.is_some()
&& entry.explanation.is_none()
|| entry.status != EntryStatus::Supported
&& entry.connection.is_none()
&& entry.explanation.is_some(),
"Saved entry has contradictory validation state; explicit recovery is required"
);
Ok(entry)
}
|