use crate::dialog::{
client_dialog::ClientInviteDialog,
dialog::{DialogState, DialogStateReceiver, TerminatedReason},
dialog_layer::DialogLayer,
invitation::InviteOption,
DialogId,
};
use crate::sip::{prelude::HeadersExt, Method, Request, SipMessage, StatusCode, Uri};
use crate::transaction::endpoint::EndpointOption;
use crate::transport::{udp::UdpConnection, TransportLayer};
use crate::EndpointBuilder;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::UdpSocket;
use tokio::sync::mpsc::unbounded_channel;
use tokio_util::sync::CancellationToken;
const PEER_TAG: &str = "peer-tag";
async fn recv_request(socket: &UdpSocket, method: Method, wait: Duration) -> (Request, SocketAddr) {
let mut buf = vec![0u8; 4096];
let deadline = tokio::time::Instant::now() + wait;
loop {
let (len, from) = tokio::time::timeout_at(deadline, socket.recv_from(&mut buf))
.await
.unwrap_or_else(|_| panic!("timeout waiting for {method}"))
.expect("recv_from failed");
let text = std::str::from_utf8(&buf[..len]).expect("non utf-8 SIP message");
if let Ok(SipMessage::Request(req)) = SipMessage::try_from(text) {
if req.method == method {
return (req, from);
}
}
}
}
async fn assert_no_bye(socket: &UdpSocket, wait: Duration, what: &str) {
assert_no_request(socket, Method::Bye, wait, what).await
}
async fn assert_no_request(socket: &UdpSocket, method: Method, wait: Duration, what: &str) {
let mut buf = vec![0u8; 4096];
let deadline = tokio::time::Instant::now() + wait;
while let Ok(Ok((len, _))) = tokio::time::timeout_at(deadline, socket.recv_from(&mut buf)).await
{
let text = std::str::from_utf8(&buf[..len]).unwrap();
if let Ok(SipMessage::Request(req)) = SipMessage::try_from(text) {
assert_ne!(req.method, method, "{what}");
}
}
}
fn response(req: &Request, code: u16, reason: &str, contact: &str) -> String {
let to = req.to_header().unwrap().value().to_string();
let to = if to.contains(";tag=") {
to
} else {
format!("{to};tag={PEER_TAG}")
};
format!(
"SIP/2.0 {code} {reason}\r\n\
Via: {}\r\n\
From: {}\r\n\
To: {to}\r\n\
Call-ID: {}\r\n\
CSeq: {}\r\n\
Contact: <{contact}>\r\n\
Content-Length: 0\r\n\r\n",
req.via_header().unwrap().value(),
req.from_header().unwrap().value(),
req.call_id_header().unwrap().value(),
req.cseq_header().unwrap().value(),
)
}
async fn reply(socket: &UdpSocket, to: SocketAddr, req: &Request, code: u16, reason: &str) {
let contact = format!("sip:bob@{}", socket.local_addr().unwrap());
socket
.send_to(response(req, code, reason, &contact).as_bytes(), to)
.await
.expect("send_to failed");
}
struct Uac {
dialog_layer: Arc<DialogLayer>,
option: InviteOption,
peer: UdpSocket,
}
async fn setup(token: &CancellationToken) -> crate::Result<Uac> {
setup_with(token, EndpointOption::default()).await
}
async fn setup_with(token: &CancellationToken, option: EndpointOption) -> crate::Result<Uac> {
let peer = UdpSocket::bind("127.0.0.1:0").await?;
let peer_port = peer.local_addr()?.port();
let transport_layer = TransportLayer::new(token.child_token());
let udp = UdpConnection::create_connection(
"127.0.0.1:0".parse().unwrap(),
None,
Some(token.child_token()),
)
.await?;
let uac_addr = udp.get_addr().addr.clone();
transport_layer.add_transport(udp.into());
let endpoint = EndpointBuilder::new()
.with_user_agent("rsipstack-test")
.with_transport_layer(transport_layer)
.with_cancel_token(token.child_token())
.with_option(option)
.build();
let endpoint_inner = endpoint.inner.clone();
tokio::spawn(async move {
let _ = endpoint_inner.serve().await;
});
let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
let option = InviteOption {
caller: Uri::try_from("sip:alice@example.com")?,
callee: Uri::try_from(format!("sip:bob@127.0.0.1:{peer_port};transport=udp").as_str())?,
contact: Uri::try_from(format!("sip:alice@{uac_addr}").as_str())?,
..Default::default()
};
Ok(Uac {
dialog_layer,
option,
peer,
})
}
async fn wait_for_state(
rx: &mut DialogStateReceiver,
what: &str,
wait: Duration,
pred: impl Fn(&DialogState) -> bool,
) -> DialogState {
tokio::time::timeout(wait, async {
loop {
let state = rx.recv().await.expect("state channel closed");
if pred(&state) {
return state;
}
}
})
.await
.unwrap_or_else(|_| panic!("timeout waiting for {what}"))
}
fn assert_in_dialog(msg: &Request, invite: &Request, what: &str) {
assert_eq!(
msg.call_id_header().unwrap().value(),
invite.call_id_header().unwrap().value(),
"{what} must carry the INVITE's Call-ID"
);
assert_eq!(
msg.from_header().unwrap().tag().unwrap(),
invite.from_header().unwrap().tag().unwrap(),
"{what} must carry our From tag"
);
assert_eq!(
msg.to_header()
.unwrap()
.tag()
.unwrap()
.map(|t| t.value().to_string()),
Some(PEER_TAG.to_string()),
"{what} must carry the 2xx's To tag"
);
}
#[derive(Clone, Copy, Debug)]
enum Order {
InviteOkFirst,
CancelOkFirst,
InviteOkLate,
}
async fn calling_id(states: &mut DialogStateReceiver) -> DialogId {
match wait_for_state(states, "Calling", Duration::from_secs(2), |s| {
matches!(s, DialogState::Calling(_))
})
.await
{
DialogState::Calling(id) => id,
_ => unreachable!(),
}
}
async fn run_crossing_2xx(order: Order, provisional: u16, remove: bool) -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let wait = Duration::from_secs(2);
let (state_sender, mut states) = unbounded_channel();
let layer = dialog_layer.clone();
let invite = tokio::spawn(async move { layer.do_invite(option, state_sender).await });
let (inv, uac) = recv_request(&peer, Method::Invite, wait).await;
let id = calling_id(&mut states).await;
let reason = if provisional == 100 {
"Trying"
} else {
"Ringing"
};
reply(&peer, uac, &inv, provisional, reason).await;
wait_for_state(&mut states, "Trying or Early", wait, |s| {
matches!(s, DialogState::Trying(_) | DialogState::Early(_, _))
})
.await;
if remove {
dialog_layer.remove_dialog(&id);
assert!(dialog_layer.is_empty());
}
invite.abort();
let _ = invite.await;
let (cancel, _) = recv_request(&peer, Method::Cancel, wait).await;
let mut terminated = None;
match order {
Order::InviteOkFirst => {
reply(&peer, uac, &inv, 200, "OK").await;
reply(&peer, uac, &cancel, 200, "OK").await;
}
Order::CancelOkFirst => {
reply(&peer, uac, &cancel, 200, "OK").await;
reply(&peer, uac, &inv, 200, "OK").await;
}
Order::InviteOkLate => {
reply(&peer, uac, &cancel, 200, "OK").await;
terminated = Some(
wait_for_state(&mut states, "Terminated", Duration::from_secs(4), |s| {
matches!(s, DialogState::Terminated(_, _))
})
.await,
);
tokio::time::sleep(Duration::from_millis(2500)).await;
reply(&peer, uac, &inv, 200, "OK").await;
}
}
let (ack, _) = recv_request(&peer, Method::Ack, wait).await;
assert_in_dialog(&ack, &inv, "ACK");
assert_eq!(
ack.cseq_header().unwrap().seq().unwrap(),
inv.cseq_header().unwrap().seq().unwrap(),
"the ACK must acknowledge the INVITE"
);
let (bye, _) = recv_request(&peer, Method::Bye, wait).await;
assert_in_dialog(&bye, &inv, "BYE");
reply(&peer, uac, &bye, 200, "OK").await;
reply(&peer, uac, &inv, 200, "OK").await;
let (ack, _) = recv_request(&peer, Method::Ack, wait).await;
assert_in_dialog(&ack, &inv, "ACK of the retransmitted 2xx");
assert_no_bye(
&peer,
Duration::from_millis(500),
"one BYE per abandoned call",
)
.await;
tokio::time::sleep(Duration::from_millis(200)).await;
let mut seen = Vec::new();
while let Ok(state) = states.try_recv() {
seen.push(state);
}
if let Some(t) = terminated {
seen.insert(0, t);
}
assert!(
!seen
.iter()
.any(|s| matches!(s, DialogState::Confirmed(_, _))),
"an abandoned call must not report Confirmed, got {seen:?}"
);
let terminations: Vec<_> = seen
.iter()
.filter(|s| matches!(s, DialogState::Terminated(_, _)))
.collect();
assert!(
matches!(
terminations.as_slice(),
[DialogState::Terminated(_, TerminatedReason::UacCancel)]
),
"expected exactly one Terminated(UacCancel), got {seen:?}"
);
assert!(
bye.cseq_header().unwrap().seq().unwrap() > inv.cseq_header().unwrap().seq().unwrap(),
"the BYE must use a new CSeq"
);
assert_eq!(
bye.uri.to_string(),
format!("sip:bob@{}", peer.local_addr()?),
"the BYE must target the 2xx's Contact"
);
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_2xx_before_cancel_response_is_acked_and_byed() -> crate::Result<()> {
run_crossing_2xx(Order::InviteOkFirst, 180, false).await
}
#[tokio::test]
async fn test_2xx_after_cancel_response_is_acked_and_byed() -> crate::Result<()> {
run_crossing_2xx(Order::CancelOkFirst, 180, false).await
}
#[tokio::test]
async fn test_2xx_after_cancel_settle_window_is_acked_and_byed() -> crate::Result<()> {
run_crossing_2xx(Order::InviteOkLate, 180, false).await
}
#[tokio::test]
async fn test_removed_dialog_2xx_crossing_the_cancel_is_acked_and_byed() -> crate::Result<()> {
run_crossing_2xx(Order::InviteOkFirst, 180, true).await?;
run_crossing_2xx(Order::InviteOkFirst, 100, true).await
}
#[tokio::test]
async fn test_removed_dialog_2xx_after_the_cancel_response_is_acked_and_byed() -> crate::Result<()>
{
run_crossing_2xx(Order::CancelOkFirst, 180, true).await
}
async fn run_cancel_answered_487(provisional: u16, remove: bool) -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let wait = Duration::from_secs(2);
let (state_sender, mut states) = unbounded_channel();
let layer = dialog_layer.clone();
let invite = tokio::spawn(async move { layer.do_invite(option, state_sender).await });
let (inv, uac) = recv_request(&peer, Method::Invite, wait).await;
let id = calling_id(&mut states).await;
let reason = if provisional == 100 {
"Trying"
} else {
"Ringing"
};
reply(&peer, uac, &inv, provisional, reason).await;
wait_for_state(&mut states, "Trying or Early", wait, |s| {
matches!(s, DialogState::Trying(_) | DialogState::Early(_, _))
})
.await;
if remove {
dialog_layer.remove_dialog(&id);
assert!(dialog_layer.is_empty());
}
invite.abort();
let _ = invite.await;
let (cancel, _) = recv_request(&peer, Method::Cancel, wait).await;
reply(&peer, uac, &cancel, 200, "OK").await;
reply(&peer, uac, &inv, 487, "Request Terminated").await;
let (ack, _) = recv_request(&peer, Method::Ack, wait).await;
assert_in_dialog(&ack, &inv, "ACK");
assert_eq!(
ack.cseq_header().unwrap().seq().unwrap(),
inv.cseq_header().unwrap().seq().unwrap(),
"the ACK must acknowledge the INVITE"
);
assert_no_bye(
&peer,
Duration::from_millis(1500),
"a cancelled call must not be BYE'd",
)
.await;
tokio::time::sleep(Duration::from_millis(200)).await;
let seen: Vec<_> = std::iter::from_fn(|| states.try_recv().ok()).collect();
assert!(
!seen
.iter()
.any(|s| matches!(s, DialogState::Confirmed(_, _))),
"a cancelled call must not report Confirmed, got {seen:?}"
);
let terminations: Vec<_> = seen
.iter()
.filter(|s| matches!(s, DialogState::Terminated(_, _)))
.collect();
assert!(
matches!(
terminations.as_slice(),
[DialogState::Terminated(_, TerminatedReason::UacCancel)]
),
"expected exactly one Terminated(UacCancel), got {seen:?}"
);
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_cancel_answered_487_sends_no_bye() -> crate::Result<()> {
run_cancel_answered_487(180, false).await
}
#[tokio::test]
async fn test_removed_cancel_answered_487_sends_no_bye() -> crate::Result<()> {
run_cancel_answered_487(180, true).await?;
run_cancel_answered_487(100, true).await
}
async fn run_aborted_invite_task(in_calling: bool, first: u16) -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let wait = Duration::from_secs(2);
let (state_sender, mut states) = unbounded_channel();
let (_dialog, join) = dialog_layer.do_invite_async(option, state_sender)?;
let (inv, uac) = recv_request(&peer, Method::Invite, wait).await;
calling_id(&mut states).await;
if !in_calling {
reply(&peer, uac, &inv, 180, "Ringing").await;
wait_for_state(&mut states, "Early", wait, |s| {
matches!(s, DialogState::Early(_, _))
})
.await;
}
join.abort();
let _ = join.await;
if in_calling {
reply(&peer, uac, &inv, first, "Response").await;
}
if first == 180 {
let (cancel, _) = recv_request(&peer, Method::Cancel, wait).await;
reply(&peer, uac, &cancel, 200, "OK").await;
reply(&peer, uac, &inv, 487, "Request Terminated").await;
}
let (ack, _) = recv_request(&peer, Method::Ack, wait).await;
assert_in_dialog(&ack, &inv, "ACK");
if first == 200 {
let (bye, _) = recv_request(&peer, Method::Bye, wait).await;
assert_in_dialog(&bye, &inv, "BYE");
reply(&peer, uac, &bye, 200, "OK").await;
}
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(dialog_layer.is_empty(), "an aborted call is not registered");
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_aborted_invite_task_in_calling_is_cancelled_after_the_180() -> crate::Result<()> {
run_aborted_invite_task(true, 180).await
}
#[tokio::test]
async fn test_aborted_invite_task_in_calling_2xx_is_acked_and_byed() -> crate::Result<()> {
run_aborted_invite_task(true, 200).await
}
#[tokio::test]
async fn test_aborted_invite_task_in_early_is_cancelled() -> crate::Result<()> {
run_aborted_invite_task(false, 180).await
}
async fn run_dropped_before_provisional(first: u16, remove: bool) -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let wait = Duration::from_secs(2);
let (state_sender, mut states) = unbounded_channel();
let layer = dialog_layer.clone();
let invite = tokio::spawn(async move { layer.do_invite(option, state_sender).await });
let (inv, uac) = recv_request(&peer, Method::Invite, wait).await;
let id = calling_id(&mut states).await;
if remove {
dialog_layer.remove_dialog(&id);
assert!(dialog_layer.is_empty());
}
invite.abort();
let _ = invite.await;
let terminated = wait_for_state(&mut states, "Terminated", Duration::from_millis(200), |s| {
matches!(s, DialogState::Terminated(_, _))
})
.await;
assert!(matches!(
terminated,
DialogState::Terminated(_, TerminatedReason::UacCancel)
));
let mut buf = vec![0u8; 4096];
let silent = tokio::time::timeout(Duration::from_millis(1100), peer.recv_from(&mut buf)).await;
assert!(silent.is_err(), "nothing may be sent before a provisional");
match first {
180 => {
reply(&peer, uac, &inv, 180, "Ringing").await;
let (cancel, _) = recv_request(&peer, Method::Cancel, wait).await;
assert_eq!(cancel.cseq_header()?.seq()?, inv.cseq_header()?.seq()?);
reply(&peer, uac, &cancel, 200, "OK").await;
reply(&peer, uac, &inv, 487, "Request Terminated").await;
}
200 => reply(&peer, uac, &inv, 200, "OK").await,
_ => reply(&peer, uac, &inv, first, "Busy Here").await,
}
let (ack, _) = recv_request(&peer, Method::Ack, wait).await;
assert_in_dialog(&ack, &inv, "ACK");
if first == 200 {
let (bye, _) = recv_request(&peer, Method::Bye, wait).await;
assert_in_dialog(&bye, &inv, "BYE");
reply(&peer, uac, &bye, 200, "OK").await;
} else {
assert_no_bye(
&peer,
Duration::from_millis(500),
"a call that was not answered",
)
.await;
}
assert!(
!std::iter::from_fn(|| states.try_recv().ok())
.any(|s| matches!(s, DialogState::Terminated(..) | DialogState::Confirmed(..))),
"no second Terminated and no Confirmed"
);
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_dropped_before_provisional_is_cancelled_after_the_180() -> crate::Result<()> {
run_dropped_before_provisional(180, false).await
}
#[tokio::test]
async fn test_dropped_before_provisional_2xx_is_acked_and_byed() -> crate::Result<()> {
run_dropped_before_provisional(200, false).await
}
#[tokio::test]
async fn test_removed_before_provisional_is_cancelled_after_the_180() -> crate::Result<()> {
run_dropped_before_provisional(180, true).await
}
#[tokio::test]
async fn test_removed_before_provisional_2xx_is_acked_and_byed() -> crate::Result<()> {
run_dropped_before_provisional(200, true).await
}
#[tokio::test]
async fn test_dropped_before_provisional_final_failure_is_acked_only() -> crate::Result<()> {
run_dropped_before_provisional(486, false).await
}
#[tokio::test]
async fn test_removed_before_provisional_final_failure_is_acked_only() -> crate::Result<()> {
run_dropped_before_provisional(486, true).await
}
async fn run_cancel_called(in_calling: bool, first: u16, last: u16) -> crate::Result<()> {
run_cancel_called_via(false, in_calling, first, last).await
}
async fn run_cancel_called_via(
legacy: bool,
in_calling: bool,
first: u16,
last: u16,
) -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let wait = Duration::from_secs(2);
let (state_sender, mut states) = unbounded_channel();
let (dialog, join) = if legacy {
let (dialog, mut tx) = dialog_layer.create_client_invite_dialog(option, state_sender)?;
let legacy = ClientInviteDialog {
inner: dialog.inner.clone(),
};
let join = tokio::spawn(async move { legacy.process_invite(&mut tx).await });
(dialog, join)
} else {
dialog_layer.do_invite_async(option, state_sender)?
};
let (inv, uac) = recv_request(&peer, Method::Invite, wait).await;
calling_id(&mut states).await;
if in_calling {
dialog.cancel().await?;
assert_no_request(
&peer,
Method::Cancel,
Duration::from_millis(1100),
"no CANCEL before a provisional",
)
.await;
}
let provisional = matches!(first, 100 | 180);
reply(&peer, uac, &inv, first, "Response").await;
if !in_calling {
wait_for_state(&mut states, "Early", wait, |s| {
matches!(s, DialogState::Early(_, _))
})
.await;
let dialog = dialog.clone();
tokio::spawn(async move { dialog.cancel().await });
}
if provisional {
let (cancel, _) = recv_request(&peer, Method::Cancel, wait).await;
assert_eq!(cancel.cseq_header()?.seq()?, inv.cseq_header()?.seq()?);
if last == 200 {
reply(&peer, uac, &inv, 200, "OK").await;
reply(&peer, uac, &cancel, 200, "OK").await;
} else {
reply(&peer, uac, &cancel, 200, "OK").await;
reply(&peer, uac, &inv, last, "Request Terminated").await;
}
}
let answered = if provisional { last } else { first };
let (ack, _) = recv_request(&peer, Method::Ack, wait).await;
assert_in_dialog(&ack, &inv, "ACK");
if answered == 200 {
let (bye, _) = recv_request(&peer, Method::Bye, wait).await;
assert_in_dialog(&bye, &inv, "BYE");
reply(&peer, uac, &bye, 200, "OK").await;
} else {
assert_no_bye(&peer, Duration::from_millis(500), "an unanswered call").await;
}
assert_no_request(
&peer,
Method::Cancel,
Duration::from_millis(300),
"a late CANCEL",
)
.await;
let (_, resp) = tokio::time::timeout(wait, join)
.await
.expect("join")
.expect("invite task")?;
assert_eq!(resp.map(|r| u16::from(r.status_code)), Some(answered));
tokio::time::sleep(Duration::from_millis(200)).await;
let seen: Vec<_> = std::iter::from_fn(|| states.try_recv().ok()).collect();
assert!(
!seen.iter().any(|s| matches!(s, DialogState::Confirmed(..))),
"a cancelled call must not report Confirmed, got {seen:?}"
);
let terminations: Vec<_> = seen
.iter()
.filter(|s| matches!(s, DialogState::Terminated(..)))
.collect();
assert_eq!(terminations.len(), 1, "one Terminated, got {seen:?}");
if answered == 200 {
assert!(matches!(
terminations[0],
DialogState::Terminated(_, TerminatedReason::UacCancel)
));
}
assert!(dialog.state().is_terminated());
assert!(
dialog_layer.is_empty(),
"a cancelled call is not registered"
);
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_cancel_in_calling_is_sent_after_the_180() -> crate::Result<()> {
run_cancel_called(true, 180, 487).await
}
#[tokio::test]
async fn test_cancel_in_calling_is_sent_after_the_100() -> crate::Result<()> {
run_cancel_called(true, 100, 487).await
}
#[tokio::test]
async fn test_cancel_in_calling_2xx_crossing_the_cancel_is_acked_and_byed() -> crate::Result<()> {
run_cancel_called(true, 180, 200).await
}
#[tokio::test]
async fn test_cancel_in_calling_2xx_without_provisional_is_acked_and_byed() -> crate::Result<()> {
run_cancel_called(true, 200, 200).await
}
#[tokio::test]
async fn test_cancel_in_calling_final_failure_is_acked_only() -> crate::Result<()> {
run_cancel_called(true, 486, 486).await
}
#[tokio::test]
async fn test_cancel_in_early_2xx_crossing_the_cancel_is_acked_and_byed() -> crate::Result<()> {
run_cancel_called(false, 180, 200).await?;
run_cancel_called(false, 180, 487).await
}
#[tokio::test]
async fn test_cancel_in_calling_with_the_legacy_client_dialog() -> crate::Result<()> {
run_cancel_called_via(true, true, 180, 487).await?;
run_cancel_called_via(true, true, 200, 200).await
}
#[tokio::test]
async fn test_cancel_in_calling_is_not_held_back_by_the_prack() -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
mut option,
peer,
} = setup(&token).await?;
option.support_prack = true;
let (state_sender, mut states) = unbounded_channel();
let (dialog, _join) = dialog_layer.do_invite_async(option, state_sender)?;
let (inv, uac) = recv_request(&peer, Method::Invite, Duration::from_secs(2)).await;
calling_id(&mut states).await;
dialog.cancel().await?;
let contact = format!("sip:bob@{}", peer.local_addr()?);
let reliable = response(&inv, 183, "Session Progress", &contact).replace(
"Content-Length: 0",
"Require: 100rel\r\nRSeq: 1\r\nContent-Length: 0",
);
peer.send_to(reliable.as_bytes(), uac).await?;
let mut buf = vec![0u8; 4096];
let (mut prack, mut cancel) = (false, false);
while !(prack && cancel) {
let (len, _) = tokio::time::timeout(Duration::from_secs(1), peer.recv_from(&mut buf))
.await
.unwrap_or_else(|_| panic!("PRACK seen: {prack}, CANCEL seen: {cancel}"))?;
if let Ok(SipMessage::Request(req)) = SipMessage::try_from(&buf[..len]) {
prack |= req.method == Method::PRack;
cancel |= req.method == Method::Cancel
&& req.cseq_header()?.seq()? == inv.cseq_header()?.seq()?;
}
}
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_cancel_in_calling_without_response_times_out() -> crate::Result<()> {
let token = CancellationToken::new();
let t1 = Duration::from_millis(20);
let option = EndpointOption {
t1,
t1x64: t1 * 64,
..Default::default()
};
let Uac {
dialog_layer,
option,
peer,
} = setup_with(&token, option).await?;
let (state_sender, mut states) = unbounded_channel();
let (dialog, join) = dialog_layer.do_invite_async(option, state_sender)?;
recv_request(&peer, Method::Invite, Duration::from_secs(2)).await;
calling_id(&mut states).await;
dialog.cancel().await?;
assert_no_request(
&peer,
Method::Cancel,
t1 * 64 + Duration::from_millis(500),
"no CANCEL without a provisional",
)
.await;
let (_, resp) = tokio::time::timeout(Duration::from_secs(2), join)
.await
.expect("join")
.expect("invite task")?;
assert_eq!(
resp.map(|r| r.status_code),
Some(StatusCode::RequestTimeout)
);
assert!(dialog.state().is_terminated());
assert!(dialog_layer.is_empty());
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_aborted_invite_before_first_poll_removes_dialog_without_sending() -> crate::Result<()>
{
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let (sender, _states) = unbounded_channel();
let (dialog, join) = dialog_layer.do_invite_async(option, sender)?;
join.abort();
assert!(join.await.unwrap_err().is_cancelled());
assert!(dialog_layer.is_empty());
assert!(matches!(
dialog.state(),
DialogState::Terminated(_, TerminatedReason::UacCancel)
));
let mut buf = [0u8; 4096];
assert!(
tokio::time::timeout(Duration::from_millis(100), peer.recv_from(&mut buf))
.await
.is_err()
);
token.cancel();
Ok(())
}
async fn run_cleanup_cancel_retransmission(final_first: bool) -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let wait = Duration::from_secs(5);
let (sender, mut states) = unbounded_channel();
let (_dialog, join) = dialog_layer.do_invite_async(option, sender)?;
let (inv, uac) = recv_request(&peer, Method::Invite, wait).await;
reply(&peer, uac, &inv, 180, "Ringing").await;
wait_for_state(&mut states, "Early", wait, |s| {
matches!(s, DialogState::Early(_, _))
})
.await;
join.abort();
let _ = join.await;
let (cancel, _) = recv_request(&peer, Method::Cancel, wait).await;
if final_first {
reply(&peer, uac, &inv, 487, "Request Terminated").await;
recv_request(&peer, Method::Ack, wait).await;
}
let started = tokio::time::Instant::now();
loop {
let (retry, _) = recv_request(&peer, Method::Cancel, wait).await;
assert_eq!(retry.to_string(), cancel.to_string());
if started.elapsed() > Duration::from_secs(2) {
reply(&peer, uac, &retry, 200, "OK").await;
break;
}
}
if !final_first {
reply(&peer, uac, &inv, 487, "Request Terminated").await;
recv_request(&peer, Method::Ack, wait).await;
}
assert!(tokio::time::timeout(Duration::from_millis(4200), async {
recv_request(&peer, Method::Cancel, Duration::from_secs(5)).await
})
.await
.is_err());
assert!(dialog_layer.is_empty());
token.cancel();
Ok(())
}
#[tokio::test]
async fn test_cleanup_cancel_survives_invite_final() -> crate::Result<()> {
run_cleanup_cancel_retransmission(true).await
}
#[tokio::test]
async fn test_cleanup_cancel_retransmits_beyond_two_seconds() -> crate::Result<()> {
run_cleanup_cancel_retransmission(false).await
}
#[tokio::test]
async fn test_confirmed_dialog_survives_invite_task_completion() -> crate::Result<()> {
let token = CancellationToken::new();
let Uac {
dialog_layer,
option,
peer,
} = setup(&token).await?;
let (state_sender, mut states) = unbounded_channel();
let (dialog, join) = dialog_layer.do_invite_async(option, state_sender)?;
let (inv, uac) = recv_request(&peer, Method::Invite, Duration::from_secs(2)).await;
calling_id(&mut states).await;
let contact = format!("sip:bob@{}", peer.local_addr()?);
let mut ok = response(&inv, 200, "OK", &contact);
ok = ok.replace(&format!(";tag={PEER_TAG}"), "");
peer.send_to(ok.as_bytes(), uac).await?;
let (_, resp) = tokio::time::timeout(Duration::from_secs(2), join)
.await
.expect("join")
.expect("invite task")?;
assert_eq!(resp.map(|r| r.status_code), Some(StatusCode::OK));
assert_no_request(
&peer,
Method::Bye,
Duration::from_millis(600),
"confirmed dialog must survive invite task completion (tag-less 200)",
)
.await;
token.cancel();
Ok(())
}