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
use super::{
    authenticate::Credential,
    dialog::{DialogInner, DialogStateSender},
    dialog_layer::DialogLayer,
    invite_dialog::InviteDialog,
};
use crate::prelude::*;
use crate::sip::{
    prelude::{HeadersExt, ToTypedHeader},
    uri::ParamsExt,
    Request, Response, SipMessage, StatusCodeKind,
};
use crate::{
    dialog::{
        dialog::{Dialog, DialogState, TerminatedReason},
        dialog_layer::DialogLayerInnerRef,
        DialogId,
    },
    transaction::{
        key::{TransactionKey, TransactionRole},
        make_tag,
        transaction::Transaction,
    },
    transport::SipAddr,
    Result,
};
use futures::FutureExt;
use tracing::{debug, info, warn};

/// INVITE Request Options
///
/// `InviteOption` contains all the parameters needed to create and send
/// an INVITE request to establish a SIP session. This structure provides
/// a convenient way to specify all the necessary information for initiating
/// a call or session.
///
/// # Fields
///
/// * `caller` - URI of the calling party (From header)
/// * `callee` - URI of the called party (To header and Request-URI)
/// * `content_type` - MIME type of the message body (default: "application/sdp")
/// * `offer` - Optional message body (typically SDP offer)
/// * `contact` - Contact URI for this user agent
/// * `credential` - Optional authentication credentials
/// * `headers` - Optional additional headers to include
///
/// # Examples
///
/// ## Basic Voice Call
///
/// ```rust,no_run
/// # use rsipstack::dialog::invitation::InviteOption;
/// # fn example() -> rsipstack::Result<()> {
/// # let sdp_offer_bytes = vec![];
/// let invite_option = InviteOption {
///     caller: "sip:alice@example.com".try_into()?,
///     callee: "sip:bob@example.com".try_into()?,
///     content_type: Some("application/sdp".to_string()),
///     offer: Some(sdp_offer_bytes),
///     contact: "sip:alice@192.168.1.100:5060".try_into()?,
///     ..Default::default()
/// };
/// # Ok(())
/// # }
/// ```
///
/// ```rust,no_run
/// # use rsipstack::dialog::dialog_layer::DialogLayer;
/// # use rsipstack::dialog::invitation::InviteOption;
/// # fn example() -> rsipstack::Result<()> {
/// # let dialog_layer: DialogLayer = todo!();
/// # let invite_option: InviteOption = todo!();
/// let request = dialog_layer.make_invite_request(&invite_option)?;
/// println!("Created INVITE to: {}", request.uri);
/// # Ok(())
/// # }
/// ```
///
/// ## Call with Custom Headers
///
/// ```rust,no_run
/// # use rsipstack::dialog::invitation::InviteOption;
/// # fn example() -> rsipstack::Result<()> {
/// # let sdp_bytes = vec![];
/// # let auth_credential = todo!();
/// let custom_headers = vec![
///     rsipstack::sip::Header::UserAgent("MyApp/1.0".into()),
///     rsipstack::sip::Header::Subject("Important Call".into()),
/// ];
///
/// let invite_option = InviteOption {
///     caller: "sip:alice@example.com".try_into()?,
///     callee: "sip:bob@example.com".try_into()?,
///     content_type: Some("application/sdp".to_string()),
///     offer: Some(sdp_bytes),
///     contact: "sip:alice@192.168.1.100:5060".try_into()?,
///     credential: Some(auth_credential),
///     headers: Some(custom_headers),
///     ..Default::default()
/// };
/// # Ok(())
/// # }
/// ```
///
/// ## Call with Authentication
///
/// ```rust,no_run
/// # use rsipstack::dialog::invitation::InviteOption;
/// # use rsipstack::dialog::authenticate::Credential;
/// # fn example() -> rsipstack::Result<()> {
/// # let sdp_bytes = vec![];
/// let credential = Credential {
///     username: "alice".to_string(),
///     password: "secret123".to_string(),
///     realm: Some("example.com".to_string()),
///     auth_username: None,
/// };
///
/// let invite_option = InviteOption {
///     caller: "sip:alice@example.com".try_into()?,
///     callee: "sip:bob@example.com".try_into()?,
///     offer: Some(sdp_bytes),
///     contact: "sip:alice@192.168.1.100:5060".try_into()?,
///     credential: Some(credential),
///     ..Default::default()
/// };
/// # Ok(())
/// # }
/// ```
#[derive(Default, Clone)]
pub struct InviteOption {
    pub caller_display_name: Option<String>,
    pub caller_params: Vec<crate::sip::uri::Param>,
    pub caller: crate::sip::Uri,
    pub callee: crate::sip::Uri,
    pub destination: Option<SipAddr>,
    pub content_type: Option<String>,
    pub offer: Option<Vec<u8>>,
    /// Local Contact. On stream transports its host and port are normally
    /// replaced with the outgoing connection's local address (and the scheme
    /// becomes `sips` over TLS). A Contact that already carries a `transport`
    /// parameter is treated as deliberately built by the caller, for example
    /// from the address a registrar reported behind NAT, and is sent unchanged.
    pub contact: crate::sip::Uri,
    pub credential: Option<Credential>,
    /// Extra headers appended to the INVITE. A `Max-Forwards` or
    /// `Content-Type` here replaces the one the stack would add, so it is
    /// never sent twice; a `Content-Type` here wins over `content_type`.
    pub headers: Option<Vec<crate::sip::Header>>,
    pub support_prack: bool,
    pub call_id: Option<String>,
    /// RFC 7989: local Session-ID UUID for this call (32 hex chars; dashed
    /// RFC 4122 input is normalized). When `None` no Session-ID header is
    /// generated. Reuse the same value on transferred calls (REFER/Replaces)
    /// to keep the session identifiable across dialogs.
    pub session_id: Option<String>,
    /// RFC 3608: preloaded route set for this out-of-dialog request. Each entry
    /// is emitted as a `Route` header, in order, ahead of the caller-supplied
    /// headers. Typically obtained from
    /// [`Registration::preloaded_route_set`](crate::dialog::registration::Registration::preloaded_route_set)
    /// so the request follows the path an IMS S-CSCF advertised at
    /// registration. Empty by default, leaving existing behaviour unchanged.
    pub route_set: Vec<crate::sip::typed::Route>,
}

