rsipstack 0.8.1

SIP Stack Rust library for building SIP applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! A 2xx that answers the INVITE after we sent CANCEL (the callee picked up
//! while the CANCEL was in flight) establishes a dialog at the far end. The
//! CANCEL has no effect on it, so the UAC must ACK the 2xx and then end the
//! session with a BYE (RFC 3261 §9.1, §15; RFC 5407 §3.1.2).
//!
//! These tests drop the `do_invite` future after a 180 — the documented way to
//! abandon an outgoing call, which cancels it — and answer the INVITE with a
//! 200 from a raw UDP peer in each wire ordering. The `removed` variants call
//! `DialogLayer::remove_dialog` before dropping the future: the INVITE still
//! has to end (CANCEL, and ACK + BYE for a 2xx) even though the layer entry is
//! already gone.
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";

/// Receive the next request with `method` on the raw peer socket within
/// `wait`, skipping anything else.
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);
            }
        }
    }
}

/// Fail if the peer receives a BYE within `wait`.
async fn assert_no_bye(socket: &UdpSocket, wait: Duration, what: &str) {
    assert_no_request(socket, Method::Bye, wait, what).await
}

/// Fail if the peer receives a `method` request within `wait`.
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}");
        }
    }
}

/// Build a response to `req` as the peer UA, adding the peer's To tag.
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}"))
}

/// The ACK and the BYE must belong to the dialog the 2xx established:
/// same Call-ID, our From tag, and the peer's To tag.
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 {
    /// 200 to the INVITE, then 200 to the CANCEL.
    InviteOkFirst,
    /// 200 to the CANCEL, then 200 to the INVITE right away.
    CancelOkFirst,
    /// 200 to the CANCEL, then 200 to the INVITE after the 2 s settle window.
    InviteOkLate,
}

/// The id the `Calling` state reports, the one the dialog is registered under.
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 {
        // The application removes the dialog from the layer first.
        dialog_layer.remove_dialog(&id);
        assert!(dialog_layer.is_empty());
    }
    // The application abandons the call: dropping the `do_invite` future
    // cancels the INVITE.
    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;
            // The dialog reports Terminated(UacCancel) once the 2 s settle
            // window passes without a final response.
            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;

    // A retransmitted 2xx is ACKed again but starts no second BYE.
    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;

    // The abandoned call reports Terminated(UacCancel) once and is never
    // reported as Confirmed.
    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
}

/// The same when the application removed the dialog from the layer before
/// dropping the `do_invite` future, in Early (180) and in Trying (100).
#[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
}

/// The same in the other wire ordering (the 200 to the CANCEL arrives before
/// the 2xx) with the dialog already removed from the layer.
#[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
}

/// A CANCEL that wins the race (487 to the INVITE) ends the call as before:
/// the 487 is ACKed and no BYE is sent — also when the application removed
/// the dialog from the layer before dropping the `do_invite` future.
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 {
        // The application removes the dialog from the layer first.
        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;

    // Exactly one Terminated(UacCancel), never Confirmed.
    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
}

/// The same when the application removed the dialog from the layer before
/// dropping the `do_invite` future, in Early (180) and in Trying (100).
#[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
}

/// Aborting a `do_invite_async` task abandons the call like dropping the
/// `do_invite` future. Aborted in Calling, the first response gets a CANCEL
/// (180) or an ACK and a BYE (200); aborted in Early, the CANCEL goes out at
/// once. Nothing stays registered in the layer.
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
}

/// Dropped before any response: Terminated(UacCancel) is reported at once and
/// nothing is sent while no provisional has arrived (RFC 3261 §9.1). The first
/// response then gets a CANCEL (180), or an ACK and a BYE (200).
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 {
        // The application removes the dialog from the layer first.
        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)
    ));
    // Over twice T1: not even an INVITE retransmission.
    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
}

/// `cancel()` on a `do_invite_async` call, in Calling (no response yet) or
/// in Early (after the 180). In Calling the CANCEL is deferred to the first
/// provisional (RFC 3261 §9.1). `first` is the peer's first response (100,
/// 180, 200 or 486); after a provisional the peer answers the CANCEL and
/// ends the INVITE with `last` (487, or a 200 that crosses the CANCEL).
async fn run_cancel_called(in_calling: bool, first: u16, last: u16) -> crate::Result<()> {
    run_cancel_called_via(false, in_calling, first, last).await
}

/// The same, with `legacy` driving the INVITE through the legacy
/// `ClientInviteDialog::process_invite` instead of `do_invite_async`.
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;
        // In Early cancel() waits for the CANCEL's response.
        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 {
            // The callee answered while the CANCEL was in flight.
            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;
    }
    // Nothing left to cancel after a final response.
    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
}

/// The same `cancel()` in Early: a 2xx that crosses the CANCEL is ACKed and
/// BYE'd, as for a dropped `do_invite` future.
#[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
}

/// The legacy `ClientInviteDialog::process_invite` sends the deferred
/// CANCEL and BYEs the 2xx alike.
#[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
}

/// A reliable 183 (RFC 3262) after `cancel()` in Calling: the CANCEL is not
/// held back until the PRACK, which the peer never answers, completes.
#[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?;
    // The PRACK goes out and is never answered; the CANCEL arrives well
    // before the PRACK's own timeout (64*T1).
    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(())
}

/// `cancel()` in Calling and no response at all: nothing but INVITE
/// retransmissions is sent, and Timer B ends the INVITE (408).
#[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)?;
    // No yield between spawn and abort: the INVITE future has not run.
    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(())
}

// Exercise both ways the old cleanup cut CANCEL short: an INVITE final
// response, and its unrelated two-second deadline.
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;
    }
    // Withhold the CANCEL response, then require a retransmission after
    // two seconds (discard earlier retries rather than counting queued data).
    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;
    }
    // A received final response must stop further CANCEL retransmissions.
    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
}

/// A `do_invite_async` task that completes normally (200 OK confirmed, no
/// cancellation) must not terminate the dialog when the task ends and its
/// guard drops: the background task ending is the API's designed lifecycle
/// (the JoinHandle detaches), not an abandoned invite — the application owns
/// the confirmed dialog from `Confirmed` on.
///
/// Regression: the guard's drop took the dialog out of the registry when the
/// early (tagless) key was still reachable and hung confirmed calls up with a
/// Reason-less BYE microseconds after the 200 OK.
#[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;

    // Drive the dialog straight to 200 OK (no provisional response). The
    // response deliberately carries NO To tag — a malformed but seen-in-the-
    // wild 2xx (RFC 3261 §13.2.2.4 requires one): the dialog must still be
    // confirmed, registered, and — crucially — not killed by the completed
    // task's guard.
    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?;

    // The invite task must finish confirmed — this is where its guard drops.
    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));

    // No BYE may arrive: the completed task must not kill the dialog.
    assert_no_request(
        &peer,
        Method::Bye,
        Duration::from_millis(600),
        "confirmed dialog must survive invite task completion (tag-less 200)",
    )
    .await;
    token.cancel();
    Ok(())
}