blob: aef48350193d82a78900dbb8bda951b4ede7cb49 (
plain) (
blame)
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
|
use std::hash::{Hash, Hasher};
use std::io::Read;
use std::time::{SystemTime, UNIX_EPOCH};
/// A session id is opaque to the provider: it only has to be stable for the life
/// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps
/// it usable as a file name.
pub fn new_id() -> String {
let mut bytes = random_bytes();
// Put the creation time in the first bytes so ids sort roughly by age.
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
bytes[..8].copy_from_slice(&ms.to_be_bytes());
let mut out = String::with_capacity(32);
for b in bytes {
out.push_str(&format!("{b:02x}"));
}
out
}
fn random_bytes() -> [u8; 16] {
let mut bytes = [0u8; 16];
if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
if f.read_exact(&mut bytes).is_ok() {
return bytes;
}
}
// Fallback: not cryptographic, but an id only has to not collide.
let mut h = std::collections::hash_map::DefaultHasher::new();
SystemTime::now().hash(&mut h);
std::process::id().hash(&mut h);
let v = h.finish();
bytes[..8].copy_from_slice(&v.to_be_bytes());
bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes());
bytes
}
|