pub struct DialogGuard {
    pub dialog_layer_inner: DialogLayerInnerRef,
    pub id: DialogId,
}

impl DialogGuard {
    pub fn new(dialog_layer: &Arc<DialogLayer>, id: DialogId) -> Self {
        Self {
            dialog_layer_inner: dialog_layer.inner.clone(),
            id,
        }
    }
}

impl Drop for DialogGuard {
    fn drop(&mut self) {
        let dlg = match self.dialog_layer_inner.dialogs.remove(&self.id.to_string()) {
            Some(dlg) => dlg,
            None => return,
        };
        let _handle = crate::platform::spawn(async move {
            if let Err(e) = dlg.hangup().await {
                info!(id = %dlg.id(), error = %e, "failed to hangup dialog");
            }
        });
    }
}

pub(super) struct DialogGuardForUnconfirmed {
    pub dialog_layer_inner: DialogLayerInnerRef,
    pub id: DialogId,
    invite_tx: Option<Transaction>,
    /// Whether the owning future started processing the INVITE.
    started: bool,
    /// The INVITE's dialog, `None` once `process_invite` returned.
    dialog: Option<InviteDialog>,
}

impl Drop for DialogGuardForUnconfirmed {
    fn drop(&mut self) {
        // Normal completion has handed ownership to the caller, even when
        // the confirmed key equals the early key (a tag-less 2xx).
        if self.dialog.is_none() {
            return;
        }
        let client_dialog = match self.dialog_layer_inner.dialogs.remove(&self.id.to_string()) {
            Some(Dialog::Invite(client_dialog)) => client_dialog,
            Some(_) => return,
            // The application already removed the dialog from the layer
            // (`DialogLayer::remove_dialog`): its INVITE still has to end.
            None => match self.dialog.take() {
                Some(client_dialog) => client_dialog,
                // `process_invite` returned: `do_invite` handles the outcome.
                None => return,
            },
        };

        // A task dropped before its first poll never sent an INVITE.
        if !self.started {
            client_dialog.inner.transition(DialogState::Terminated(
                client_dialog.id(),
                TerminatedReason::UacCancel,
            ));
            return;
        }

        match client_dialog.state() {
            DialogState::Terminated(_, _) => {}
            state @ (DialogState::Calling(_)
            | DialogState::Trying(_)
            | DialogState::Early(_, _)) => {
                // CANCEL cannot be sent before a provisional response (RFC 3261
                // ยง9.1): a Calling dialog ends now, its INVITE is CANCELed once
                // a provisional arrives.
                let calling = matches!(state, DialogState::Calling(_));
                let invite_tx = self.invite_tx.take();
                if calling || invite_tx.is_none() {
                    client_dialog.inner.transition(DialogState::Terminated(
                        client_dialog.id(),
                        TerminatedReason::UacCancel,
                    ));
                }
                let Some(mut invite_tx) = invite_tx else {
                    return;
                };

                debug!(%self.id, "unconfirmed dialog dropped, cancelling it");
                let _handle = crate::platform::spawn(async move {
                    if calling {
                        invite_tx.stop_retransmissions();
                        let window = invite_tx.endpoint_inner.option.t1x64;
                        let first = wait_response(&mut invite_tx, window, false).await;
                        if !first
                            .as_ref()
                            .is_some_and(|r| r.status_code.kind() == StatusCodeKind::Provisional)
                        {
                            drop(invite_tx);
                            bye_if_2xx(&client_dialog, first).await;
                            return;
                        }
                    }
                    let final_window = invite_tx.endpoint_inner.option.t1x64;
                    invite_tx.stop_retransmissions();

                    // CANCEL is a separate transaction. Keep driving it to its
                    // own response or timeout even if the INVITE finishes first.
                    let cancel_dialog = client_dialog.clone();
                    let _handle = crate::platform::spawn(async move {
                        if let Err(e) = cancel_dialog.send_cancel().await {
                            warn!(id = %cancel_dialog.id(), error = %e, "dialog cancel failed");
                        }
                    });
                    if !calling {
                        client_dialog.inner.transition(DialogState::Terminated(
                            client_dialog.id(),
                            TerminatedReason::UacCancel,
                        ));
                        debug!(id = %client_dialog.id(), "dialog terminated");
                    }

                    // The callee may still answer after the CANCEL: keep the
                    // INVITE transaction until its final response (up to
                    // 64*T1) so a 2xx is ACKed, then end that session with a
                    // BYE (RFC 3261 ยง9.1, ยง15).
                    let final_response = wait_response(&mut invite_tx, final_window, true).await;
                    // Closing the command channel terminates the dialog loop.
                    drop(invite_tx);
                    bye_if_2xx(&client_dialog, final_response).await;
                });
            }
            // A completed invite task is NOT an abandoned invite: for
            // `do_invite_async` the background task always ends right after
            // the dialog confirms (the JoinHandle detaches), and the
            // application owns the confirmed dialog from `Confirmed` on.
            // Hanging it up here killed established calls whenever the
            // dialog's registry entry was still reachable under the early
            // (tag-less) key โ€” e.g. a 200 OK without a To tag, whose
            // confirmed key equals the early key. Unconfirmed branches above
            // keep their CANCEL cleanup (those ARE abandonment).
            DialogState::Confirmed(_, _) => {}
            _ => {}
        }
    }
}

