Skip to main content

rsipstack/dialog/
dialog_layer.rs

1use super::authenticate::Credential;
2use super::dialog::{DialogSnapshot, DialogStateSender};
3use super::publication::{ClientPublicationDialog, ServerPublicationDialog};
4use super::subscription::{ClientSubscriptionDialog, ServerSubscriptionDialog};
5use super::{dialog::Dialog, invite_dialog::InviteDialog, DialogId};
6use crate::prelude::*;
7
8use crate::dialog::dialog::{DialogInner, DialogStateReceiver};
9use crate::platform::sync::RwMap;
10use crate::sip::prelude::HeadersExt;
11use crate::transaction::key::TransactionRole;
12use crate::transaction::make_tag;
13use crate::transaction::transaction::transaction_event_sender_noop;
14use crate::transaction::{endpoint::EndpointInnerRef, transaction::Transaction};
15use crate::Result;
16use core::sync::atomic::{AtomicU32, Ordering};
17use tracing::debug;
18
19/// Internal Dialog Layer State
20///
21/// `DialogLayerInner` contains the core state for managing multiple SIP dialogs.
22/// It maintains a registry of active dialogs and tracks sequence numbers for
23/// dialog creation.
24///
25/// # Fields
26///
27/// * `last_seq` - Atomic counter for generating unique sequence numbers
28/// * `dialogs` - Thread-safe map of active dialogs indexed by DialogId
29///
30/// # Thread Safety
31///
32/// This structure is designed to be shared across multiple threads safely:
33/// * `last_seq` uses atomic operations for lock-free increments
34/// * `dialogs` uses RwLock for concurrent read access with exclusive writes
35pub struct DialogLayerInner {
36    pub(super) last_seq: AtomicU32,
37    pub(super) dialogs: RwMap<String, Dialog>,
38}
39pub type DialogLayerInnerRef = Arc<DialogLayerInner>;
40
41/// SIP Dialog Layer
42///
43/// `DialogLayer` provides high-level dialog management functionality for SIP
44/// applications. It handles dialog creation, lookup, and lifecycle management
45/// while coordinating with the transaction layer.
46///
47/// # Key Responsibilities
48///
49/// * Creating and managing SIP dialogs
50/// * Dialog identification and routing
51/// * Dialog state tracking and cleanup
52/// * Integration with transaction layer
53/// * Sequence number management
54///
55/// # Usage Patterns
56///
57/// ## Server-side Dialog Creation
58///
59/// ```rust,no_run
60/// use rsipstack::dialog::dialog_layer::DialogLayer;
61/// use rsipstack::transaction::endpoint::EndpointInner;
62/// use std::sync::Arc;
63/// # fn example() -> rsipstack::Result<()> {
64/// # let endpoint: Arc<EndpointInner> = todo!();
65/// # let transaction = todo!();
66/// # let state_sender = todo!();
67/// # let credential = None;
68/// # let contact_uri = None;
69/// // Create dialog layer
70/// let dialog_layer = DialogLayer::new(endpoint.clone());
71///
72/// // Handle incoming INVITE transaction
73/// let server_dialog = dialog_layer.get_or_create_server_invite(
74///     &transaction,
75///     state_sender,
76///     credential,
77///     contact_uri
78/// )?;
79///
80/// // Accept the call
81/// server_dialog.accept(None, None)?;
82/// # Ok(())
83/// # }
84/// ```
85///
86/// ## Dialog Lookup and Routing
87///
88/// ```rust,no_run
89/// # use rsipstack::dialog::dialog_layer::DialogLayer;
90/// # async fn example() -> rsipstack::Result<()> {
91/// # let dialog_layer: DialogLayer = todo!();
92/// # let request = todo!();
93/// # let mut transaction = todo!();
94/// // Find existing dialog for incoming request
95/// if let Some(mut dialog) = dialog_layer.match_dialog(&transaction) {
96///     // Route to existing dialog
97///     dialog.handle(&mut transaction).await?;
98/// } else {
99///     // Create new dialog or reject
100/// }
101/// # Ok(())
102/// # }
103/// ```
104///
105/// ## Dialog Cleanup
106///
107/// ```rust,no_run
108/// # use rsipstack::dialog::dialog_layer::DialogLayer;
109/// # fn example() {
110/// # let dialog_layer: DialogLayer = todo!();
111/// # let dialog_id = todo!();
112/// // Remove completed dialog
113/// dialog_layer.remove_dialog(&dialog_id);
114/// # }
115/// ```
116///
117/// # Dialog Lifecycle
118///
119/// 1. **Creation** - Dialog created from incoming INVITE or outgoing request
120/// 2. **Early State** - Dialog exists but not yet confirmed
121/// 3. **Confirmed** - Dialog established with 2xx response and ACK
122/// 4. **Active** - Dialog can exchange in-dialog requests
123/// 5. **Terminated** - Dialog ended with BYE or error
124/// 6. **Cleanup** - Dialog removed from layer
125///
126/// # Thread Safety
127///
128/// DialogLayer is thread-safe and can be shared across multiple tasks:
129/// * Dialog lookup operations are concurrent
130/// * Dialog creation is serialized when needed
131/// * Automatic cleanup prevents memory leaks
132pub struct DialogLayer {
133    pub endpoint: EndpointInnerRef,
134    pub inner: DialogLayerInnerRef,
135}
136
137impl DialogLayer {
138    pub fn new(endpoint: EndpointInnerRef) -> Self {
139        Self {
140            endpoint,
141            inner: Arc::new(DialogLayerInner {
142                last_seq: AtomicU32::new(0),
143                dialogs: RwMap::new(),
144            }),
145        }
146    }
147
148    pub fn get_or_create_server_invite(
149        &self,
150        tx: &Transaction,
151        state_sender: DialogStateSender,
152        credential: Option<Credential>,
153        local_contact: Option<crate::sip::Uri>,
154    ) -> Result<InviteDialog> {
155        let mut id = DialogId::try_from(tx)?;
156        if !id.local_tag.is_empty() {
157            let dlg = self.inner.dialogs.get(&id.to_string());
158            match dlg {
159                Some(Dialog::Invite(dlg)) => return Ok(dlg),
160                _ => {
161                    return Err(crate::Error::DialogError(
162                        "the dialog not found".to_string(),
163                        id,
164                        crate::sip::StatusCode::CallTransactionDoesNotExist,
165                    ));
166                }
167            }
168        }
169        id.local_tag = make_tag().to_string(); // generate to tag
170
171        let mut local_contact = local_contact;
172        if local_contact.is_none() {
173            local_contact = self
174                .build_local_contact(credential.as_ref().map(|cred| cred.username.clone()), None)
175                .ok();
176        }
177
178        let dlg_inner = DialogInner::new(
179            TransactionRole::Server,
180            id.clone(),
181            tx.original.clone(),
182            self.endpoint.clone(),
183            state_sender,
184            credential,
185            local_contact,
186            tx.tu_sender.clone(),
187        )?;
188
189        *dlg_inner.remote_contact.lock() = tx.original.contact_header().ok().cloned();
190
191        if let Some(conn) = &tx.connection {
192            let transport = conn.transport();
193            if !matches!(transport, crate::sip::Transport::Udp) {
194                let mut remote_uri = dlg_inner.remote_uri.lock();
195                if !remote_uri
196                    .params
197                    .iter()
198                    .any(|p| matches!(p, crate::sip::Param::Transport(_)))
199                {
200                    remote_uri
201                        .params
202                        .push(crate::sip::Param::Transport(transport));
203                }
204            }
205        }
206
207        let dialog = InviteDialog::from_inner(Arc::new(dlg_inner));
208        dialog.inner.set_server_connection(tx.connection.clone());
209        self.inner
210            .dialogs
211            .insert(id.to_string(), Dialog::Invite(dialog.clone()));
212        debug!(%id, "server invite dialog created");
213        Ok(dialog)
214    }
215
216    pub fn get_or_create_server_subscription(
217        &self,
218        tx: &Transaction,
219        state_sender: DialogStateSender,
220        credential: Option<Credential>,
221        local_contact: Option<crate::sip::Uri>,
222    ) -> Result<ServerSubscriptionDialog> {
223        let mut id = DialogId::try_from(tx)?;
224        if !id.local_tag.is_empty() {
225            let dlg = self.inner.dialogs.get(&id.to_string());
226            match dlg {
227                Some(Dialog::ServerSubscription(dlg)) => return Ok(dlg),
228                _ => {
229                    return Err(crate::Error::DialogError(
230                        "the dialog not found".to_string(),
231                        id,
232                        crate::sip::StatusCode::CallTransactionDoesNotExist,
233                    ));
234                }
235            }
236        }
237        id.local_tag = make_tag().to_string(); // generate to tag
238
239        let mut local_contact = local_contact;
240        if local_contact.is_none() {
241            local_contact = self
242                .build_local_contact(credential.as_ref().map(|cred| cred.username.clone()), None)
243                .ok();
244        }
245
246        let dlg_inner = DialogInner::new(
247            TransactionRole::Server,
248            id.clone(),
249            tx.original.clone(),
250            self.endpoint.clone(),
251            state_sender,
252            credential,
253            local_contact,
254            tx.tu_sender.clone(),
255        )?;
256
257        *dlg_inner.remote_contact.lock() = tx.original.contact_header().ok().cloned();
258        dlg_inner.set_server_connection(tx.connection.clone());
259
260        let dialog = ServerSubscriptionDialog {
261            inner: Arc::new(dlg_inner),
262        };
263        self.inner
264            .dialogs
265            .insert(id.to_string(), Dialog::ServerSubscription(dialog.clone()));
266        debug!(%id, "server subscription dialog created");
267        Ok(dialog)
268    }
269
270    pub fn get_or_create_server_publication(
271        &self,
272        tx: &Transaction,
273        state_sender: DialogStateSender,
274        credential: Option<Credential>,
275        local_contact: Option<crate::sip::Uri>,
276    ) -> Result<ServerPublicationDialog> {
277        let mut id = DialogId::try_from(tx)?;
278        if !id.local_tag.is_empty() {
279            let dlg = self.inner.dialogs.get(&id.to_string());
280            match dlg {
281                Some(Dialog::ServerPublication(dlg)) => return Ok(dlg),
282                _ => {
283                    return Err(crate::Error::DialogError(
284                        "the dialog not found".to_string(),
285                        id,
286                        crate::sip::StatusCode::CallTransactionDoesNotExist,
287                    ));
288                }
289            }
290        }
291        id.local_tag = make_tag().to_string(); // generate to tag
292
293        let mut local_contact = local_contact;
294        if local_contact.is_none() {
295            local_contact = self
296                .build_local_contact(credential.as_ref().map(|cred| cred.username.clone()), None)
297                .ok();
298        }
299
300        let dlg_inner = DialogInner::new(
301            TransactionRole::Server,
302            id.clone(),
303            tx.original.clone(),
304            self.endpoint.clone(),
305            state_sender,
306            credential,
307            local_contact,
308            tx.tu_sender.clone(),
309        )?;
310
311        *dlg_inner.remote_contact.lock() = tx.original.contact_header().ok().cloned();
312        dlg_inner.set_server_connection(tx.connection.clone());
313
314        let dialog = ServerPublicationDialog::new(Arc::new(dlg_inner));
315        self.inner
316            .dialogs
317            .insert(id.to_string(), Dialog::ServerPublication(dialog.clone()));
318        debug!(%id, "server publication dialog created");
319        Ok(dialog)
320    }
321
322    pub fn get_or_create_client_publication(
323        &self,
324        call_id: String,
325        from_tag: String,
326        to_tag: String,
327        initial_request: crate::sip::Request,
328        state_sender: DialogStateSender,
329        credential: Option<Credential>,
330        local_contact: Option<crate::sip::Uri>,
331    ) -> Result<ClientPublicationDialog> {
332        let id = DialogId {
333            call_id,
334            local_tag: from_tag,
335            remote_tag: to_tag,
336        };
337
338        if let Some(Dialog::ClientPublication(dlg)) = self.get_dialog(&id) {
339            return Ok(dlg);
340        }
341
342        let mut local_contact = local_contact;
343        if local_contact.is_none() {
344            local_contact = self
345                .build_local_contact(credential.as_ref().map(|cred| cred.username.clone()), None)
346                .ok();
347        }
348
349        let dlg_inner = DialogInner::new(
350            TransactionRole::Client,
351            id.clone(),
352            initial_request,
353            self.endpoint.clone(),
354            state_sender,
355            credential,
356            local_contact,
357            {
358                let (tx, _) = crate::platform::mpsc::unbounded_channel();
359                tx
360            },
361        )?;
362
363        let dialog = ClientPublicationDialog::new(Arc::new(dlg_inner));
364        self.inner
365            .dialogs
366            .insert(id.to_string(), Dialog::ClientPublication(dialog.clone()));
367        Ok(dialog)
368    }
369
370    pub fn get_or_create_client_subscription(
371        &self,
372        call_id: String,
373        from_tag: String,
374        to_tag: String,
375        initial_request: crate::sip::Request,
376        state_sender: DialogStateSender,
377        credential: Option<Credential>,
378        local_contact: Option<crate::sip::Uri>,
379    ) -> Result<ClientSubscriptionDialog> {
380        let id = DialogId {
381            call_id,
382            local_tag: from_tag,
383            remote_tag: to_tag,
384        };
385
386        if let Some(Dialog::ClientSubscription(dlg)) = self.get_dialog(&id) {
387            return Ok(dlg);
388        }
389
390        let mut local_contact = local_contact;
391        if local_contact.is_none() {
392            local_contact = self
393                .build_local_contact(credential.as_ref().map(|cred| cred.username.clone()), None)
394                .ok();
395        }
396
397        let dlg_inner = DialogInner::new(
398            TransactionRole::Client,
399            id.clone(),
400            initial_request,
401            self.endpoint.clone(),
402            state_sender,
403            credential,
404            local_contact,
405            {
406                let (tx, _) = crate::platform::mpsc::unbounded_channel();
407                tx
408            },
409        )?;
410
411        let dialog = ClientSubscriptionDialog {
412            inner: Arc::new(dlg_inner),
413        };
414        self.inner
415            .dialogs
416            .insert(id.to_string(), Dialog::ClientSubscription(dialog.clone()));
417        Ok(dialog)
418    }
419
420    pub fn increment_last_seq(&self) -> u32 {
421        self.inner.last_seq.fetch_add(1, Ordering::Relaxed);
422        self.inner.last_seq.load(Ordering::Relaxed)
423    }
424
425    pub fn len(&self) -> usize {
426        self.inner.dialogs.len()
427    }
428
429    pub fn is_empty(&self) -> bool {
430        self.inner.dialogs.is_empty()
431    }
432
433    pub fn all_dialog_ids(&self) -> Vec<String> {
434        self.inner.dialogs.with(|m| m.keys().cloned().collect())
435    }
436
437    pub fn get_dialog(&self, id: &DialogId) -> Option<Dialog> {
438        self.get_dialog_with(&id.to_string())
439    }
440
441    pub fn get_dialog_with(&self, id: &String) -> Option<Dialog> {
442        self.inner.dialogs.get(id)
443    }
444    /// Returns all client-side INVITE dialogs (UAC) that share the given Call-ID.
445    ///
446    /// In a forking scenario, multiple client dialogs can exist for the same
447    /// Call-ID (same local From-tag, different remote To-tags). This helper
448    /// scans the internal dialog registry and returns all `InviteDialog`
449    /// instances whose `DialogId.call_id` equals the provided `call_id`.
450    ///
451    /// The returned vector may be empty if no matching client dialogs are found.
452    pub fn get_client_dialog_by_call_id(&self, call_id: &str) -> Vec<InviteDialog> {
453        self.inner.dialogs.with(|m| {
454            m.values()
455                .filter_map(|d| match d {
456                    Dialog::Invite(client_dlg) if client_dlg.id().call_id == call_id => {
457                        Some(client_dlg.clone())
458                    }
459                    _ => None,
460                })
461                .collect()
462        })
463    }
464
465    /// Restore a dialog from persisted snapshot.
466    ///
467    /// Restores only CONFIRMED snapshots.
468    /// Non-confirmed snapshots are ignored (warn inside try_restore_from_snapshot).
469    ///
470    /// Returns:
471    /// - Ok(true)  => restored and inserted
472    /// - Ok(false) => skipped (already exists or not confirmed)
473    pub fn restore_from_snapshot(
474        &self,
475        snapshot: DialogSnapshot,
476        state_sender: DialogStateSender,
477    ) -> crate::Result<bool> {
478        // Already restored?
479        if self.get_dialog(&snapshot.id).is_some() {
480            return Ok(false);
481        }
482
483        let tu_sender = transaction_event_sender_noop();
484
485        let Some(inner) = DialogInner::try_restore_from_snapshot(
486            snapshot,
487            self.endpoint.clone(),
488            state_sender,
489            tu_sender,
490        )?
491        else {
492            // not confirmed -> ignored
493            return Ok(false);
494        };
495
496        let inner = Arc::new(inner);
497        let dialog = Dialog::from_inner(inner.role, inner.clone());
498
499        let key = dialog.id().to_string();
500
501        self.inner.dialogs.insert(key, dialog);
502
503        Ok(true)
504    }
505
506    pub fn remove_dialog(&self, id: &DialogId) {
507        if let Some(d) = self.inner.dialogs.remove(&id.to_string()) {
508            d.on_remove()
509        }
510    }
511
512    pub fn match_dialog(&self, tx: &Transaction) -> Option<Dialog> {
513        let id = DialogId::try_from(tx).ok()?;
514        self.get_dialog(&id)
515    }
516
517    pub fn new_dialog_state_channel(&self) -> (DialogStateSender, DialogStateReceiver) {
518        crate::platform::mpsc::unbounded_channel()
519    }
520
521    pub fn build_local_contact(
522        &self,
523        username: Option<String>,
524        params: Option<Vec<crate::sip::Param>>,
525    ) -> Result<crate::sip::Uri> {
526        let addr = self
527            .endpoint
528            .transport_layer
529            .get_addrs()
530            .first()
531            .ok_or(crate::Error::EndpointError("not sipaddrs".to_string()))?
532            .clone();
533
534        let scheme = if matches!(addr.r#type, Some(crate::sip::Transport::Tls)) {
535            crate::sip::Scheme::Sips
536        } else {
537            crate::sip::Scheme::Sip
538        };
539
540        let mut params = params.unwrap_or_default();
541        if !matches!(addr.r#type, Some(crate::sip::Transport::Udp) | None) {
542            if let Some(t) = addr.r#type {
543                params.push(crate::sip::Param::Transport(t))
544            }
545        }
546        let auth = username.map(|user| crate::sip::Auth {
547            user,
548            password: None,
549        });
550        Ok(crate::sip::Uri {
551            scheme: Some(scheme),
552            auth,
553            host_with_port: addr.addr.clone(),
554            params,
555            ..Default::default()
556        })
557    }
558}