diff options
Diffstat (limited to '')
| -rw-r--r-- | src/session.rs | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..aef4835 --- /dev/null +++ b/src/session.rs | |||
| @@ -0,0 +1,39 @@ | |||
| 1 | use std::hash::{Hash, Hasher}; | ||
| 2 | use std::io::Read; | ||
| 3 | use std::time::{SystemTime, UNIX_EPOCH}; | ||
| 4 | |||
| 5 | /// A session id is opaque to the provider: it only has to be stable for the life | ||
| 6 | /// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps | ||
| 7 | /// it usable as a file name. | ||
| 8 | pub fn new_id() -> String { | ||
| 9 | let mut bytes = random_bytes(); | ||
| 10 | // Put the creation time in the first bytes so ids sort roughly by age. | ||
| 11 | let ms = SystemTime::now() | ||
| 12 | .duration_since(UNIX_EPOCH) | ||
| 13 | .map(|d| d.as_millis() as u64) | ||
| 14 | .unwrap_or(0); | ||
| 15 | bytes[..8].copy_from_slice(&ms.to_be_bytes()); | ||
| 16 | |||
| 17 | let mut out = String::with_capacity(32); | ||
| 18 | for b in bytes { | ||
| 19 | out.push_str(&format!("{b:02x}")); | ||
| 20 | } | ||
| 21 | out | ||
| 22 | } | ||
| 23 | |||
| 24 | fn random_bytes() -> [u8; 16] { | ||
| 25 | let mut bytes = [0u8; 16]; | ||
| 26 | if let Ok(mut f) = std::fs::File::open("/dev/urandom") { | ||
| 27 | if f.read_exact(&mut bytes).is_ok() { | ||
| 28 | return bytes; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | // Fallback: not cryptographic, but an id only has to not collide. | ||
| 32 | let mut h = std::collections::hash_map::DefaultHasher::new(); | ||
| 33 | SystemTime::now().hash(&mut h); | ||
| 34 | std::process::id().hash(&mut h); | ||
| 35 | let v = h.finish(); | ||
| 36 | bytes[..8].copy_from_slice(&v.to_be_bytes()); | ||
| 37 | bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); | ||
| 38 | bytes | ||
| 39 | } | ||
