use super::{
authenticate::{handle_client_authenticate, AuthRetry, Credential},
invite_dialog::InviteDialog,
publication::{ClientPublicationDialog, ServerPublicationDialog},
subscription::{ClientSubscriptionDialog, ServerSubscriptionDialog},
DialogId,
};
use crate::platform::mpsc::{self, UnboundedReceiver, UnboundedSender};
use crate::platform::sync::Mutex;
use crate::platform::CancellationToken;
use crate::prelude::*;
use crate::sip::{
headers::typed::record_route::split_rr_values,
prelude::{HeadersExt, ToTypedHeader},
typed::{CSeq, Contact},
Header, Method, Param, Request, Response, Route, SipMessage, StatusCode, StatusCodeKind,
};
use crate::{
transaction::{
endpoint::EndpointInnerRef,
key::{TransactionKey, TransactionRole},
make_uuid_v4,
transaction::{Transaction, TransactionEventSender},
},
transport::{SipAddr, SipConnection},
Result,
};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use futures::FutureExt;
use tracing::{debug, info, warn};
pub type TransactionCommandSender = crate::platform::BoundedSender<TransactionCommand>;
pub type TransactionCommandReceiver = crate::platform::BoundedReceiver<TransactionCommand>;
#[derive(Debug)]
pub enum TransactionCommand {
Respond {
status: StatusCode,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
},
}
#[derive(Clone, Debug)]
pub struct TransactionHandle {
sender: TransactionCommandSender,
}
impl TransactionHandle {
pub fn new() -> (Self, TransactionCommandReceiver) {
let (tx, rx) = mpsc::channel(4);
(Self { sender: tx }, rx)
}
pub async fn reply(
&self,
status: StatusCode,
) -> core::result::Result<(), mpsc::error::SendError<TransactionCommand>> {
self.respond(status, None, None).await
}
pub async fn respond(
&self,
status: StatusCode,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> core::result::Result<(), mpsc::error::SendError<TransactionCommand>> {
self.sender
.send(TransactionCommand::Respond {
status,
headers,
body,
})
.await
}
}
#[derive(Clone, Debug)]
pub enum DialogState {
Calling(DialogId),
Trying(DialogId),
Early(DialogId, crate::sip::Response),
WaitAck(DialogId, crate::sip::Response),
Confirmed(DialogId, crate::sip::Response),
Updated(DialogId, crate::sip::Request, TransactionHandle),
Publish(DialogId, crate::sip::Request, TransactionHandle),
Notify(DialogId, crate::sip::Request, TransactionHandle),
Refer(DialogId, crate::sip::Request, TransactionHandle),
Message(DialogId, crate::sip::Request, TransactionHandle),
Info(DialogId, crate::sip::Request, TransactionHandle),
Options(DialogId, crate::sip::Request, TransactionHandle),
Terminated(DialogId, TerminatedReason),
}
#[derive(Debug, Clone)]
pub enum TerminatedReason {
Timeout,
UacCancel,
UacBye,
UasBye,
UacBusy,
UasBusy,
UasDecline,
ProxyError(crate::sip::StatusCode),
ProxyAuthRequired,
UacOther(crate::sip::StatusCode),
UasOther(crate::sip::StatusCode),
}
#[derive(Debug, Clone)]
pub struct ReferStatus {
pub status_code: crate::sip::StatusCode,
pub is_terminated: bool,
}
impl ReferStatus {
pub fn parse(req: &crate::sip::Request) -> Option<Self> {
use crate::sip::HasHeaders;
let mut event = None;
for header in req.headers().iter() {
if let crate::sip::Header::Other(name, value) = header {
if name.to_string().eq_ignore_ascii_case("event") {
event = Some(value.to_string().to_lowercase());
break;
}
}
}
let event = event?;
if !event.contains("refer") {
return None;
}
let mut sub_state = None;
for header in req.headers().iter() {
if let crate::sip::Header::Other(name, value) = header {
if name.to_string().eq_ignore_ascii_case("subscription-state") {
sub_state = Some(value.to_string().to_lowercase());
break;
}
}
}
let sub_state = sub_state?;
let is_terminated = sub_state.contains("terminated");
let body = core::str::from_utf8(&req.body).ok()?;
let status_line = body.lines().find(|l| l.starts_with("SIP/2.0"))?;
let parts: Vec<&str> = status_line.split_whitespace().collect();
if parts.len() < 2 {
return None;
}
let code: u16 = parts[1].parse().ok()?;
let status_code = crate::sip::StatusCode::from(code);
Some(Self {
status_code,
is_terminated,
})
}
}
#[derive(Clone)]
pub enum Dialog {
Invite(InviteDialog),
ServerSubscription(ServerSubscriptionDialog),
ClientSubscription(ClientSubscriptionDialog),
ServerPublication(ServerPublicationDialog),
ClientPublication(ClientPublicationDialog),
}
impl Dialog {
pub fn state(&self) -> DialogState {
match self {
Dialog::Invite(d) => d.state(),
Dialog::ServerSubscription(d) => d.state(),
Dialog::ClientSubscription(d) => d.state(),
Dialog::ServerPublication(d) => d.state(),
Dialog::ClientPublication(d) => d.state(),
}
}
pub fn as_subscription(&self) -> Option<Dialog> {
match self {
Dialog::Invite(d) => Some(d.as_subscription()),
Dialog::ServerSubscription(_) => Some(self.clone()),
Dialog::ClientSubscription(_) => Some(self.clone()),
_ => None,
}
}
}
#[derive(Clone)]
pub(super) struct RemoteReliableState {
last_rseq: u32,
invite_cseq: u32,
prack_request: Request,
}
pub(super) struct RemoteTarget {
uri: crate::sip::Uri,
contact: crate::sip::headers::untyped::Contact,
}
pub struct DialogInner {
pub role: TransactionRole,
pub cancel_token: CancellationToken,
pub id: Mutex<DialogId>,
pub state: Mutex<DialogState>,
pub local_seq: AtomicU32,
pub local_contact: Option<crate::sip::Uri>,
pub remote_contact: Mutex<Option<crate::sip::headers::untyped::Contact>>,
pub remote_seq: AtomicU32,
pub remote_uri: Mutex<crate::sip::Uri>,
remote_target_cseq: Mutex<Option<u32>>,
pub from: crate::sip::typed::From,
pub to: Mutex<crate::sip::typed::To>,
pub credential: Option<Credential>,
pub route_set: Mutex<Vec<Route>>,
pub(super) endpoint_inner: EndpointInnerRef,
pub(super) state_sender: DialogStateSender,
pub(super) tu_sender: TransactionEventSender,
pub(super) session_id: Mutex<Option<SessionIdState>>,
pub(super) initial_request: Mutex<Request>,
pub(super) supports_100rel: bool,
pub(super) remote_reliable: Mutex<Option<RemoteReliableState>>,
pub(super) remote_ack: Mutex<Option<Request>>,
pub(super) server_connection: Mutex<Option<SipConnection>>,
pub(super) dialback_target: Mutex<Option<SipAddr>>,
pub(super) cancel_requested: AtomicBool,
pub(super) cancel_deferred: AtomicBool,
}
pub type DialogStateReceiver = UnboundedReceiver<DialogState>;
pub type DialogStateSender = UnboundedSender<DialogState>;
pub(super) type DialogInnerRef = Arc<DialogInner>;
impl DialogState {
pub fn id(&self) -> &DialogId {
match self {
DialogState::Calling(id)
| DialogState::Trying(id)
| DialogState::Early(id, _)
| DialogState::WaitAck(id, _)
| DialogState::Confirmed(id, _)
| DialogState::Updated(id, _, _)
| DialogState::Publish(id, _, _)
| DialogState::Notify(id, _, _)
| DialogState::Info(id, _, _)
| DialogState::Options(id, _, _)
| DialogState::Refer(id, _, _)
| DialogState::Message(id, _, _)
| DialogState::Terminated(id, _) => id,
}
}
pub fn can_cancel(&self) -> bool {
matches!(
self,
DialogState::Calling(_) | DialogState::Trying(_) | DialogState::Early(_, _)
)
}
pub fn is_confirmed(&self) -> bool {
matches!(self, DialogState::Confirmed(_, _))
}
pub fn is_terminated(&self) -> bool {
matches!(self, DialogState::Terminated(_, _))
}
pub fn waiting_ack(&self) -> bool {
matches!(self, DialogState::WaitAck(_, _))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DialogSnapshotState {
Calling,
Trying,
Early,
WaitAck,
Confirmed,
Terminated,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SessionIdState {
pub local: String,
pub remote: Option<String>,
}
#[derive(Clone, Debug)]
pub struct DialogSnapshot {
pub state: DialogSnapshotState,
pub role: TransactionRole,
pub id: DialogId,
pub from: crate::sip::typed::From,
pub to: crate::sip::typed::To,
pub local_cseq: u32,
pub remote_cseq: u32,
pub local_contact: Option<crate::sip::Uri>,
pub remote_uri: crate::sip::Uri,
pub remote_contact: Option<crate::sip::headers::untyped::Contact>,
pub route_set: Vec<Route>,
pub supports_100rel: bool,
pub session_id: Option<SessionIdState>,
}
impl DialogInner {
#[allow(clippy::too_many_arguments)]
pub fn new(
role: TransactionRole,
id: DialogId,
initial_request: Request,
endpoint_inner: EndpointInnerRef,
state_sender: DialogStateSender,
credential: Option<Credential>,
local_contact: Option<crate::sip::Uri>,
tu_sender: TransactionEventSender,
) -> Result<Self> {
let cseq = initial_request.cseq_header()?.seq()?;
let remote_uri = match role {
TransactionRole::Client => initial_request.uri.clone(),
TransactionRole::Server => initial_request
.typed_contact_headers()?
.first()
.map(|c| c.uri.clone())
.ok_or_else(|| crate::Error::Error("missing Contact header".to_string()))?,
};
let from = initial_request.from_header()?.typed()?;
let mut to = initial_request.to_header()?.typed()?;
if !to.params.iter().any(|p| matches!(p, Param::Tag(_))) {
let tag = match role {
TransactionRole::Client => &id.remote_tag,
TransactionRole::Server => &id.local_tag,
};
if !tag.is_empty() {
to.params.push(crate::sip::Param::Tag(tag.clone().into()));
}
}
let mut route_set: Vec<Route> = Vec::new();
if let TransactionRole::Server = role {
route_set = initial_request
.record_route_headers()
.into_iter()
.flat_map(|rr| split_rr_values(rr.value()))
.map(Route::from)
.collect();
}
let supports_100rel = initial_request.header_contains_token("Supported", "100rel")
|| initial_request.header_contains_token("Require", "100rel");
let session_id = Self::extract_session_id(&initial_request, role);
Ok(Self {
role,
cancel_token: CancellationToken::new(),
id: Mutex::new(id.clone()),
from,
to: Mutex::new(to),
local_seq: AtomicU32::new(cseq),
remote_uri: Mutex::new(remote_uri),
remote_target_cseq: Mutex::new(None),
remote_seq: AtomicU32::new(0),
credential,
route_set: Mutex::new(route_set),
endpoint_inner,
state_sender,
tu_sender,
state: Mutex::new(DialogState::Calling(id)),
initial_request: Mutex::new(initial_request),
session_id: Mutex::new(session_id),
local_contact,
remote_contact: Mutex::new(None),
supports_100rel,
remote_reliable: Mutex::new(None),
remote_ack: Mutex::new(None),
server_connection: Mutex::new(None),
dialback_target: Mutex::new(None),
cancel_requested: AtomicBool::new(false),
cancel_deferred: AtomicBool::new(false),
})
}
fn extract_session_id(
initial_request: &Request,
role: TransactionRole,
) -> Option<SessionIdState> {
let sid = initial_request.session_id_header()?;
if !sid.is_valid_header() {
return None;
}
let peer = sid.local_uuid()?;
match role {
TransactionRole::Client => Some(SessionIdState {
local: peer,
remote: sid.remote_uuid(),
}),
TransactionRole::Server => Some(SessionIdState {
local: make_dialog_session_uuid(),
remote: Some(peer),
}),
}
}
pub fn observe_peer_session_uuid(&self, peer: Option<String>) {
let Some(uuid) = peer else {
return;
};
if !crate::sip::headers::SessionId::is_valid(&uuid)
|| uuid == crate::sip::headers::SessionId::NIL
{
return;
}
let mut state = self.session_id.lock();
if let Some(sid) = state.as_mut() {
if sid.local != uuid {
sid.remote = Some(uuid);
}
}
}
pub fn session_id_state(&self) -> Option<SessionIdState> {
self.session_id.lock().clone()
}
pub fn set_server_connection(&self, connection: Option<SipConnection>) {
*self.server_connection.lock() = connection.clone();
*self.dialback_target.lock() = connection.and_then(|conn| conn.get_remote_addr().cloned());
}
pub fn can_cancel(&self) -> bool {
self.state.lock().can_cancel()
}
pub fn is_confirmed(&self) -> bool {
self.state.lock().is_confirmed()
}
pub fn is_terminated(&self) -> bool {
self.state.lock().is_terminated()
}
pub fn waiting_ack(&self) -> bool {
self.state.lock().waiting_ack()
}
pub fn get_local_seq(&self) -> u32 {
self.local_seq.load(Ordering::Relaxed)
}
pub fn increment_local_seq(&self) -> u32 {
self.local_seq.fetch_add(1, Ordering::Relaxed);
self.local_seq.load(Ordering::Relaxed)
}
pub fn update_remote_tag(&self, tag: &str) -> Result<()> {
self.id.lock().remote_tag = tag.to_string();
if self.role == TransactionRole::Client {
let mut to = self.to.lock();
*to = to.clone().with_tag(tag.into());
}
Ok(())
}
fn clear_remote_reliable(&self) {
self.remote_reliable.lock().take();
}
pub(super) fn prepare_prack_request(&self, resp: &Response) -> Result<Option<Request>> {
if !resp.header_contains_token("Require", "100rel") {
return Ok(None);
}
let Some(rseq) = resp.rseq_value() else {
warn!(
id = self.id.lock().to_string(),
"received reliable provisional response without RSeq"
);
return Ok(None);
};
if rseq == 0 || rseq > 0x7fff_ffff {
return Ok(None);
}
let cseq_header = resp.cseq_header()?;
let cseq = cseq_header.seq()?;
let method = cseq_header.method()?;
if method != Method::Invite {
return Ok(None);
}
{
let state_guard = self.remote_reliable.lock();
if let Some(state) = state_guard.as_ref() {
if state.invite_cseq == cseq && state.last_rseq == rseq {
return Ok(Some(state.prack_request.clone()));
}
if cseq < state.invite_cseq || (state.invite_cseq == cseq && state.last_rseq > rseq)
{
return Ok(None);
}
}
}
self.refresh_target_from_response(resp)?;
let rack_value = format!("{} {} {}", rseq, cseq, method);
let mut headers = vec![Header::RAck(rack_value.into())];
if self.supports_100rel {
headers.push(Header::Supported("100rel".into()));
}
let prack_request = self.make_request(
Method::PRack,
Some(self.increment_local_seq()),
None,
None,
Some(headers),
None,
)?;
let state = RemoteReliableState {
last_rseq: rseq,
invite_cseq: cseq,
prack_request: prack_request.clone(),
};
{
let mut state_guard = self.remote_reliable.lock();
*state_guard = Some(state);
}
Ok(Some(prack_request))
}
pub(super) async fn handle_provisional_response(&self, resp: &Response) -> Result<()> {
let to_header = resp.to_header()?;
if let Ok(Some(tag)) = to_header.tag() {
self.update_remote_tag(tag.value())?;
}
if let Some(prack) = self.prepare_prack_request(resp)? {
let _ = self.send_prack_request(prack).await?;
}
Ok(())
}
pub(super) async fn send_prack_request(&self, request: Request) -> Result<Option<Response>> {
let method = request.method().to_owned();
let key = TransactionKey::from_request(&request, TransactionRole::Client)?;
let affinity_connection = self.resolve_affinity_connection();
let mut tx = Transaction::new_client(
key,
request,
self.endpoint_inner.clone(),
affinity_connection,
);
if let Some(route) = tx.original.route_header() {
if let Ok(first_route) = route.typed() {
tx.destination = SipAddr::try_from(&first_route.uri).ok();
}
}
match tx.send().await {
Ok(_) => {
debug!(
id = self.id.lock().to_string(),
method = %method,
destination=tx.destination.as_ref().map(|d| d.to_string()).as_deref(),
key=%tx.key,
"request sent done",
);
}
Err(e) => {
warn!(
id = self.id.lock().to_string(),
destination = tx.destination.as_ref().map(|d| d.to_string()).as_deref(),
method = %method,
"failed to send request error: {}",
e
);
debug!(id = self.id.lock().to_string(), req = %tx.original, "request that failed to send");
return Err(e);
}
}
let mut auth = AuthRetry::new();
while let Some(msg) = tx.receive().await {
match msg {
SipMessage::Response(resp) => match resp.status_code {
StatusCode::Trying => continue,
StatusCode::ProxyAuthenticationRequired | StatusCode::Unauthorized => {
let id = self.id.lock().clone();
if !auth.should_answer(&resp) {
debug!(
id = self.id.lock().to_string(),
"received {} response after auth sent", resp.status_code
);
self.transition(DialogState::Terminated(
id,
TerminatedReason::ProxyAuthRequired,
));
break;
}
if let Some(cred) = &self.credential {
let new_seq = self.increment_local_seq();
tx = handle_client_authenticate(new_seq, &tx, resp, cred).await?;
tx.send().await?;
continue;
} else {
debug!(
id = self.id.lock().to_string(),
"received 407 response without auth option"
);
self.transition(DialogState::Terminated(
id,
TerminatedReason::ProxyAuthRequired,
));
break;
}
}
_ => {
return Ok(Some(resp));
}
},
_ => break,
}
}
Ok(None)
}
pub fn set_remote_target(
&self,
uri: crate::sip::Uri,
contact: Option<crate::sip::headers::untyped::Contact>,
) {
*self.remote_uri.lock() = uri;
*self.remote_contact.lock() = contact;
}
pub(super) fn is_target_refresh(method: Method) -> bool {
matches!(method, Method::Invite | Method::Update)
}
pub(super) fn parse_target_refresh_contact(
message: &impl HeadersExt,
) -> Result<Option<RemoteTarget>> {
let headers = message.contact_headers();
if headers.is_empty() {
return Ok(None);
}
let contacts = message.typed_contact_headers()?;
if headers.len() != 1 || contacts.len() != 1 {
return Err(crate::Error::Error(
"target refresh requires a single Contact URI".into(),
));
}
let uri = contacts[0].uri.clone();
if !matches!(
uri.scheme,
Some(crate::sip::Scheme::Sip | crate::sip::Scheme::Sips)
) || uri.host_with_port.host.to_string().is_empty()
{
return Err(crate::Error::Error(
"target refresh requires a SIP or SIPS Contact URI".into(),
));
}
Ok(Some(RemoteTarget {
uri,
contact: headers[0].clone(),
}))
}
fn refresh_target_from_response(&self, response: &Response) -> Result<()> {
if let Some(target) = Self::parse_target_refresh_contact(response)? {
self.set_remote_target(target.uri, Some(target.contact));
}
Ok(())
}
fn accept_target_refresh(&self, cseq: u32, target: &RemoteTarget) {
let mut last = self.remote_target_cseq.lock();
if last.is_some_and(|accepted| cseq <= accepted) {
return;
}
self.set_remote_target(target.uri.clone(), Some(target.contact.clone()));
*last = Some(cseq);
}
fn accepts_target_refresh(method: Method, response: &Response) -> bool {
Self::is_target_refresh(method)
&& (response.status_code.kind() == StatusCodeKind::Successful
|| (method == Method::Invite
&& response.status_code.kind() == StatusCodeKind::Provisional
&& response.status_code != StatusCode::Trying
&& response.header_contains_token("Require", "100rel")
&& response
.rseq_value()
.is_some_and(|rseq| (1..=0x7fff_ffff).contains(&rseq))))
}
pub(crate) fn update_route_set_from_response(&self, resp: &Response) {
if !matches!(self.role, TransactionRole::Client) {
return;
}
let mut new_route_set: Vec<Route> = resp
.record_route_headers()
.into_iter()
.flat_map(|rr| split_rr_values(rr.value()))
.map(Route::from)
.collect();
new_route_set.reverse();
*self.route_set.lock() = new_route_set;
}
pub(super) fn make_request_with_vias(
&self,
method: crate::sip::Method,
cseq: Option<u32>,
vias: Vec<crate::sip::headers::typed::Via>,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> Result<crate::sip::Request> {
let mut out: Vec<Header> = Vec::new();
let cseq_header = CSeq {
seq: cseq.unwrap_or_else(|| self.increment_local_seq()),
method,
};
for via in vias {
out.push(Header::Via(via.into()));
}
out.push(Header::CallId(self.id.lock().call_id.clone().into()));
let to = self.to.lock().clone().to_string();
let from = self.from.clone().to_string();
match self.role {
TransactionRole::Client => {
out.push(Header::From(from.into()));
out.push(Header::To(to.into()));
}
TransactionRole::Server => {
out.push(Header::From(to.into()));
out.push(Header::To(from.into()));
}
}
out.push(Header::CSeq(cseq_header.into()));
out.push(Header::UserAgent(
self.endpoint_inner.user_agent.clone().into(),
));
if let Some(uri) = self.local_contact.as_ref() {
out.push(Contact::from(uri.clone()).into());
}
{
let route_set = self.route_set.lock();
out.extend(route_set.iter().cloned().map(Header::Route));
}
out.push(Header::MaxForwards(70.into()));
{
let state = self.session_id.lock();
if let Some(sid) = state.as_ref() {
let caller_supplied = headers
.as_ref()
.is_some_and(|hs| hs.iter().any(|h| matches!(h, Header::SessionId(_))));
if !caller_supplied {
if let Some(h) = build_session_id_header(&sid.local, sid.remote.as_deref()) {
out.push(h);
}
}
}
}
out.push(Header::ContentLength(
body.as_ref().map_or(0u32, |b| b.len() as u32).into(),
));
if let Some(extra) = headers {
for h in extra {
if !is_system_header(&h) {
out.push(h);
}
}
}
Ok(crate::sip::Request {
method,
uri: self.remote_uri.lock().clone(),
headers: out.into(),
body: body.unwrap_or_default(),
version: crate::sip::Version::V2,
})
}
pub(super) fn make_request(
&self,
method: crate::sip::Method,
cseq: Option<u32>,
addr: Option<crate::transport::SipAddr>,
branch: Option<Param>,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> Result<crate::sip::Request> {
let addr = addr.or_else(|| self.via_addr_for_send_transport());
let via = self.endpoint_inner.get_via(addr, branch)?;
self.make_request_with_vias(method, cseq, vec![via], headers, body)
}
fn via_addr_for_send_transport(&self) -> Option<crate::transport::SipAddr> {
use crate::sip::uri::ParamsExt;
let transport = match self.resolve_affinity_connection() {
Some(connection) => connection.get_addr().r#type,
None if self.endpoint_inner.locator.is_some() => None,
None => match self.endpoint_inner.transport_layer.outbound.as_ref() {
Some(outbound) => outbound.r#type,
None => {
let route = self.route_set.lock().first().cloned();
match route {
Some(route) => route
.typed()
.ok()
.and_then(|route| route.uri.transport().cloned()),
None => self.remote_uri.lock().transport().cloned(),
}
}
},
}
.filter(|t| *t != crate::sip::Transport::Udp)?;
let listens = self.endpoint_inner.transport_layer.get_listen_addrs();
if let Some(addr) = listens.iter().find(|a| a.r#type == Some(transport)) {
return Some(addr.clone());
}
let mut addr = listens.first().cloned()?;
addr.r#type = Some(transport);
Some(addr)
}
pub(super) fn make_response(
&self,
request: &Request,
status: StatusCode,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> crate::sip::Response {
let mut resp_headers = crate::sip::Headers::default();
let request_peer_uuid = request.session_id_header().and_then(|s| s.local_uuid());
let request_has_history = !request.history_info_headers().is_empty();
let user_supplied_history = headers
.as_ref()
.is_some_and(|hs| hs.iter().any(|h| matches!(h, Header::HistoryInfo(_))));
for header in request.headers.iter() {
match header {
Header::Via(via) => {
resp_headers.push(Header::Via(via.clone()));
}
Header::From(from) => {
resp_headers.push(Header::From(from.clone()));
}
Header::To(to) => {
let mut to = match to.clone().typed() {
Ok(to) => to,
Err(e) => {
info!(error = %e, "error parsing to header");
continue;
}
};
if status != StatusCode::Trying
&& !to.params.iter().any(|p| matches!(p, Param::Tag(_)))
{
to.params.push(crate::sip::Param::Tag(
self.id.lock().local_tag.clone().into(),
));
}
resp_headers.push(Header::To(to.into()));
}
Header::CSeq(cseq) => {
resp_headers.push(Header::CSeq(cseq.clone()));
}
Header::CallId(call_id) => {
resp_headers.push(Header::CallId(call_id.clone()));
}
Header::RecordRoute(rr) => {
resp_headers.push(Header::RecordRoute(rr.clone()));
}
_ => {}
}
}
if let Some(c) = self.local_contact.as_ref() {
resp_headers.push(Contact::from(c.clone()).into())
}
if status != StatusCode::Trying {
{
let state = self.session_id.lock();
if let Some(sid) = state.as_ref() {
let remote = request_peer_uuid.clone().or_else(|| sid.remote.clone());
if let Some(h) = build_session_id_header(&sid.local, remote.as_deref()) {
resp_headers.push(h);
}
}
}
if request_has_history && !user_supplied_history {
for h in request.headers.iter() {
if let Header::HistoryInfo(hi) = h {
resp_headers.push(Header::HistoryInfo(hi.clone()));
}
}
}
}
if let Some(headers) = headers {
for header in headers {
match &header {
crate::sip::Header::Other(name, _) => {
let lname = name.to_ascii_lowercase();
resp_headers.retain(|h| {
!matches!(
h,
crate::sip::Header::Other(n, _) if n.to_ascii_lowercase() == lname
)
});
resp_headers.push(header);
}
crate::sip::Header::HistoryInfo(_) => {
resp_headers.push(header);
}
_ => resp_headers.unique_push(header),
}
}
}
resp_headers.retain(|h| !matches!(h, Header::ContentLength(_) | Header::UserAgent(_)));
resp_headers.push(Header::ContentLength(
body.as_ref().map_or(0u32, |b| b.len() as u32).into(),
));
resp_headers.push(Header::UserAgent(
self.endpoint_inner.user_agent.clone().into(),
));
Response {
status_code: status,
wire_reason: None,
headers: resp_headers,
body: body.unwrap_or_default(),
version: *request.version(),
}
}
fn resolve_affinity_connection(&self) -> Option<SipConnection> {
let conn = self.server_connection.lock().clone();
let reason = match &conn {
None => "no-recorded-connection",
Some(c) if !c.is_reliable() => "connection-not-reliable",
Some(c) => match c.cancel_token() {
Some(token) if token.is_cancelled() => "connection-cancelled",
_ => return conn,
},
};
debug!(
id = %self.id.lock(),
has_route_set = !self.route_set.lock().is_empty(),
why = reason,
"affinity unavailable"
);
None
}
#[cfg(test)]
pub fn test_resolve_affinity_connection(&self) -> Option<SipConnection> {
self.resolve_affinity_connection()
}
fn fallback_target_from_initial_via(initial_request: &Request) -> Option<SipAddr> {
let via = initial_request.via_header().ok()?.typed().ok()?;
let received = via.received()?.ok()?;
let port: u16 = via.rport()??;
Some(SipAddr {
r#type: Some(via.transport),
addr: crate::sip::HostWithPort {
host: crate::sip::Host::IpAddr(received),
port: Some(port.into()),
},
})
}
async fn send_dialog_request(&self, request: Request) -> Result<Option<Response>> {
let method = request.method().to_owned();
let key = TransactionKey::from_request(&request, TransactionRole::Client)?;
let affinity_connection = self.resolve_affinity_connection();
let mut tx = Transaction::new_client(
key,
request,
self.endpoint_inner.clone(),
affinity_connection,
);
if let Some(route) = tx.original.route_header() {
if let Ok(first_route) = route.typed() {
tx.destination = SipAddr::try_from(&first_route.uri).ok();
}
}
let need_fallback_retry;
let mut send_error = None;
match tx.send().await {
Ok(_) => {
debug!(
id = self.id.lock().to_string(),
method = %method,
destination=tx.destination.as_ref().map(|d| d.to_string()).as_deref(),
key=%tx.key,
"request sent done",
);
need_fallback_retry = tx.connection.is_none();
}
Err(e) => {
need_fallback_retry = self.role == TransactionRole::Server && method != Method::Ack;
if !need_fallback_retry {
warn!(
id = self.id.lock().to_string(),
destination = tx.destination.as_ref().map(|d| d.to_string()).as_deref(),
method = %method,
"failed to send request error: {}",
e
);
debug!(id = self.id.lock().to_string(), req = %tx.original, "request that failed to send");
return Err(e);
}
send_error = Some(e);
}
}
if need_fallback_retry && method != Method::Ack {
let fallback_addr = {
let stored = self.dialback_target.lock().clone();
match stored {
Some(addr) => Some(addr),
None => {
let initial = self.initial_request.lock();
Self::fallback_target_from_initial_via(&initial)
}
}
};
if let Some(fallback_addr) = fallback_addr {
info!(
id = self.id.lock().to_string(),
method = %method,
fallback = %fallback_addr,
"no usable connection, retrying via recorded flow address"
);
tx.destination = Some(fallback_addr.clone());
let transport = fallback_addr.r#type.unwrap_or_default();
let listens = self.endpoint_inner.transport_layer.get_listen_addrs();
let listener = listens
.iter()
.find(|a| a.r#type.unwrap_or_default() == transport)
.cloned()
.or_else(|| {
let mut addr = listens.first().cloned()?;
addr.r#type = Some(transport);
Some(addr)
});
let branch = tx
.original
.top_via_header()
.and_then(|via| via.typed())
.ok()
.filter(|via| via.transport != transport)
.and_then(|via| {
via.params
.into_iter()
.find(|p| matches!(p, Param::Branch(_)))
});
if let (Some(listener), Some(branch)) = (listener, branch) {
if let (Ok(new_via), Ok(via)) = (
self.endpoint_inner.get_via(Some(listener), Some(branch)),
tx.original.via_header_mut(),
) {
via.update_first_value(|_| Ok(new_via.into())).ok();
}
}
if let Err(e) = tx.send().await {
warn!(
id = self.id.lock().to_string(),
destination = %fallback_addr,
"fallback send failed error: {}",
e
);
}
} else {
debug!(
id = self.id.lock().to_string(),
method = %method,
"no usable connection and no dial-back target; giving up after first send"
);
if let Some(e) = send_error {
return Err(e);
}
}
}
let mut auth = AuthRetry::new();
while let Some(msg) = tx.receive().await {
match msg {
SipMessage::Response(resp) => {
let peer_uuid = resp.session_id_header().and_then(|s| s.local_uuid());
self.observe_peer_session_uuid(peer_uuid);
let status = resp.status_code.clone();
if status == StatusCode::Trying {
continue;
}
if Self::is_target_refresh(method)
&& !DialogId::try_from((&resp, TransactionRole::Client))
.is_ok_and(|id| id == *self.id.lock())
{
warn!(id = %self.id.lock(), "ignoring target refresh response for another dialog");
continue;
}
if status.kind() == StatusCodeKind::Provisional {
if method == Method::Invite {
self.handle_provisional_response(&resp).await?;
}
let state = DialogState::Early(self.id.lock().clone(), resp);
if self.can_cancel() {
self.transition(state);
} else if !self.is_terminated() {
self.state_sender.send(state).ok();
}
continue;
}
if matches!(
status,
StatusCode::ProxyAuthenticationRequired | StatusCode::Unauthorized
) {
let id = self.id.lock().clone();
if !auth.should_answer(&resp) {
debug!(
id = self.id.lock().to_string(),
"received {} response after auth sent", status
);
self.transition(DialogState::Terminated(
id,
TerminatedReason::ProxyAuthRequired,
));
break;
}
if let Some(cred) = &self.credential {
let new_seq = match method {
crate::sip::Method::Cancel => self.get_local_seq(),
_ => self.increment_local_seq(),
};
tx = handle_client_authenticate(new_seq, &tx, resp, cred).await?;
tx.send().await?;
continue;
} else {
debug!(
id = self.id.lock().to_string(),
"received 407 response without auth option"
);
self.transition(DialogState::Terminated(
id,
TerminatedReason::ProxyAuthRequired,
));
continue;
}
}
debug!(
id = self.id.lock().to_string(),
method = %method,
"dialog do_request done: {:?}", status
);
if Self::is_target_refresh(method)
&& status.kind() == StatusCodeKind::Successful
{
self.refresh_target_from_response(&resp)?;
}
if !matches!(method, Method::PRack) {
self.clear_remote_reliable();
}
return Ok(Some(resp));
}
_ => break,
}
}
Ok(None)
}
pub(super) async fn do_request(&self, request: Request) -> Result<Option<Response>> {
self.send_dialog_request(request).boxed().await
}
pub(super) async fn send_bye(&self, request: Request, reason: TerminatedReason) -> Result<()> {
let result = self.do_request(request).await;
let id = self.id.lock().clone();
self.transition(DialogState::Terminated(id, reason));
result.map(|_| ())
}
pub(super) async fn bye_forked_branch(&self, resp: &Response) -> Result<()> {
let contact_uri = resp
.typed_contact_headers()?
.first()
.map(|c| c.uri.clone())
.ok_or_else(|| crate::Error::Error("missing Contact header".to_string()))?;
let mut routes: Vec<Route> = resp
.record_route_headers()
.into_iter()
.flat_map(|rr| split_rr_values(rr.value()))
.map(Route::from)
.collect();
routes.reverse();
let to = resp.to_header()?.clone();
let id = self.id.lock().clone();
let via = self
.endpoint_inner
.get_via(self.via_addr_for_send_transport(), None)?;
let cseq = CSeq {
seq: self.increment_local_seq(),
method: Method::Bye,
};
let mut headers: Vec<Header> = vec![
Header::Via(via.into()),
Header::CallId(id.call_id.clone().into()),
Header::From(self.from.clone().to_string().into()),
Header::To(to),
Header::CSeq(cseq.into()),
Header::UserAgent(self.endpoint_inner.user_agent.clone().into()),
];
if let Some(uri) = self.local_contact.as_ref() {
headers.push(Contact::from(uri.clone()).into());
}
headers.extend(routes.into_iter().map(Header::Route));
headers.push(Header::MaxForwards(70.into()));
debug!(id = %id, uri = %contact_uri, "sending BYE to a forked dialog");
self.do_request(crate::sip::Request {
method: Method::Bye,
uri: contact_uri,
headers: headers.into(),
body: Vec::new(),
version: crate::sip::Version::V2,
})
.await?;
Ok(())
}
pub(super) async fn end_session_without_ack(&self, tx: &Transaction, answered_2xx: bool) {
if !answered_2xx
|| tx.state != crate::transaction::TransactionState::Terminated
|| self.is_terminated()
{
return;
}
let id = self.id.lock().clone();
warn!(%id, "no ACK for the 2xx within 64*T1, ending the session");
let bye = self.make_request(Method::Bye, None, None, None, None, None);
self.transition(DialogState::Terminated(
id.clone(),
TerminatedReason::Timeout,
));
match bye {
Ok(bye) => {
if let Err(e) = self.do_request(bye).await {
warn!(%id, error = %e, "BYE after missing ACK failed");
}
}
Err(e) => warn!(%id, error = %e, "failed to build BYE after missing ACK"),
}
}
pub fn snapshot(&self) -> DialogSnapshot {
let id = self.id.lock().clone();
let state = match &*self.state.lock() {
DialogState::Calling(_) => DialogSnapshotState::Calling,
DialogState::Trying(_) => DialogSnapshotState::Trying,
DialogState::Early(_, _) => DialogSnapshotState::Early,
DialogState::WaitAck(_, _) => DialogSnapshotState::WaitAck,
DialogState::Confirmed(_, _) => DialogSnapshotState::Confirmed,
DialogState::Terminated(_, _) => DialogSnapshotState::Terminated,
DialogState::Updated(_, _, _)
| DialogState::Publish(_, _, _)
| DialogState::Notify(_, _, _)
| DialogState::Refer(_, _, _)
| DialogState::Message(_, _, _)
| DialogState::Info(_, _, _)
| DialogState::Options(_, _, _) => DialogSnapshotState::Confirmed,
};
DialogSnapshot {
state,
role: self.role,
id: id.clone(),
from: self.from.clone(),
to: self.to.lock().clone(),
local_cseq: self.local_seq.load(Ordering::Relaxed),
remote_cseq: self.remote_seq.load(Ordering::Relaxed),
local_contact: self.local_contact.clone(),
remote_uri: self.remote_uri.lock().clone(),
remote_contact: self.remote_contact.lock().clone(),
route_set: self.route_set.lock().clone(),
supports_100rel: self.supports_100rel,
session_id: self.session_id.lock().clone(),
}
}
pub(crate) fn try_restore_from_snapshot(
snapshot: DialogSnapshot,
endpoint_inner: EndpointInnerRef,
state_sender: DialogStateSender,
tu_sender: TransactionEventSender,
) -> Result<Option<Self>> {
if snapshot.state != DialogSnapshotState::Confirmed {
warn!(
dialog_id = %snapshot.id,
state = ?snapshot.state,
"ignoring non-confirmed dialog snapshot during restore"
);
return Ok(None);
}
let mut to = snapshot.to.clone();
let to_tag = match snapshot.role {
TransactionRole::Client => snapshot.id.remote_tag.clone(),
TransactionRole::Server => snapshot.id.local_tag.clone(),
};
if !to_tag.is_empty()
&& !to
.params
.iter()
.any(|p| matches!(p, crate::sip::Param::Tag(_)))
{
to.params.push(crate::sip::Param::Tag(to_tag.into()));
}
let mut from = snapshot.from.clone();
let from_tag = match snapshot.role {
TransactionRole::Client => snapshot.id.local_tag.clone(),
TransactionRole::Server => snapshot.id.remote_tag.clone(),
};
if !from_tag.is_empty() && from.tag().is_none() {
from = from.with_tag(from_tag.into());
}
let role = snapshot.role;
let initial_request = Mutex::new(Self::build_restored_initial_request(
role,
&snapshot.id,
&from,
&to,
&snapshot.remote_uri,
snapshot.local_cseq,
snapshot.local_contact.as_ref(),
endpoint_inner.user_agent.as_str(),
snapshot.session_id.as_ref(),
));
Ok(Some(Self {
role,
cancel_token: CancellationToken::new(),
id: Mutex::new(snapshot.id.clone()),
state: Mutex::new(DialogState::Confirmed(
snapshot.id.clone(),
Response::default(),
)),
local_seq: AtomicU32::new(snapshot.local_cseq),
remote_seq: AtomicU32::new(snapshot.remote_cseq),
local_contact: snapshot.local_contact,
remote_uri: Mutex::new(snapshot.remote_uri),
remote_target_cseq: Mutex::new(Some(snapshot.remote_cseq)),
remote_contact: Mutex::new(snapshot.remote_contact),
from,
to: Mutex::new(to),
credential: None,
route_set: Mutex::new(snapshot.route_set),
endpoint_inner,
state_sender,
tu_sender,
initial_request,
session_id: Mutex::new(snapshot.session_id),
supports_100rel: snapshot.supports_100rel,
remote_reliable: Mutex::new(None),
remote_ack: Mutex::new(None),
server_connection: Mutex::new(None),
dialback_target: Mutex::new(None),
cancel_requested: AtomicBool::new(false),
cancel_deferred: AtomicBool::new(false),
}))
}
fn build_restored_initial_request(
role: TransactionRole,
id: &DialogId,
from: &crate::sip::typed::From,
to: &crate::sip::typed::To,
remote_uri: &crate::sip::Uri,
local_seq: u32,
local_contact: Option<&crate::sip::Uri>,
user_agent: &str,
session_id: Option<&SessionIdState>,
) -> Request {
use crate::sip::Version;
let mut headers: Vec<Header> = Vec::new();
headers.push(Header::CallId(id.call_id.clone().into()));
let from_str = from.clone().to_string();
let to_str = to.clone().to_string();
match role {
TransactionRole::Client => {
headers.push(Header::From(from_str.into()));
headers.push(Header::To(to_str.into()));
}
TransactionRole::Server => {
headers.push(Header::From(to_str.into()));
headers.push(Header::To(from_str.into()));
}
}
let cseq = CSeq {
seq: local_seq,
method: Method::Invite,
};
headers.push(Header::CSeq(cseq.into()));
headers.push(Header::UserAgent(user_agent.to_string().into()));
if let Some(uri) = local_contact {
headers.push(Contact::from(uri.clone()).into());
}
if let Some(sid) = session_id {
let header = match role {
TransactionRole::Client => {
build_session_id_header(&sid.local, sid.remote.as_deref())
}
TransactionRole::Server => build_session_id_header(
sid.remote
.as_deref()
.unwrap_or(crate::sip::headers::SessionId::NIL),
Some(&sid.local),
),
};
if let Some(h) = header {
headers.push(h);
}
}
headers.push(Header::ContentLength(0u32.into()));
Request {
method: Method::Invite,
uri: remote_uri.clone(),
headers: headers.into(),
body: Vec::new(),
version: Version::V2,
}
}
pub(super) fn transition(&self, state: DialogState) {
self.transition_locked(&mut self.state.lock(), state);
}
pub(super) fn transition_if_calling(&self) -> bool {
let id = self.id.lock().clone();
let mut state = self.state.lock();
if !matches!(&*state, DialogState::Calling(_)) {
return false;
}
self.transition_locked(&mut state, DialogState::Calling(id));
true
}
pub(super) fn confirm_unless_cancelled(&self, confirmed: DialogState) -> bool {
let id = self.id.lock().clone();
let mut state = self.state.lock();
if self.cancel_requested.load(Ordering::SeqCst) {
let cancelled = DialogState::Terminated(id, TerminatedReason::UacCancel);
self.transition_locked(&mut state, cancelled);
return true;
}
self.transition_locked(&mut state, confirmed);
false
}
fn transition_locked(&self, old_state: &mut DialogState, state: DialogState) {
if let DialogState::Terminated(id, _) = &*old_state {
debug!(id = %id, target = %state, "dialog already terminated, ignoring late transition");
return;
}
match state {
DialogState::Updated(_, _, _)
| DialogState::Notify(_, _, _)
| DialogState::Info(_, _, _)
| DialogState::Options(_, _, _)
| DialogState::Refer(_, _, _) => {
self.state_sender.send(state).ok();
return;
}
_ => {}
}
if let (DialogState::Confirmed(_, _), DialogState::WaitAck(_, _)) = (&*old_state, &state) {
warn!(target = %state, "dialog already confirmed, ignoring transition");
return;
}
debug!(from = %old_state, to = %state, "transitioning state");
*old_state = state.clone();
self.state_sender.send(state).ok();
}
#[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))]
pub async fn process_transaction_handle(
&self,
tx: &mut Transaction,
mut rx: TransactionCommandReceiver,
) -> Result<()> {
let target = if Self::is_target_refresh(tx.original.method) {
match Self::parse_target_refresh_contact(&tx.original) {
Ok(target) => target,
Err(_) => return tx.reply(StatusCode::BadRequest).await,
}
} else {
None
};
let cseq = tx.original.cseq_header()?.seq()?;
let timeout_duration = self.endpoint_inner.option.t1x64;
let result = crate::platform::timeout(timeout_duration, async {
while let Some(cmd) = rx.recv().await {
match cmd {
TransactionCommand::Respond {
status,
headers,
body,
} => {
let is_final = status.kind() != StatusCodeKind::Provisional;
let response = self.make_response(&tx.original, status, headers, body);
let accepts_refresh =
Self::accepts_target_refresh(tx.original.method, &response);
tx.respond(response).await?;
if let Some(target) = &target {
if accepts_refresh {
self.accept_target_refresh(cseq, target);
}
}
if is_final {
return Ok(());
}
}
}
}
Err(crate::Error::TransactionError(
"User dropped handle without final response".into(),
tx.key.clone(),
))
})
.await;
match result {
Ok(Ok(())) => Ok(()),
Ok(Err(_)) | Err(_) => {
let id = self.id.lock().to_string();
warn!(
id,
"{} handle dropped or timed out without final reply, returning 501",
tx.original.method,
);
tx.reply(StatusCode::NotImplemented).await
}
}
}
}
impl core::fmt::Display for DialogState {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
DialogState::Calling(id) => write!(f, "{}(Calling)", id),
DialogState::Trying(id) => write!(f, "{}(Trying)", id),
DialogState::Early(id, _) => write!(f, "{}(Early)", id),
DialogState::WaitAck(id, _) => write!(f, "{}(WaitAck)", id),
DialogState::Confirmed(id, _) => write!(f, "{}(Confirmed)", id),
DialogState::Updated(id, _, _) => write!(f, "{}(Updated)", id),
DialogState::Publish(id, _, _) => write!(f, "{}(Publish)", id),
DialogState::Notify(id, _, _) => write!(f, "{}(Notify)", id),
DialogState::Info(id, _, _) => write!(f, "{}(Info)", id),
DialogState::Options(id, _, _) => write!(f, "{}(Options)", id),
DialogState::Refer(id, _, _) => write!(f, "{}(Refer)", id),
DialogState::Message(id, _, _) => write!(f, "{}(Message)", id),
DialogState::Terminated(id, reason) => write!(f, "{}(Terminated {:?})", id, reason),
}
}
}
impl Dialog {
pub fn id(&self) -> DialogId {
match self {
Dialog::Invite(d) => d.inner.id.lock().clone(),
Dialog::ServerSubscription(d) => d.inner.id.lock().clone(),
Dialog::ClientSubscription(d) => d.inner.id.lock().clone(),
Dialog::ServerPublication(d) => d.inner.id.lock().clone(),
Dialog::ClientPublication(d) => d.inner.id.lock().clone(),
}
}
pub fn from(&self) -> &crate::sip::typed::From {
match self {
Dialog::Invite(d) => &d.inner.from,
Dialog::ServerSubscription(d) => &d.inner.from,
Dialog::ClientSubscription(d) => &d.inner.from,
Dialog::ServerPublication(d) => &d.inner.from,
Dialog::ClientPublication(d) => &d.inner.from,
}
}
pub fn to(&self) -> crate::sip::typed::To {
match self {
Dialog::Invite(d) => d.inner.to.lock().clone(),
Dialog::ServerSubscription(d) => d.inner.to.lock().clone(),
Dialog::ClientSubscription(d) => d.inner.to.lock().clone(),
Dialog::ServerPublication(d) => d.inner.to.lock().clone(),
Dialog::ClientPublication(d) => d.inner.to.lock().clone(),
}
}
pub fn from_inner(role: TransactionRole, inner: DialogInnerRef) -> Self {
let _ = role;
Dialog::Invite(InviteDialog::from_inner(inner))
}
pub fn remote_contact(&self) -> Option<crate::sip::Uri> {
match self {
Dialog::Invite(d) => d.inner.remote_contact.lock().as_ref().and_then(|c| {
crate::sip::typed::Contact::parse(c.value())
.ok()
.map(|c| c.uri)
}),
Dialog::ServerSubscription(d) => d.inner.remote_contact.lock().as_ref().and_then(|c| {
crate::sip::typed::Contact::parse(c.value())
.ok()
.map(|c| c.uri)
}),
Dialog::ClientSubscription(d) => d.inner.remote_contact.lock().as_ref().and_then(|c| {
crate::sip::typed::Contact::parse(c.value())
.ok()
.map(|c| c.uri)
}),
Dialog::ServerPublication(d) => d.inner.remote_contact.lock().as_ref().and_then(|c| {
crate::sip::typed::Contact::parse(c.value())
.ok()
.map(|c| c.uri)
}),
Dialog::ClientPublication(d) => d.inner.remote_contact.lock().as_ref().and_then(|c| {
crate::sip::typed::Contact::parse(c.value())
.ok()
.map(|c| c.uri)
}),
}
}
pub async fn handle(&mut self, tx: &mut Transaction) -> Result<()> {
match self {
Dialog::Invite(d) => d.handle(tx).await,
Dialog::ServerSubscription(d) => d.handle(tx).await,
Dialog::ClientSubscription(d) => d.handle(tx).await,
Dialog::ServerPublication(d) => d.handle(tx).await,
Dialog::ClientPublication(d) => d.handle(tx).await,
}
}
pub fn on_remove(&self) {
match self {
Dialog::Invite(d) => {
d.inner.cancel_token.cancel();
}
Dialog::ServerSubscription(d) => {
d.inner.cancel_token.cancel();
}
Dialog::ClientSubscription(d) => {
d.inner.cancel_token.cancel();
}
Dialog::ServerPublication(d) => {
d.inner.cancel_token.cancel();
}
Dialog::ClientPublication(d) => {
d.inner.cancel_token.cancel();
}
}
}
pub async fn hangup(&self) -> Result<()> {
self.hangup_with_headers(None).await
}
pub async fn hangup_with_headers(
&self,
headers: Option<Vec<crate::sip::Header>>,
) -> Result<()> {
match self {
Dialog::Invite(d) => d.hangup_with_headers(headers).await,
Dialog::ServerSubscription(d) => d.unsubscribe_with_headers(headers).await,
Dialog::ClientSubscription(d) => d.unsubscribe_with_headers(headers).await,
Dialog::ServerPublication(d) => d.close_with_headers(headers).await,
Dialog::ClientPublication(d) => d.close_with_headers(headers).await,
}
}
pub fn can_cancel(&self) -> bool {
match self {
Dialog::Invite(d) => d.inner.can_cancel(),
Dialog::ServerSubscription(d) => d.inner.can_cancel(),
Dialog::ClientSubscription(d) => d.inner.can_cancel(),
Dialog::ServerPublication(d) => d.inner.can_cancel(),
Dialog::ClientPublication(d) => d.inner.can_cancel(),
}
}
pub fn set_remote_target(
&self,
uri: crate::sip::Uri,
contact: Option<crate::sip::headers::untyped::Contact>,
) {
match self {
Dialog::Invite(d) => d.inner.set_remote_target(uri, contact),
Dialog::ServerSubscription(d) => d.inner.set_remote_target(uri, contact),
Dialog::ClientSubscription(d) => d.inner.set_remote_target(uri, contact),
Dialog::ServerPublication(d) => d.inner.set_remote_target(uri, contact),
Dialog::ClientPublication(d) => d.inner.set_remote_target(uri, contact),
}
}
pub async fn request(
&self,
method: crate::sip::Method,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> Result<Option<crate::sip::Response>> {
match self {
Dialog::Invite(d) => d.request(method, headers, body).await,
Dialog::ServerSubscription(d) => d.request(method, headers, body).await,
Dialog::ClientSubscription(d) => d.request(method, headers, body).await,
Dialog::ServerPublication(d) => d.request(method, headers, body).await,
Dialog::ClientPublication(d) => d.request(method, headers, body).await,
}
}
pub async fn refer(
&self,
refer_to: impl Into<crate::sip::ReferTo>,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> Result<Option<crate::sip::Response>> {
match self {
Dialog::Invite(d) => d.refer(refer_to, headers, body).await,
Dialog::ServerSubscription(d) => d.refer(refer_to, headers, body).await,
Dialog::ClientSubscription(d) => d.refer(refer_to, headers, body).await,
Dialog::ServerPublication(d) => d.refer(refer_to, headers, body).await,
Dialog::ClientPublication(d) => d.refer(refer_to, headers, body).await,
}
}
pub async fn message(
&self,
headers: Option<Vec<crate::sip::Header>>,
body: Option<Vec<u8>>,
) -> Result<Option<crate::sip::Response>> {
match self {
Dialog::Invite(d) => d.message(headers, body).await,
Dialog::ServerSubscription(d) => d.message(headers, body).await,
Dialog::ClientSubscription(d) => d.message(headers, body).await,
Dialog::ServerPublication(d) => d.message(headers, body).await,
Dialog::ClientPublication(d) => d.message(headers, body).await,
}
}
}
fn is_system_header(h: &crate::sip::Header) -> bool {
use crate::sip::Header::*;
matches!(
h,
Via(_)
| CallId(_)
| From(_)
| To(_)
| CSeq(_)
| MaxForwards(_)
| ContentLength(_)
| Route(_)
)
}
pub(crate) fn make_dialog_session_uuid() -> String {
make_uuid_v4().replace('-', "")
}
pub(crate) fn build_session_id_header(local: &str, remote: Option<&str>) -> Option<Header> {
let header = match remote {
Some(remote) => crate::sip::headers::SessionId::from_pair(local, remote),
None => crate::sip::headers::SessionId::from_local(local),
}
.ok()?;
Some(Header::SessionId(header))
}