use crate::platform::mpsc::{UnboundedReceiver, UnboundedSender};
use crate::prelude::*;
use crate::transport::{SipAddr, SipConnection};
use core::time::Duration;
use key::TransactionKey;
pub use transaction::Transaction;
pub mod endpoint;
pub mod key;
pub mod message;
mod timer;
pub mod transaction;
pub use endpoint::Endpoint;
pub use endpoint::EndpointBuilder;
#[cfg(test)]
mod tests;
pub const TO_TAG_LEN: usize = 8;
pub const BRANCH_LEN: usize = 12;
pub const CNONCE_LEN: usize = 8;
pub const CALL_ID_LEN: usize = 22;
pub const DEFAULT_CALLID_SUFFIX: &str = "restsend.com";
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CallIdFormat {
#[default]
UuidWithSuffix,
Uuid,
}
pub struct IncomingRequest {
pub request: crate::sip::Request,
pub connection: SipConnection,
pub from: SipAddr,
}
pub type TransactionReceiver = UnboundedReceiver<Transaction>;
pub type TransactionSender = UnboundedSender<Transaction>;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TransactionState {
Nothing,
Calling,
Trying,
Proceeding,
Accepted,
Completed,
Confirmed,
Terminated,
}
impl core::fmt::Display for TransactionState {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
TransactionState::Nothing => write!(f, "Nothing"),
TransactionState::Calling => write!(f, "Calling"),
TransactionState::Trying => write!(f, "Trying"),
TransactionState::Proceeding => write!(f, "Proceeding"),
TransactionState::Accepted => write!(f, "Accepted"),
TransactionState::Completed => write!(f, "Completed"),
TransactionState::Confirmed => write!(f, "Confirmed"),
TransactionState::Terminated => write!(f, "Terminated"),
}
}
}
#[derive(Debug, PartialEq)]
pub enum TransactionType {
ClientInvite,
ClientNonInvite,
ServerInvite,
ServerNonInvite,
}
impl core::fmt::Display for TransactionType {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
TransactionType::ClientInvite => write!(f, "ClientInvite"),
TransactionType::ClientNonInvite => write!(f, "ClientNonInvite"),
TransactionType::ServerInvite => write!(f, "ServerInvite"),
TransactionType::ServerNonInvite => write!(f, "ServerNonInvite"),
}
}
}
#[non_exhaustive]
pub enum TransactionTimer {
TimerA(TransactionKey, Duration),
TimerB(TransactionKey),
TimerC(TransactionKey),
TimerD(TransactionKey),
TimerK(TransactionKey),
TimerG(TransactionKey, Duration),
TimerL(TransactionKey),
TimerM(TransactionKey),
TimerCleanup(TransactionKey),
}
impl TransactionTimer {
pub fn key(&self) -> &TransactionKey {
match self {
TransactionTimer::TimerA(key, _) => key,
TransactionTimer::TimerB(key) => key,
TransactionTimer::TimerC(key) => key,
TransactionTimer::TimerD(key) => key,
TransactionTimer::TimerG(key, _) => key,
TransactionTimer::TimerK(key) => key,
TransactionTimer::TimerL(key) => key,
TransactionTimer::TimerM(key) => key,
TransactionTimer::TimerCleanup(key) => key,
}
}
}
impl core::fmt::Display for TransactionTimer {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
TransactionTimer::TimerA(key, duration) => {
write!(f, "TimerA: {} {}", key, duration.as_millis())
}
TransactionTimer::TimerB(key) => write!(f, "TimerB: {}", key),
TransactionTimer::TimerC(key) => write!(f, "TimerC: {}", key),
TransactionTimer::TimerD(key) => write!(f, "TimerD: {}", key),
TransactionTimer::TimerG(key, duration) => {
write!(f, "TimerG: {} {}", key, duration.as_millis())
}
TransactionTimer::TimerK(key) => write!(f, "TimerK: {}", key),
TransactionTimer::TimerL(key) => write!(f, "TimerL: {}", key),
TransactionTimer::TimerM(key) => write!(f, "TimerM: {}", key),
TransactionTimer::TimerCleanup(key) => write!(f, "TimerCleanup: {}", key),
}
}
}
pub fn make_via_branch() -> crate::sip::Param {
crate::sip::Param::Branch(format!("z9hG4bK{}", random_text(BRANCH_LEN)).into())
}
pub fn make_call_id(suffix: Option<&str>, format: CallIdFormat) -> crate::sip::headers::CallId {
match format {
CallIdFormat::UuidWithSuffix => format!(
"{}@{}",
make_uuid_v4(),
suffix.unwrap_or(DEFAULT_CALLID_SUFFIX)
)
.into(),
CallIdFormat::Uuid => make_uuid_v4().into(),
}
}
pub fn make_uuid_v4() -> String {
let mut b = [0u8; 16];
fill_random_bytes(&mut b);
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
format!(
"{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13],
b[14], b[15]
)
}
#[cfg(all(feature = "std", not(target_family = "wasm")))]
fn fill_random_bytes(buf: &mut [u8]) {
use rand::Rng;
rand::rng().fill_bytes(buf);
}
#[cfg(not(feature = "std"))]
fn fill_random_bytes(buf: &mut [u8]) {
use crate::platform::atomic64::AtomicU64;
use core::sync::atomic::Ordering;
static STATE: AtomicU64 = AtomicU64::new(0x9E37_79B9_7F4A_7C15);
let mut i = 0;
while i < buf.len() {
let mut x = STATE.load(Ordering::Relaxed);
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
STATE.store(x, Ordering::Relaxed);
let out = x.wrapping_mul(0x2545_F491_4F6C_DD1D);
let take = (buf.len() - i).min(8);
buf[i..i + take].copy_from_slice(&out.to_le_bytes()[..take]);
i += take;
}
}
#[cfg(target_family = "wasm")]
fn fill_random_bytes(buf: &mut [u8]) {
for byte in buf.iter_mut() {
*byte = (js_sys::Math::random() * 256.0) as u8;
}
}
pub fn make_tag() -> crate::sip::param::Tag {
random_text(TO_TAG_LEN).into()
}
#[cfg(all(feature = "std", not(target_family = "wasm")))]
pub fn random_text(count: usize) -> String {
use rand::RngExt;
rand::rng()
.sample_iter(rand::distr::Alphanumeric)
.take(count)
.map(char::from)
.collect::<String>()
}
#[cfg(not(feature = "std"))]
pub fn random_text(count: usize) -> String {
const ALNUM: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let mut bytes = vec![0u8; count];
fill_random_bytes(&mut bytes);
bytes
.iter()
.map(|b| ALNUM[(b % 62) as usize] as char)
.collect()
}
#[cfg(target_family = "wasm")]
pub fn random_text(count: usize) -> String {
(0..count)
.map(|_| {
let r = js_sys::Math::random();
let c = (r * 16.0) as u8;
if c < 10 {
(c + 48) as char
} else {
(c + 87) as char
}
})
.collect()
}