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                    // Blindly forward the REFER's custom headers onto the
550                    // transfer INVITE: INVITE-mode carriers (e.g. Aliyun CC)
551                    // attach routing data to the REFER (User-to-User,
552                    // X-ACC-Bizdata, X-AliyunIVR-*) and expect it to survive
553                    // the transfer hop. Protocol headers are typed (never
554                    // `Header::Other`), so collecting Other headers only is
555                    // inherently safe; User-to-User is added explicitly since
556                    // rsipstack types it; X-Referred-* are skipped because
557                    // do_refer regenerates them for the new hop.
558                    let mut extra_headers: HashMap<String, String> = req
559                        .headers
560                        .iter()
561                        .filter_map(|h| {
562                            if let rsipstack::rsip::Header::Other(name, value) = h {
563                                let name = name.to_string();
564                                if name.eq_ignore_ascii_case("X-Referred-To")
565                                    || name.eq_ignore_ascii_case("X-Referred-From")
566                                    || name.eq_ignore_ascii_case("X-Referred-Id")
567                                {
568                                    return None;
569                                }
570                                return Some((name, value.to_string()));
571                            }
572                            None
573                        })
574                        .collect();
575                    if let Some(user_to_user) = req.headers.iter().find_map(|h| {
576                        if let rsipstack::rsip::Header::UserToUser(h) = h {
577                            return Some(h.value().to_string());
578                        }
579                        None
580                    }) {
581                        extra_headers.insert("User-to-User".to_string(), user_to_user);
582                    }
583                    let extra_headers = (!extra_headers.is_empty()).then_some(extra_headers);
584                    info!(session_id = states.session_id, %dialog_id, %refer_to, "received REFER");
585                    tx_handle
586                        .reply(rsipstack::rsip::StatusCode::Other(202, "Accepted".into()))
587                        .await
588                        .ok();
589                    // RFC 3515: the 202 opens an implicit subscription; report
590                    // progress on the parent dialog. Whether the transfer is
591                    // actually attempted is decided by the call actor. The
592                    // Trying NOTIFY waits for the next Confirmed event — the
593                    // 202 itself flips the dialog back to confirmed, so this
594                    // is deterministic and free of state races.
595                    let notifier = Arc::new(ReferProgressNotifier::new(
596                        self.dialog_layer.clone(),
597                        dialog_id.clone(),
598                    ));
599                    states.pending_refer_notify = Some(notifier.clone());
600                    states
601                        .event_sender
602                        .send(crate::event::SessionEvent::TransferRequest {
603                            track_id: states.track_id.clone(),
604                            timestamp: crate::media::get_timestamp(),
605                            refer_to,
606                            referred_by,
607                            extra_headers,
608                            refer: Some(states.leg.is_refer),
609                            leg_session_id: Some(
610                                states.leg.progress.load_full().session_id.clone()
611                            ),
612                            notify: Some(notifier),
613                        })
614                        .ok();
615                }
616                DialogState::Notify(dialog_id, _req, tx_handle) => {
617                    info!(
618                        session_id = states.session_id,
619                        %dialog_id,
620                        "dialog notify received"
621                    );
622                    tx_handle.reply(rsipstack::rsip::StatusCode::OK).await.ok();
623                }
624                DialogState::Terminated(dialog_id, reason) => {
625                    info!(
626                        session_id = states.session_id,
627                        ?dialog_id,
628                        ?reason,
629                        "dialog terminated"
630                    );
631                    states.terminated_reason = Some(reason.clone());
632                    return Ok(());
633                }
634                other_state => {
635                    info!(
636                        session_id = states.session_id,
637                        %other_state,
638                        "dialog received other state"
639                    );
640                }
641            }
642        }
643        Ok(())
644    }
645
646    pub(super) async fn process_dialog(&mut self, mut states: InviteDialogStates) {
647        let token = states.cancel_token.clone();
648        tokio::select! {
649            _ = token.cancelled() => {
650                states.terminated_reason = Some(TerminatedReason::UacCancel);
651            }
652            _ = self.dialog_event_loop(&mut states) => {}
653        };
654
655        // Update hangup headers from the leg extras if available
656        let extras = states.leg.extras.load_full();
657        if let Some(headers) = crate::sip_util::hangup_headers_from_extras(&extras) {
658            match &mut self.hangup_headers {
659                Some(existing) => existing.extend(headers),
660                None => self.hangup_headers = Some(headers),
661            }
662        }
663
664        self.drop_async().await;
665    }
666}
667
668/// Apply a hold/resume transition to the media track and emit the Hold event.
669async fn apply_hold_state(states: &mut InviteDialogStates, is_on_hold: bool) {
670    if is_on_hold {
671        states
672            .media_stream
673            .hold_track(Some(states.track_id.clone()))
674            .await;
675    } else {
676        states
677            .media_stream
678            .resume_track(Some(states.track_id.clone()))
679            .await;
680    }
681    states
682        .event_sender
683        .send(crate::event::SessionEvent::Hold {
684            track_id: states.track_id.clone(),
685            timestamp: crate::media::get_timestamp(),
686            on_hold: is_on_hold,
687            refer: Some(states.leg.is_refer),
688        })
689        .ok();
690}
691
692#[derive(Clone)]
693pub struct Invitation {
694    pub dialog_layer: Arc<DialogLayer>,
695    pub pending_dialogs: Arc<std::sync::Mutex<HashMap<DialogId, PendingDialog>>>,
696    /// Maps the (short) public session id of an incoming call to the DialogId
697    /// captured when the INVITE arrived. Incoming sessions no longer reuse the
698    /// raw dialog-id string, so every session-id based lookup resolves here.
699    sessions: Arc<std::sync::Mutex<HashMap<String, DialogId>>>,
700}
701
702impl Invitation {
703    pub fn new(dialog_layer: Arc<DialogLayer>) -> Self {
704        Self {
705            dialog_layer,
706            pending_dialogs: Arc::new(std::sync::Mutex::new(HashMap::new())),
707            sessions: Arc::new(std::sync::Mutex::new(HashMap::new())),
708        }
709    }
710
711    pub fn register_session(&self, session_id: &str, dialog_id: &DialogId) {
712        self.sessions
713            .lock()
714            .map(|mut ss| ss.insert(session_id.to_string(), dialog_id.clone()))
715            .ok();
716    }
717
718    pub fn unregister_session(&self, session_id: &str) {
719        self.sessions
720            .lock()
721            .map(|mut ss| ss.remove(session_id))
722            .ok();
723    }
724
725    pub fn session_exists(&self, session_id: &str) -> bool {
726        self.sessions
727            .lock()
728            .map(|ss| ss.contains_key(session_id))
729            .unwrap_or(false)
730    }
731
732    pub fn add_pending(&self, dialog_id: DialogId, pending: PendingDialog) {
733        self.pending_dialogs
734            .lock()
735            .map(|mut ps| ps.insert(dialog_id, pending))
736            .ok();
737    }
738
739    pub fn get_pending_call(&self, dialog_id: &DialogId) -> Option<PendingDialog> {
740        self.pending_dialogs
741            .lock()
742            .ok()
743            .and_then(|mut ps| ps.remove(dialog_id))
744    }
745
746    pub fn has_pending_call(&self, dialog_id: &DialogId) -> bool {
747        self.pending_dialogs
748            .lock()
749            .ok()
750            .map(|ps| ps.contains_key(dialog_id))
751            .unwrap_or(false)
752    }
753
754    pub fn find_dialog_id_by_session_id(&self, session_id: &str) -> Option<DialogId> {
755        if let Some(id) = self
756            .sessions
757            .lock()
758            .ok()
759            .and_then(|ss| ss.get(session_id).cloned())
760        {
761            return Some(id);
762        }
763        self.pending_dialogs.lock().ok().and_then(|ps| {
764            ps.iter()
765                .find(|(id, _)| id.to_string() == session_id)
766                .map(|(id, _)| id.clone())
767        })
768    }
769
770    /// Reject a pending dialog or hang up an established one.
771    pub async fn hangup(
772        &self,
773        dialog_id: DialogId,
774        code: Option<rsipstack::rsip::StatusCode>,
775        reason: Option<String>,
776    ) -> Result<()> {
777        if let Some(call) = self.get_pending_call(&dialog_id) {
778            call.dialog.reject(code, reason).ok();
779        }
780        if let Some(dialog) = remove_dialog(&self.dialog_layer, &dialog_id) {
781            dialog.hangup().await.ok();
782        }
783        Ok(())
784    }
785
786    pub async fn invite(
787        &self,
788        invite_option: InviteOption,
789        state_sender: DialogStateSender,
790    ) -> Result<(DialogId, Option<Vec<u8>>), rsipstack::Error> {
791        let (dialog, resp) = self
792            .dialog_layer
793            .do_invite(invite_option, state_sender)
794            .await?;
795
796        let offer = match resp {
797            Some(resp) => match resp.status_code.kind() {
798                rsipstack::rsip::StatusCodeKind::Successful => {
799                    let offer = resp.body.clone();
800                    Some(offer)
801                }
802                _ => {
803                    let reason = resp
804                        .reason_phrase()
805                        .unwrap_or(&resp.status_code.to_string())
806                        .to_string();
807                    return Err(rsipstack::Error::DialogError(
808                        reason,
809                        dialog.id(),
810                        resp.status_code,
811                    ));
812                }
813            },
814            None => {
815                return Err(rsipstack::Error::DialogError(
816                    "no response received".to_string(),
817                    dialog.id(),
818                    rsipstack::rsip::StatusCode::NotAcceptableHere,
819                ));
820            }
821        };
822        Ok((dialog.id(), offer))
823    }
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829    use crate::call::state::CallProgress;
830    use crate::media::stream::MediaStreamBuilder;
831
832    // SDP used to simulate an early-media 183 Session Progress response.
833    const EARLY_MEDIA_SDP: &str = "v=0\r\n\
834        o=- 1000 1 IN IP4 192.168.1.100\r\n\
835        s=SIP Call\r\n\
836        t=0 0\r\n\
837        m=audio 10000 RTP/AVP 0\r\n\
838        c=IN IP4 192.168.1.100\r\n\
839        a=rtpmap:0 PCMU/8000\r\n\
840        a=sendrecv\r\n";
841
842    fn make_states(has_early_media: bool) -> InviteDialogStates {
843        let (event_tx, _event_rx) = tokio::sync::broadcast::channel(16);
844        let media_stream = Arc::new(
845            MediaStreamBuilder::new(event_tx.clone())
846                .with_id("test-stream".to_string())
847                .build(),
848        );
849        let cancel_token = CancellationToken::new();
850        let leg = LegShared::new(1000, true, CallProgress::default());
851
852        InviteDialogStates {
853            is_client: true,
854            session_id: "test-session".to_string(),
855            track_id: "test-track".to_string(),
856            cancel_token: cancel_token.clone(),
857            event_sender: event_tx.clone(),
858            leg,
859            media_stream,
860            terminated_reason: None,
861            has_early_media,
862            initial_confirmed: false,
863            hangup_reason: None,
864            pending_refer_notify: None,
865        }
866    }
867
868    /// Verify that when a 183 Session Progress with SDP arrives (`DialogState::Early`),
869    /// the early SDP is stored in the leg progress so it can serve as a fallback
870    /// when the final 200 OK has an empty body.
871    #[tokio::test]
872    async fn test_early_sdp_stored_in_leg_progress() {
873        let mut states = make_states(false);
874
875        // Simulate DialogState::Early with SDP body (183 Session Progress):
876        // same steps the Early branch performs.
877        let answer = EARLY_MEDIA_SDP.to_string();
878        let has_sdp = !answer.is_empty();
879        if states.is_client && has_sdp {
880            states.has_early_media = true;
881            states.leg.update_progress(|p| p.try_set_answer(&answer));
882        }
883
884        // Assert: early SDP is stored
885        let progress = states.leg.progress.load_full();
886        assert!(
887            progress.answer.is_some(),
888            "leg progress answer should be set after 183 with SDP"
889        );
890        assert_eq!(
891            progress.answer.as_deref().unwrap(),
892            EARLY_MEDIA_SDP,
893            "leg progress answer should contain the early SDP"
894        );
895        assert!(states.has_early_media, "has_early_media should be true");
896    }
897
898    /// Verify that when a 200 OK arrives with an empty body after early media has been
899    /// negotiated, the leg progress retains the early SDP (not overwritten with "").
900    ///
901    /// This is the regression test for the bug where a late 200 OK with empty body would
902    /// cause `SessionEvent::Answer { sdp: "" }` to be emitted, making the answer event
903    /// appear as if no SDP was negotiated.
904    #[tokio::test]
905    async fn test_confirmed_empty_body_keeps_early_sdp() {
906        let mut states = make_states(false);
907
908        // Step 1: simulate 183 with SDP → set has_early_media and progress answer
909        states.has_early_media = true;
910        states
911            .leg
912            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
913
914        // Step 2: simulate 200 OK with empty body (Confirmed handler logic)
915        states
916            .leg
917            .update_progress(|p| p.on_confirmed("dialog-1".to_string()));
918        // The Confirmed handler only calls update_remote_description when the body
919        // is non-empty; it does NOT overwrite the progress answer.
920        let confirmed_answer = String::new();
921        assert!(
922            confirmed_answer.trim().is_empty(),
923            "empty body must not be applied"
924        );
925
926        // Assert: leg progress still holds the early SDP
927        let progress = states.leg.progress.load_full();
928        assert!(
929            progress.answer.is_some(),
930            "answer must not be None after 200 OK with empty body"
931        );
932        let stored_answer = progress.answer.as_deref().unwrap();
933        assert!(
934            !stored_answer.is_empty(),
935            "answer must not be empty after 200 OK with empty body"
936        );
937        assert_eq!(
938            stored_answer, EARLY_MEDIA_SDP,
939            "answer should still be the early SDP after 200 OK with empty body"
940        );
941    }
942
943    /// Verify that `create_outgoing_sip_track`'s fallback logic works:
944    /// when the 200 OK body is empty but the leg progress has the early SDP,
945    /// the fallback path is taken and the early SDP is returned (not an empty string).
946    #[tokio::test]
947    async fn test_answer_fallback_to_early_sdp_when_200ok_empty() {
948        // Simulate what the Early (183) handler does: store the early SDP.
949        let states = make_states(true);
950        states
951            .leg
952            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
953
954        // Simulate what create_outgoing_sip_track does when 200 OK has empty body.
955        let early = states.leg.progress.load_full().answer.clone();
956        let raw_answer: Option<Vec<u8>> = Some(vec![]); // empty body from 200 OK
957
958        let (answer, already_applied) =
959            crate::call::state::resolve_final_answer(raw_answer, early.as_ref()).unwrap();
960
961        // The answer returned to setup_caller_track (and used in SessionEvent::Answer)
962        // must be the early SDP, not an empty string.
963        assert!(
964            !answer.is_empty(),
965            "Resolved answer must not be empty — should contain the early SDP"
966        );
967        assert_eq!(
968            answer, EARLY_MEDIA_SDP,
969            "Resolved answer should be the early SDP from the 183 handler"
970        );
971        assert!(
972            already_applied,
973            "remote_description_already_applied should be true when using early SDP fallback"
974        );
975    }
976
977    /// Verify the normal case: when 200 OK carries its own SDP body,
978    /// that SDP is used directly (not the early SDP) and remote description
979    /// should be applied.
980    #[tokio::test]
981    async fn test_answer_uses_200ok_sdp_when_present() {
982        const FINAL_SDP: &str = "v=0\r\n\
983            o=- 2000 2 IN IP4 10.0.0.1\r\n\
984            s=SIP Call\r\n\
985            t=0 0\r\n\
986            m=audio 20000 RTP/AVP 0\r\n\
987            c=IN IP4 10.0.0.1\r\n\
988            a=rtpmap:0 PCMU/8000\r\n\
989            a=sendrecv\r\n";
990
991        let states = make_states(true);
992        states
993            .leg
994            .update_progress(|p| p.try_set_answer(EARLY_MEDIA_SDP));
995
996        let early = states.leg.progress.load_full().answer.clone();
997        let (answer, already_applied) = crate::call::state::resolve_final_answer(
998            Some(FINAL_SDP.as_bytes().to_vec()),
999            early.as_ref(),
1000        )
1001        .unwrap();
1002
1003        assert_eq!(
1004            answer, FINAL_SDP,
1005            "When 200 OK has SDP, it should be used (not the early SDP)"
1006        );
1007        assert!(
1008            !already_applied,
1009            "remote_description_already_applied should be false when 200 OK has SDP body"
1010        );
1011    }
1012
1013    /// Regression: `on_terminated` runs in a synchronous `Drop` context.
1014    /// The old implementation used `try_write` and silently dropped the
1015    /// status/reason updates AND the TrackEnd/Hangup events when the lock was
1016    /// contended. The lock-free (ArcSwap) implementation must always emit both
1017    /// events and record the termination, even while another task keeps
1018    /// mutating the progress concurrently.
1019    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1020    async fn test_on_terminated_always_emits_events_and_records_state() {
1021        use crate::event::SessionEvent;
1022        use std::sync::atomic::{AtomicBool, Ordering};
1023
1024        let mut states = make_states(false);
1025        states.terminated_reason = Some(TerminatedReason::UacCancel);
1026        let leg = states.leg.clone();
1027        let event_sender = states.event_sender.clone();
1028        let mut event_receiver = event_sender.subscribe();
1029
1030        // Hammer the progress concurrently, as a busy actor would.
1031        let stop = Arc::new(AtomicBool::new(false));
1032        let stop2 = stop.clone();
1033        let progress = leg.progress.clone();
1034        let writer = crate::spawn(async move {
1035            while !stop2.load(Ordering::Relaxed) {
1036                // Touch unrelated fields, like a busy actor would (never the
1037                // termination fields), so writers don't clobber each other.
1038                progress.rcu(|p| {
1039                    let mut p = CallProgress::clone(p);
1040                    p.answer_time.get_or_insert_with(chrono::Utc::now);
1041                    p
1042                });
1043                tokio::task::yield_now().await;
1044            }
1045        });
1046
1047        // Give the writer a moment to start contending.
1048        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1049
1050        // Synchronous drop, exactly like the real dialog task teardown.
1051        drop(states);
1052
1053        stop.store(true, Ordering::Relaxed);
1054        let _ = writer.await;
1055
1056        // Both events must have been emitted despite the concurrent writer.
1057        let mut saw_track_end = false;
1058        let mut saw_hangup = false;
1059        while let Ok(event) = event_receiver.try_recv() {
1060            match event {
1061                SessionEvent::TrackEnd { .. } => saw_track_end = true,
1062                SessionEvent::Hangup { refer, .. } => {
1063                    assert_eq!(refer, Some(true), "refer flag comes from the leg");
1064                    saw_hangup = true;
1065                }
1066                _ => {}
1067            }
1068        }
1069        assert!(
1070            saw_track_end,
1071            "TrackEnd must be emitted from on_terminated even under contention"
1072        );
1073        assert!(
1074            saw_hangup,
1075            "Hangup must be emitted from on_terminated even under contention"
1076        );
1077
1078        // The termination must be recorded (487 for UacCancel); the concurrent
1079        // writer only ever writes 100, so observing 487 proves the rcu landed.
1080        let progress = leg.progress.load_full();
1081        assert_eq!(progress.last_status_code, 487);
1082        assert_eq!(
1083            progress.hangup_reason,
1084            Some(crate::callrecord::CallRecordHangupReason::Canceled)
1085        );
1086    }
1087
1088    /// A minimal counting track that records how many times its remote
1089    /// description was (force-)updated, without touching any real media.
1090    struct CountingTrack {
1091        id: TrackId,
1092        config: crate::media::track::TrackConfig,
1093        processor_chain: crate::media::processor::ProcessorChain,
1094        updates: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1095    }
1096
1097    #[async_trait::async_trait]
1098    impl crate::media::track::Track for CountingTrack {
1099        fn ssrc(&self) -> u32 {
1100            0
1101        }
1102        fn id(&self) -> &TrackId {
1103            &self.id
1104        }
1105        fn config(&self) -> &crate::media::track::TrackConfig {
1106            &self.config
1107        }
1108        fn processor_chain(&mut self) -> &mut crate::media::processor::ProcessorChain {
1109            &mut self.processor_chain
1110        }
1111        async fn handshake(
1112            &mut self,
1113            _offer: String,
1114            _timeout: Option<tokio::time::Duration>,
1115        ) -> Result<String> {
1116            Ok(String::new())
1117        }
1118        async fn update_remote_description(&mut self, _answer: &String) -> Result<()> {
1119            self.updates
1120                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1121            Ok(())
1122        }
1123        async fn update_remote_description_force(&mut self, _answer: &String) -> Result<()> {
1124            self.updates
1125                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1126            Ok(())
1127        }
1128        async fn start(
1129            &mut self,
1130            _event_sender: EventSender,
1131            _packet_sender: crate::media::track::TrackPacketSender,
1132        ) -> Result<()> {
1133            Ok(())
1134        }
1135        async fn stop(&self) -> Result<()> {
1136            Ok(())
1137        }
1138        async fn send_packet(&mut self, _packet: &crate::media::AudioFrame) -> Result<()> {
1139            Ok(())
1140        }
1141    }
1142
1143    /// Regression: a client dialog must apply its remote SDP answer exactly
1144    /// once. The `initial_confirmed` guard exists because the final `Confirmed`
1145    /// event fires both when the 200 OK is processed *and* again when the ACK
1146    /// for the re-INVITE completes; without the guard the answer would be
1147    /// re-applied (and a duplicate `TrackStart`/`SessionEvent::Answer` emitted).
1148    #[tokio::test]
1149    async fn test_confirmed_applies_remote_answer_only_once() {
1150        let mut states = make_states(false);
1151
1152        let updates = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1153        let track = CountingTrack {
1154            id: states.track_id.clone(),
1155            config: crate::media::track::TrackConfig::default(),
1156            processor_chain: crate::media::processor::ProcessorChain::new(16000),
1157            updates: updates.clone(),
1158        };
1159        states
1160            .media_stream
1161            .update_track(Box::new(track), None)
1162            .await;
1163
1164        let endpoint = {
1165            let mut builder = rsipstack::EndpointBuilder::new();
1166            builder.build()
1167        };
1168        let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
1169
1170        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<DialogState>();
1171        let mut guard = DialogStateReceiverGuard::new(dialog_layer, rx, None);
1172
1173        let dialog_id = DialogId {
1174            call_id: "test-call-id".to_string(),
1175            local_tag: "test-local-tag".to_string(),
1176            remote_tag: "test-remote-tag".to_string(),
1177        };
1178
1179        let mut resp = rsipstack::rsip::Response::default();
1180        resp.body = EARLY_MEDIA_SDP.as_bytes().to_vec();
1181
1182        // Two Confirmed events (200 OK + re-INVITE ACK) must only apply once.
1183        tx.send(DialogState::Confirmed(dialog_id.clone(), resp.clone()))
1184            .unwrap();
1185        tx.send(DialogState::Confirmed(dialog_id, resp)).unwrap();
1186        drop(tx);
1187
1188        guard
1189            .dialog_event_loop(&mut states)
1190            .await
1191            .expect("dialog event loop must complete");
1192
1193        assert_eq!(
1194            updates.load(std::sync::atomic::Ordering::SeqCst),
1195            1,
1196            "remote answer must be applied exactly once, not on the re-INVITE ACK Confirmed event"
1197        );
1198    }
1199
1200    #[test]
1201    fn test_session_map_register_find_unregister() {
1202        let endpoint = {
1203            let mut builder = rsipstack::EndpointBuilder::new();
1204            builder.build()
1205        };
1206        let invitation = Invitation::new(Arc::new(DialogLayer::new(endpoint.inner.clone())));
1207
1208        let dialog_id = DialogId {
1209            call_id: "long-call-id-from-carrier".to_string(),
1210            local_tag: String::new(),
1211            remote_tag: "remote-tag".to_string(),
1212        };
1213
1214        assert!(!invitation.session_exists("s.3f9a2b1c4d5e"));
1215        assert!(
1216            invitation
1217                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1218                .is_none()
1219        );
1220
1221        invitation.register_session("s.3f9a2b1c4d5e", &dialog_id);
1222        assert!(invitation.session_exists("s.3f9a2b1c4d5e"));
1223        assert_eq!(
1224            invitation
1225                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1226                .unwrap(),
1227            dialog_id
1228        );
1229
1230        invitation.unregister_session("s.3f9a2b1c4d5e");
1231        assert!(!invitation.session_exists("s.3f9a2b1c4d5e"));
1232        assert!(
1233            invitation
1234                .find_dialog_id_by_session_id("s.3f9a2b1c4d5e")
1235                .is_none()
1236        );
1237        // Unregistering an unknown session is a no-op.
1238        invitation.unregister_session("s.unknown");
1239    }
1240
1241    /// The legacy fallback must keep resolving session ids that match a pending
1242    /// dialog's dialog-id string (e.g. sessions registered before the mapping
1243    /// table existed, or callers still using the raw dialog id).
1244    #[test]
1245    fn test_find_dialog_id_falls_back_to_pending_scan() {
1246        use rsipstack::dialog::dialog::DialogInner;
1247        use rsipstack::dialog::invite_dialog::InviteDialog;
1248        use rsipstack::rsip::typed::{CSeq, Contact, From, To, Via};
1249        use rsipstack::rsip::{Header, Request};
1250        use rsipstack::transaction::key::TransactionRole;
1251
1252        let endpoint = {
1253            let mut builder = rsipstack::EndpointBuilder::new();
1254            builder.build()
1255        };
1256        let invitation = Invitation::new(Arc::new(DialogLayer::new(endpoint.inner.clone())));
1257
1258        let dialog_id = DialogId {
1259            call_id: "legacy-call-id".to_string(),
1260            local_tag: String::new(),
1261            remote_tag: "remote-tag".to_string(),
1262        };
1263
1264        let initial_request = Request {
1265            method: rsipstack::rsip::Method::Invite,
1266            uri: rsipstack::rsip::Uri::try_from("sip:bob@example.com:5060").unwrap(),
1267            headers: vec![
1268                Via::parse("SIP/2.0/UDP alice.example.com:5060;branch=z9hG4bKnashds")
1269                    .unwrap()
1270                    .into(),
1271                CSeq::parse("1 INVITE").unwrap().into(),
1272                From::parse("Alice <sip:alice@example.com>;tag=remote-tag")
1273                    .unwrap()
1274                    .into(),
1275                To::parse("Bob <sip:bob@example.com>").unwrap().into(),
1276                Header::CallId("legacy-call-id".into()),
1277                Contact::parse("<sip:alice@alice.example.com:5060>")
1278                    .unwrap()
1279                    .into(),
1280                Header::MaxForwards("70".into()),
1281            ]
1282            .into(),
1283            version: rsipstack::rsip::Version::V2,
1284            body: vec![],
1285        };
1286
1287        let (state_sender, _state_receiver) = tokio::sync::mpsc::unbounded_channel();
1288        let (tu_sender, _tu_receiver) = tokio::sync::mpsc::unbounded_channel();
1289        let inner = std::sync::Arc::new(
1290            DialogInner::new(
1291                TransactionRole::Server,
1292                dialog_id.clone(),
1293                initial_request,
1294                endpoint.inner.clone(),
1295                state_sender,
1296                None,
1297                None,
1298                tu_sender,
1299            )
1300            .expect("failed to create dialog inner"),
1301        );
1302        let dialog = InviteDialog::from_inner(inner);
1303
1304        assert!(
1305            invitation
1306                .find_dialog_id_by_session_id(&dialog_id.to_string())
1307                .is_none()
1308        );
1309
1310        invitation.add_pending(
1311            dialog_id.clone(),
1312            PendingDialog {
1313                token: tokio_util::sync::CancellationToken::new(),
1314                dialog,
1315                state_receiver: {
1316                    let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
1317                    rx
1318                },
1319            },
1320        );
1321
1322        assert_eq!(
1323            invitation
1324                .find_dialog_id_by_session_id(&dialog_id.to_string())
1325                .unwrap(),
1326            dialog_id
1327        );
1328    }
1329}