/// Wait up to `limit` for the INVITE transaction's first response, or its
/// first final one.
async fn wait_response(
    invite_tx: &mut Transaction,
    limit: core::time::Duration,
    final_only: bool,
) -> Option<Response> {
    let wait = async {
        while let Some(msg) = invite_tx.receive().await {
            if let SipMessage::Response(resp) = msg {
                if !final_only || resp.status_code.kind() != StatusCodeKind::Provisional {
                    return Some(resp);
                }
            }
        }
        None
    };
    crate::platform::timeout(limit, wait).await.ok().flatten()
}

/// End the session a 2xx to an abandoned INVITE established.
pub(super) async fn bye_if_2xx(client_dialog: &InviteDialog, resp: Option<Response>) {
    if let Some(resp) = resp.filter(|r| r.status_code.kind() == StatusCodeKind::Successful) {
        info!(id = %client_dialog.id(), "2xx after CANCEL, sending BYE");
        if let Err(e) = client_dialog.bye_2xx_after_cancel(&resp).await {
            warn!(id = %client_dialog.id(), error = %e, "BYE after CANCEL failed");
        }
    }
}

pub type InviteAsyncResult = Result<(DialogId, Option<Response>)>;

impl DialogLayer {
    /// Create an INVITE request from options
    ///
    /// Constructs a properly formatted SIP INVITE request based on the
    /// provided options. This method handles all the required headers
    /// and parameters according to RFC 3261.
    ///
    /// # Parameters
    ///
    /// * `opt` - INVITE options containing all necessary parameters
    ///
    /// # Returns
    ///
    /// * `Ok(Request)` - Properly formatted INVITE request
    /// * `Err(Error)` - Failed to create request
    ///
    /// # Generated Headers
    ///
    /// The method automatically generates:
    /// * Via header with branch parameter
    /// * From header with tag parameter
    /// * To header (without tag for initial request)
    /// * Contact header
    /// * Content-Type header
    /// * CSeq header with incremented sequence number
    /// * Call-ID header
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use rsipstack::dialog::dialog_layer::DialogLayer;
    /// # use rsipstack::dialog::invitation::InviteOption;
    /// # fn example() -> rsipstack::Result<()> {
    /// # let dialog_layer: DialogLayer = todo!();
    /// # let invite_option: InviteOption = todo!();
    /// let request = dialog_layer.make_invite_request(&invite_option)?;
    /// println!("Created INVITE to: {}", request.uri);
    /// # Ok(())
    /// # }
    /// ```
    pub fn make_invite_request(&self, opt: &InviteOption) -> Result<Request> {
        let last_seq = self.increment_last_seq();
        let to = crate::sip::typed::To {
            display_name: None,
            uri: opt.callee.clone(),
            params: vec![],
        };
        let recipient = to.uri.clone();

        let from = crate::sip::typed::From {
            display_name: opt.caller_display_name.clone(),
            uri: opt.caller.clone(),
            params: opt.caller_params.clone(),
        }
        .with_tag(make_tag());

        let call_id = opt
            .call_id
            .as_ref()
            .map(|id| crate::sip::headers::CallId::from(id.clone()));

        let target_transport = opt
            .destination
            .as_ref()
            .and_then(|d| d.r#type)
            .or_else(|| opt.callee.transport().cloned())
            .filter(|t| *t != crate::sip::Transport::Udp);

        let transport_addr = target_transport.and_then(|transport| {
            // Listeners only (see `DialogInner::via_addr_for_send_transport`):
            // a connection-cache match advertised the remote peer's address as
            // our own Via on initial INVITEs toward WS/WSS targets.
            let listens = self.endpoint.transport_layer.get_listen_addrs();
            listens
                .iter()
                .find(|a| a.r#type == Some(transport))
                .cloned()
                .or_else(|| {
                    let mut addr = listens.first().cloned()?;
                    addr.r#type = Some(transport);
                    Some(addr)
                })
        });

        let via = self.endpoint.get_via(transport_addr.clone(), None)?;
        let mut request = self.endpoint.make_request(
            crate::sip::Method::Invite,
            recipient,
            via,
            from,
            to,
            last_seq,
            call_id,
        );

        // RFC 3608: preload the Service-Route set learned at registration as
        // Route headers, in order, so this out-of-dialog request traverses the
        // proxies the registrar (e.g. an IMS S-CSCF) requires. Plain push, not
        // unique_push, because a route set legitimately has several Route
        // headers.
        for route in &opt.route_set {
            request.headers.push(route.clone().into());
        }

        // A Contact that names its transport was built deliberately by the
        // caller (e.g. with the public address learned from a REGISTER
        // response behind NAT); keep it rather than rewriting it to the local
        // socket address.
        let caller_built_contact = opt
            .contact
            .params
            .iter()
            .any(|p| matches!(p, crate::sip::Param::Transport(_)));
        let contact = if let Some(addr) = transport_addr.as_ref().filter(|_| !caller_built_contact)
        {
            let mut uri = opt.contact.clone();
            uri.host_with_port = addr.addr.clone();
            if !uri
                .params
                .iter()
                .any(|p| matches!(p, crate::sip::Param::Transport(_)))
            {
                uri.params.push(crate::sip::Param::Transport(
                    addr.r#type.unwrap_or(crate::sip::Transport::Tcp),
                ));
            }
            if addr.r#type == Some(crate::sip::Transport::Tls) {
                uri.scheme = Some(crate::sip::Scheme::Sips);
            }
            crate::sip::typed::Contact {
                display_name: None,
                uri,
                params: vec![],
            }
        } else {
            crate::sip::typed::Contact {
                display_name: None,
                uri: opt.contact.clone(),
                params: vec![],
            }
        };

        request
            .headers
            .unique_push(crate::sip::Header::Contact(contact.into()));

        request.headers.unique_push(crate::sip::Header::ContentType(
            opt.content_type
                .clone()
                .unwrap_or("application/sdp".to_string())
                .into(),
        ));

        if opt.support_prack {
            request
                .headers
                .unique_push(crate::sip::Header::Supported("100rel".into()));
        }

        // RFC 7044 ยง6.1: advertise histinfo so peers include History-Info in
        // responses. Plain push โ€” multiple Supported header lines are legal.
        // The request's own headers and the caller-supplied ones (appended
        // below) are both checked to avoid duplicates.
        if self.endpoint.option.history_info_enabled {
            let already = request
                .headers
                .iter()
                .chain(opt.headers.iter().flatten())
                .any(|h| {
                    matches!(h, crate::sip::Header::Supported(s)
                        if s.value().split(',').any(|t| t.trim().eq_ignore_ascii_case("histinfo")))
                });
            if !already {
                request
                    .headers
                    .push(crate::sip::Header::Supported("histinfo".into()));
            }
        }

        // RFC 7989: only include Session-ID when the application opted in;
        // initial requests carry `<local>;remote=<nil>`.
        if let Some(raw) = opt.session_id.as_deref() {
            let uuid = crate::sip::headers::SessionId::normalize(raw)?;
            request
                .headers
                .unique_push(crate::sip::headers::SessionId::from_local(&uuid)?.into());
        }
        // can't override default headers
        if let Some(headers) = opt.headers.as_ref() {
            for header in headers {
                // only override "max-forwards" and "content-type" headers
                // so as not to duplicate them; this is important because
                // some clients consider messages with duplicate single-valued
                // headers as malformed and may silently ignore invites
                match header {
                    crate::sip::Header::MaxForwards(_) | crate::sip::Header::ContentType(_) => {
                        request.headers.unique_push(header.clone())
                    }
                    _ => request.headers.push(header.clone()),
                }
            }
        }
        Ok(request)
    }

    /// Send an INVITE request and create a client dialog
    ///
    /// This is the main method for initiating outbound calls. It creates
    /// an INVITE request, sends it, and manages the resulting dialog.
    /// The method handles the complete INVITE transaction including
    /// authentication challenges and response processing.
    ///
    /// # Parameters
    ///
    /// * `opt` - INVITE options containing all call parameters
    /// * `state_sender` - Channel for receiving dialog state updates
    ///
    /// # Returns
    ///
    /// * `Ok((InviteDialog, Option<Response>))` - Created dialog and final response
    /// * `Err(Error)` - Failed to send INVITE or process responses
    ///
    /// # Call Flow
    ///
    /// 1. Creates INVITE request from options
    /// 2. Creates client dialog and transaction
    /// 3. Sends INVITE request
    /// 4. Processes responses (1xx, 2xx, 3xx-6xx)
    /// 5. Handles authentication challenges if needed
    /// 6. Returns established dialog and final response
    ///
    /// # Examples
    ///
    /// ## Basic Call Setup
    ///
    /// ```rust,no_run
    /// # use rsipstack::dialog::dialog_layer::DialogLayer;
    /// # use rsipstack::dialog::invitation::InviteOption;
    /// # async fn example() -> rsipstack::Result<()> {
    /// # let dialog_layer: DialogLayer = todo!();
    /// # let invite_option: InviteOption = todo!();
    /// # let state_sender = todo!();
    /// let (dialog, response) = dialog_layer.do_invite(invite_option, state_sender).await?;
    ///
    /// if let Some(resp) = response {
    ///     match resp.status_code {
    ///         rsipstack::sip::StatusCode::OK => {
    ///             println!("Call answered!");
    ///             // Process SDP answer in resp.body
    ///         },
    ///         rsipstack::sip::StatusCode::BusyHere => {
    ///             println!("Called party is busy");
    ///         },
    ///         _ => {
    ///             println!("Call failed: {}", resp.status_code);
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Monitoring Dialog State
    ///
    /// ```rust,no_run
    /// # use rsipstack::dialog::dialog_layer::DialogLayer;
    /// # use rsipstack::dialog::invitation::InviteOption;
    /// # use rsipstack::dialog::dialog::DialogState;
    /// # async fn example() -> rsipstack::Result<()> {
    /// # let dialog_layer: DialogLayer = todo!();
    /// # let invite_option: InviteOption = todo!();
    /// let (state_tx, mut state_rx) = tokio::sync::mpsc::unbounded_channel();
    /// let (dialog, response) = dialog_layer.do_invite(invite_option, state_tx).await?;
    ///
    /// // Monitor dialog state changes
    /// tokio::spawn(async move {
    ///     while let Some(state) = state_rx.recv().await {
    ///         match state {
    ///             DialogState::Early(_, resp) => {
    ///                 println!("Ringing: {}", resp.status_code);
    ///             },
    ///             DialogState::Confirmed(_,_) => {
    ///                 println!("Call established");
    ///             },
    ///             DialogState::Terminated(_, code) => {
    ///                 println!("Call ended: {:?}", code);
    ///                 break;
    ///             },
    ///             _ => {}
    ///         }
    ///     }
    /// });
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Error Handling
    ///
    /// The method can fail for various reasons:
    /// * Network connectivity issues
    /// * Authentication failures
    /// * Invalid SIP URIs or headers
    /// * Transaction timeouts
    /// * Protocol violations
    ///
    /// # Important: Cleanup Required
    ///
    /// When a 2xx response is received, the confirmed dialog is registered in
    /// the internal dialog registry (not when [`InviteDialog::cancel`] was
    /// called: that 2xx is ended with a BYE). **The caller is responsible for removing it**
    /// after the dialog terminates by calling [`DialogLayer::remove_dialog`]
    /// with the dialog's [`DialogId`].
    ///
    /// The recommended pattern is to listen for
    /// [`DialogState::Terminated`](crate::dialog::dialog::DialogState::Terminated)
    /// on the `state_sender` channel and call `remove_dialog` when received.
    /// See the "Monitoring Dialog State" example above.
    ///
    /// Failure to call `remove_dialog` will cause the dialog to remain in the
    /// registry indefinitely, resulting in a memory leak.
    ///
    /// # Authentication
    ///
    /// If credentials are provided in the options, the method will
    /// automatically handle 401/407 authentication challenges by
    /// resending the request with proper authentication headers.
    pub async fn do_invite(
        &self,
        opt: InviteOption,
        state_sender: DialogStateSender,
    ) -> Result<(InviteDialog, Option<Response>)> {
        let (dialog, tx) = self.create_client_invite_dialog(opt, state_sender)?;
        let id = dialog.id();

        self.inner
            .dialogs
            .insert(id.to_string(), Dialog::Invite(dialog.clone()));

        let mut guard = DialogGuardForUnconfirmed {
            dialog_layer_inner: self.inner.clone(),
            id: id.clone(),
            invite_tx: Some(tx),
            started: true,
            dialog: Some(dialog.clone()),
        };

        let tx = guard
            .invite_tx
            .as_mut()
            .expect("transcation should be avaible");

        let r = dialog
            .process_invite_with_registration(tx, |new_id| {
                self.inner.dialogs.with_mut(|dialogs| {
                    dialogs.remove(&id.to_string());
                    dialogs.insert(new_id.to_string(), Dialog::Invite(dialog.clone()));
                });
            })
            .boxed()
            .await;
        guard.dialog = None;
        if !dialog.inner.is_confirmed() {
            self.inner.dialogs.remove(&id.to_string());
        }

        match r {
            Ok((new_dialog_id, resp)) => {
                match resp {
                    Some(ref r)
                        if r.status_code.kind() == crate::sip::StatusCodeKind::Successful =>
                    {
                        // Registration happened before ACK, and must not be
                        // repeated after a concurrent BYE/remove_dialog.
                        // RFC 6026 ยง7.2: the client transaction is in Accepted
                        // with Timer M (64*T1) armed. Keep receiving until it
                        // ends so retransmitted 2xx keep being re-ACKed and
                        // forked 2xx are observed; abandoning the transaction
                        // here would leave it (and its timers) in the
                        // endpoint's table and silently stop the re-ACKs.
                        if let Some(mut tx) = guard.invite_tx.take() {
                            let dlg = dialog.clone();
                            let confirmed_tag = new_dialog_id.remote_tag.clone();
                            crate::platform::spawn(async move {
                                let mut seen_forks: Vec<String> = Vec::new();
                                while let Some(msg) = tx.receive().await {
                                    dlg.end_forked_branch(&msg, &confirmed_tag, &mut seen_forks)
                                        .await;
                                }
                                debug!(id = %new_dialog_id, "accepted transaction drained (Timer M expired)");
                            });
                        }
                    }
                    _ => {}
                }
                Ok((dialog, resp))
            }
            Err(e) => Err(e),
        }
    }

    /// Asynchronously executes an INVITE transaction in the background.
    ///
    /// Registers the dialog under an early dialog ID while the INVITE is in progress.
    /// On a 2xx response, the early entry is replaced by the confirmed dialog
    /// ID before sending ACK, so incoming requests can be handled immediately.
    /// Returns a JoinHandle resolving to the final dialog ID and response.
    ///
    /// # Important: Cleanup Required
    ///
    /// On a successful (2xx) response the confirmed dialog is registered in
    /// the internal dialog registry (not when [`InviteDialog::cancel`] was
    /// called: that 2xx is ended with a BYE). **The caller must remove it** after the
    /// dialog terminates by calling [`DialogLayer::remove_dialog`] with the
    /// confirmed dialog's [`DialogId`].
    ///
    /// Listen for
    /// [`DialogState::Terminated`](crate::dialog::dialog::DialogState::Terminated)
    /// on the `state_sender` channel and call `remove_dialog` when received.
    /// Failure to do so will keep the dialog in the registry and cause a
    /// memory leak.
    pub fn do_invite_async(
        self: &Arc<Self>,
        opt: InviteOption,
        state_sender: DialogStateSender,
    ) -> Result<(InviteDialog, crate::platform::JoinHandle<InviteAsyncResult>)> {
        let (dialog, tx) = self.create_client_invite_dialog(opt, state_sender)?;
        let id0 = dialog.id();

        // 1) register early key (so in-dialog requests can be matched)
        self.inner
            .dialogs
            .insert(id0.to_string(), Dialog::Invite(dialog.clone()));

        let inner = self.inner.clone();
        let dialog_clone = dialog.clone();

        // Own the guard before spawning so an abort before the first poll
        // also removes the early registry entry.
        let mut guard = DialogGuardForUnconfirmed {
            dialog_layer_inner: inner.clone(),
            id: id0.clone(),
            invite_tx: Some(tx),
            started: false,
            dialog: Some(dialog_clone.clone()),
        };

        // 2) run invite in background, keep registry updated like do_invite()
        let handle = crate::platform::spawn_with_result(async move {
            guard.started = true;
            let invite_tx = guard
                .invite_tx
                .as_mut()
                .expect("transaction should be available");
            let r = dialog_clone
                .process_invite_with_registration(invite_tx, |new_id| {
                    inner.dialogs.with_mut(|dialogs| {
                        dialogs.remove(&id0.to_string());
                        dialogs.insert(new_id.to_string(), Dialog::Invite(dialog_clone.clone()));
                    });
                })
                .boxed()
                .await;
            guard.dialog = None;
            let mut tx = guard
                .invite_tx
                .take()
                .expect("transaction should be available");

            if !dialog_clone.inner.is_confirmed() {
                inner.dialogs.remove(&id0.to_string());
            }

            match &r {
                Ok((new_id, resp_opt)) => {
                    let is_2xx = resp_opt
                        .as_ref()
                        .map(|resp| {
                            resp.status_code.kind() == crate::sip::StatusCodeKind::Successful
                        })
                        .unwrap_or(false);

                    if is_2xx {
                        // The full key was registered before ACK. Do not
                        // resurrect a dialog the application already removed.
                        // RFC 6026 ยง7.2: keep draining the Accepted transaction
                        // until Timer M ends it (re-ACKs retransmitted 2xx,
                        // observes forked 2xx, and detaches it from the
                        // endpoint's table). See do_invite for the rationale.
                        let confirmed_id = new_id.clone();
                        let confirmed_tag = new_id.remote_tag.clone();
                        let forked_dlg = dialog_clone.clone();
                        crate::platform::spawn(async move {
                            let mut seen_forks: Vec<String> = Vec::new();
                            while let Some(msg) = tx.receive().await {
                                forked_dlg
                                    .end_forked_branch(&msg, &confirmed_tag, &mut seen_forks)
                                    .await;
                            }
                            debug!(id = %confirmed_id, "accepted transaction drained (Timer M expired)");
                        });
                    }
                }
                Err(e) => debug!(%id0, error = %e, "async invite failed"),
            }

            r
        });

        Ok((dialog, handle))
    }

    pub fn create_client_invite_dialog(
        &self,
        opt: InviteOption,
        state_sender: DialogStateSender,
    ) -> Result<(InviteDialog, Transaction)> {
        let mut request = self.make_invite_request(&opt)?;
        request.body = opt.offer.unwrap_or_default();
        request
            .headers
            .unique_push(crate::sip::Header::ContentLength(
                (request.body.len() as u32).into(),
            ));
        let key = TransactionKey::from_request(&request, TransactionRole::Client)?;
        let mut tx = Transaction::new_client(key, request.clone(), self.endpoint.clone(), None);

        if opt.destination.is_some() {
            tx.destination = opt.destination;
        } else {
            if let Some(route) = tx.original.route_header() {
                if let Ok(first_route) = route.typed() {
                    tx.destination = SipAddr::try_from(&first_route.uri).ok();
                }
            }
        }

        let id = DialogId::try_from(&tx)?;

        let local_contact = request
            .contact_header()
            .ok()
            .and_then(|c| c.typed().ok().map(|ct| ct.uri))
            .or(Some(opt.contact));

        let dlg_inner = DialogInner::new(
            TransactionRole::Client,
            id.clone(),
            request.clone(),
            self.endpoint.clone(),
            state_sender,
            opt.credential,
            local_contact,
            tx.tu_sender.clone(),
        )?;

        if let Some(destination) = &tx.destination {
            let uri = destination.clone().into();
            *dlg_inner.remote_uri.lock() = uri;
        }
        let dialog = InviteDialog::from_inner(Arc::new(dlg_inner));
        dialog.inner.reserve_invite(&tx)?;
        Ok((dialog, tx))
    }
}