use super::*;
#[inline]
pub(crate) fn session_now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|dur: Duration| dur.as_secs())
.unwrap_or(0)
}
#[inline]
pub(crate) fn session_shard_index(session_id: &str) -> usize {
let mut hasher: XxHash3_64 = XxHash3_64::default();
hasher.write(session_id.as_bytes());
(hasher.finish() as usize) & (SESSION_SHARD_COUNT - 1)
}
#[inline]
pub(crate) fn mix64(mut x: u64) -> u64 {
x = (x ^ (x >> 30)).wrapping_mul(SPLITMIX_MUL1);
x = (x ^ (x >> 27)).wrapping_mul(SPLITMIX_MUL2);
x ^ (x >> 31)
}
#[inline]
pub(crate) fn write_hex_u64(word: u64, dst: &mut [u8]) {
let mut idx: usize = 0;
while idx < 16 {
let shift: usize = (15 - idx) * 4;
dst[idx] = HEX_DIGITS[((word >> shift) & 0x0F) as usize];
idx += 1;
}
}
#[inline]
pub fn generate_session_id() -> String {
let seed: u64 = *SESSION_SEED.get_or_init(|| {
let nanos: u128 = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|dur: Duration| dur.as_nanos())
.unwrap_or(0);
let pid: u64 = process::id() as u64;
let probe: u64 = (&nanos as *const u128) as usize as u64;
mix64((nanos as u64) ^ pid.rotate_left(23) ^ probe)
});
let seq: u64 = SESSION_SEQ.fetch_add(1, Ordering::Relaxed);
let hi: u64 = mix64(seed.wrapping_add(seq.wrapping_mul(SPLITMIX_GAMMA)));
let lo: u64 = mix64(hi.wrapping_add(SPLITMIX_GAMMA) ^ seq.rotate_left(31));
let mut buf: [u8; 32] = [0u8; 32];
write_hex_u64(hi, &mut buf[0..16]);
write_hex_u64(lo, &mut buf[16..32]);
from_utf8(&buf).unwrap_or_default().to_owned()
}
#[inline]
pub(crate) fn sha256(data: &[u8]) -> [u8; 32] {
sha256_finalize_from_state(SHA256_INIT, data, 0)
}
#[inline]
pub(crate) fn sha256_finalize_from_state(
mut state: [u32; 8],
data: &[u8],
prefix_bytes: u64,
) -> [u8; 32] {
let bit_len: u64 = prefix_bytes.wrapping_add(data.len() as u64).wrapping_mul(8);
let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
for block in blocks {
sha256_compress(&mut state, block);
}
let rem: usize = rem_slice.len();
let mut block: [u8; 64] = [0u8; 64];
block[..rem].copy_from_slice(rem_slice);
block[rem] = 0x80;
if rem < 56 {
block[56..64].copy_from_slice(&bit_len.to_be_bytes());
sha256_compress(&mut state, &block);
} else {
sha256_compress(&mut state, &block);
let mut last_block: [u8; 64] = [0u8; 64];
last_block[56..64].copy_from_slice(&bit_len.to_be_bytes());
sha256_compress(&mut state, &last_block);
}
let mut out: [u8; 32] = [0u8; 32];
for (i, word) in state.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
#[inline]
pub(crate) fn sha256_finalize_32(
mut state: [u32; 8],
digest: &[u8; 32],
prefix_bytes: u64,
) -> [u8; 32] {
let bit_len: u64 = prefix_bytes.wrapping_add(32).wrapping_mul(8);
let mut block: [u8; 64] = [0u8; 64];
block[..32].copy_from_slice(digest);
block[32] = 0x80;
block[56..64].copy_from_slice(&bit_len.to_be_bytes());
sha256_compress(&mut state, &block);
let mut out: [u8; 32] = [0u8; 32];
for (i, word) in state.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
#[inline(always)]
fn sha256_round_at(s: &mut [u32; 8], base: usize, kw: u32) {
let a: u32 = s[base & 7];
let b: u32 = s[(base + 1) & 7];
let c: u32 = s[(base + 2) & 7];
let d: u32 = s[(base + 3) & 7];
let e: u32 = s[(base + 4) & 7];
let f: u32 = s[(base + 5) & 7];
let g: u32 = s[(base + 6) & 7];
let h: u32 = s[(base + 7) & 7];
let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch: u32 = (e & f) ^ ((!e) & g);
let temp1: u32 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(kw);
let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
s[(base + 3) & 7] = d.wrapping_add(temp1);
s[(base + 7) & 7] = temp1.wrapping_add(s0.wrapping_add(maj));
}
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
let mut w: [u32; 64] = [0u32; 64];
let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
for (slot, word) in w[..16].iter_mut().zip(words.iter()) {
*slot = u32::from_be_bytes(*word);
}
for i in 16..64usize {
let w15: u32 = w[i - 15];
let w2: u32 = w[i - 2];
let s0: u32 = w15.rotate_right(7) ^ w15.rotate_right(18) ^ (w15 >> 3);
let s1: u32 = w2.rotate_right(17) ^ w2.rotate_right(19) ^ (w2 >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut s: [u32; 8] = *state;
let (k_chunks, _): (&[[u32; 8]], &[u32]) = SHA256_K.as_chunks::<8>();
let (w_chunks, _): (&[[u32; 8]], &[u32]) = w.as_chunks::<8>();
for (k, w8) in k_chunks.iter().zip(w_chunks.iter()) {
sha256_round_at(&mut s, 0, k[0].wrapping_add(w8[0]));
sha256_round_at(&mut s, 7, k[1].wrapping_add(w8[1]));
sha256_round_at(&mut s, 6, k[2].wrapping_add(w8[2]));
sha256_round_at(&mut s, 5, k[3].wrapping_add(w8[3]));
sha256_round_at(&mut s, 4, k[4].wrapping_add(w8[4]));
sha256_round_at(&mut s, 3, k[5].wrapping_add(w8[5]));
sha256_round_at(&mut s, 2, k[6].wrapping_add(w8[6]));
sha256_round_at(&mut s, 1, k[7].wrapping_add(w8[7]));
}
for (dst, &delta) in state.iter_mut().zip(s.iter()) {
*dst = dst.wrapping_add(delta);
}
}
#[inline]
pub(crate) fn precompute_hmac_sha256_key(key: &[u8]) -> HmacSha256Key {
let mut pad: [u8; 64] = [0x36u8; 64];
if key.len() > 64 {
let hashed: [u8; 32] = sha256(key);
for (slot, &byte) in pad[..32].iter_mut().zip(hashed.iter()) {
*slot ^= byte;
}
} else {
for (slot, &byte) in pad[..key.len()].iter_mut().zip(key.iter()) {
*slot ^= byte;
}
}
let mut ipad_state: [u32; 8] = SHA256_INIT;
sha256_compress(&mut ipad_state, &pad);
for slot in &mut pad {
*slot ^= 0x6a;
}
let mut opad_state: [u32; 8] = SHA256_INIT;
sha256_compress(&mut opad_state, &pad);
HmacSha256Key {
ipad_state,
opad_state,
}
}
#[inline]
pub(crate) fn hmac_sha256_with_key(pre: &HmacSha256Key, data: &[u8]) -> [u8; 32] {
let inner_hash: [u8; 32] = sha256_finalize_from_state(pre.ipad_state, data, 64);
sha256_finalize_32(pre.opad_state, &inner_hash, 64)
}
#[inline]
pub(crate) fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
let pre: HmacSha256Key = precompute_hmac_sha256_key(key);
hmac_sha256_with_key(&pre, data)
}
#[inline]
pub(crate) fn encode_hex_32_stack(bytes: &[u8; 32]) -> [u8; 64] {
let mut out: [u8; 64] = [0u8; 64];
for (idx, &byte) in bytes.iter().enumerate() {
out[idx * 2] = HEX_DIGITS[(byte >> 4) as usize];
out[idx * 2 + 1] = HEX_DIGITS[(byte & 0x0F) as usize];
}
out
}
#[inline]
pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff: u8 = 0;
for (&x, &y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
#[inline]
pub(crate) fn is_valid_cookie_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|b: u8| b.is_ascii_alphanumeric() || COOKIE_TOKEN_PUNCTUATION.contains(&b))
}
#[inline]
pub(crate) fn find_cookie_value<'a>(raw_cookie: &'a str, target_name: &str) -> Option<&'a str> {
if raw_cookie.trim().is_empty() {
return None;
}
for part in raw_cookie.split(COOKIE_PAIR_DELIMITER) {
let trimmed: &'a str = part.trim();
if trimmed.is_empty() {
continue;
}
if let Some((name, value)) = trimmed.split_once(COOKIE_KV_DELIMITER) {
let name: &'a str = name.trim();
if name != target_name {
continue;
}
let value: &'a str = value.trim();
if is_valid_cookie_name(name) && !value.bytes().any(|b: u8| b <= 0x1F || b == 0x7F) {
return Some(value);
}
}
}
None
}
#[inline]
pub(crate) fn is_valid_set_cookie_value(value: &str) -> bool {
!value
.bytes()
.any(|b: u8| b <= 0x1F || b == 0x7F || b == b'"' || b == b',' || b == b';' || b == b'\\')
}
pub fn sign_session_cookie(session_id: &str, secret: &[u8]) -> String {
let mac: [u8; 32] = hmac_sha256(secret, session_id.as_bytes());
let hex: [u8; 64] = encode_hex_32_stack(&mac);
let mut out: String = String::with_capacity(session_id.len() + 1 + hex.len());
out.push_str(session_id);
out.push('.');
if let Ok(sig) = from_utf8(&hex) {
out.push_str(sig);
}
out
}
#[inline]
pub(crate) fn verify_session_cookie_with_key<'a>(
cookie_value: &'a str,
pre: &HmacSha256Key,
) -> Option<&'a str> {
let (id, provided_sig): (&'a str, &'a str) = cookie_value.split_once('.')?;
if id.is_empty() || provided_sig.len() != 64 {
return None;
}
let expected_mac: [u8; 32] = hmac_sha256_with_key(pre, id.as_bytes());
let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
if constant_time_eq(provided_sig.as_bytes(), &expected_sig) {
Some(id)
} else {
None
}
}
#[inline]
pub fn verify_session_cookie(cookie_value: &str, secret: &[u8]) -> Option<String> {
let (id, provided_sig): (&str, &str) = cookie_value.split_once('.')?;
if id.is_empty() || provided_sig.len() != 64 {
return None;
}
let expected_mac: [u8; 32] = hmac_sha256(secret, id.as_bytes());
let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
if constant_time_eq(provided_sig.as_bytes(), &expected_sig) {
Some(id.to_owned())
} else {
None
}
}