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

/*
nonvolatile

Jacob Sacco
August 2019
*/

//!Nonvolatile is a library for storing persistent settings and configuration data out of the way.
//!
//!Nonvolatile state is created by instantiating a `State` instance with a name, 
//!usually the name of the program creating it. Any set values are written to disk 
//!in some common directory depending on the 
//!platform being used. Values persist until they are overwritten, and can be 
//!accessed by any program that loads the state with that name. `State` instances
//!are exclusive (i.e., two programs or two instances of the same program cannot 
//!have the same `State` open at the same time).
//!
//!Most of the builtin types, and any type that implements `serde::Serialize`/`Deserialize` 
//!may be passed into and read from `State::set` and `State::get`.
//!
//!
//!# Example
//!
//!```rust
//!use nonvolatile::State;
//!use generic_error::*;
//!
//!fn main() -> Result<()> {
//!	
//!	//create a new state instance with the name "foo"
//!	let mut state = State::load_else_create("foo")?;
//!	//set some variables in foo
//!	state.set("var", "some value")?;
//!	state.set("user_wants_pie", true)?;
//!	
//!	//destroy the state variable
//!	drop(state);
//!	
//!	//create a new state instance
//!	let state = State::load_else_create("foo")?;
//!	//retrieve the previously set variable.
//!	assert_eq!(state.get::<bool>("user_wants_pie"), Some(true));
//!	assert_eq!(state.get::<String>("var").unwrap(), "some value");
//!	Ok(())
//!}
//!```
//!
//!
//!# Notes
//!
//!By default, state for a given name will be stored in 
//!`$HOME/.local/rust_nonvolatile/<name>` for Linux and MacOS systems, and 
//!`%appdata%\rust_nonvolatile\<name>` for Windows systems. If $HOME or %appdata% 
//!are not defined in the program environment, then nonvolatile will fall back to 
//!`/etc` and `C:\ProgramData` for Linux/MacOS and Windows respectively. 
//!
//!If your environment is unreliable, or you have a location where you'd rather keep settings
//!and configuration, the default storage location can be overridden using the 
//!`*_from` functions (`new_from` instead of `new`, `load_from` instead of `load`, 
//!`load_else_create_from` instead of `load_else_create`). 
//!
//!Be careful to be consistent 
//!with the storage location! If you use a state from one location during one instance
//!of your program, and then use a state from a different location during the next,
//!you will be left with two non-matching states with the same name in different places.
//!
//!
//!# Available State Functions
//!
//!```rust 
//! pub fn set<T>               (&mut self, var: &str, value: T) -> Result<()>
//! pub fn get<'de, T>          (&self, var: &str)               -> Option<T>
//! pub fn has                  (&self, item: &str)              -> bool
//! pub fn delete               (&mut self, name: &str)          -> Result<()>
//!
//! pub fn load_else_create     (name: &str)                     -> Result<State>
//! pub fn load_else_create_from(name: &str, storage_path: &str) -> Result<State>
//! pub fn new                  (name: &str)                     -> Result<State>
//! pub fn new_from             (name: &str, storage_path: &str) -> Result<State>
//! pub fn load                 (name: &str)                     -> Result<State>
//! pub fn load_from            (name: &str, storage_path: &str) -> Result<State>
//! pub fn destroy_state        (name: &str)
//! pub fn destroy_state_from   (name: &str, storage_path: &str)
//! ```

#![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(())
}


