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
19pub struct DialogLayerInner {
36 pub(super) last_seq: AtomicU32,
37 pub(super) dialogs: RwMap<String, Dialog>,
38}
39pub type DialogLayerInnerRef = Arc<DialogLayerInner>;
40
41pub 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(); 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(); 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(); 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 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 pub fn restore_from_snapshot(
474 &self,
475 snapshot: DialogSnapshot,
476 state_sender: DialogStateSender,
477 ) -> crate::Result<bool> {
478 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 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}