|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * SPDX-FileCopyrightText: 2026 VEY-OSS Developers. |
| 4 | + */ |
| 5 | + |
| 6 | +use std::hash::Hasher; |
| 7 | +use std::time::Duration; |
| 8 | + |
| 9 | +use quinn_proto::{ConnectionId, ConnectionIdGenerator, InvalidCid}; |
| 10 | +use rustc_hash::FxHasher; |
| 11 | +use zerocopy::{FromBytes, IntoBytes}; |
| 12 | + |
| 13 | +const CID_LENGTH: usize = 20; |
| 14 | +const CID_COOKIE_LENGTH: usize = 8; |
| 15 | +const CID_NONCE_LENGTH: usize = 4; |
| 16 | + |
| 17 | +#[derive(Clone, Copy)] |
| 18 | +pub struct QuinnReuseportIdGenerator { |
| 19 | + key: u64, |
| 20 | + cookie: u64, |
| 21 | + cid_lifetime: Option<Duration>, |
| 22 | +} |
| 23 | + |
| 24 | +impl QuinnReuseportIdGenerator { |
| 25 | + pub fn new(cookie: u64) -> Self { |
| 26 | + let key = rand::random(); |
| 27 | + QuinnReuseportIdGenerator { |
| 28 | + key, |
| 29 | + cookie, |
| 30 | + cid_lifetime: None, |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl ConnectionIdGenerator for QuinnReuseportIdGenerator { |
| 36 | + fn generate_cid(&mut self) -> ConnectionId { |
| 37 | + let mut buf = [0; CID_LENGTH]; |
| 38 | + buf[..CID_COOKIE_LENGTH].copy_from_slice(&self.cookie.to_be_bytes()); |
| 39 | + rand::fill(&mut buf[CID_COOKIE_LENGTH..CID_COOKIE_LENGTH + CID_NONCE_LENGTH]); |
| 40 | + |
| 41 | + let mut hasher = FxHasher::default(); |
| 42 | + hasher.write_u64(self.key); |
| 43 | + hasher.write(&buf[..CID_COOKIE_LENGTH + CID_NONCE_LENGTH]); |
| 44 | + let hash = hasher.finish(); |
| 45 | + buf[CID_COOKIE_LENGTH + CID_NONCE_LENGTH..].copy_from_slice(&hash.as_bytes()); |
| 46 | + ConnectionId::new(&buf) |
| 47 | + } |
| 48 | + |
| 49 | + fn validate(&self, cid: &ConnectionId) -> Result<(), InvalidCid> { |
| 50 | + if cid.len() != CID_LENGTH { |
| 51 | + return Err(InvalidCid); |
| 52 | + } |
| 53 | + |
| 54 | + let cookie = u64::from_be_bytes(cid[..CID_COOKIE_LENGTH].try_into().unwrap()); |
| 55 | + if cookie != self.cookie { |
| 56 | + return Err(InvalidCid); |
| 57 | + } |
| 58 | + |
| 59 | + let given_hash = u64::ref_from_bytes(&cid[CID_COOKIE_LENGTH + CID_NONCE_LENGTH..]) |
| 60 | + .map_err(|_e| InvalidCid)?; |
| 61 | + |
| 62 | + let mut hasher = FxHasher::default(); |
| 63 | + hasher.write_u64(self.key); |
| 64 | + hasher.write(&cid[..CID_COOKIE_LENGTH + CID_NONCE_LENGTH]); |
| 65 | + let expected_hash = hasher.finish(); |
| 66 | + |
| 67 | + if *given_hash != expected_hash { |
| 68 | + Err(InvalidCid) |
| 69 | + } else { |
| 70 | + Ok(()) |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + fn cid_len(&self) -> usize { |
| 75 | + 20 |
| 76 | + } |
| 77 | + |
| 78 | + fn cid_lifetime(&self) -> Option<Duration> { |
| 79 | + self.cid_lifetime |
| 80 | + } |
| 81 | +} |
0 commit comments