rsipstack 0.5.7

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
use super::{
    authenticate::Credential,
    client_dialog::ClientInviteDialog,
    dialog::{DialogInner, DialogStateSender},
    dialog_layer::DialogLayer,
};
use crate::sip::{
    prelude::{HeadersExt, ToTypedHeader},
    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 std::sync::Arc;
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()),
/// };
///
/// 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>>,
    pub contact: crate::sip::Uri,
    pub credential: Option<Credential>,
    pub headers: Option<Vec<crate::sip::Header>>,
    pub support_prack: bool,
    pub call_id: Option<String>,
}

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 = tokio::spawn(async move {
            if let Err(e) = dlg.hangup().await {
                info!(id = %dlg.id(), error = %e, "failed to hangup dialog");
            }
        });
    }
}

pub(super) struct DialogGuardForUnconfirmed<'a> {
    pub dialog_layer_inner: &'a DialogLayerInnerRef,
    pub id: &'a DialogId,
    invite_tx: Option<Transaction>,
}

impl<'a> Drop for DialogGuardForUnconfirmed<'a> {
    fn drop(&mut self) {
        // If the dialog is still unconfirmed, we should try to cancel it
        if let Some((_, dlg)) = self.dialog_layer_inner.dialogs.remove(&self.id.to_string()) {
            debug!(%self.id, "unconfirmed dialog dropped, cancelling it");
            let invite_tx = self.invite_tx.take();
            let _handle = tokio::spawn(async move {
                if let Dialog::ClientInvite(ref client_dialog) = dlg {
                    if client_dialog.inner.can_cancel() {
                        if let Err(e) = client_dialog.cancel().await {
                            warn!(id = %client_dialog.id(), error = %e, "dialog cancel failed");
                            return;
                        }

                        if let Some(mut invite_tx) = invite_tx {
                            let duration = tokio::time::Duration::from_secs(2);
                            let timeout = tokio::time::sleep(duration);
                            tokio::pin!(timeout);
                            loop {
                                tokio::select! {
                                    _ = &mut timeout => break,
                                    msg = invite_tx.receive() => {
                                        if let Some(msg) = msg{
                                            if let SipMessage::Response(resp) = msg {
                                                if resp.status_code.kind() != StatusCodeKind::Provisional {
                                                    debug!(
                                                        id = %client_dialog.id(),
                                                        status = %resp.status_code,
                                                        "received final response"
                                                    );
                                                    break;
                                                }
                                            }
                                        }else{
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        let _ = client_dialog.inner.transition(DialogState::Terminated(
                            client_dialog.id(),
                            TerminatedReason::UacCancel,
                        ));
                        debug!(id = %client_dialog.id(), "dialog terminated");
                        return;
                    }
                }

                if let Err(e) = dlg.hangup().await {
                    info!(id = %dlg.id(), error = %e, "failed to hangup unconfirmed dialog");
                }
            });
        }
    }
}

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 via = self.endpoint.get_via(None, None)?;
        let mut request = self.endpoint.make_request(
            crate::sip::Method::Invite,
            recipient,
            via,
            from,
            to,
            last_seq,
            call_id,
        );

        let contact = 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()));
        }
        // can't override default headers
        if let Some(headers) = opt.headers.as_ref() {
            for header in headers {
                // only override if it is a "max-forwards" header
                // so as not to duplicate it; this is important because
                // some clients consider messages with duplicate "max-forwards"
                // headers as malformed and may silently ignore invites
                match header {
                    crate::sip::Header::MaxForwards(_) => {
                        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((ClientInviteDialog, 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
    ///
    /// # 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<(ClientInviteDialog, 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::ClientInvite(dialog.clone()));

        debug!(%id, "client invite dialog created");
        let mut guard = DialogGuardForUnconfirmed {
            dialog_layer_inner: &self.inner,
            id: &id,
            invite_tx: Some(tx),
        };

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

        let r = dialog.process_invite(tx).boxed().await;
        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 =>
                    {
                        debug!(
                            "client invite dialog confirmed: {} => {}",
                            id, new_dialog_id
                        );
                        self.inner.dialogs.insert(
                            new_dialog_id.to_string(),
                            Dialog::ClientInvite(dialog.clone()),
                        );
                    }
                    _ => {}
                }
                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.
    /// Once completed, the early entry is removed and, on 2xx response,
    /// the dialog is re-registered under the confirmed dialog ID.
    /// Returns a JoinHandle resolving to the final dialog ID and response.
    pub fn do_invite_async(
        self: &Arc<Self>,
        opt: InviteOption,
        state_sender: DialogStateSender,
    ) -> Result<(
        ClientInviteDialog,
        tokio::task::JoinHandle<InviteAsyncResult>,
    )> {
        let (dialog, mut 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::ClientInvite(dialog.clone()));

        debug!(%id0, "client invite dialog created (async)");

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

        // 2) run invite in background, keep registry updated like do_invite()
        let handle = tokio::spawn(async move {
            let r = dialog_clone.process_invite(&mut tx).boxed().await;

            // remove early key
            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 {
                        debug!("client invite dialog confirmed: {} => {}", id0, new_id);
                        inner.dialogs.insert(
                            new_id.to_string(),
                            Dialog::ClientInvite(dialog_clone.clone()),
                        );
                    }
                }
                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<(ClientInviteDialog, 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 dlg_inner = DialogInner::new(
            TransactionRole::Client,
            id.clone(),
            request.clone(),
            self.endpoint.clone(),
            state_sender,
            opt.credential,
            Some(opt.contact),
            tx.tu_sender.clone(),
        )?;

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