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
use std::fs::Metadata;
use std::io::ErrorKind;
#[cfg(target_os = "linux")]
use std::os::linux::fs::MetadataExt;
#[cfg(target_os = "macos")]
use std::os::macos::fs::MetadataExt;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
use filetime::FileTime;
use hashbrown::HashSet;
use rand::distributions::Distribution;
use rand::{thread_rng, Rng};
use touch::file as touch_file;
use crate::prelude::*;
#[cfg(target_family = "unix")]
use users::{get_current_gid, get_current_uid};
#[derive(Debug)]
pub struct DistinctAlpha;
pub type Sid = [u8; 4];
pub fn uuid_to_gid_u32(u: Uuid) -> u32 {
let b_ref = u.as_bytes();
let mut x: [u8; 4] = [0; 4];
x.clone_from_slice(&b_ref[12..16]);
u32::from_be_bytes(x)
}
fn uuid_from_u64_u32(a: u64, b: u32, sid: Sid) -> Uuid {
let mut v: Vec<u8> = Vec::with_capacity(16);
v.extend_from_slice(&a.to_be_bytes());
v.extend_from_slice(&b.to_be_bytes());
v.extend_from_slice(&sid);
#[allow(clippy::expect_used)]
uuid::Builder::from_slice(v.as_slice())
.expect("invalid slice for uuid builder")
.into_uuid()
}
pub fn uuid_from_duration(d: Duration, sid: Sid) -> Uuid {
uuid_from_u64_u32(d.as_secs(), d.subsec_nanos(), sid)
}
pub fn password_from_random() -> String {
let rand_string: String = thread_rng().sample_iter(&DistinctAlpha).take(48).collect();
rand_string
}
pub fn backup_code_from_random() -> HashSet<String> {
(0..8).map(|_| readable_password_from_random()).collect()
}
pub fn readable_password_from_random() -> String {
let mut trng = thread_rng();
format!(
"{}-{}-{}-{}",
(&mut trng)
.sample_iter(&DistinctAlpha)
.take(5)
.collect::<String>(),
(&mut trng)
.sample_iter(&DistinctAlpha)
.take(5)
.collect::<String>(),
(&mut trng)
.sample_iter(&DistinctAlpha)
.take(5)
.collect::<String>(),
(&mut trng)
.sample_iter(&DistinctAlpha)
.take(5)
.collect::<String>(),
)
}
pub fn duration_from_epoch_now() -> Duration {
#[allow(clippy::expect_used)]
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("invalid duration from epoch now")
}
pub fn touch_file_or_quit(file_path: &str) {
if PathBuf::from(file_path).exists() {
let t = FileTime::from_system_time(SystemTime::now());
match filetime::set_file_times(file_path, t, t) {
Ok(_) => debug!(
"Successfully touched existing file {}, can continue",
file_path
),
Err(e) => {
match e.kind() {
ErrorKind::PermissionDenied => {
error!("Permission denied writing to {}, quitting.", file_path)
}
_ => {
error!(
"Failed to write to {} due to error: {:?} ... quitting.",
file_path, e
)
}
}
std::process::exit(1);
}
}
} else {
match touch_file::write(file_path, "", false) {
Ok(_) => debug!("Successfully touched new file {}", file_path),
Err(e) => {
error!(
"Failed to write to {} due to error: {:?} ... quitting.",
file_path, e
);
std::process::exit(1);
}
};
}
}
impl Distribution<char> for DistinctAlpha {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
const RANGE: u32 = 55;
const GEN_ASCII_STR_CHARSET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ\
abcdefghjkpqrstuvwxyz\
0123456789";
loop {
let var = rng.next_u32() >> (32 - 6);
if var < RANGE {
return GEN_ASCII_STR_CHARSET[var as usize] as char;
}
}
}
}
#[cfg(target_family = "unix")]
pub fn file_permissions_readonly(meta: &Metadata) -> bool {
let cuid = get_current_uid();
let cgid = get_current_gid();
let f_gid = meta.st_gid();
let f_uid = meta.st_uid();
let f_mode = meta.st_mode();
!(
cuid == f_uid ||
(cgid == f_gid && (f_mode & 0o0020) != 0) ||
((f_mode & 0o0002) != 0)
)
}
#[cfg(not(target_family = "unix"))]
pub fn file_permissions_readonly(meta: &Metadata) -> bool {
debug!(
"Windows target asked to check metadata on {:?} returning false",
meta
);
false
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use std::time::Duration;
use crate::utils::{uuid_from_duration, uuid_to_gid_u32};
#[test]
fn test_utils_uuid_from_duration() {
let u1 = uuid_from_duration(Duration::from_secs(1), [0xff; 4]);
assert_eq!(
"00000000-0000-0001-0000-0000ffffffff",
u1.as_hyphenated().to_string()
);
let u2 = uuid_from_duration(Duration::from_secs(1000), [0xff; 4]);
assert_eq!(
"00000000-0000-03e8-0000-0000ffffffff",
u2.as_hyphenated().to_string()
);
}
#[test]
fn test_utils_uuid_to_gid_u32() {
let u1 = uuid!("00000000-0000-0001-0000-000000000000");
let r1 = uuid_to_gid_u32(u1);
assert!(r1 == 0);
let u2 = uuid!("00000000-0000-0001-0000-0000ffffffff");
let r2 = uuid_to_gid_u32(u2);
assert!(r2 == 0xffffffff);
let u3 = uuid!("00000000-0000-0001-0000-ffff12345678");
let r3 = uuid_to_gid_u32(u3);
assert!(r3 == 0x12345678);
}
}