Skip to main content

active_call/call/
sip.rs

1use crate::call::state::{CallProgress, LegShared};
2use crate::callrecord::CallRecordHangupReason;
3use crate::event::EventSender;
4use crate::media::TrackId;
5use crate::media::stream::MediaStream;
6use crate::useragent::invitation::PendingDialog;
7use anyhow::Result;
8use chrono::Utc;
9use rsipstack::dialog::DialogId;
10use rsipstack::dialog::dialog::{
11    Dialog, DialogState, DialogStateReceiver, DialogStateSender, TerminatedReason,
12};
13use rsipstack::dialog::dialog_layer::DialogLayer;
14use rsipstack::dialog::invitation::InviteOption;
15use std::collections::HashMap;
16use std::sync::Arc;
17use tokio_util::sync::CancellationToken;
18use tracing::{debug, info, warn};
19
20/// Remove `id` from the dialog layer and return the dialog, ready to be
21/// hung up. Shared by the dialog guards and `Invitation::hangup`.
22pub(crate) fn remove_dialog(layer: &DialogLayer, id: &DialogId) -> Option<Dialog> {
23    let dialog = layer.get_dialog(id)?;
24    layer.remove_dialog(id);
25    Some(dialog)
26}
27
28/// Reports transfer progress back to the referrer over the RFC 3515 implicit
29/// subscription created by an in-dialog REFER: `Event: refer` NOTIFYs sent on
30/// the parent dialog (100 Trying after the 202, then a terminal status).
31#[derive(Clone)]
32pub struct ReferProgressNotifier {
33    dialog_layer: Arc<DialogLayer>,
34    dialog_id: DialogId,
35    /// Set once the referrer shows it does not support refer subscriptions
36    /// (e.g. 405/501 on the first NOTIFY); further NOTIFYs are skipped.
37    disabled: Arc<std::sync::atomic::AtomicBool>,
38}
39
40impl std::fmt::Debug for ReferProgressNotifier {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("ReferProgressNotifier")
43            .field("dialog_id", &self.dialog_id)
44            .field("disabled", &self.disabled.load(std::sync::atomic::Ordering::Relaxed))
45            .finish()
46    }
47}
48
49impl ReferProgressNotifier {
50    pub fn new(dialog_layer: Arc<DialogLayer>, dialog_id: DialogId) -> Self {
51        Self {
52            dialog_layer,
53            dialog_id,
54            disabled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
55        }
56    }
57
58    async fn notify(&self, code: u16, sub_state: &str) {
59        if self.disabled.load(std::sync::atomic::Ordering::Relaxed) {
60            debug!(
61                id = %self.dialog_id,
62                code,
63                "refer notify skipped: referrer does not support refer subscriptions"
64            );
65            return;
66        }
67        let dialog = match self.dialog_layer.get_dialog(&self.dialog_id) {
68            Some(Dialog::Invite(dialog)) => dialog,
69            Some(_) => {
70                debug!(
71                    id = %self.dialog_id,
72                    "refer notify: dialog is not an invite dialog, skipping"
73                );
74                return;
75            }
76            None => {
77                debug!(
78                    id = %self.dialog_id,
79                    "refer notify: parent dialog gone, skipping"
80                );
81                return;
82            }
83        };
84        let status = match rsipstack::rsip::StatusCode::try_from(code) {
85            Ok(status) => status,
86            Err(_) => rsipstack::rsip::StatusCode::ServerInternalError,
87        };
88        match dialog.notify_refer(status, sub_state).await {
89            Ok(Some(response)) => {
90                // A referrer that rejects NOTIFY with 405/501 does not
91                // implement refer subscriptions (e.g. INVITE-mode bridges);
92                // stop sending further notifies for this transfer.
93                let response_code = u16::from(response.status_code().clone());
94                if matches!(response_code, 405 | 501) {
95                    self.disabled
96                        .store(true, std::sync::atomic::Ordering::Relaxed);
97                    info!(
98                        id = %self.dialog_id,
99                        code = response_code,
100                        "refer notify rejected, disabling further refer notifies"
101                    );
102                } else {
103                    info!(
104                        id = %self.dialog_id,
105                        code,
106                        sub_state,
107                        "refer notify sent"
108                    );
109                }
110            },
111            Ok(None) => warn!(
112                id = %self.dialog_id,
113                code,
114                "refer notify skipped: dialog not confirmed"
115            ),
116            Err(e) => warn!(
117                id = %self.dialog_id,
118                code,
119                "failed to send refer notify: {}",
120                e
121            ),
122        }
123    }
124
125    /// Transfer attempt accepted and in progress (sent right after the 202).
126    pub async fn trying(&self) {
127        self.notify(100, "active").await;
128    }
129
130    /// Terminal status of the transfer attempt: 2xx reports success, any
131    /// other code a failure (body is a `message/sipfrag` status line).
132    pub async fn finished(&self, code: u16) {
133        let sub_state = if (200..300).contains(&code) {
134            "terminated;reason=noresource".to_string()
135        } else {
136            format!("terminated;reason=SIP;cause={code}")
137        };
138        self.notify(code, &sub_state).await;
139    }
140}
141
142pub struct DialogStateReceiverGuard {
143    pub(super) dialog_layer: Arc<DialogLayer>,
144    pub(super) receiver: DialogStateReceiver,
145    pub(super) dialog_id: Option<DialogId>,
146    pub(super) hangup_headers: Option<Vec<rsipstack::rsip::Header>>,
147}
148
149impl DialogStateReceiverGuard {
150    pub fn new(
151        dialog_layer: Arc<DialogLayer>,
152        receiver: DialogStateReceiver,
153        hangup_headers: Option<Vec<rsipstack::rsip::Header>>,
154    ) -> Self {
155        Self {
156            dialog_layer,
157            receiver,
158            dialog_id: None,
159            hangup_headers,
160        }
161    }
162    pub async fn recv(&mut self) -> Option<DialogState> {
163        let state = self.receiver.recv().await;
164        if let Some(ref s) = state {
165            self.dialog_id = Some(s.id().clone());
166        }
167        state
168    }
169
170    fn take_dialog(&mut self) -> Option<Dialog> {
171        let id = self.dialog_id.take()?;
172        info!(%id, "dialog removed on  drop");
173        if let Some(dialog) = remove_dialog(&self.dialog_layer, &id) {
174            return Some(dialog);
175        }
176        // A client dialog is only re-registered under its tag-bearing id once
177        // do_invite's process_invite() fully completes; while still ringing
178        // it's registered under the pre-response id (empty remote tag). Our
179        // tracked `id` already reflects whatever tag the latest DialogState
180        // event carried (e.g. a 183's), so the exact-key lookup above misses
181        // it for any dialog hung up before it's confirmed. Fall back to a
182        // call-id scan, which is unaffected by that id mutation.
183        self.dialog_layer
184            .get_client_dialog_by_call_id(&id.call_id)
185            .into_iter()
186            .next()
187            .map(Dialog::Invite)
188    }
189
190    pub async fn drop_async(&mut self) {
191        if let Some(dialog) = self.take_dialog() {
192            if let Err(e) = dialog.hangup_with_headers(self.hangup_headers.take()).await {
193                warn!(id=%dialog.id(), "error hanging up dialog on drop: {}", e);
194            }
195        }
196    }
197}
198
199impl Drop for DialogStateReceiverGuard {
200    fn drop(&mut self) {
201        if let Some(dialog) = self.take_dialog() {
202            crate::spawn(async move {
203                if let Err(e) = dialog.hangup().await {
204                    warn!(id=%dialog.id(), "error hanging up dialog on drop: {}", e);
205                }
206            });
207        }
208    }
209}
210
211pub(super) struct InviteDialogStates {
212    pub is_client: bool,
213    pub session_id: String,
214    pub track_id: TrackId,
215    pub cancel_token: CancellationToken,
216    pub event_sender: EventSender,
217    /// Lock-free shared state of the leg this dialog belongs to.
218    pub leg: LegShared,
219    pub media_stream: Arc<MediaStream>,
220    pub terminated_reason: Option<TerminatedReason>,
221    pub has_early_media: bool,
222    /// Set once the initial INVITE's answer has been applied via
223    /// `DialogState::Confirmed`. rsipstack reuses the same `Confirmed` event
224    /// for the ACK of a re-INVITE we received (see `handle_reinvite`), but
225    /// in that case the body is the PBX's own locally-generated answer, not
226    /// a remote description — that re-invite was already fully handled via
227    /// `DialogState::Updated`/`handshake()`. Re-applying it here corrupts
228    /// the peer connection's remote SSRC/address with our own values.
229    initial_confirmed: bool,
230    /// Hangup intent carried by this leg (refer legs with `auto_hangup`),
231    /// reported on the leg's TrackEnd so the call actor can hang up.
232    pub hangup_reason: Option<CallRecordHangupReason>,
233    /// REFER notifier waiting for the dialog to return to the confirmed
234    /// state (the 202 reply transitions it back); the RFC 3515 Trying
235    /// NOTIFY is sent from the next `Confirmed` event.
236    pub pending_refer_notify: Option<Arc<ReferProgressNotifier>>,
237}
238
239impl InviteDialogStates {
240    pub(super) fn new(
241        is_client: bool,
242        session_id: String,
243        track_id: TrackId,
244        event_sender: EventSender,
245        media_stream: Arc<MediaStream>,
246        leg: LegShared,
247        cancel_token: CancellationToken,
248        hangup_reason: Option<CallRecordHangupReason>,
249    ) -> Self {
250        Self {
251            is_client,
252            session_id,
253            track_id,
254            cancel_token,
255            event_sender,
256            leg,
257            media_stream,
258            terminated_reason: None,
259            has_early_media: false,
260            initial_confirmed: false,
261            hangup_reason,
262            pending_refer_notify: None,
263        }
264    }
265}
266
267impl InviteDialogStates {
268    /// Called from `Drop` (synchronous context): everything used here is
269    /// lock-free (ArcSwap rcu/load + broadcast send), so no state or events
270    /// can be lost the way a failed `try_write` used to lose them.
271    pub(super) fn on_terminated(&mut self) {
272        let term = CallProgress::termination(self.terminated_reason.as_ref());
273        let status_code = term.status_code;
274        let reason = term.hangup_reason;
275        self.leg.update_progress(|p| {
276            p.last_status_code = status_code;
277            p.set_hangup_reason(reason.clone());
278        });
279        let progress = self.leg.progress.load_full();
280
281        // The auto-hangup intent (refer legs) must only fire when the refer
282        // leg was actually ANSWERED: if the transfer target rejected or timed
283        // out, the transfer failed and the caller stays in the original call.
284        let auto_hangup = self
285            .hangup_reason
286            .clone()
287            .filter(|_| progress.answer_time.is_some());
288        self.event_sender
289            .send(crate::event::SessionEvent::TrackEnd {
290                track_id: self.track_id.clone(),
291                timestamp: crate::media::get_timestamp(),
292                duration: progress
293                    .answer_time
294                    .map(|t| (Utc::now() - t).num_milliseconds())
295                    .unwrap_or_default() as u64,
296                ssrc: self.leg.ssrc,
297                play_id: None,
298                auto_hangup,
299            })
300            .ok();
301        // A superseded INVITE-mode bridge leg ends by internal replace, not
302        // by a real hangup — the client must not see a Hangup event (it
303        // would close the WebSocket and tear the whole session down).
304        if !progress.superseded {
305            let hangup_event = self
306                .leg
307                .build_hangup_event(self.track_id.clone(), Some(term.initiator.to_string()));
308            self.event_sender.send(hangup_event).ok();
309        }
310    }
311}
312
313impl Drop for InviteDialogStates {
314    fn drop(&mut self) {
315        self.on_terminated();
316        self.cancel_token.cancel();
317    }
318}
319
320impl DialogStateReceiverGuard {
321    pub(self) async fn dialog_event_loop(&mut self, states: &mut InviteDialogStates) -> Result<()> {
322        while let Some(event) = self.recv().await {
323            match event {
324                DialogState::Calling(dialog_id) => {
325                    info!(session_id=states.session_id, %dialog_id, "dialog calling");
326                    states
327                        .leg
328                        .update_progress(|p| p.session_id = dialog_id.to_string());
329                }
330                DialogState::Trying(_) => {}
331                DialogState::Early(dialog_id, resp) => {
332                    let code = resp.status_code.code();
333                    let body = resp.body();
334                    let answer = String::from_utf8_lossy(body);
335                    let has_sdp = !answer.is_empty();
336                    info!(session_id=states.session_id, %dialog_id, has_sdp=%has_sdp, "dialog early ({}): \n{}", code, answer);
337
338                    states.leg.update_progress(|p| p.on_early(code));
339
340                    if !states.is_client {
341                        continue;
342                    }
343
344                    states
345                        .event_sender
346                        .send(crate::event::SessionEvent::Ringing {
347                            track_id: states.track_id.clone(),
348                            timestamp: crate::media::get_timestamp(),
349                            early_media: has_sdp,
350                            refer: Some(states.leg.is_refer),
351                        })?;
352
353                    if has_sdp {
354                        states.has_early_media = true;
355                        states.leg.update_progress(|p| p.try_set_answer(&answer));
356                        states
357                            .media_stream
358                            .update_remote_description_provisional(
359                                &states.track_id,
360                                &answer.to_string(),
361                            )
362                            .await?;
363                    }
364                }
365                DialogState::Confirmed(dialog_id, msg) => {
366                    info!(session_id=states.session_id, %dialog_id, has_early_media=%states.has_early_media, "dialog confirmed");
367                    states
368                        .leg
369                        .update_progress(|p| p.on_confirmed(dialog_id.to_string()));
370                    if states.is_client && !states.initial_confirmed {
371                        states.initial_confirmed = true;
372                        let answer = String::from_utf8_lossy(msg.body());
373                        let answer = answer.trim();
374                        if !answer.is_empty() {
375                            if states.has_early_media {
376                                info!(
377                                    session_id = states.session_id,
378                                    "updating remote description with final answer after early media (force=true)"
379                                );
380                                // Force update when transitioning from early media (183) to confirmed (200 OK)
381                                // This ensures media parameters are properly updated even if SDP appears similar
382                                if let Err(e) = states
383                                    .media_stream
384                                    .update_remote_description_force(
385                                        &states.track_id,
386                                        &answer.to_string(),
387                                    )
388                                    .await
389                                {
390                                    tracing::warn!(
391                                        session_id = states.session_id,
392                                        "failed to force update remote description on confirmed: {}",
393                                        e
394                                    );
395                                }
396                            } else {
397                                if let Err(e) = states
398                                    .media_stream
399                                    .update_remote_description(
400                                        &states.track_id,
401                                        &answer.to_string(),
402                                    )
403                                    .await
404                                {
405                                    tracing::warn!(
406                                        session_id = states.session_id,
407                                        "failed to update remote description on confirmed: {}",
408                                        e
409                                    );
410                                }
411                            }
412                        }
413                    }
414                    // The dialog is back in the confirmed state (either the
415                    // initial ACK, or rsipstack returning from a mid-dialog
416                    // request like REFER) — flush the pending RFC 3515
417                    // Trying NOTIFY.
418                    if let Some(notifier) = states.pending_refer_notify.take() {
419                        notifier.trying().await;
420                    }
421                }
422                DialogState::Info(dialog_id, req, tx_handle) => {
423                    let body_str = String::from_utf8_lossy(req.body());
424                    info!(session_id=states.session_id, %dialog_id, body=%body_str, "dialog info received");
425                    if body_str.starts_with("Signal=") {
426                        let digit = body_str.trim_start_matches("Signal=").chars().next();
427                        if let Some(digit) = digit {
428                            states.event_sender.send(crate::event::SessionEvent::Dtmf {
429                                track_id: states.track_id.clone(),
430                                timestamp: crate::media::get_timestamp(),
431                                digit: digit.to_string(),
432                                refer: Some(states.leg.is_refer),
433                            })?;
434                        }
435                    }
436                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
437                }
438                DialogState::Message(dialog_id, req, tx_handle) => {
439                    let body_str = String::from_utf8_lossy(req.body()).to_string();
440                    let content_type = req.headers.iter().find_map(|h| {
441                        if let rsipstack::rsip::Header::ContentType(content_type) = h {
442                            Some(content_type.value().to_string())
443                        } else {
444                            None
445                        }
446                    });
447                    info!(
448                        session_id=states.session_id,
449                        %dialog_id,
450                        content_type=content_type.as_deref(),
451                        body=%body_str,
452                        "dialog message received"
453                    );
454                    states
455                        .event_sender
456                        .send(crate::event::SessionEvent::Message {
457                            track_id: states.track_id.clone(),
458                            timestamp: crate::media::get_timestamp(),
459                            body: body_str,
460                            content_type,
461                            refer: Some(states.leg.is_refer),
462                        })
463                        .ok();
464                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
465                }
466                DialogState::Updated(dialog_id, _req, tx_handle) => {
467                    info!(session_id = states.session_id, %dialog_id, "dialog update received");
468                    let mut answer_sdp = None;
469                    if let Some(sdp_body) = _req.body().get(..) {
470                        let sdp_str = String::from_utf8_lossy(sdp_body);
471                        if !sdp_str.is_empty()
472                            && (_req.method == rsipstack::rsip::Method::Invite
473                                || _req.method == rsipstack::rsip::Method::Update)
474                        {
475                            info!(session_id=states.session_id, %dialog_id, method=%_req.method, "handling re-invite/update offer");
476
477                            // Detect hold state from SDP
478                            let is_on_hold =
479                                crate::media::negotiate::detect_hold_state_from_sdp(&sdp_str);
480                            info!(session_id=states.session_id, %dialog_id, is_on_hold=%is_on_hold, "detected hold state from re-invite SDP");
481
482                            // Update media stream hold state + emit hold event
483                            apply_hold_state(states, is_on_hold).await;
484
485                            match states
486                                .media_stream
487                                .handshake(&states.track_id, sdp_str.to_string(), None)
488                                .await
489                            {
490                                Ok(sdp) => answer_sdp = Some(sdp),
491                                Err(e) => {
492                                    warn!(
493                                        session_id = states.session_id,
494                                        "failed to handle re-invite: {}", e
495                                    );
496                                }
497                            }
498                        } else {
499                            info!(session_id=states.session_id, %dialog_id, "updating remote description:\n{}", sdp_str);
500
501                            // Also check hold state for non-INVITE/UPDATE messages with SDP
502                            let is_on_hold =
503                                crate::media::negotiate::detect_hold_state_from_sdp(&sdp_str);
504                            apply_hold_state(states, is_on_hold).await;
505
506                            states
507                                .media_stream
508                                .update_remote_description(&states.track_id, &sdp_str.to_string())
509                                .await?;
510                        }
511                    }
512
513                    if let Some(sdp) = answer_sdp {
514                        tx_handle
515                            .respond(
516                                rsipstack::rsip::StatusCode::OK,
517                                Some(vec![rsipstack::rsip::Header::ContentType(
518                                    "application/sdp".to_string().into(),
519                                )]),
520                                Some(sdp.into()),
521                            )
522                            .await
523                            .ok();
524                    } else {
525                        tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
526                    }
527                }
528                DialogState::Options(dialog_id, _req, tx_handle) => {
529                    info!(session_id = states.session_id, %dialog_id, "dialog options received");
530                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
531                }
532                DialogState::Refer(dialog_id, req, tx_handle) => {
533                    let refer_to = req
534                        .headers
535                        .iter()
536                        .find_map(|h| {
537                            if let rsipstack::rsip::Header::ReferTo(h) = h {
538                                return Some(h.value().to_string());
539                            }
540                            None
541                        })
542                        .unwrap_or_default();
543                    let referred_by = req.headers.iter().find_map(|h| {
544                        if let rsipstack::rsip::Header::ReferredBy(h) = h {
545                            return Some(h.value().to_string());
546                        }
547                        None
548                    });
549                    info!(session_id = states.session_id, %dialog_id, %refer_to, "received REFER");
550                    tx_handle
551                        .reply(rsipstack::rsip::StatusCode::Other(202, "Accepted".into()))
552                        .await
553                        .ok();
554                    // RFC 3515: the 202 opens an implicit subscription; report
555                    // progress on the parent dialog. Whether the transfer is
556                    // actually attempted is decided by the call actor. The
557                    // Trying NOTIFY waits for the next Confirmed event — the
558                    // 202 itself flips the dialog back to confirmed, so this
559                    // is deterministic and free of state races.
560                    let notifier = Arc::new(ReferProgressNotifier::new(
561                        self.dialog_layer.clone(),
562                        dialog_id.clone(),
563                    ));
564                    states.pending_refer_notify = Some(notifier.clone());
565                    states
566                        .event_sender
567                        .send(crate::event::SessionEvent::TransferRequest {
568                            track_id: states.track_id.clone(),
569                            timestamp: crate::media::get_timestamp(),
570                            refer_to,
571                            referred_by,
572                            refer: Some(states.leg.is_refer),
573                            leg_session_id: Some(
574                                states.leg.progress.load_full().session_id.clone()
575                            ),
576                            notify: Some(notifier),
577                        })
578                        .ok();
579                }
580                DialogState::Notify(dialog_id, _req, tx_handle) => {
581                    info!(
582                        session_id = states.session_id,
583                        %dialog_id,
584                        "dialog notify received"
585                    );
586                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
587                }
588                DialogState::Terminated(dialog_id, reason) => {
589                    info!(
590                        session_id = states.session_id,
591                        ?dialog_id,
592                        ?reason,
593                        "dialog terminated"
594                    );
595                    states.terminated_reason = Some(reason.clone());
596                    return Ok(());
597                }
598                other_state => {
599                    info!(
600                        session_id = states.session_id,
601                        %other_state,
602                        "dialog received other state"
603                    );
604                }
605            }
606        }
607        Ok(())
608    }
609
610    pub(super) async fn process_dialog(&mut self, mut states: InviteDialogStates) {
611        let token = states.cancel_token.clone();
612        tokio::select! {
613            _ = token.cancelled() => {
614                states.terminated_reason = Some(TerminatedReason::UacCancel);
615            }
616            _ = self.dialog_event_loop(&mut states) => {}
617        };
618
619        // Update hangup headers from the leg extras if available
620        let extras = states.leg.extras.load_full();
621        if let Some(headers) = crate::sip_util::hangup_headers_from_extras(&extras) {
622            match &mut self.hangup_headers {
623                Some(existing) => existing.extend(headers),
624                None => self.hangup_headers = Some(headers),
625            }
626        }
627
628        self.drop_async().await;
629    }
630}
631
632/// Apply a hold/resume transition to the media track and emit the Hold event.
633async fn apply_hold_state(states: &mut InviteDialogStates, is_on_hold: bool) {
634    if is_on_hold {
635        states
636            .media_stream
637            .hold_track(Some(states.track_id.clone()))
638            .await;
639    } else {
640        states
641            .media_stream
642            .resume_track(Some(states.track_id.clone()))
643            .await;
644    }
645    states
646        .event_sender
647        .send(crate::event::SessionEvent::Hold {
648            track_id: states.track_id.clone(),
649            timestamp: crate::media::get_timestamp(),
650            on_hold: is_on_hold,
651            refer: Some(states.leg.is_refer),
652        })
653        .ok();
654}
655
656#[derive(Clone)]
657pub struct Invitation {
658    pub dialog_layer: Arc<DialogLayer>,
659    pub pending_dialogs: Arc<std::sync::Mutex<HashMap<DialogId, PendingDialog>>>,
660    /// Maps the (short) public session id of an incoming call to the DialogId
661    /// captured when the INVITE arrived. Incoming sessions no longer reuse the
662    /// raw dialog-id string, so every session-id based lookup resolves here.
663    sessions: Arc<std::sync::Mutex<HashMap<String, DialogId>>>,
664}
665
666impl Invitation {
667    pub fn new(dialog_layer: Arc<DialogLayer>) -> Self {
668        Self {
669            dialog_layer,
670            pending_dialogs: Arc::new(std::sync::Mutex::new(HashMap::new())),
671            sessions: Arc::new(std::sync::Mutex::new(HashMap::new())),
672        }
673    }
674
675    pub fn register_session(&self, session_id: &str, dialog_id: &DialogId) {
676        self.sessions
677            .lock()
678            .map(|mut ss| ss.insert(session_id.to_string(), dialog_id.clone()))
679            .ok();
680    }
681
682    pub fn unregister_session(&self, session_id: &str) {
683        self.sessions
684            .lock()
685            .map(|mut ss| ss.remove(session_id))
686            .ok();
687    }
688
689    pub fn session_exists(&self, session_id: &str) -> bool {
690        self.sessions
691            .lock()
692            .map(|ss| ss.contains_key(session_id))
693            .unwrap_or(false)
694    }
695
696    pub fn add_pending(&self, dialog_id: DialogId, pending: PendingDialog) {
697        self.pending_dialogs
698            .lock()
699            .map(|mut ps| ps.insert(dialog_id, pending))
700            .ok();
701    }
702
703    pub fn get_pending_call(&self, dialog_id: &DialogId) -> Option<PendingDialog> {
704        self.pending_dialogs
705            .lock()
706            .ok()
707            .and_then(|mut ps| ps.remove(dialog_id))
708    }
709
710    pub fn has_pending_call(&self, dialog_id: &DialogId) -> bool {
711        self.pending_dialogs
712            .lock()
713            .ok()
714            .map(|ps| ps.contains_key(dialog_id))
715            .unwrap_or(false)
716    }
717
718    pub fn find_dialog_id_by_session_id(&self, session_id: &str) -> Option<DialogId> {
719        if let Some(id) = self
720            .sessions
721            .lock()
722            .ok()
723            .and_then(|ss| ss.get(session_id).cloned())
724        {
725            return Some(id);
726        }
727        self.pending_dialogs.lock().ok().and_then(|ps| {
728            ps.iter()
729                .find(|(id, _)| id.to_string() == session_id)
730                .map(|(id, _)| id.clone())
731        })
732    }
733
734    /// Reject a pending dialog or hang up an established one.
735    pub async fn hangup(
736        &self,
737        dialog_id: DialogId,
738        code: Option<rsipstack::rsip::StatusCode>,
739        reason: Option<String>,
740    ) -> Result<()> {
741        if let Some(call) = self.get_pending_call(&dialog_id) {
742            call.dialog.reject(code, reason).ok();
743        }
744        if let Some(dialog) = remove_dialog(&self.dialog_layer, &dialog_id) {
745            dialog.hangup().await.ok();
746        }
747        Ok(())
748    }
749
750    pub async fn invite(
751        &self,
752        invite_option: InviteOption,
753        state_sender: DialogStateSender,
754    ) -> Result<(DialogId, Option<Vec<u8>>), rsipstack::Error> {
755        let (dialog, resp) = self
756            .dialog_layer
757            .do_invite(invite_option, state_sender)
758            .await?;
759
760        let offer = match resp {
761            Some(resp) => match resp.status_code.kind() {
762                rsipstack::rsip::StatusCodeKind::Successful => {
763                    let offer = resp.body.clone();
764                    Some(offer)
765                }
766                _ => {
767                    let reason = resp
768                        .reason_phrase()
769                        .unwrap_or(&resp.status_code.to_string())
770                        .to_string();
771                    return Err(rsipstack::Error::DialogError(
772                        reason,
773                        dialog.id(),
774                        resp.status_code,
775                    ));
776                }
777            },
778            None => {
779                return Err(rsipstack::Error::DialogError(
780                    "no response received".to_string(),
781                    dialog.id(),
782                    rsipstack::rsip::StatusCode::NotAcceptableHere,
783                ));
784            }
785        };
786        Ok((dialog.id(), offer))
787    }
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793    use crate::call::state::CallProgress;
794    use crate::media::stream::MediaStreamBuilder;
795
796    // SDP used to simulate an early-media 183 Session Progress response.
797    const EARLY_MEDIA_SDP: &str = "v=0\r\n\
798        o=- 1000 1 IN IP4 192.168.1.100\r\n\
799        s=SIP Call\r\n\
800        t=0 0\r\n\
801        m=audio 10000 RTP/AVP 0\r\n\
802        c=IN IP4 192.168.1.100\r\n\
803        a=rtpmap:0 PCMU/8000\r\n\
804        a=sendrecv\r\n";
805
806    fn make_states(has_early_media: bool) -> InviteDialogStates {
807        let (event_tx, _event_rx) = tokio::sync::broadcast::channel(16);
808        let media_stream = Arc::new(
809            MediaStreamBuilder::new(event_tx.clone())
810                .with_id("test-stream".to_string())
811                .build(),
812        );
813        let cancel_token = CancellationToken::new();
814        let leg = LegShared::new(1000, true, CallProgress::default());
815
816        InviteDialogStates {
817            is_client: true,
818            session_id: "test-session".to_string(),
819            track_id: "test-track".to_string(),
820            cancel_token: cancel_token.clone(),
821            event_sender: event_tx.clone(),
822            leg,
823            media_stream,
824            terminated_reason: None,
825            has_early_media,
826            initial_confirmed: false,
827            hangup_reason: None,
828            pending_refer_notify: None,
829        }
830    }
831
832    /// Verify that when a 183 Session Progress with SDP arrives (`DialogState::Early`),
833    /// the early SDP is stored in the leg progress so it can serve as a fallback
834    /// when the final 200 OK has an empty body.
835    #[tokio::test]
836    async fn test_early_sdp_stored_in_leg_progress() {
837        let mut states = make_states(false);
838
839        // Simulate DialogState::Early with SDP body (183 Session Progress):
840        // same steps the Early branch performs.
841        let answer = EARLY_MEDIA_SDP.to_string();
842        let has_sdp = !answer.is_empty();
843        if states.is_client && has_sdp {
844            states.has_early_media = true;
845            states.leg.update_progress(|p| p.try_set_answer(&answer));
846        }
847
848        // Assert: early SDP is stored
849        let progress = states.leg.progress.load_full();
850        assert!(
851            progress.answer.is_some(),
852            "leg progress answer should be set after 183 with SDP"
853        );
854        assert_eq!(
855            progress.answer.as_deref().unwrap(),
856            EARLY_MEDIA_SDP,
857            "leg progress answer should contain the early SDP"
858        );
859        assert!(states.has_early_media, "has_early_media should be true");
860    }
861
862    /// Verify that when a 200 OK arrives with an empty body after early media has been
863    /// negotiated, the leg progress retains the early SDP (not overwritten with "").
864    ///
865    /// This is the regression test for the bug where a late 200 OK with empty body would
866    /// cause `SessionEvent::Answer { sdp: "" }` to be emitted, making the answer event
867    /// appear as if no SDP was negotiated.
868    #[tokio::test]
869    async fn test_confirmed_empty_body_keeps_early_sdp() {
870        let mut states = make_states(false);
871
872        // Step 1: simulate 183 with SDP → set has_early_media and progress answer
873        states.has_early_media = true;
874        states
875            .leg
876            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
877
878        // Step 2: simulate 200 OK with empty body (Confirmed handler logic)
879        states
880            .leg
881            .update_progress(|p| p.on_confirmed("dialog-1".to_string()));
882        // The Confirmed handler only calls update_remote_description when the body
883        // is non-empty; it does NOT overwrite the progress answer.
884        let confirmed_answer = String::new();
885        assert!(
886            confirmed_answer.trim().is_empty(),
887            "empty body must not be applied"
888        );
889
890        // Assert: leg progress still holds the early SDP
891        let progress = states.leg.progress.load_full();
892        assert!(
893            progress.answer.is_some(),
894            "answer must not be None after 200 OK with empty body"
895        );
896        let stored_answer = progress.answer.as_deref().unwrap();
897        assert!(
898            !stored_answer.is_empty(),
899            "answer must not be empty after 200 OK with empty body"
900        );
901        assert_eq!(
902            stored_answer, EARLY_MEDIA_SDP,
903            "answer should still be the early SDP after 200 OK with empty body"
904        );
905    }
906
907    /// Verify that `create_outgoing_sip_track`'s fallback logic works:
908    /// when the 200 OK body is empty but the leg progress has the early SDP,
909    /// the fallback path is taken and the early SDP is returned (not an empty string).
910    #[tokio::test]
911    async fn test_answer_fallback_to_early_sdp_when_200ok_empty() {
912        // Simulate what the Early (183) handler does: store the early SDP.
913        let states = make_states(true);
914        states
915            .leg
916            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
917
918        // Simulate what create_outgoing_sip_track does when 200 OK has empty body.
919        let early = states.leg.progress.load_full().answer.clone();
920        let raw_answer: Option<Vec<u8>> = Some(vec![]); // empty body from 200 OK
921
922        let (answer, already_applied) =
923            crate::call::state::resolve_final_answer(raw_answer, early.as_ref()).unwrap();
924
925        // The answer returned to setup_caller_track (and used in SessionEvent::Answer)
926        // must be the early SDP, not an empty string.
927        assert!(
928            !answer.is_empty(),
929            "Resolved answer must not be empty — should contain the early SDP"
930        );
931        assert_eq!(
932            answer, EARLY_MEDIA_SDP,
933            "Resolved answer should be the early SDP from the 183 handler"
934        );
935        assert!(
936            already_applied,
937            "remote_description_already_applied should be true when using early SDP fallback"
938        );
939    }
940
941    /// Verify the normal case: when 200 OK carries its own SDP body,
942    /// that SDP is used directly (not the early SDP) and remote description
943    /// should be applied.
944    #[tokio::test]
945    async fn test_answer_uses_200ok_sdp_when_present() {
946        const FINAL_SDP: &str = "v=0\r\n\
947            o=- 2000 2 IN IP4 10.0.0.1\r\n\
948            s=SIP Call\r\n\
949            t=0 0\r\n\
950            m=audio 20000 RTP/AVP 0\r\n\
951            c=IN IP4 10.0.0.1\r\n\
952            a=rtpmap:0 PCMU/8000\r\n\
953            a=sendrecv\r\n";
954
955        let states = make_states(true);
956        states
957            .leg
958            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
959
960        let early = states.leg.progress.load_full().answer.clone();
961        let (answer, already_applied) = crate::call::state::resolve_final_answer(
962            Some(FINAL_SDP.as_bytes().to_vec()),
963            early.as_ref(),
964        )
965        .unwrap();
966
967        assert_eq!(
968            answer, FINAL_SDP,
969            "When 200 OK has SDP, it should be used (not the early SDP)"
970        );
971        assert!(
972            !already_applied,
973            "remote_description_already_applied should be false when 200 OK has SDP body"
974        );
975    }
976
977    /// Regression: `on_terminated` runs in a synchronous `Drop` context.
978    /// The old implementation used `try_write` and silently dropped the
979    /// status/reason updates AND the TrackEnd/Hangup events when the lock was
980    /// contended. The lock-free (ArcSwap) implementation must always emit both
981    /// events and record the termination, even while another task keeps
982    /// mutating the progress concurrently.
983    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
984    async fn test_on_terminated_always_emits_events_and_records_state() {
985        use crate::event::SessionEvent;
986        use std::sync::atomic::{AtomicBool, Ordering};
987
988        let mut states = make_states(false);
989        states.terminated_reason = Some(TerminatedReason::UacCancel);
990        let leg = states.leg.clone();
991        let event_sender = states.event_sender.clone();
992        let mut event_receiver = event_sender.subscribe();
993
994        // Hammer the progress concurrently, as a busy actor would.
995        let stop = Arc::new(AtomicBool::new(false));
996        let stop2 = stop.clone();
997        let progress = leg.progress.clone();
998        let writer = crate::spawn(async move {
999            while !stop2.load(Ordering::Relaxed) {
1000                // Touch unrelated fields, like a busy actor would (never the
1001                // termination fields), so writers don't clobber each other.
1002                progress.rcu(|p| {
1003                    let mut p = CallProgress::clone(p);
1004                    p.answer_time.get_or_insert_with(chrono::Utc::now);
1005                    p
1006                });
1007                tokio::task::yield_now().await;
1008            }
1009        });
1010
1011        // Give the writer a moment to start contending.
1012        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1013
1014        // Synchronous drop, exactly like the real dialog task teardown.
1015        drop(states);
1016
1017        stop.store(true, Ordering::Relaxed);
1018        let _ = writer.await;
1019
1020        // Both events must have been emitted despite the concurrent writer.
1021        let mut saw_track_end = false;
1022        let mut saw_hangup = false;
1023        while let Ok(event) = event_receiver.try_recv() {
1024            match event {
1025                SessionEvent::TrackEnd { .. } => saw_track_end = true,
1026                SessionEvent::Hangup { refer, .. } => {
1027                    assert_eq!(refer, Some(true), "refer flag comes from the leg");
1028                    saw_hangup = true;
1029                }
1030                _ => {}
1031            }
1032        }
1033        assert!(
1034            saw_track_end,
1035            "TrackEnd must be emitted from on_terminated even under contention"
1036        );
1037        assert!(
1038            saw_hangup,
1039            "Hangup must be emitted from on_terminated even under contention"
1040        );
1041
1042        // The termination must be recorded (487 for UacCancel); the concurrent
1043        // writer only ever writes 100, so observing 487 proves the rcu landed.
1044        let progress = leg.progress.load_full();
1045        assert_eq!(progress.last_status_code, 487);
1046        assert_eq!(
1047            progress.hangup_reason,
1048            Some(crate::callrecord::CallRecordHangupReason::Canceled)
1049        );
1050    }
1051
1052    /// A minimal counting track that records how many times its remote
1053    /// description was (force-)updated, without touching any real media.
1054    struct CountingTrack {
1055        id: TrackId,
1056        config: crate::media::track::TrackConfig,
1057        processor_chain: crate::media::processor::ProcessorChain,
1058        updates: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1059    }
1060
1061    #[async_trait::async_trait]
1062    impl crate::media::track::Track for CountingTrack {
1063        fn ssrc(&self) -> u32 {
1064            0
1065        }
1066        fn id(&self) -> &TrackId {
1067            &self.id
1068        }
1069        fn config(&self) -> &crate::media::track::TrackConfig {
1070            &self.config
1071        }
1072        fn processor_chain(&mut self) -> &mut crate::media::processor::ProcessorChain {
1073            &mut self.processor_chain
1074        }
1075        async fn handshake(
1076            &mut self,
1077            _offer: String,
1078            _timeout: Option<tokio::time::Duration>,
1079        ) -> Result<String> {
1080            Ok(String::new())
1081        }
1082        async fn update_remote_description(&mut self, _answer: &String) -> Result<()> {
1083            self.updates
1084                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1085            Ok(())
1086        }
1087        async fn update_remote_description_force(&mut self, _answer: &String) -> Result<()> {
1088            self.updates
1089                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1090            Ok(())
1091        }
1092        async fn start(
1093            &mut self,
1094            _event_sender: EventSender,
1095            _packet_sender: crate::media::track::TrackPacketSender,
1096        ) -> Result<()> {
1097            Ok(())
1098        }
1099        async fn stop(&self) -> Result<()> {
1100            Ok(())
1101        }
1102        async fn send_packet(&mut self, _packet: &crate::media::AudioFrame) -> Result<()> {
1103            Ok(())
1104        }
1105    }
1106
1107    /// Regression: a client dialog must apply its remote SDP answer exactly
1108    /// once. The `initial_confirmed` guard exists because the final `Confirmed`
1109    /// event fires both when the 200 OK is processed *and* again when the ACK
1110    /// for the re-INVITE completes; without the guard the answer would be
1111    /// re-applied (and a duplicate `TrackStart`/`SessionEvent::Answer` emitted).
1112    #[tokio::test]
1113    async fn test_confirmed_applies_remote_answer_only_once() {
1114        let mut states = make_states(false);
1115
1116        let updates = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1117        let track = CountingTrack {
1118            id: states.track_id.clone(),
1119            config: crate::media::track::TrackConfig::default(),
1120            processor_chain: crate::media::processor::ProcessorChain::new(16000),
1121            updates: updates.clone(),
1122        };
1123        states
1124            .media_stream
1125            .update_track(Box::new(track), None)
1126            .await;
1127
1128        let endpoint = {
1129            let mut builder = rsipstack::EndpointBuilder::new();
1130            builder.build()
1131        };
1132        let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
1133
1134        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<DialogState>();
1135        let mut guard = DialogStateReceiverGuard::new(dialog_layer, rx, None);
1136
1137        let dialog_id = DialogId {
1138            call_id: "test-call-id".to_string(),
1139            local_tag: "test-local-tag".to_string(),
1140            remote_tag: "test-remote-tag".to_string(),
1141        };
1142
1143        let mut resp = rsipstack::rsip::Response::default();
1144        resp.body = EARLY_MEDIA_SDP.as_bytes().to_vec();
1145
1146        // Two Confirmed events (200 OK + re-INVITE ACK) must only apply once.
1147        tx.send(DialogState::Confirmed(dialog_id.clone(), resp.clone()))
1148            .unwrap();
1149        tx.send(DialogState::Confirmed(dialog_id, resp)).unwrap();
1150        drop(tx);
1151
1152        guard
1153            .dialog_event_loop(&mut states)
1154            .await
1155            .expect("dialog event loop must complete");
1156
1157        assert_eq!(
1158            updates.load(std::sync::atomic::Ordering::SeqCst),
1159            1,
1160            "remote answer must be applied exactly once, not on the re-INVITE ACK Confirmed event"
1161        );
1162    }
1163
1164    #[test]
1165    fn test_session_map_register_find_unregister() {
1166        let endpoint = {
1167            let mut builder = rsipstack::EndpointBuilder::new();
1168            builder.build()
1169        };
1170        let invitation = Invitation::new(Arc::new(DialogLayer::new(endpoint.inner.clone())));
1171
1172        let dialog_id = DialogId {
1173            call_id: "long-call-id-from-carrier".to_string(),
1174            local_tag: String::new(),
1175            remote_tag: "remote-tag".to_string(),
1176        };
1177
1178        assert!(!invitation.session_exists("s.3f9a2b1c4d5e"));
1179        assert!(
1180            invitation
1181                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1182                .is_none()
1183        );
1184
1185        invitation.register_session("s.3f9a2b1c4d5e", &dialog_id);
1186        assert!(invitation.session_exists("s.3f9a2b1c4d5e"));
1187        assert_eq!(
1188            invitation
1189                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1190                .unwrap(),
1191            dialog_id
1192        );
1193
1194        invitation.unregister_session("s.3f9a2b1c4d5e");
1195        assert!(!invitation.session_exists("s.3f9a2b1c4d5e"));
1196        assert!(
1197            invitation
1198                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1199                .is_none()
1200        );
1201        // Unregistering an unknown session is a no-op.
1202        invitation.unregister_session("s.unknown");
1203    }
1204
1205    /// The legacy fallback must keep resolving session ids that match a pending
1206    /// dialog's dialog-id string (e.g. sessions registered before the mapping
1207    /// table existed, or callers still using the raw dialog id).
1208    #[test]
1209    fn test_find_dialog_id_falls_back_to_pending_scan() {
1210        use rsipstack::dialog::dialog::DialogInner;
1211        use rsipstack::dialog::invite_dialog::InviteDialog;
1212        use rsipstack::rsip::typed::{CSeq, Contact, From, To, Via};
1213        use rsipstack::rsip::{Header, Request};
1214        use rsipstack::transaction::key::TransactionRole;
1215
1216        let endpoint = {
1217            let mut builder = rsipstack::EndpointBuilder::new();
1218            builder.build()
1219        };
1220        let invitation = Invitation::new(Arc::new(DialogLayer::new(endpoint.inner.clone())));
1221
1222        let dialog_id = DialogId {
1223            call_id: "legacy-call-id".to_string(),
1224            local_tag: String::new(),
1225            remote_tag: "remote-tag".to_string(),
1226        };
1227
1228        let initial_request = Request {
1229            method: rsipstack::rsip::Method::Invite,
1230            uri: rsipstack::rsip::Uri::try_from("sip:bob@example.com:5060").unwrap(),
1231            headers: vec![
1232                Via::parse("SIP/2.0/UDP alice.example.com:5060;branch=z9hG4bKnashds")
1233                    .unwrap()
1234                    .into(),
1235                CSeq::parse("1 INVITE").unwrap().into(),
1236                From::parse("Alice <sip:alice@example.com>;tag=remote-tag")
1237                    .unwrap()
1238                    .into(),
1239                To::parse("Bob <sip:bob@example.com>").unwrap().into(),
1240                Header::CallId("legacy-call-id".into()),
1241                Contact::parse("<sip:alice@alice.example.com:5060>")
1242                    .unwrap()
1243                    .into(),
1244                Header::MaxForwards("70".into()),
1245            ]
1246            .into(),
1247            version: rsipstack::rsip::Version::V2,
1248            body: vec![],
1249        };
1250
1251        let (state_sender, _state_receiver) = tokio::sync::mpsc::unbounded_channel();
1252        let (tu_sender, _tu_receiver) = tokio::sync::mpsc::unbounded_channel();
1253        let inner = std::sync::Arc::new(
1254            DialogInner::new(
1255                TransactionRole::Server,
1256                dialog_id.clone(),
1257                initial_request,
1258                endpoint.inner.clone(),
1259                state_sender,
1260                None,
1261                None,
1262                tu_sender,
1263            )
1264            .expect("failed to create dialog inner"),
1265        );
1266        let dialog = InviteDialog::from_inner(inner);
1267
1268        assert!(
1269            invitation
1270                .find_dialog_id_by_session_id(&dialog_id.to_string())
1271                .is_none()
1272        );
1273
1274        invitation.add_pending(
1275            dialog_id.clone(),
1276            PendingDialog {
1277                token: tokio_util::sync::CancellationToken::new(),
1278                dialog,
1279                state_receiver: {
1280                    let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
1281                    rx
1282                },
1283            },
1284        );
1285
1286        assert_eq!(
1287            invitation
1288                .find_dialog_id_by_session_id(&dialog_id.to_string())
1289                .unwrap(),
1290            dialog_id
1291        );
1292    }
1293}