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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
#![crate_name = "nonvolatile"]
#![crate_type = "lib"]
#![crate_type = "rlib"]
use whoami;
use whoami::Platform::{Linux, Windows, MacOS};
use serde::{Serialize, Deserialize};
use serde_yaml;
use std::fs::{
create_dir_all,
rename,
metadata,
read_to_string,
OpenOptions,
remove_file,
remove_dir_all,
};
use std::collections::HashMap;
use std::env;
use std::io::Write;
use std::process;
use std::thread;
use std::time;
use std::mem::drop;
use std::vec::Vec;
use std::convert::Into;
use std::path::PathBuf;
use rand::random;
use sysinfo::{System, ProcessExt, SystemExt, Pid};
use generic_error::{Result, GenErr, GenericError};
use regex::Regex;
use lazy_static::lazy_static;
#[cfg(test)]
mod tests;
#[derive(Serialize, Deserialize, Debug)]
pub struct State {
name: String,
path: String,
identifier: String,
lockfile_path: String,
manifest_path: String,
tmp_manifest_path: String,
items: HashMap<String, String>,
}
enum WhoOwns {
Me,
Other,
Nobody,
}
lazy_static! {
static ref PATH_VALID: Regex = Regex::new("^[a-zA-Z0-9-_ ~.()]+$").unwrap();
}
fn check_path_valid(path: &str) -> Result<()> {
if path.len() == 0 {
return GenErr!("nonvolatile: state name/path cannot be empty");
}
if path.len() > 500 {
return GenErr!("nonvolatile: state name/path cannot be longer than 200 chars. ({} chars)", path.len());
}
if path.len() > 200 {
return GenErr!("nonvolatile: state name/path cannot be longer than 200 chars. (\"{}\" is {} chars)", path, path.len());
}
if !PATH_VALID.is_match(path) {
return GenErr!("nonvolatile: state name/path can only contain alphanumeric characters, spaces, and \"-_~.()\". \"{}\" is invalid", path);
}
if path.starts_with(".") || path.starts_with(" ") {
return GenErr!("nonvolatile: state name/path cannot start with '{}'. (\"{}\")", path.chars().nth(0).unwrap(), path);
}
if path.ends_with(" ") {
return GenErr!("nonvolatile: state name/path cannot end with ' '. (\"{}\")", path);
}
Ok(())
}
fn canonicalize_path<S>(path: S) -> String
where S: Into<PathBuf>
{
let path: PathBuf = path.into();
let mut cwd = match env::current_dir() {
Ok(cwd) => cwd,
Err(_) => return path.to_string_lossy().to_string()
};
cwd.push(path);
let full_path = cwd.to_string_lossy().to_string();
let full_path = full_path.replace("\\", "/");
let full_path = full_path.replace("//", "/");
return full_path.replace("/./", "/");
}
fn build_var_path(var: &str, sub_dir: &str) -> Result<String> {
let s = match env::var(var) {
Ok(s) => s,
Err(_) => match whoami::platform() {
Windows => String::from("C:/ProgramData"),
_ => String::from("/etc")
}
};
Ok(format!("{}/{}", s, sub_dir))
}
fn get_storage_dir() -> Result<String> {
match whoami::platform() {
Linux => {
build_var_path("HOME", ".local/rust_nonvolatile")
},
Windows => {
build_var_path("appdata", "rust_nonvolatile")
},
MacOS => {
build_var_path("HOME", ".local/rust_nonvolatile")
}
_ => GenErr!("nonvolatile: {} not supported", whoami::platform()),
}
}
fn get_state_id() -> Result<String> {
let this_pid = process::id();
let mut system = System::new();
system.refresh_processes();
let this_proc = match system.get_processes().get(&(this_pid as Pid)) {
Some(process) => process,
None => return GenErr!("nonvolatile internal error: my pid should be {} but no process is listed at that PID", this_pid)
};
let exe_path = this_proc.exe().to_string_lossy().to_string();
Ok(format!("{}\n{}\n{}", process::id(), random::<u32>(), exe_path))
}
fn match_state_id(my_id: &str, read_id: &str) -> WhoOwns {
if my_id == read_id {
return WhoOwns::Me;
}
let parts: Vec<&str> = read_id.split("\n").collect();
let parts = match parts.len() {
3 => (parts[0], parts[1], parts[2]),
_ => return WhoOwns::Nobody,
};
let read_pid: u32 = match parts.0.parse() {
Ok(pid) => pid,
Err(_) => return WhoOwns::Nobody,
};
let mut system = System::new();
system.refresh_processes();
for (other_pid, process) in system.get_processes() {
let exe_path = process.exe().to_string_lossy().to_string();
if *other_pid as u32 == read_pid && parts.2 == &exe_path {
return WhoOwns::Other;
}
}
WhoOwns::Nobody
}
fn get_lock_acquired(lockfile_path: &str, state_id: &str) -> Result<bool> {
let mdata = match metadata(lockfile_path) {
Ok(mdata) => mdata,
Err(_) => return Ok(false),
};
if !mdata.is_file() {
return Ok(false);
}
let read_id = read_to_string(lockfile_path)?;
match match_state_id(state_id, &read_id) {
WhoOwns::Me => return Ok(true),
WhoOwns::Other => return GenErr!("lockfile {} already owned by state {}", lockfile_path, read_id),
WhoOwns::Nobody => return Ok(false),
}
}
fn acquire_dir(lockfile_path: &str, state_id: &str) -> Result<()> {
match get_lock_acquired(lockfile_path, state_id) {
Ok(true) => return Ok(()),
Ok(false) => (),
Err(e) => {
return Err(e)
},
};
let _ = remove_file(lockfile_path);
let mut file = OpenOptions::new().write(true).create(true).open(lockfile_path)?;
match write!(file, "{}", state_id) {
Ok(_) => (),
Err(e) => {
let _ = remove_file(lockfile_path);
return Err(e.into());
},
};
drop(file);
thread::sleep(time::Duration::new(0, 1000));
match get_lock_acquired(lockfile_path, state_id) {
Ok(true) => Ok(()),
Ok(false) => GenErr!("Nobody owns the lock, but I still managed to fail to acquire it!"),
Err(e) => Err(e),
}
}
impl State {
fn write_manifest(&self) -> Result<()> {
let mut file = OpenOptions::new().write(true).create(true).open(&self.tmp_manifest_path)?;
let data = serde_yaml::to_vec(self)?;
file.write(&data)?;
rename(&self.tmp_manifest_path, &self.manifest_path)?;
Ok(())
}
pub fn set<T>(&mut self, var: &str, value: T) -> Result<()> where T: Serialize {
let _ = self.items.insert(String::from(var), serde_yaml::to_string(&value)?);
self.write_manifest()
}
pub fn get<'de, T>(&self, var: &str) -> Option<T> where for<'a> T: Deserialize<'a> {
let item = self.items.get(var)?;
match serde_yaml::from_str(item) {
Ok(obj) => Some(obj),
Err(_) => None,
}
}
pub fn has(&self, item: &str) -> bool {
self.items.contains_key(item)
}
pub fn delete(&mut self, name: &str) -> Result<()> {
let _ = self.items.remove(name);
self.write_manifest()
}
pub fn load_else_create(name: &str) -> Result<State> {
State::load(name).or_else(|_| State::new(name))
}
pub fn load_else_create_from(name: &str, storage_path: &str) -> Result<State> {
State::load_from(name, storage_path).or_else(|_| State::new_from(name, storage_path))
}
pub fn new(name: &str) -> Result<State> {
let dir = get_storage_dir()?;
State::new_from(name, &dir)
}
pub fn new_from(name: &str, storage_path: &str) -> Result<State> {
check_path_valid(name)?;
let path = canonicalize_path(format!("{}/{}", storage_path, name));
create_dir_all(&path)?;
let items: HashMap<String, String> = HashMap::new();
let state_id = match get_state_id() {
Ok(id) => id,
Err(e) => return Err(e.into())
};
let lockfile_path = format!("{}/{}", &path, "~rust_nonvolatile.lock");
acquire_dir(&lockfile_path, &state_id)?;
let state = State {
name: String::from(name),
path: path.clone(),
identifier: state_id,
lockfile_path: lockfile_path.clone(),
manifest_path: format!("{}/{}", &path, ".manifest"),
tmp_manifest_path: format!("{}/{}", &path, ".manifest_tmp"),
items: items,
};
match state.write_manifest() {
Ok(_) => Ok(state),
Err(e) => {
let _ = remove_file(&lockfile_path);
Err(e.into())
}
}
}
pub fn load(name: &str) -> Result<State> {
let dir = get_storage_dir()?;
State::load_from(name, &dir)
}
pub fn load_from(name: &str, storage_path: &str) -> Result<State> {
check_path_valid(name)?;
let path = canonicalize_path(format!("{}/{}", storage_path, name));
let manifest_path = format!("{}/{}", &path, ".manifest");
let state_id = match get_state_id() {
Ok(id) => id,
Err(e) => return Err(e.into())
};
let lockfile_path = format!("{}/{}", &path, "~rust_nonvolatile.lock");
acquire_dir(&lockfile_path, &state_id)?;
let data = match read_to_string(&manifest_path) {
Ok(data) => data,
Err(e) => {
let _ = remove_file(&lockfile_path);
return Err(GenericError::from(e));
}
};
let mut state: State = match serde_yaml::from_str(&data) {
Ok(state) => state,
Err(e) => {
let _ = remove_file(&lockfile_path);
return Err(GenericError::from(e));
}
};
state.identifier = state_id;
state.lockfile_path = lockfile_path;
Ok(state)
}
pub fn destroy_state(name: &str) {
if let Err(_) = check_path_valid(name) {
return;
}
if let Ok(dir) = get_storage_dir() {
let path = format!("{}/{}", dir, name);
let _ = remove_dir_all(path);
}
}
pub fn destroy_state_from(name: &str, storage_path: &str) {
if let Err(_) = check_path_valid(name) {
return;
}
let path = format!("{}/{}", storage_path, name);
let _ = remove_dir_all(path);
}
}
impl Drop for State {
fn drop(&mut self) {
let _ = remove_file(&self.lockfile_path);
}
}