///std::fs has a canonicalization function, but it doesn't work on paths that don't exist,
///so this is a poor-man's rendition
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() //if fetching the CWD fails, then give up and return the original.
	};
	cwd.push(path);
	let full_path = cwd.to_string_lossy().to_string(); //.push just returns `path` if `path` is absolute
	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() {	//An error here indicates that either $HOME or %appdata% is not defined
			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(())
	}
	
	
	///Set a variable with name `var` and value `value`. 
	///
	///The name of the set value must be distinct from any other values you set,
	///but otherwise no restrictions apply. The type of `value` must be serializable, 
	///but no other restrictions apply. 
	///
	///The value is written out to storage immediately.
	///
	///### Example
	///
	///```rust
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", my_var);
	///
	///let some_other_var: HashMap<u64, String> = HashMap::new();
	///... //add some stuff to the map
	///state.set("some_other_var", some_other_var.clone()) //save the map for later!
	///```
	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()
	}
	

	///Try to retrieve a variable that was previously written to storage. 
	///
	///The return will be the value if it can be found, or None if:
	/// * no value with that name is stored, or
	/// * the stored value had a type incompatible with the `get` call.
	///
	///`get` does not modify or remove the stored value, it only reads it.
	///
	///### Example
	///
	///```rust
	///let my_var: String = state.get("my var");
	///
	///let some_other_var = state.get::<HashMap<u64, String>>("some_other_var");
	///```
	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,
		}
	}


	///Check if the given item/key exists in the state.
	///
	///### Example
	///
	///```rust
	///state.delete("user_wants_to_die");
	///println!("{}", state.has("user_wants_to_die")); // false
	///state.set("user_wants_to_die", true);
	///println!("{}", state.has("user_wants_to_die")); // true
	///```
	pub fn has(&self, item: &str) -> bool {
		self.items.contains_key(item)
	}
	
	
	///Delete a stored variable. If the variable does not exist, nothing happens.
	///
	///### Example
	///
	///```rust
	///let my_var = String::from("wait no don't delete me");
	///state.set("my var", my_var);
	///...
	/// // oop, looks like we don't need my_var to be stored for some reason
	///state.delete("my var");
	///```
	pub fn delete(&mut self, name: &str) -> Result<()> {
		let _ = self.items.remove(name);
		self.write_manifest()
	}


	///Load state of the given name if it exists. If not, create new state and return that.
	///
	///The name must obey naming rules for your filesystem. To simplify cross platform
	///compatibility, names are restricted to alphanumeric characters, spaces, and any of `-_~.()`.
	///
	///### Example
	///
	///```rust
	///let state = State::load_else_create("my_state");
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", &my_var);
	///```
	pub fn load_else_create(name: &str) -> Result<State> {
		State::load(name).or_else(|_| State::new(name))
	}
	
	
	///Load state of the given name from the given custom storage location if the 
	///state exists exists. If not, create new state at the custom location and 
	///return that.
	///
	///The name must obey naming rules for your filesystem. To simplify cross platform
	///compatibility, names are restricted to alphanumeric characters, spaces, and any of `-_~.()`.
	///
	///the storage path may be relative or absolute, and doesn't have to already exist 
	///(but it must be creatable). The state will be stored in 
	///`<storage_path>/<name>`. Accessing that location directly is not recommended.
	///
	///### Example
	///
	///```rust
	///let state = State::load_else_create_from("my_state", ".");	// load or create state from the CWD
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", &my_var);
	///```
	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))
	}


	///Create a new State object with the given name.
	///
	///The name must obey naming rules for your filesystem. To simplify cross platform
	///compatibility, names are restricted to alphanumeric characters, spaces, and any of `-_~.()`.
	///
	///If there is a preexisting state with that name, it will be overwritten by `new`.
	///If the preexisting state is open by someone or something else, then `new` will fail
	///and return an error.
	///
	///### Example
	///
	///```rust
	///let state = State::new("my_state");
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", my_var);
	///```
	pub fn new(name: &str) -> Result<State> {
		let dir = get_storage_dir()?;
		State::new_from(name, &dir)
	}
	

	///Create a new State object with the given name, and a custom storage location.
	///
	///The name must obey naming rules for your filesystem. To simplify cross platform
	///compatibility, names are restricted to alphanumeric characters, spaces, and any of `-_~.()`.
	///
	///the storage path may be relative or absolute, and doesn't have to already exist 
	///(but it must be creatable). The state will be stored in 
	///`<storage_path>/<name>`. Accessing that location directly is not recommended.
	///
	///If there is a preexisting state with that name, it will be overwritten by `new_from`.
	///If the preexisting state is open by someone or something else, then `new_from` will fail
	///and return an error.
	///
	///### Example
	///
	///```rust
	///let state = State::new_from("my_state", ".");	// create the state in the CWD
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", my_var);
	///```
	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())
			}
		}
	}


	///Attempt to load state of the given name
	///
	///If there is no state with that name, an error will be returned.
	///
	///### Example
	///
	///```rust
	///let state = State::load("my_state");
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", my_var);
	///```
	pub fn load(name: &str) -> Result<State> {
		let dir = get_storage_dir()?;		
		State::load_from(name, &dir)
	}
	
	
	///Attempt to load state of the given name from a custom storage location.
	///
	///If there is no state with that name at that location, an error will be returned.
	///
	///### Example
	///
	///```rust
	///let state = State::load_from("my_state", ".");	// load state from the CWD
	///let my_var = String::from("this is like a string or something");
	///state.set("my var", &my_var);
	///```
	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)
	}
	
	
	///Destroy the state of the given name. If no state exists with that name, nothing happens.
	///
	///### Example
	///
	///```rust
	///let state = State::load_else_create("foo").unwrap();
	///... // do stuff with the state
	///drop(state);
	///
	/// // ... 
	///
	/// //oh, turns out we don't need those settings stored after all...?
	///State::destroy_state("foo");
	///```
	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);
		} 
	}


	///Destroy the state of the given name at the given custom storage location. 
	///If no state exists with that name at that location, nothing happens.
	///
	///### Example
	///
	///```rust
	///let state = State::load_else_create_from("foo", ".").unwrap(); // load or create the state in the CWD
	///... // do stuff with the state
	///drop(state);
	///
	/// // ... 
	///
	/// //oh, turns out we don't need those settings stored after all...?
	///State::destroy_state_from("foo", ".");
	///```
	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);
	}
}