use super::endpoint::EndpointInnerRef;
use super::key::TransactionKey;
use super::{SipConnection, TransactionState, TransactionTimer, TransactionType};
use crate::dialog::DialogId;
use crate::platform::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use crate::prelude::*;
use crate::sip::{
ContentLength, HasHeaders, Header, HeadersExt, Method, Request, Response, SipMessage,
StatusCode, StatusCodeKind,
};
use crate::transaction::key::TransactionRole;
use crate::transaction::make_tag;
use crate::transport::SipAddr;
use crate::{Error, Result};
use tracing::{debug, trace, warn};
pub type TransactionEventReceiver = UnboundedReceiver<TransactionEvent>;
pub type TransactionEventSender = UnboundedSender<TransactionEvent>;
pub enum TransactionEvent {
Received(SipMessage, Option<SipConnection>),
Timer(TransactionTimer),
Respond(Response),
Terminate(TransactionKey),
}
pub fn transaction_event_sender_noop() -> TransactionEventSender {
#[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))]
let (tx, mut rx) = unbounded_channel::<TransactionEvent>();
crate::platform::spawn(async move {
while let Some(_ev) = rx.recv().await {
}
});
tx
}
pub struct Transaction {
pub transaction_type: TransactionType,
pub key: TransactionKey,
pub original: Request,
pub destination: Option<SipAddr>,
pub state: TransactionState,
pub endpoint_inner: EndpointInnerRef,
pub connection: Option<SipConnection>,
pub last_response: Option<Response>,
pub last_ack: Option<Request>,
pub tu_receiver: TransactionEventReceiver,
pub tu_sender: TransactionEventSender,
pub timer_a: Option<u64>,
pub timer_b: Option<u64>,
pub timer_c: Option<u64>,
pub timer_d: Option<u64>,
pub timer_k: Option<u64>, pub timer_g: Option<u64>, pub timer_l: Option<u64>, pub timer_m: Option<u64>, retransmission: bool,
is_cleaned_up: bool,
}
impl Transaction {
fn new(
transaction_type: TransactionType,
key: TransactionKey,
original: Request,
connection: Option<SipConnection>,
endpoint_inner: EndpointInnerRef,
) -> Self {
let (tu_sender, tu_receiver) = unbounded_channel();
let state = if matches!(
transaction_type,
TransactionType::ServerInvite | TransactionType::ServerNonInvite
) {
TransactionState::Trying
} else {
TransactionState::Nothing
};
trace!(%key, %state, "transaction created");
let tx = Self {
transaction_type,
endpoint_inner,
connection,
key,
original,
destination: None,
state,
last_response: None,
last_ack: None,
timer_a: None,
timer_b: None,
timer_c: None,
timer_d: None,
timer_k: None,
timer_g: None,
retransmission: true,
timer_l: None,
timer_m: None,
tu_receiver,
tu_sender,
is_cleaned_up: false,
};
tx.endpoint_inner
.attach_transaction(&tx.key, tx.tu_sender.clone());
tx
}
pub fn new_client(
key: TransactionKey,
original: Request,
endpoint_inner: EndpointInnerRef,
connection: Option<SipConnection>,
) -> Self {
let tx_type = match original.method {
Method::Invite => TransactionType::ClientInvite,
_ => TransactionType::ClientNonInvite,
};
Transaction::new(tx_type, key, original, connection, endpoint_inner)
}
pub fn new_server(
key: TransactionKey,
original: Request,
endpoint_inner: EndpointInnerRef,
connection: Option<SipConnection>,
) -> Self {
let tx_type = match original.method {
Method::Invite | Method::Ack => TransactionType::ServerInvite,
_ => TransactionType::ServerNonInvite,
};
Transaction::new(tx_type, key, original, connection, endpoint_inner)
}
pub async fn send(&mut self) -> Result<()> {
match self.transaction_type {
TransactionType::ClientInvite | TransactionType::ClientNonInvite => {}
_ => {
return Err(Error::TransactionError(
"send is only valid for client transactions".to_string(),
self.key.clone(),
));
}
}
let lookup_result = if self.connection.is_none() {
let target_uri = self.resolve_target_uri().await?;
Some(
self.endpoint_inner
.transport_layer
.lookup(&target_uri, Some(&self.key))
.await,
)
} else {
None
};
if let Some(Ok((connection, resolved_addr))) = &lookup_result {
self.connection.replace(connection.clone());
self.destination.replace(resolved_addr.clone());
}
if self.destination.is_none() {
if let Some(connection) = self.connection.as_ref() {
if connection.is_reliable() {
if let Some(remote_addr) = connection.get_remote_addr() {
debug!(key = %self.key, destination = %remote_addr, "destination from affinity connection");
self.destination.replace(remote_addr.clone());
}
}
}
}
let content_length_header =
Header::ContentLength(ContentLength::from(self.original.body().len() as u32));
self.original
.headers_mut()
.unique_push(content_length_header);
let message = if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector.before_send(self.original.to_owned().into(), self.destination.as_ref())
} else {
self.original.to_owned().into()
};
let mut stream_failed = false;
if let Some(connection) = self.connection.as_ref() {
if let Err(e) = connection.send(message, self.destination.as_ref()).await {
warn!(key = %self.key, error = %e, "send failed");
stream_failed = connection.is_stream();
}
} else {
debug!(key = %self.key, "no connection, will retry on timer");
}
self.transition(TransactionState::Calling)?;
if stream_failed {
self.on_stream_send_failure()?;
}
Ok(())
}
fn on_stream_send_failure(&mut self) -> Result<()> {
if let Some(connection) = self.connection.as_ref() {
self.endpoint_inner
.transport_layer
.retire_connection(connection);
}
let response =
self.endpoint_inner
.make_response(&self.original, StatusCode::ServiceUnavailable, None);
self.inform_tu_response(response)
}
async fn resolve_target_uri(&self) -> Result<SipAddr> {
match &self.destination {
Some(addr) => Ok(addr.clone()),
None => {
let dest = self.original.destination();
if let Some(locator) = self.endpoint_inner.locator.as_ref() {
locator.locate(&dest).await
} else {
SipAddr::try_from(&dest)
}
}
}
}
pub async fn reply_with(
&mut self,
status_code: StatusCode,
headers: Vec<Header>,
body: Option<Vec<u8>>,
) -> Result<()> {
match status_code.kind() {
StatusCodeKind::Provisional => {}
_ => {
let to = self.original.to_header()?;
if to.tag()?.is_none() {
self.original
.headers
.unique_push(to.clone().with_tag(make_tag()).into());
}
}
}
let mut resp = self
.endpoint_inner
.make_response(&self.original, status_code, body);
resp.headers.extend(headers);
self.respond(resp).await
}
pub async fn reply(&mut self, status_code: StatusCode) -> Result<()> {
self.reply_with(status_code, vec![], None).await
}
pub async fn respond(&mut self, response: Response) -> Result<()> {
match self.transaction_type {
TransactionType::ServerInvite | TransactionType::ServerNonInvite => {}
_ => {
return Err(Error::TransactionError(
"respond is only valid for server transactions".to_string(),
self.key.clone(),
));
}
}
let new_state = match response.status_code.kind() {
StatusCodeKind::Provisional => match response.status_code {
StatusCode::Trying => TransactionState::Trying,
_ => TransactionState::Proceeding,
},
StatusCodeKind::Successful => match self.transaction_type {
TransactionType::ServerInvite => TransactionState::Accepted,
_ => TransactionState::Terminated,
},
_ => match self.transaction_type {
TransactionType::ServerInvite => TransactionState::Completed,
_ => TransactionState::Terminated,
},
};
self.can_transition(&new_state)?;
let connection = self.connection.as_ref().ok_or(Error::TransactionError(
"no connection found".to_string(),
self.key.clone(),
))?;
let response = if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector.before_send(
response.clone().to_owned().into(),
self.destination.as_ref(),
)
} else {
response.to_owned().into()
};
trace!(key = %self.key, response = %response, "responding");
match response.clone() {
SipMessage::Response(resp) => self.last_response.replace(resp),
_ => None,
};
connection.send(response, self.destination.as_ref()).await?;
self.transition(new_state).map(|_| ())
}
fn can_transition(&self, target: &TransactionState) -> Result<()> {
match (&self.state, target) {
(&TransactionState::Nothing, &TransactionState::Calling)
| (&TransactionState::Nothing, &TransactionState::Trying)
| (&TransactionState::Nothing, &TransactionState::Proceeding)
| (&TransactionState::Nothing, &TransactionState::Terminated)
| (&TransactionState::Calling, &TransactionState::Calling)
| (&TransactionState::Calling, &TransactionState::Trying)
| (&TransactionState::Calling, &TransactionState::Proceeding)
| (&TransactionState::Calling, &TransactionState::Accepted) | (&TransactionState::Calling, &TransactionState::Completed)
| (&TransactionState::Calling, &TransactionState::Terminated)
| (&TransactionState::Trying, &TransactionState::Trying) | (&TransactionState::Trying, &TransactionState::Proceeding)
| (&TransactionState::Trying, &TransactionState::Accepted) | (&TransactionState::Trying, &TransactionState::Completed)
| (&TransactionState::Trying, &TransactionState::Confirmed)
| (&TransactionState::Trying, &TransactionState::Terminated)
| (&TransactionState::Proceeding, &TransactionState::Proceeding)
| (&TransactionState::Proceeding, &TransactionState::Accepted) | (&TransactionState::Proceeding, &TransactionState::Completed)
| (&TransactionState::Proceeding, &TransactionState::Confirmed)
| (&TransactionState::Proceeding, &TransactionState::Terminated)
| (&TransactionState::Accepted, &TransactionState::Accepted) | (&TransactionState::Accepted, &TransactionState::Terminated) | (&TransactionState::Completed, &TransactionState::Confirmed)
| (&TransactionState::Completed, &TransactionState::Terminated)
| (&TransactionState::Confirmed, &TransactionState::Terminated) => Ok(()),
_ => {
Err(Error::TransactionError(
format!(
"invalid state transition from {} to {}",
self.state, target
),
self.key.clone(),
))
}
}
}
pub async fn send_cancel(&mut self, cancel: Request) -> Result<()> {
if self.transaction_type != TransactionType::ClientInvite {
return Err(Error::TransactionError(
"send_cancel is only valid for client invite transactions".to_string(),
self.key.clone(),
));
}
match self.state {
TransactionState::Calling | TransactionState::Trying | TransactionState::Proceeding => {
if let Some(connection) = &self.connection {
let cancel = if let Some(ref inspector) = self.endpoint_inner.message_inspector
{
inspector.before_send(cancel.to_owned().into(), self.destination.as_ref())
} else {
cancel.to_owned().into()
};
connection.send(cancel, self.destination.as_ref()).await?;
}
Ok(())
}
_ => Err(Error::TransactionError(
format!("invalid state for sending CANCEL {:?}", self.state),
self.key.clone(),
)),
}
}
pub async fn send_ack(&mut self, mut connection: Option<SipConnection>) -> Result<()> {
if self.transaction_type != TransactionType::ClientInvite {
return Err(Error::TransactionError(
"send_ack is only valid for client invite transactions".to_string(),
self.key.clone(),
));
}
match self.state {
TransactionState::Completed | TransactionState::Accepted => {} _ => {
return Err(Error::TransactionError(
format!("invalid state for sending ACK {:?}", self.state),
self.key.clone(),
));
}
}
let ack = match self.last_ack.clone() {
Some(ack) if Self::cached_ack_matches_response(&ack, self.last_response.as_ref()) => {
ack
}
_ => {
let resp = self.last_response.as_ref().ok_or(Error::TransactionError(
"no last response found to send ACK".to_string(),
self.key.clone(),
))?;
self.endpoint_inner.make_ack(&self.original, resp)?
}
};
if let Some(resp) = self.last_response.as_ref() {
if resp.status_code.kind() == StatusCodeKind::Successful {
let reuse_existing = connection
.as_ref()
.map(|conn| conn.is_reliable())
.unwrap_or(false);
if !reuse_existing {
let target = ack.destination();
let addr = match self.endpoint_inner.locator.as_ref() {
Some(locator) => match locator.locate(&target).await {
Ok(addr) => Some(addr),
Err(e) => {
warn!(key = %self.key, error = %e, "ack locator failed");
None
}
},
None => (&target).try_into().ok(),
};
if let Some(addr) = addr {
match self
.endpoint_inner
.transport_layer
.lookup(&addr, Some(&self.key))
.await
{
Ok((via_connection, resolved_addr)) => {
if !via_connection.is_reliable() {
self.destination.replace(resolved_addr);
}
connection = Some(via_connection);
}
Err(e) => {
warn!(key = %self.key, error = %e, "ack lookup failed");
}
}
}
}
}
}
let ack = if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector.before_send(ack.to_owned().into(), self.destination.as_ref())
} else {
ack.to_owned().into()
};
match ack.clone() {
SipMessage::Request(ref ack_req) => self.last_ack.replace(ack_req.clone()),
_ => None,
};
if let Some(ref conn) = connection {
if let Err(e) = conn.send(ack, self.destination.as_ref()).await {
warn!(key = %self.key, error = %e, "ack send failed");
}
} else {
debug!(key = %self.key, "no connection for ack");
}
if self.state == TransactionState::Completed {
self.transition(TransactionState::Terminated).map(|_| ())
} else {
debug_assert_eq!(
self.state,
TransactionState::Accepted,
"send_ack reached post-send dispatch in unexpected state; the entry guard restricts to Completed|Accepted",
);
Ok(())
}
}
pub async fn receive(&mut self) -> Option<SipMessage> {
while let Some(event) = self.tu_receiver.recv().await {
match event {
TransactionEvent::Received(msg, connection) => {
if let Some(msg) = match msg {
SipMessage::Request(req) => self.on_received_request(req, connection).await,
SipMessage::Response(resp) => {
self.on_received_response(resp, connection).await
}
} {
return Some(msg);
}
}
TransactionEvent::Timer(t) => {
self.on_timer(t).await.ok();
}
TransactionEvent::Respond(response) => {
self.respond(response).await.ok();
}
TransactionEvent::Terminate(key) => {
debug!(%key, "received terminate event");
return None;
}
}
}
None
}
pub(crate) fn stop_retransmissions(&mut self) {
self.retransmission = false;
self.timer_a
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
}
pub async fn send_trying(&mut self) -> Result<()> {
let response = self
.endpoint_inner
.make_response(&self.original, StatusCode::Trying, None);
self.respond(response).await
}
pub fn is_terminated(&self) -> bool {
self.state == TransactionState::Terminated
}
}
impl Transaction {
fn inform_tu_response(&mut self, response: Response) -> Result<()> {
let msg = if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector.after_received(SipMessage::Response(response), None)
} else {
SipMessage::Response(response)
};
self.tu_sender
.send(TransactionEvent::Received(msg, None))
.map_err(|e| Error::TransactionError(e.to_string(), self.key.clone()))
}
async fn on_received_request(
&mut self,
req: Request,
connection: Option<SipConnection>,
) -> Option<SipMessage> {
match self.transaction_type {
TransactionType::ClientInvite | TransactionType::ClientNonInvite => return None,
_ => {}
}
if self.connection.is_none() && connection.is_some() {
self.connection = connection;
}
if req.method == Method::Cancel {
let forward_to_tu = match self.state {
TransactionState::Proceeding | TransactionState::Trying => true,
TransactionState::Completed => false,
_ => {
if let Some(connection) = &self.connection {
let resp = self.endpoint_inner.make_response(
&req,
StatusCode::CallTransactionDoesNotExist,
None,
);
let resp =
if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector.before_send(resp.into(), self.destination.as_ref())
} else {
resp.into()
};
connection.send(resp, self.destination.as_ref()).await.ok();
}
return None;
}
};
if let Some(connection) = &self.connection {
let resp = self
.endpoint_inner
.make_response(&req, StatusCode::OK, None);
let resp = if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector.before_send(resp.into(), self.destination.as_ref())
} else {
resp.into()
};
connection.send(resp, self.destination.as_ref()).await.ok();
}
return forward_to_tu.then(|| req.into());
}
match self.state {
TransactionState::Trying | TransactionState::Proceeding => {
if let Some(last_response) = &self.last_response {
self.respond(last_response.to_owned()).await.ok();
}
}
TransactionState::Accepted => {
if req.method == Method::Ack {
let ack_seq = req.cseq_header().and_then(|c| c.seq()).ok();
let invite_seq = self.original.cseq_header().and_then(|c| c.seq()).ok();
if ack_seq != invite_seq {
debug!(
key = %self.key,
?ack_seq,
?invite_seq,
"ignoring ACK with a CSeq that does not match the INVITE"
);
return None;
}
self.transition(TransactionState::Terminated).ok();
return Some(req.into());
}
}
TransactionState::Completed | TransactionState::Confirmed
if req.method == Method::Ack =>
{
let ack_seq = req.cseq_header().and_then(|c| c.seq()).ok();
let invite_seq = self.original.cseq_header().and_then(|c| c.seq()).ok();
if ack_seq != invite_seq {
debug!(
key = %self.key,
?ack_seq,
?invite_seq,
"ignoring ACK with a CSeq that does not match the INVITE"
);
return None;
}
self.transition(TransactionState::Confirmed).ok();
return Some(req.into());
}
_ => {}
}
None
}
async fn on_received_response(
&mut self,
resp: Response,
connection: Option<SipConnection>,
) -> Option<SipMessage> {
match self.transaction_type {
TransactionType::ServerInvite | TransactionType::ServerNonInvite => return None,
_ => {}
}
if self.transaction_type == TransactionType::ClientInvite
&& resp.status_code.kind() == StatusCodeKind::Successful
&& resp.has_multiple_vias()
{
if self.state != TransactionState::Accepted {
self.can_transition(&TransactionState::Accepted).ok()?;
self.transition(TransactionState::Accepted).ok()?;
}
self.last_response.replace(resp.clone());
return Some(SipMessage::Response(resp));
}
let new_state = match resp.status_code.kind() {
StatusCodeKind::Provisional => {
if resp.status_code == StatusCode::Trying {
TransactionState::Trying
} else {
TransactionState::Proceeding
}
}
StatusCodeKind::Successful => {
if self.transaction_type == TransactionType::ClientInvite {
if !self.endpoint_inner.option.auto_ack_2xx {
TransactionState::Terminated
} else {
TransactionState::Accepted
}
} else {
TransactionState::Terminated
}
}
_ => {
if self.transaction_type == TransactionType::ClientInvite {
TransactionState::Completed
} else {
TransactionState::Terminated
}
}
};
self.can_transition(&new_state).ok()?;
let is_client_invite_2xx_in_accepted = self.transaction_type
== TransactionType::ClientInvite
&& new_state == TransactionState::Accepted;
if !is_client_invite_2xx_in_accepted && self.state == new_state {
if let Some(last) = self.last_response.as_ref() {
if last.status_code == resp.status_code && last.body == resp.body {
return None;
}
}
}
self.last_response.replace(resp.clone());
let auto_ack_client_invite = self.transaction_type == TransactionType::ClientInvite
&& (new_state == TransactionState::Completed
|| new_state == TransactionState::Accepted);
self.transition(new_state).ok();
if auto_ack_client_invite {
if let Err(e) = self.send_ack(connection).await {
warn!(
key = %self.key,
state = %self.state,
error = %e,
"auto-ACK for client INVITE final response failed; downstream TU may need to handle ACK explicitly",
);
}
}
Some(SipMessage::Response(resp))
}
async fn retransmit_last_response(
&mut self,
key: &TransactionKey,
duration: &Duration,
) -> Result<()> {
if let Some(last_response) = &self.last_response {
if let Some(connection) = &self.connection {
let last_response =
if let Some(ref inspector) = self.endpoint_inner.message_inspector {
inspector
.before_send(last_response.to_owned().into(), self.destination.as_ref())
} else {
last_response.to_owned().into()
};
connection
.send(last_response, self.destination.as_ref())
.await?;
}
}
let duration = (*duration * 2).min(self.endpoint_inner.option.t2);
let timer_g = self
.endpoint_inner
.timers
.timeout(duration, TransactionTimer::TimerG(key.clone(), duration));
self.timer_g.replace(timer_g);
Ok(())
}
async fn on_timer(&mut self, timer: TransactionTimer) -> Result<()> {
match self.state {
TransactionState::Calling | TransactionState::Trying => {
if matches!(
self.transaction_type,
TransactionType::ClientInvite | TransactionType::ClientNonInvite
) {
if let TransactionTimer::TimerA(key, duration) = timer {
if !self.retransmission {
return Ok(());
}
if self.connection.is_none() {
if let Ok(target) = self.resolve_target_uri().await {
if let Ok((connection, resolved_addr)) = self
.endpoint_inner
.transport_layer
.lookup(&target, Some(&self.key))
.await
{
self.connection.replace(connection);
self.destination.replace(resolved_addr);
}
}
}
if let Some(connection) = &self.connection {
let retry_message = if let Some(ref inspector) =
self.endpoint_inner.message_inspector
{
inspector.before_send(
self.original.to_owned().into(),
self.destination.as_ref(),
)
} else {
self.original.to_owned().into()
};
if let Err(e) = connection
.send(retry_message, self.destination.as_ref())
.await
{
warn!(key = %self.key, error = %e, "timer A resend failed");
if connection.is_stream() {
return self.on_stream_send_failure();
}
}
} else {
debug!(key = %self.key, "timer A: no connection yet");
}
let duration = (duration * 2).min(self.endpoint_inner.option.t1x64);
let timer_a = self
.endpoint_inner
.timers
.timeout(duration, TransactionTimer::TimerA(key, duration));
self.timer_a.replace(timer_a);
} else if let TransactionTimer::TimerB(_) = timer {
let timeout_response = self.endpoint_inner.make_response(
&self.original,
StatusCode::RequestTimeout,
None,
);
self.inform_tu_response(timeout_response)?;
}
}
}
TransactionState::Proceeding => {
if matches!(timer, TransactionTimer::TimerC(_))
|| (matches!(timer, TransactionTimer::TimerB(_))
&& self.transaction_type == TransactionType::ClientNonInvite)
{
let timeout_response = self.endpoint_inner.make_response(
&self.original,
StatusCode::RequestTimeout,
None,
);
self.inform_tu_response(timeout_response)?;
}
}
TransactionState::Completed => {
if let TransactionTimer::TimerG(key, duration) = timer {
self.retransmit_last_response(&key, &duration).await?;
} else if let TransactionTimer::TimerD(_) = timer {
self.transition(TransactionState::Terminated)?;
} else if let TransactionTimer::TimerK(_) = timer {
self.transition(TransactionState::Terminated)?;
}
}
TransactionState::Accepted => {
match (&self.transaction_type, &timer) {
(TransactionType::ServerInvite, TransactionTimer::TimerL(_))
| (TransactionType::ClientInvite, TransactionTimer::TimerM(_)) => {
self.transition(TransactionState::Terminated)?;
}
(TransactionType::ServerInvite, TransactionTimer::TimerG(key, duration)) => {
self.retransmit_last_response(key, &duration).await?;
}
(
TransactionType::ClientNonInvite
| TransactionType::ServerNonInvite
| TransactionType::ClientInvite,
TransactionTimer::TimerG(_, _),
) => {
warn!(
key = %self.key,
tx_type = %self.transaction_type,
"Timer G fired outside the server Accepted state; ignoring",
);
}
(_, TransactionTimer::TimerL(_) | TransactionTimer::TimerM(_)) => {
warn!(
key = %self.key,
tx_type = %self.transaction_type,
"RFC 6026 Accepted-state timer fired with mismatched transaction type",
);
}
(_, TransactionTimer::TimerA(_, _))
| (_, TransactionTimer::TimerB(_))
| (_, TransactionTimer::TimerC(_))
| (_, TransactionTimer::TimerD(_))
| (_, TransactionTimer::TimerK(_))
| (_, TransactionTimer::TimerCleanup(_)) => {}
}
}
TransactionState::Confirmed => {
if let TransactionTimer::TimerK(_) = timer {
self.transition(TransactionState::Terminated)?;
}
}
_ => {}
}
Ok(())
}
fn transition(&mut self, state: TransactionState) -> Result<TransactionState> {
if self.state == state {
return Ok(self.state.clone());
}
match state {
TransactionState::Nothing => {}
TransactionState::Calling => {
if matches!(
self.transaction_type,
TransactionType::ClientInvite | TransactionType::ClientNonInvite
) {
match self.connection.as_ref() {
Some(connection) if !connection.is_reliable() => {
let timer_a = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1,
TransactionTimer::TimerA(
self.key.clone(),
self.endpoint_inner.option.t1,
),
);
self.timer_a.replace(timer_a);
}
None => {
let timer_a = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1,
TransactionTimer::TimerA(
self.key.clone(),
self.endpoint_inner.option.t1,
),
);
self.timer_a.replace(timer_a);
}
_ => {} }
self.timer_b.replace(self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1x64,
TransactionTimer::TimerB(self.key.clone()),
));
}
}
TransactionState::Trying | TransactionState::Proceeding => {
self.timer_a.take().map(|id| -> Option<TransactionTimer> {
self.endpoint_inner.timers.cancel(id)
});
if matches!(self.transaction_type, TransactionType::ClientInvite) {
self.timer_b.take().map(|id| -> Option<TransactionTimer> {
self.endpoint_inner.timers.cancel(id)
});
if self.timer_c.is_none() {
let timer_c = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.timerc,
TransactionTimer::TimerC(self.key.clone()),
);
self.timer_c.replace(timer_c);
}
}
}
TransactionState::Accepted => {
self.timer_a
.take()
.map(|id| self.endpoint_inner.timers.cancel(id));
self.timer_b
.take()
.map(|id| self.endpoint_inner.timers.cancel(id));
self.timer_c
.take()
.map(|id| self.endpoint_inner.timers.cancel(id));
match self.transaction_type {
TransactionType::ServerInvite => {
let timer_l = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1x64,
TransactionTimer::TimerL(self.key.clone()),
);
self.timer_l.replace(timer_l);
let timer_g = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1,
TransactionTimer::TimerG(
self.key.clone(),
self.endpoint_inner.option.t1,
),
);
self.timer_g.replace(timer_g);
if let Some(ref resp) = self.last_response {
let dialog_id = DialogId::try_from((resp, TransactionRole::Server))?;
let seq = self.original.cseq_header().and_then(|c| c.seq()).ok();
if let Some(seq) = seq {
self.endpoint_inner
.waiting_ack_cseq
.insert((dialog_id.clone(), seq), self.key.clone());
}
self.endpoint_inner
.waiting_ack
.insert(dialog_id, self.key.clone());
}
debug!(
key = %self.key,
"entered Accepted state (server); Timer L and Timer G armed, waiting for ACK"
);
}
TransactionType::ClientInvite => {
let timer_m = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1x64,
TransactionTimer::TimerM(self.key.clone()),
);
self.timer_m.replace(timer_m);
debug!(
key = %self.key,
"entered Accepted state (client); Timer M armed, awaiting expiry or 2xx retransmits"
);
}
_ => {
return Err(Error::TransactionError(
format!(
"Accepted state is INVITE-only (transaction type was {})",
self.transaction_type
),
self.key.clone(),
));
}
}
}
TransactionState::Completed => {
self.timer_a.take().map(|id| -> Option<TransactionTimer> {
self.endpoint_inner.timers.cancel(id)
});
self.timer_b.take().map(|id| -> Option<TransactionTimer> {
self.endpoint_inner.timers.cancel(id)
});
self.timer_c.take().map(|id| -> Option<TransactionTimer> {
self.endpoint_inner.timers.cancel(id)
});
if self.transaction_type == TransactionType::ServerInvite {
let connection = self.connection.as_ref().ok_or(Error::TransactionError(
"no connection found".to_string(),
self.key.clone(),
))?;
if !connection.is_reliable() {
let timer_g = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1,
TransactionTimer::TimerG(
self.key.clone(),
self.endpoint_inner.option.t1,
),
);
self.timer_g.replace(timer_g);
}
debug!(key=%self.key, last = self.last_response.is_none(), "entered confirmed state, waiting for ACK");
if let Some(ref resp) = self.last_response {
let dialog_id = DialogId::try_from((resp, TransactionRole::Server))?;
self.endpoint_inner
.waiting_ack
.insert(dialog_id, self.key.clone());
}
}
let timer_d = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t1x64,
TransactionTimer::TimerD(self.key.clone()),
);
self.timer_d.replace(timer_d);
}
TransactionState::Confirmed => {
self.cleanup_timer();
if self.transaction_type == TransactionType::ServerInvite {
if let Some(ref resp) = self.last_response {
if let Ok(dialog_id) = DialogId::try_from((resp, self.role())) {
self.endpoint_inner.forget_waiting_ack(
dialog_id,
&self.original,
&self.key,
);
}
}
}
let timer_k = self.endpoint_inner.timers.timeout(
self.endpoint_inner.option.t4,
TransactionTimer::TimerK(self.key.clone()),
);
self.timer_k.replace(timer_k);
}
TransactionState::Terminated => {
self.cleanup();
self.tu_sender
.send(TransactionEvent::Terminate(self.key.clone()))
.ok(); }
}
debug!(
key = %self.key,
from = %self.state,
to = %state,
"transition"
);
self.state = state;
Ok(self.state.clone())
}
fn cleanup_timer(&mut self) {
self.timer_a
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_b
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_c
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_d
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_k
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_g
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_l
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
self.timer_m
.take()
.map(|id| -> Option<TransactionTimer> { self.endpoint_inner.timers.cancel(id) });
}
fn cached_ack_matches_response(ack: &Request, resp: Option<&Response>) -> bool {
let Some(resp) = resp else {
return true;
};
let ack_tag = ack
.to_header()
.ok()
.and_then(|h| h.tag().ok())
.flatten()
.map(|t| t.value().to_string());
let resp_tag = resp
.to_header()
.ok()
.and_then(|h| h.tag().ok())
.flatten()
.map(|t| t.value().to_string());
match (ack_tag, resp_tag) {
(Some(a), Some(b)) => a == b,
_ => true,
}
}
pub fn role(&self) -> TransactionRole {
match self.transaction_type {
crate::transaction::TransactionType::ClientInvite
| crate::transaction::TransactionType::ClientNonInvite => TransactionRole::Client,
crate::transaction::TransactionType::ServerInvite
| crate::transaction::TransactionType::ServerNonInvite => TransactionRole::Server,
}
}
fn cleanup(&mut self) {
if self.is_cleaned_up {
return;
}
self.is_cleaned_up = true;
self.cleanup_timer();
let is_server_invite_waiting_ack =
matches!(self.transaction_type, TransactionType::ServerInvite)
&& self.state == TransactionState::Completed;
if !is_server_invite_waiting_ack {
if let Some(Ok(dialog_id)) = self
.last_response
.as_ref()
.map(|resp| DialogId::try_from((resp, self.role())))
{
self.endpoint_inner
.forget_waiting_ack(dialog_id, &self.original, &self.key);
}
}
let last_message = {
match self.transaction_type {
TransactionType::ClientInvite => {
if matches!(
self.state,
TransactionState::Proceeding | TransactionState::Trying
) && self.last_ack.is_none()
{
if let Some(ref resp) = self.last_response {
let auto_ack = self.endpoint_inner.option.auto_ack_2xx
|| resp.status_code.kind() != StatusCodeKind::Successful;
if auto_ack {
if let Ok(ack) = self.endpoint_inner.make_ack(&self.original, resp)
{
self.last_ack.replace(ack);
}
}
}
}
self.last_ack.take().map(SipMessage::Request)
}
TransactionType::ServerNonInvite => {
self.last_response.take().map(SipMessage::Response)
}
TransactionType::ServerInvite => {
self.last_response.clone().map(SipMessage::Response)
}
_ => None,
}
};
self.endpoint_inner
.detach_transaction(&self.key, last_message);
}
}
impl Drop for Transaction {
fn drop(&mut self) {
self.cleanup();
trace!(key=%self.key, state=%self.state, "transaction dropped");
}
}