Skip to main content

gemini_adk_fluent_rs/telephony/
sip.rs

1//! In-process SIP — answer raw SIP calls with no carrier service in the path.
2//!
3//! *(feature `sip`)* Where [`super::twilio`] relies on a carrier
4//! service to terminate the phone network and hand audio over a WebSocket,
5//! this module terminates the call itself: SIP signalling via
6//! [`rsipstack`](https://docs.rs/rsipstack) (the stack underneath the
7//! `rustpbx` PBX), and G.711-over-RTP media built from this crate's own pure
8//! layers ([`super::rtp`], [`super::sdp`], [`super::g711`]).
9//! Any SIP endpoint — a softphone, an Asterisk/FreeSWITCH PBX, a provider's
10//! SIP trunk — dials the agent directly, and each call attaches to a Live
11//! session through the same [`voice::pump`](crate::voice::pump) as every
12//! other audio surface.
13//!
14//! ```ignore
15//! // `ignore`: `SipAgent` needs the `sip` feature and a bound UDP socket.
16//! let mut agent = SipAgent::bind("0.0.0.0:5060".parse()?).await?;
17//! while let Some(incoming) = agent.next_call().await {
18//!     let session = Live::builder()
19//!         .instruction("Answer the phone politely.")
20//!         .greeting("Greet the caller.")
21//!         .connect_from_env().await?;
22//!     let call = incoming.answer(&session).await?;
23//!     tokio::spawn(async move { call.ended().await; });
24//! }
25//! ```
26//!
27//! RFC 4733 telephone events (DTMF) are negotiated in the SDP answer when
28//! the offer proposes them; keypresses land in session state under the
29//! shared [`super::bridge`] keys, where flow guards read them —
30//! identical to the Twilio path. An `RTP/SAVP` offer with SDES keys is
31//! answered with SRTP ([`super::srtp`]), and [`SipAgent::register`] registers
32//! the agent with a PBX or trunk so it can be reached by address. Media is
33//! symmetric RTP: the agent sends to the offer's address but re-latches onto
34//! the source of the first arriving packet, which keeps NATted softphones
35//! working.
36
37use std::net::{IpAddr, SocketAddr};
38use std::sync::Arc;
39use std::time::Duration;
40
41use tokio::net::UdpSocket;
42use tokio::sync::{mpsc, watch};
43use tokio::task::JoinHandle;
44use tokio_util::sync::CancellationToken;
45
46use rsipstack::EndpointBuilder;
47use rsipstack::dialog::dialog::DialogState;
48use rsipstack::dialog::dialog_layer::DialogLayer;
49use rsipstack::dialog::invite_dialog::InviteDialog;
50use rsipstack::transport::TransportLayer;
51use rsipstack::transport::udp::UdpConnection;
52
53use gemini_adk_rs::State;
54use gemini_adk_rs::live::LiveHandle;
55
56use super::bridge::{self, DtmfDeduper, FillerConfig};
57use super::g711;
58use super::rtp::{self, PT_PCMA, RtpSender, SAMPLES_PER_PACKET};
59use super::sdp::{self, AudioOffer};
60use super::srtp::{CryptoAttribute, MasterKey, SrtpSession};
61use crate::voice::{Playback, VoicePump, pump};
62
63/// Errors from the SIP agent.
64#[derive(Debug)]
65pub enum SipError {
66    /// Binding or socket I/O failed.
67    Io(std::io::Error),
68    /// The SIP stack reported an error (boxed: it is large).
69    Sip(Box<rsipstack::Error>),
70    /// The INVITE carried no answerable audio offer (no `m=audio`, port 0).
71    NoAudioOffer,
72    /// The offer had audio but no G.711 codec this agent can speak.
73    NoCommonCodec,
74    /// The offer asked for SRTP with no crypto suite this agent supports.
75    NoCommonCrypto,
76    /// The registrar refused the registration (its final status code).
77    RegistrationRejected(u16),
78    /// A registrar or contact URI did not parse.
79    InvalidUri(String),
80}
81
82impl std::fmt::Display for SipError {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        match self {
85            Self::Io(e) => write!(f, "sip io error: {e}"),
86            Self::Sip(e) => write!(f, "sip stack error: {e:?}"),
87            Self::NoAudioOffer => write!(f, "INVITE carried no answerable audio offer"),
88            Self::NoCommonCodec => write!(f, "no common G.711 codec with the caller"),
89            Self::NoCommonCrypto => write!(f, "no common SRTP crypto suite with the caller"),
90            Self::RegistrationRejected(code) => {
91                write!(f, "registrar refused the registration: {code}")
92            }
93            Self::InvalidUri(uri) => write!(f, "invalid SIP URI: {uri}"),
94        }
95    }
96}
97
98impl std::error::Error for SipError {}
99
100impl From<std::io::Error> for SipError {
101    fn from(e: std::io::Error) -> Self {
102        Self::Io(e)
103    }
104}
105
106impl From<rsipstack::Error> for SipError {
107    fn from(e: rsipstack::Error) -> Self {
108        Self::Sip(Box::new(e))
109    }
110}
111
112// ── Agent ────────────────────────────────────────────────────────────────────
113
114/// A SIP user agent server: binds a UDP SIP port and yields incoming calls.
115pub struct SipAgent {
116    dialog_layer: Arc<DialogLayer>,
117    incoming: rsipstack::transaction::TransactionReceiver,
118    cancel: CancellationToken,
119    local_ip: IpAddr,
120    sip_port: u16,
121}
122
123impl SipAgent {
124    /// Bind the SIP signalling port (conventionally 5060/udp) and start the
125    /// endpoint's serve loop in the background.
126    pub async fn bind(addr: SocketAddr) -> Result<SipAgent, SipError> {
127        let cancel = CancellationToken::new();
128        let transport_layer = TransportLayer::new(cancel.child_token());
129        let udp = UdpConnection::create_connection(addr, None, Some(cancel.child_token()))
130            .await
131            .map_err(SipError::from)?;
132        let sip_port = udp
133            .get_addr()
134            .addr
135            .port
136            .as_ref()
137            .map(|p| u16::from(*p))
138            .unwrap_or(addr.port());
139        transport_layer.add_transport(udp.into());
140
141        let endpoint = EndpointBuilder::new()
142            .with_user_agent("gemini-rs")
143            .with_cancel_token(cancel.child_token())
144            .with_transport_layer(transport_layer)
145            .build();
146        // Endpoint::serve owns listener startup in rsipstack. Starting
147        // listeners separately would race the endpoint's transport receiver.
148        let inner = endpoint.inner.clone();
149        tokio::spawn(async move {
150            let _ = inner.serve().await;
151        });
152
153        let incoming = endpoint.incoming_transactions().map_err(SipError::from)?;
154        let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
155
156        Ok(SipAgent {
157            dialog_layer,
158            incoming,
159            cancel,
160            local_ip: addr.ip(),
161            sip_port,
162        })
163    }
164
165    /// Wait for the next incoming call. In-dialog requests (BYE, re-INVITE,
166    /// ACK) and non-call methods are handled internally; only new INVITEs
167    /// surface. Returns `None` once the agent is shut down.
168    pub async fn next_call(&mut self) -> Option<IncomingCall> {
169        loop {
170            let mut tx = tokio::select! {
171                _ = self.cancel.cancelled() => return None,
172                tx = self.incoming.recv() => tx?,
173            };
174            use rsipstack::rsip::{Method, StatusCode};
175            match &tx.original.method {
176                Method::Invite => {
177                    let offer = match sdp::parse_audio_offer(
178                        String::from_utf8_lossy(&tx.original.body).as_ref(),
179                    ) {
180                        Some(offer) => offer,
181                        None => {
182                            let _ = tx.reply(StatusCode::NotAcceptableHere).await;
183                            continue;
184                        }
185                    };
186                    let (state_tx, state_rx) = mpsc::unbounded_channel();
187                    let contact = format!(
188                        "sip:gemini@{}:{};transport=udp",
189                        advertised_ip(self.local_ip, &offer),
190                        self.sip_port
191                    );
192                    let contact = match rsipstack::rsip::Uri::try_from(contact.as_str()) {
193                        Ok(uri) => uri,
194                        Err(_) => {
195                            let _ = tx.reply(StatusCode::ServerInternalError).await;
196                            continue;
197                        }
198                    };
199                    let dialog = match self.dialog_layer.get_or_create_server_invite(
200                        &tx,
201                        state_tx,
202                        None,
203                        Some(contact),
204                    ) {
205                        Ok(dialog) => dialog,
206                        Err(err) => {
207                            tracing::warn!("rejecting INVITE: {err:?}");
208                            let _ = tx.reply(StatusCode::ServerInternalError).await;
209                            continue;
210                        }
211                    };
212                    use rsipstack::rsip::HeadersExt as _;
213                    let from = tx
214                        .original
215                        .from_header()
216                        .map(std::string::ToString::to_string)
217                        .unwrap_or_default();
218                    let _ = dialog.ringing(None, None);
219                    // Responses (180/200/603) are queued events on the INVITE
220                    // transaction. The dialog's handler pumps them onto the
221                    // wire and processes ACK/CANCEL into dialog state changes.
222                    let mut handler = dialog.clone();
223                    let stop = self.cancel.clone();
224                    tokio::spawn(async move {
225                        tokio::select! {
226                            _ = stop.cancelled() => {}
227                            _ = handler.handle(&mut tx) => {}
228                        }
229                    });
230                    return Some(IncomingCall {
231                        dialog,
232                        state_rx,
233                        offer,
234                        from,
235                        local_ip: self.local_ip,
236                        dialog_layer: self.dialog_layer.clone(),
237                        filler: None,
238                        cancel: self.cancel.child_token(),
239                    });
240                }
241                Method::Ack | Method::Bye | Method::Cancel | Method::Info | Method::Update => {
242                    // In-dialog requests: route to the owning dialog.
243                    match self.dialog_layer.match_dialog(&tx) {
244                        Some(mut dialog) => {
245                            tokio::spawn(async move {
246                                let _ = dialog.handle(&mut tx).await;
247                            });
248                        }
249                        None => {
250                            let _ = tx.reply(StatusCode::CallTransactionDoesNotExist).await;
251                        }
252                    }
253                }
254                Method::Options => {
255                    let _ = tx.reply(StatusCode::OK).await;
256                }
257                _ => {
258                    let _ = tx.reply(StatusCode::MethodNotAllowed).await;
259                }
260            }
261        }
262    }
263
264    /// The SIP port actually bound (useful with port 0).
265    pub fn sip_port(&self) -> u16 {
266        self.sip_port
267    }
268
269    /// Stop the endpoint and every call it produced.
270    pub fn shutdown(&self) {
271        self.cancel.cancel();
272    }
273
274    /// Register this agent with a registrar, so calls to the account's
275    /// address reach it.
276    ///
277    /// The first REGISTER (answering a digest challenge with the account's
278    /// credentials) happens before this returns, so a wrong password or an
279    /// unreachable registrar fails here. After that, the returned
280    /// [`SipRegistration`] refreshes the binding at three quarters of the
281    /// granted lifetime, and retries after a failure, until it is
282    /// [unregistered](SipRegistration::unregister) or the agent shuts down.
283    ///
284    /// ```ignore
285    /// let agent = SipAgent::bind("0.0.0.0:5060".parse()?).await?;
286    /// let registration = agent
287    ///     .register(SipAccount::new("sip:pbx.example.com", "agent", "secret"))
288    ///     .await?;
289    /// // ... take calls with agent.next_call() ...
290    /// registration.unregister().await?;
291    /// ```
292    pub async fn register(&self, account: SipAccount) -> Result<SipRegistration, SipError> {
293        use rsipstack::dialog::authenticate::Credential;
294        use rsipstack::dialog::registration::Registration;
295
296        let registrar = rsipstack::rsip::Uri::try_from(account.registrar.as_str())
297            .map_err(|_| SipError::InvalidUri(account.registrar.clone()))?;
298        let mut registration = Registration::new(
299            self.dialog_layer.endpoint.clone(),
300            Some(Credential {
301                username: account.username.clone(),
302                password: account.password.clone(),
303                realm: account.realm.clone(),
304                auth_username: None,
305            }),
306        );
307        if let Some(contact) = &account.contact {
308            let uri = rsipstack::rsip::Uri::try_from(contact.as_str())
309                .map_err(|_| SipError::InvalidUri(contact.clone()))?;
310            registration.contact = Some(rsipstack::rsip::typed::Contact {
311                display_name: None,
312                uri,
313                params: vec![],
314            });
315        }
316
317        let requested = account.expires;
318        let granted = register_once(&mut registration, &registrar, requested).await?;
319        let (state_tx, state_rx) =
320            watch::channel(RegistrationState::Registered { expires: granted });
321        let cancel = self.cancel.child_token();
322        let stop = cancel.clone();
323        let task = tokio::spawn(async move {
324            let mut next = refresh_after(granted);
325            loop {
326                tokio::select! {
327                    _ = stop.cancelled() => break,
328                    _ = tokio::time::sleep(next) => {}
329                }
330                match register_once(&mut registration, &registrar, requested).await {
331                    Ok(granted) => {
332                        next = refresh_after(granted);
333                        let _ = state_tx.send(RegistrationState::Registered { expires: granted });
334                    }
335                    Err(error) => {
336                        tracing::warn!("SIP re-registration failed: {error}");
337                        next = RETRY_AFTER;
338                        let _ = state_tx.send(RegistrationState::Retrying {
339                            error: error.to_string(),
340                        });
341                    }
342                }
343            }
344            // Remove the binding, unless the endpoint itself is gone.
345            let removed = tokio::time::timeout(
346                UNREGISTER_TIMEOUT,
347                register_once(&mut registration, &registrar, Duration::ZERO),
348            )
349            .await
350            .unwrap_or_else(|_| Err(SipError::Io(std::io::ErrorKind::TimedOut.into())));
351            let _ = state_tx.send(RegistrationState::Unregistered);
352            removed.map(|_| ())
353        });
354        Ok(SipRegistration {
355            state: state_rx,
356            cancel: cancel.drop_guard(),
357            task,
358        })
359    }
360}
361
362// ── Registration ─────────────────────────────────────────────────────────────
363
364/// How long after a failed refresh to try again.
365const RETRY_AFTER: Duration = Duration::from_secs(30);
366/// How long un-registering may take before it is abandoned.
367const UNREGISTER_TIMEOUT: Duration = Duration::from_secs(5);
368
369/// A SIP account on a registrar (a PBX or a SIP trunk provider).
370#[derive(Clone)]
371pub struct SipAccount {
372    /// The registrar's URI, e.g. `sip:pbx.example.com`.
373    pub registrar: String,
374    /// The account's user name, also the user part of the registered address.
375    pub username: String,
376    /// The account's password, for digest authentication.
377    pub password: String,
378    /// The authentication realm, when the registrar needs it named.
379    pub realm: Option<String>,
380    /// The Contact URI to register. By default it is built from the agent's
381    /// address, corrected by the address the registrar reports seeing
382    /// (`received`/`rport`), which keeps an agent behind NAT reachable.
383    pub contact: Option<String>,
384    /// The binding lifetime to ask for (the registrar may grant less).
385    pub expires: Duration,
386}
387
388impl SipAccount {
389    /// An account with a one-hour binding.
390    pub fn new(
391        registrar: impl Into<String>,
392        username: impl Into<String>,
393        password: impl Into<String>,
394    ) -> Self {
395        Self {
396            registrar: registrar.into(),
397            username: username.into(),
398            password: password.into(),
399            realm: None,
400            contact: None,
401            expires: Duration::from_secs(3600),
402        }
403    }
404
405    /// Name the authentication realm.
406    pub fn realm(mut self, realm: impl Into<String>) -> Self {
407        self.realm = Some(realm.into());
408        self
409    }
410
411    /// Register this Contact URI instead of the derived one.
412    pub fn contact(mut self, contact: impl Into<String>) -> Self {
413        self.contact = Some(contact.into());
414        self
415    }
416
417    /// Ask for a binding lifetime (rounded down to whole seconds).
418    pub fn expires(mut self, expires: Duration) -> Self {
419        self.expires = expires;
420        self
421    }
422}
423
424impl std::fmt::Debug for SipAccount {
425    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426        f.debug_struct("SipAccount")
427            .field("registrar", &self.registrar)
428            .field("username", &self.username)
429            .field("password", &"[redacted]")
430            .field("realm", &self.realm)
431            .field("contact", &self.contact)
432            .field("expires", &self.expires)
433            .finish()
434    }
435}
436
437/// Where a [`SipRegistration`] stands.
438#[derive(Debug, Clone, PartialEq, Eq)]
439#[non_exhaustive]
440pub enum RegistrationState {
441    /// The registrar holds a binding for this long from the last refresh.
442    Registered {
443        /// The lifetime the registrar granted.
444        expires: Duration,
445    },
446    /// The last refresh failed; it is retried shortly. The previous binding
447    /// may still be live until it expires.
448    Retrying {
449        /// Why the refresh failed.
450        error: String,
451    },
452    /// The binding was removed, or the agent shut down.
453    Unregistered,
454}
455
456/// A live registration, kept fresh in the background. See
457/// [`SipAgent::register`].
458pub struct SipRegistration {
459    state: watch::Receiver<RegistrationState>,
460    // Dropped without `unregister`, the registration still stops refreshing
461    // and removes its binding, in the background.
462    cancel: tokio_util::sync::DropGuard,
463    task: JoinHandle<Result<(), SipError>>,
464}
465
466impl SipRegistration {
467    /// The registration's current state.
468    pub fn state(&self) -> RegistrationState {
469        self.state.borrow().clone()
470    }
471
472    /// A receiver that sees every state change, e.g. to alert when a refresh
473    /// starts failing.
474    pub fn watch(&self) -> watch::Receiver<RegistrationState> {
475        self.state.clone()
476    }
477
478    /// Stop refreshing and remove the binding from the registrar
479    /// (a REGISTER with a zero lifetime).
480    pub async fn unregister(self) -> Result<(), SipError> {
481        drop(self.cancel);
482        match self.task.await {
483            Ok(result) => result,
484            Err(_) => Ok(()),
485        }
486    }
487}
488
489/// One REGISTER exchange; the lifetime granted on success.
490async fn register_once(
491    registration: &mut rsipstack::dialog::registration::Registration,
492    registrar: &rsipstack::rsip::Uri,
493    expires: Duration,
494) -> Result<Duration, SipError> {
495    let requested = u32::try_from(expires.as_secs()).unwrap_or(u32::MAX);
496    let response = registration
497        .register(registrar.clone(), Some(requested))
498        .await?;
499    let code = u16::from(response.status_code.clone());
500    if !(200..300).contains(&code) {
501        return Err(SipError::RegistrationRejected(code));
502    }
503    Ok(granted_expires(&response).unwrap_or(expires))
504}
505
506/// The lifetime a 2xx to REGISTER grants: the `expires` parameter of the
507/// Contact, else the `Expires` header.
508fn granted_expires(response: &rsipstack::rsip::Response) -> Option<Duration> {
509    use rsipstack::rsip::Header;
510    let mut header = None;
511    for h in response.headers.iter() {
512        match h {
513            Header::Contact(contact) => {
514                let text = contact.to_string().to_ascii_lowercase();
515                if let Some(value) = text
516                    .split(';')
517                    .find_map(|p| p.trim().strip_prefix("expires="))
518                {
519                    let digits: String = value.chars().take_while(char::is_ascii_digit).collect();
520                    if let Ok(secs) = digits.parse() {
521                        return Some(Duration::from_secs(secs));
522                    }
523                }
524            }
525            Header::Expires(expires) => {
526                header = expires.value().trim().parse().ok().map(Duration::from_secs);
527            }
528            _ => {}
529        }
530    }
531    header
532}
533
534/// When to refresh a binding granted for `expires`: at three quarters of
535/// it, but not sooner than a few seconds.
536fn refresh_after(expires: Duration) -> Duration {
537    (expires * 3 / 4).max(Duration::from_secs(5))
538}
539
540// ── Incoming call ────────────────────────────────────────────────────────────
541
542/// A ringing inbound call: answer it onto a session, or reject it.
543pub struct IncomingCall {
544    dialog: InviteDialog,
545    state_rx: mpsc::UnboundedReceiver<DialogState>,
546    /// The caller's parsed audio offer.
547    pub offer: AudioOffer,
548    /// The caller's `From` header, for screening/logging.
549    pub from: String,
550    local_ip: IpAddr,
551    dialog_layer: Arc<DialogLayer>,
552    filler: Option<FillerConfig>,
553    cancel: CancellationToken,
554}
555
556impl IncomingCall {
557    /// Play a latency-masking filler clip when the model stays silent too
558    /// long after the caller stops speaking — see
559    /// [`bridge::spawn_latency_filler`]. The clip must be mono PCM16 at
560    /// 8 kHz (the call's playback rate).
561    pub fn filler(mut self, config: FillerConfig) -> Self {
562        self.filler = Some(config);
563        self
564    }
565
566    /// Answer the call onto a connected session: bind an RTP socket, send the
567    /// SDP answer in the 200 OK, and start the media loop.
568    ///
569    /// When the offer proposes RFC 4733 telephone events, the answer accepts
570    /// them and keypresses are written to session state via
571    /// [`bridge::record_dtmf`]. The caller's `From` identity lands under
572    /// [`bridge::KEY_CALLER`].
573    pub async fn answer(self, handle: &LiveHandle) -> Result<SipCall, SipError> {
574        let payload_type = self.offer.g711_payload_type().ok_or_else(|| {
575            let _ = self.dialog.reject(None, None);
576            SipError::NoCommonCodec
577        })?;
578
579        let media_ip = advertised_ip(self.local_ip, &self.offer);
580        let rtp_socket = UdpSocket::bind((self.local_ip, 0)).await?;
581        let rtp_port = rtp_socket.local_addr()?.port();
582        let remote: SocketAddr = format!("{}:{}", self.offer.host, self.offer.port)
583            .parse()
584            .map_err(|_| SipError::NoAudioOffer)?;
585
586        let telephone_event_pt = self.offer.telephone_event_pt;
587        let (answer, srtp) = if self.offer.secure {
588            // SRTP (SDES): decrypt with the caller's key, encrypt with ours,
589            // answering the first offered suite we support.
590            let Some(theirs) = self
591                .offer
592                .crypto
593                .iter()
594                .find_map(|c| CryptoAttribute::parse(c))
595            else {
596                let _ = self
597                    .dialog
598                    .reject(Some(rsipstack::rsip::StatusCode::NotAcceptableHere), None);
599                return Err(SipError::NoCommonCrypto);
600            };
601            let ours = CryptoAttribute {
602                tag: theirs.tag,
603                suite: theirs.suite,
604                key: MasterKey::generate()?,
605            };
606            let answer = sdp::secure_audio_answer(
607                seed() as u64,
608                &media_ip.to_string(),
609                rtp_port,
610                payload_type,
611                telephone_event_pt,
612                &ours.to_value(),
613            );
614            let srtp = SrtpPair {
615                inbound: SrtpSession::new(theirs.suite, &theirs.key),
616                outbound: SrtpSession::new(ours.suite, &ours.key),
617            };
618            (answer, Some(srtp))
619        } else {
620            let answer = sdp::audio_answer(
621                seed() as u64,
622                &media_ip.to_string(),
623                rtp_port,
624                payload_type,
625                telephone_event_pt,
626            );
627            (answer, None)
628        };
629        self.dialog
630            .accept(None, Some(answer.into_bytes()))
631            .map_err(SipError::from)?;
632        let _ = handle.state().set(bridge::KEY_CALLER, self.from.clone());
633
634        let cancel = self.cancel;
635        let media = rtp_media(
636            handle,
637            Arc::new(rtp_socket),
638            remote,
639            MediaFormat {
640                payload_type,
641                telephone_event_pt,
642            },
643            self.filler,
644            srtp,
645            cancel.clone(),
646        );
647
648        // Tear the media down when the dialog terminates (BYE, error).
649        let mut state_rx = self.state_rx;
650        let media_cancel = cancel.clone();
651        let dialog_id = self.dialog.id();
652        let dialog_layer = self.dialog_layer;
653        let ended = tokio::spawn(async move {
654            loop {
655                tokio::select! {
656                    _ = media_cancel.cancelled() => break,
657                    state = state_rx.recv() => {
658                        if matches!(state, None | Some(DialogState::Terminated(..))) {
659                            break;
660                        }
661                    }
662                }
663            }
664            media_cancel.cancel();
665            dialog_layer.remove_dialog(&dialog_id);
666        });
667
668        Ok(SipCall {
669            dialog: self.dialog,
670            media,
671            cancel,
672            ended,
673        })
674    }
675
676    /// Decline the call (486 Busy Here by default).
677    pub fn reject(self) {
678        let _ = self.dialog.reject(None, None);
679    }
680}
681
682// ── Live call ────────────────────────────────────────────────────────────────
683
684/// An answered SIP call with media flowing.
685pub struct SipCall {
686    dialog: InviteDialog,
687    media: MediaTasks,
688    cancel: CancellationToken,
689    ended: JoinHandle<()>,
690}
691
692impl SipCall {
693    /// Wait until the call ends (caller hung up, or [`hangup`](Self::hangup)).
694    pub async fn ended(self) {
695        let _ = self.ended.await;
696        self.media.stop().await;
697    }
698
699    /// Hang up: send BYE and stop the media loop.
700    pub async fn hangup(self) {
701        let _ = self.dialog.bye().await;
702        self.cancel.cancel();
703        let _ = self.ended.await;
704        self.media.stop().await;
705    }
706}
707
708// ── Media loop ───────────────────────────────────────────────────────────────
709
710struct MediaTasks {
711    pump: VoicePump,
712    inbound: JoinHandle<()>,
713    outbound: JoinHandle<()>,
714    filler: Option<JoinHandle<()>>,
715}
716
717impl MediaTasks {
718    async fn stop(self) {
719        self.inbound.abort();
720        self.outbound.abort();
721        if let Some(filler) = self.filler {
722            filler.abort();
723        }
724        self.pump.abort();
725        self.pump.join().await;
726    }
727}
728
729/// The negotiated payload types of a call.
730#[derive(Clone, Copy)]
731struct MediaFormat {
732    /// The G.711 codec.
733    payload_type: u8,
734    /// RFC 4733 telephone events, when negotiated.
735    telephone_event_pt: Option<u8>,
736}
737
738/// The two SRTP directions of a secure call.
739struct SrtpPair {
740    /// Keyed by the caller: unprotects what arrives.
741    inbound: SrtpSession,
742    /// Keyed by us: protects what we send.
743    outbound: SrtpSession,
744}
745
746/// Wire a session's voice pump to G.711-over-RTP on a UDP socket.
747///
748/// Symmetric RTP: packets go to `remote` until the first packet arrives,
749/// whose source address then becomes the send target (NAT re-latch).
750fn rtp_media(
751    handle: &LiveHandle,
752    socket: Arc<UdpSocket>,
753    remote: SocketAddr,
754    format: MediaFormat,
755    filler: Option<FillerConfig>,
756    srtp: Option<SrtpPair>,
757    cancel: CancellationToken,
758) -> MediaTasks {
759    let (srtp_in, srtp_out) = match srtp {
760        Some(pair) => (Some(pair.inbound), Some(pair.outbound)),
761        None => (None, None),
762    };
763    let (mic_tx, mic_rx) = mpsc::channel::<Vec<i16>>(64);
764    let (speaker_tx, speaker_rx) = mpsc::channel::<Playback>(64);
765    let voice_pump = pump(
766        handle,
767        mic_rx,
768        super::TWILIO_HZ,
769        speaker_tx.clone(),
770        super::TWILIO_HZ,
771    );
772    let (peer_tx, peer_rx) = watch::channel(remote);
773
774    let filler = filler.map(|config| bridge::spawn_latency_filler(handle, speaker_tx, config));
775
776    let inbound = tokio::spawn(inbound_loop(
777        socket.clone(),
778        format,
779        handle.state().clone(),
780        mic_tx,
781        peer_tx,
782        srtp_in,
783        cancel.clone(),
784    ));
785    let outbound = tokio::spawn(outbound_loop(
786        socket,
787        format.payload_type,
788        speaker_rx,
789        peer_rx,
790        srtp_out,
791        cancel,
792    ));
793
794    MediaTasks {
795        pump: voice_pump,
796        inbound,
797        outbound,
798        filler,
799    }
800}
801
802async fn inbound_loop(
803    socket: Arc<UdpSocket>,
804    format: MediaFormat,
805    state: State,
806    mic_tx: mpsc::Sender<Vec<i16>>,
807    peer_tx: watch::Sender<SocketAddr>,
808    mut srtp: Option<SrtpSession>,
809    cancel: CancellationToken,
810) {
811    let MediaFormat {
812        payload_type,
813        telephone_event_pt,
814    } = format;
815    let mut buf = [0u8; 2048];
816    let mut latched = false;
817    let mut dtmf = DtmfDeduper::default();
818    // Keypad tones stay away from the model; without RFC 4733 they are the
819    // only record of a keypress, so they are also counted.
820    let mut guard =
821        bridge::KeypadGuard::new(state.clone(), 8_000).record_in_band(telephone_event_pt.is_none());
822    loop {
823        let (len, source) = tokio::select! {
824            _ = cancel.cancelled() => break,
825            received = socket.recv_from(&mut buf) => match received {
826                Ok(pair) => pair,
827                Err(_) => break,
828            },
829        };
830        let decrypted;
831        let datagram = match srtp.as_mut() {
832            // A packet that fails authentication is dropped unread, and
833            // does not re-latch the peer address.
834            Some(srtp) => match srtp.unprotect(&buf[..len]) {
835                Ok(plain) => {
836                    decrypted = plain;
837                    &decrypted[..]
838                }
839                Err(_) => continue,
840            },
841            None => &buf[..len],
842        };
843        let Some(packet) = rtp::parse(datagram) else {
844            continue; // stray non-RTP traffic on the media port
845        };
846        if telephone_event_pt == Some(packet.payload_type) {
847            // RFC 4733 keypress: emit once per end-marked event.
848            if let Some(event) = rtp::parse_telephone_event(&packet.payload)
849                && dtmf.accept(event.end, packet.timestamp)
850                && let Some(digit) = event.digit()
851            {
852                bridge::record_dtmf(&state, digit);
853            }
854            continue;
855        }
856        if packet.payload_type != payload_type {
857            continue; // a payload type we did not negotiate
858        }
859        if !latched {
860            let _ = peer_tx.send(source);
861            latched = true;
862        }
863        let mut samples = if payload_type == PT_PCMA {
864            g711::decode_alaw(&packet.payload)
865        } else {
866            g711::decode_ulaw(&packet.payload)
867        };
868        crate::voice::InputAudioProcessor::process_frame(&mut guard, &mut samples);
869        if mic_tx.send(samples).await.is_err() {
870            break;
871        }
872    }
873}
874
875async fn outbound_loop(
876    socket: Arc<UdpSocket>,
877    payload_type: u8,
878    mut speaker_rx: mpsc::Receiver<Playback>,
879    peer_rx: watch::Receiver<SocketAddr>,
880    mut srtp: Option<SrtpSession>,
881    cancel: CancellationToken,
882) {
883    let silence_byte: u8 = if payload_type == PT_PCMA { 0xD5 } else { 0xFF };
884    let seed = seed();
885    let mut sender = RtpSender::new(payload_type, seed, (seed >> 16) as u16, seed.rotate_left(8));
886    let mut pending: std::collections::VecDeque<i16> = std::collections::VecDeque::new();
887    let mut ticker = tokio::time::interval(Duration::from_millis(20));
888    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
889
890    loop {
891        tokio::select! {
892            _ = cancel.cancelled() => break,
893            playback = speaker_rx.recv() => match playback {
894                Some(Playback::Chunk(samples)) => pending.extend(samples),
895                // Barge-in on raw RTP: we ARE the buffer — drop it.
896                Some(Playback::Flush) => pending.clear(),
897                None => break,
898            },
899            _ = ticker.tick() => {
900                if pending.is_empty() {
901                    sender.skip_silence(SAMPLES_PER_PACKET as u32);
902                    continue;
903                }
904                let take = pending.len().min(SAMPLES_PER_PACKET);
905                let mut payload = Vec::with_capacity(SAMPLES_PER_PACKET);
906                for sample in pending.drain(..take) {
907                    payload.push(if payload_type == PT_PCMA {
908                        g711::linear_to_alaw(sample)
909                    } else {
910                        g711::linear_to_ulaw(sample)
911                    });
912                }
913                // Constant 20 ms ptime: pad a short tail with silence.
914                payload.resize(SAMPLES_PER_PACKET, silence_byte);
915                let mut datagram = sender.packetize(&payload, SAMPLES_PER_PACKET as u32);
916                if let Some(srtp) = srtp.as_mut() {
917                    match srtp.protect(&datagram) {
918                        Some(protected) => datagram = protected,
919                        None => continue,
920                    }
921                }
922                let target = *peer_rx.borrow();
923                if socket.send_to(&datagram, target).await.is_err() {
924                    break;
925                }
926            }
927        }
928    }
929}
930
931/// The IP to advertise for media. A wildcard bind cannot go into SDP, so
932/// discover the interface that routes toward the caller's offer address.
933fn advertised_ip(local: IpAddr, offer: &AudioOffer) -> IpAddr {
934    if !local.is_unspecified() {
935        return local;
936    }
937    let probe = std::net::UdpSocket::bind("0.0.0.0:0")
938        .and_then(|s| {
939            s.connect((offer.host.as_str(), offer.port))?;
940            s.local_addr()
941        })
942        .map(|a| a.ip());
943    probe.unwrap_or(local)
944}
945
946/// A cheap non-cryptographic seed for SSRC/sequence/timestamp offsets.
947fn seed() -> u32 {
948    let nanos = std::time::SystemTime::now()
949        .duration_since(std::time::UNIX_EPOCH)
950        .map(|d| d.subsec_nanos())
951        .unwrap_or(0);
952    nanos ^ (std::process::id().rotate_left(16))
953}
954
955#[cfg(test)]
956mod lifecycle_tests;
957
958#[cfg(test)]
959mod migration_tests;
960
961#[cfg(test)]
962mod tests {
963    use super::*;
964
965    async fn recv_status(socket: &UdpSocket, buf: &mut [u8]) -> Option<String> {
966        let deadline = Duration::from_secs(3);
967        let (len, _) = tokio::time::timeout(deadline, socket.recv_from(buf))
968            .await
969            .ok()?
970            .ok()?;
971        String::from_utf8_lossy(&buf[..len])
972            .lines()
973            .next()
974            .map(str::to_string)
975    }
976
977    /// A throwaway password, random per test run.
978    fn test_password() -> String {
979        MasterKey::generate().unwrap().to_inline()
980    }
981
982    /// A registrar that challenges a REGISTER without credentials (401) and
983    /// grants one with them for 60 s. Every request it sees is forwarded.
984    async fn fake_registrar() -> (SocketAddr, mpsc::UnboundedReceiver<String>) {
985        fake_registrar_with_expiry(60).await
986    }
987
988    async fn fake_registrar_with_expiry(
989        expires: u32,
990    ) -> (SocketAddr, mpsc::UnboundedReceiver<String>) {
991        let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
992        let addr = socket.local_addr().unwrap();
993        let (seen_tx, seen_rx) = mpsc::unbounded_channel();
994        tokio::spawn(async move {
995            let mut buf = [0u8; 4096];
996            while let Ok((len, from)) = socket.recv_from(&mut buf).await {
997                let request = String::from_utf8_lossy(&buf[..len]).to_string();
998                let echoed: Vec<&str> = request
999                    .lines()
1000                    .filter(|l| {
1001                        let l = l.to_ascii_lowercase();
1002                        ["via:", "from:", "call-id:", "cseq:"]
1003                            .iter()
1004                            .any(|h| l.starts_with(h))
1005                    })
1006                    .collect();
1007                let to = request
1008                    .lines()
1009                    .find(|l| l.to_ascii_lowercase().starts_with("to:"))
1010                    .unwrap_or("To: <sip:unknown@invalid>");
1011                let authorized = request.to_ascii_lowercase().contains("\nauthorization:");
1012                let (status, extra) = if authorized {
1013                    let contact = request
1014                        .lines()
1015                        .find(|l| l.to_ascii_lowercase().starts_with("contact:"))
1016                        .unwrap_or("Contact: <sip:alice@127.0.0.1>");
1017                    ("200 OK", format!("{contact};expires={expires}\r\n"))
1018                } else {
1019                    (
1020                        "401 Unauthorized",
1021                        "WWW-Authenticate: Digest realm=\"test\", nonce=\"n1\", algorithm=MD5\r\n"
1022                            .to_string(),
1023                    )
1024                };
1025                let response = format!(
1026                    "SIP/2.0 {status}\r\n{}\r\n{to};tag=reg\r\n{extra}Content-Length: 0\r\n\r\n",
1027                    echoed.join("\r\n")
1028                );
1029                let _ = socket.send_to(response.as_bytes(), from).await;
1030                let _ = seen_tx.send(request);
1031            }
1032        });
1033        (addr, seen_rx)
1034    }
1035
1036    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1037    async fn registration_refreshes_and_shutdown_stops_waiting_for_calls() {
1038        let (registrar, mut seen) = fake_registrar_with_expiry(8).await;
1039        let mut agent = SipAgent::bind("127.0.0.1:0".parse().unwrap())
1040            .await
1041            .unwrap();
1042        let registration = agent
1043            .register(SipAccount::new(
1044                format!("sip:{registrar}"),
1045                "alice",
1046                test_password(),
1047            ))
1048            .await
1049            .unwrap();
1050        // Consume the initial challenge and authenticated request, then wait
1051        // for the next REGISTER at three quarters of the granted lifetime.
1052        seen.recv().await.unwrap();
1053        seen.recv().await.unwrap();
1054        let refresh = tokio::time::timeout(Duration::from_secs(10), seen.recv())
1055            .await
1056            .expect("registration refreshes")
1057            .expect("registrar running");
1058        assert!(refresh.starts_with("REGISTER "));
1059        if !refresh.to_ascii_lowercase().contains("authorization:") {
1060            let authenticated = tokio::time::timeout(Duration::from_secs(5), seen.recv())
1061                .await
1062                .expect("refresh answers the challenge")
1063                .expect("registrar running");
1064            assert!(
1065                authenticated
1066                    .to_ascii_lowercase()
1067                    .contains("authorization:")
1068            );
1069        }
1070        tokio::time::timeout(Duration::from_secs(5), registration.unregister())
1071            .await
1072            .expect("unregister finishes")
1073            .expect("unregister succeeds");
1074        let cancel = agent.cancel.clone();
1075        tokio::spawn(async move {
1076            tokio::time::sleep(Duration::from_millis(50)).await;
1077            cancel.cancel();
1078        });
1079        assert!(
1080            tokio::time::timeout(Duration::from_secs(2), agent.next_call())
1081                .await
1082                .expect("shutdown wakes next_call")
1083                .is_none()
1084        );
1085    }
1086
1087    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1088    async fn registers_with_digest_auth_and_unregisters() {
1089        let password = test_password();
1090        let (registrar, mut seen) = fake_registrar().await;
1091        let agent = SipAgent::bind("127.0.0.1:0".parse().unwrap())
1092            .await
1093            .expect("bind agent");
1094
1095        let registration = tokio::time::timeout(
1096            Duration::from_secs(5),
1097            agent.register(
1098                SipAccount::new(format!("sip:{registrar}"), "alice", &password)
1099                    .expires(Duration::from_secs(300)),
1100            ),
1101        )
1102        .await
1103        .expect("registration finishes")
1104        .expect("registrar accepts");
1105        assert_eq!(
1106            registration.state(),
1107            RegistrationState::Registered {
1108                expires: Duration::from_secs(60)
1109            },
1110            "the lifetime the registrar granted, not the one asked for"
1111        );
1112
1113        let first = seen.recv().await.unwrap();
1114        assert!(first.starts_with("REGISTER "), "{first}");
1115        assert!(!first.to_ascii_lowercase().contains("authorization:"));
1116        let answered = loop {
1117            let request = seen.recv().await.unwrap();
1118            if request.to_ascii_lowercase().contains("authorization:") {
1119                break request;
1120            }
1121        };
1122        use rsipstack::rsip::{DigestGenerator, HeadersExt as _, Method, Request};
1123        let initial = Request::try_from(first.as_str()).unwrap();
1124        let authenticated = Request::try_from(answered.as_str()).unwrap();
1125        let auth = rsipstack::rsip::typed::Authorization::parse(
1126            authenticated.authorization_header().unwrap().value(),
1127        )
1128        .unwrap();
1129        assert_eq!(auth.username, "alice");
1130        assert_eq!(auth.realm, "test");
1131        assert_eq!(auth.nonce, "n1");
1132        assert_eq!(auth.uri, authenticated.uri);
1133        assert!(DigestGenerator::from(&auth, &password, &Method::Register).verify(&auth.response));
1134        assert_eq!(
1135            authenticated.cseq_header().unwrap().seq().unwrap(),
1136            initial.cseq_header().unwrap().seq().unwrap() + 1
1137        );
1138        assert_eq!(
1139            authenticated.call_id_header().unwrap().value(),
1140            initial.call_id_header().unwrap().value()
1141        );
1142        assert_ne!(
1143            authenticated.via_header().unwrap().value(),
1144            initial.via_header().unwrap().value(),
1145            "the authenticated retry uses a new transaction branch"
1146        );
1147        assert!(
1148            !answered.contains(&password),
1149            "the password never goes on the wire"
1150        );
1151
1152        tokio::time::timeout(Duration::from_secs(5), registration.unregister())
1153            .await
1154            .expect("unregister finishes")
1155            .expect("registrar accepts the removal");
1156        let mut removed = false;
1157        while let Ok(request) = seen.try_recv() {
1158            removed |= request
1159                .lines()
1160                .any(|l| l.eq_ignore_ascii_case("expires: 0"));
1161        }
1162        assert!(
1163            removed,
1164            "a REGISTER with a zero lifetime removes the binding"
1165        );
1166        agent.shutdown();
1167    }
1168
1169    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1170    async fn a_refused_registration_fails_at_once() {
1171        // A registrar that refuses everyone.
1172        let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
1173        let registrar = socket.local_addr().unwrap();
1174        tokio::spawn(async move {
1175            let mut buf = [0u8; 4096];
1176            while let Ok((len, from)) = socket.recv_from(&mut buf).await {
1177                let request = String::from_utf8_lossy(&buf[..len]).to_string();
1178                let echoed: Vec<&str> = request
1179                    .lines()
1180                    .filter(|l| {
1181                        let l = l.to_ascii_lowercase();
1182                        ["via:", "from:", "to:", "call-id:", "cseq:"]
1183                            .iter()
1184                            .any(|h| l.starts_with(h))
1185                    })
1186                    .collect();
1187                let response = format!(
1188                    "SIP/2.0 403 Forbidden\r\n{}\r\nContent-Length: 0\r\n\r\n",
1189                    echoed.join("\r\n")
1190                );
1191                let _ = socket.send_to(response.as_bytes(), from).await;
1192            }
1193        });
1194        let agent = SipAgent::bind("127.0.0.1:0".parse().unwrap())
1195            .await
1196            .unwrap();
1197        let result = tokio::time::timeout(
1198            Duration::from_secs(5),
1199            agent.register(SipAccount::new(
1200                format!("sip:{registrar}"),
1201                "mallory",
1202                test_password(),
1203            )),
1204        )
1205        .await
1206        .expect("finishes");
1207        assert!(
1208            matches!(result, Err(SipError::RegistrationRejected(403))),
1209            "{:?}",
1210            result.err()
1211        );
1212        agent.shutdown();
1213    }
1214
1215    /// Read datagrams until a SIP response with status `code` arrives.
1216    async fn recv_response(socket: &UdpSocket, code: &str) -> String {
1217        let mut buf = [0u8; 4096];
1218        loop {
1219            let (len, _) = tokio::time::timeout(Duration::from_secs(3), socket.recv_from(&mut buf))
1220                .await
1221                .expect("a response")
1222                .unwrap();
1223            let text = String::from_utf8_lossy(&buf[..len]).to_string();
1224            if text.lines().next().is_some_and(|l| l.contains(code)) {
1225                return text;
1226            }
1227        }
1228    }
1229
1230    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1231    async fn an_srtp_offer_gets_encrypted_media_both_ways() {
1232        use super::super::srtp::SrtpSuite;
1233        use base64::Engine as _;
1234
1235        // The model says 200 ms of a tone once the call is up.
1236        let tone: Vec<u8> = (0..4800i16)
1237            .flat_map(|i| (if i % 48 < 24 { 6000i16 } else { -6000 }).to_le_bytes())
1238            .collect();
1239        let (transport, control) = crate::live::scripted::ScriptedServer::new()
1240            .frame(serde_json::json!({
1241                "serverContent": { "modelTurn": { "parts": [{ "inlineData": {
1242                    "mimeType": "audio/pcm;rate=24000",
1243                    "data": base64::engine::general_purpose::STANDARD.encode(&tone),
1244                } }] } }
1245            }))
1246            .into_transport();
1247        let handle = crate::live::Live::builder()
1248            .connect_with_transport(transport)
1249            .await
1250            .unwrap();
1251
1252        let mut agent = SipAgent::bind("127.0.0.1:0".parse().unwrap())
1253            .await
1254            .unwrap();
1255        let target = format!("127.0.0.1:{}", agent.sip_port());
1256        let (call_tx, call_rx) = tokio::sync::oneshot::channel();
1257        tokio::spawn(async move {
1258            if let Some(incoming) = agent.next_call().await {
1259                let _ = call_tx.send(incoming);
1260            }
1261            // Keep the agent (and its endpoint) alive for the call.
1262            std::future::pending::<()>().await;
1263        });
1264
1265        // The caller: a SIP socket, an RTP socket, and its own SRTP key.
1266        let uac = UdpSocket::bind("127.0.0.1:0").await.unwrap();
1267        let uac_port = uac.local_addr().unwrap().port();
1268        let media = UdpSocket::bind("127.0.0.1:0").await.unwrap();
1269        let media_port = media.local_addr().unwrap().port();
1270        let caller_key = MasterKey::generate().unwrap();
1271        let sdp_body = format!(
1272            "v=0\r\no=probe 1 1 IN IP4 127.0.0.1\r\ns=call\r\nc=IN IP4 127.0.0.1\r\nt=0 0\r\n\
1273             m=audio {media_port} RTP/SAVP 0\r\na=rtpmap:0 PCMU/8000\r\n\
1274             a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:{}\r\n",
1275            caller_key.to_inline()
1276        );
1277        let invite = format!(
1278            "INVITE sip:gemini@{target} SIP/2.0\r\n\
1279             Via: SIP/2.0/UDP 127.0.0.1:{uac_port};branch=z9hG4bKsrtp1\r\n\
1280             Max-Forwards: 70\r\n\
1281             From: <sip:probe@127.0.0.1>;tag=srtp\r\n\
1282             To: <sip:gemini@{target}>\r\n\
1283             Call-ID: srtp-1@127.0.0.1\r\n\
1284             CSeq: 1 INVITE\r\n\
1285             Contact: <sip:probe@127.0.0.1:{uac_port}>\r\n\
1286             Content-Type: application/sdp\r\n\
1287             Content-Length: {}\r\n\r\n{sdp_body}",
1288            sdp_body.len()
1289        );
1290        uac.send_to(invite.as_bytes(), &target).await.unwrap();
1291        let incoming = tokio::time::timeout(Duration::from_secs(3), call_rx)
1292            .await
1293            .unwrap()
1294            .unwrap();
1295        assert!(incoming.offer.secure);
1296        let _call = incoming.answer(&handle).await.expect("answers with SRTP");
1297
1298        let ok = recv_response(&uac, "200").await;
1299        let answer_sdp = ok.split("\r\n\r\n").nth(1).unwrap();
1300        let answer = sdp::parse_audio_offer(answer_sdp).expect("an SDP answer");
1301        assert!(answer.secure, "{answer_sdp}");
1302        let agent_crypto = CryptoAttribute::parse(&answer.crypto[0]).unwrap();
1303        assert_eq!(agent_crypto.tag, 1);
1304        assert_eq!(agent_crypto.suite, SrtpSuite::AesCm128HmacSha1_80);
1305        assert_ne!(
1306            agent_crypto.key, caller_key,
1307            "the agent sends under its own key"
1308        );
1309        let agent_rtp = format!("{}:{}", answer.host, answer.port);
1310
1311        let speak = |key: &MasterKey, first: u16| {
1312            let mut session = SrtpSession::new(SrtpSuite::AesCm128HmacSha1_80, key);
1313            (first..first + 15)
1314                .map(|seq| {
1315                    session
1316                        .protect(&rtp::build(&rtp::RtpPacket {
1317                            payload_type: 0,
1318                            marker: seq == first,
1319                            sequence: seq,
1320                            timestamp: u32::from(seq) * 160,
1321                            ssrc: 0xCA11_E500,
1322                            payload: vec![0x10; 160],
1323                        }))
1324                        .unwrap()
1325                })
1326                .collect::<Vec<_>>()
1327        };
1328        let heard = || {
1329            control
1330                .outbound_frames()
1331                .iter()
1332                .filter_map(|frame| serde_json::from_slice::<serde_json::Value>(frame).ok())
1333                .any(|message| message.pointer("/realtimeInput/audio").is_some())
1334        };
1335
1336        // Caller → agent under a key the agent was not given: dropped.
1337        for packet in speak(&MasterKey::generate().unwrap(), 100) {
1338            media.send_to(&packet, &agent_rtp).await.unwrap();
1339        }
1340        tokio::time::sleep(Duration::from_millis(200)).await;
1341        assert!(
1342            !heard(),
1343            "packets that fail authentication never reach the model"
1344        );
1345
1346        // Under the offered key: decrypted speech reaches the model.
1347        for packet in speak(&caller_key, 200) {
1348            media.send_to(&packet, &agent_rtp).await.unwrap();
1349            tokio::time::sleep(Duration::from_millis(5)).await;
1350        }
1351        tokio::time::sleep(Duration::from_millis(200)).await;
1352        assert!(heard(), "decrypted caller audio reached the model");
1353
1354        // Agent → caller: the model's audio arrives as SRTP under the
1355        // agent's key, and decrypts to non-silent G.711.
1356        control.release();
1357        let mut from_agent = SrtpSession::new(agent_crypto.suite, &agent_crypto.key);
1358        let mut buf = [0u8; 2048];
1359        let (len, _) = tokio::time::timeout(Duration::from_secs(3), media.recv_from(&mut buf))
1360            .await
1361            .expect("the agent sends media")
1362            .unwrap();
1363        let plain = from_agent
1364            .unprotect(&buf[..len])
1365            .expect("authenticates under the answered key");
1366        let packet = rtp::parse(&plain).unwrap();
1367        assert_eq!(packet.payload_type, 0);
1368        assert!(packet.payload.iter().any(|b| *b != 0xFF), "not silence");
1369    }
1370
1371    #[test]
1372    fn an_account_never_prints_its_password() {
1373        let password = test_password();
1374        let account = SipAccount::new("sip:pbx.example.com", "alice", &password);
1375        assert!(!format!("{account:?}").contains(&password));
1376    }
1377
1378    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1379    async fn answers_options_and_rings_then_rejects_an_invite() {
1380        let mut agent = SipAgent::bind("127.0.0.1:0".parse().unwrap())
1381            .await
1382            .expect("bind agent");
1383        let agent_port = agent.sip_port();
1384        // Drive the agent loop concurrently: OPTIONS is answered inside it,
1385        // and the INVITE surfaces through the channel.
1386        let (call_tx, call_rx) = tokio::sync::oneshot::channel();
1387        tokio::spawn(async move {
1388            if let Some(incoming) = agent.next_call().await {
1389                let _ = call_tx.send(incoming);
1390            }
1391        });
1392
1393        let uac = UdpSocket::bind("127.0.0.1:0").await.unwrap();
1394        let uac_port = uac.local_addr().unwrap().port();
1395        let target = format!("127.0.0.1:{agent_port}");
1396        let mut buf = [0u8; 2048];
1397
1398        // OPTIONS gets a 200 without surfacing a call.
1399        let options = format!(
1400            "OPTIONS sip:gemini@{target} SIP/2.0\r\n\
1401             Via: SIP/2.0/UDP 127.0.0.1:{uac_port};branch=z9hG4bKopt1\r\n\
1402             Max-Forwards: 70\r\n\
1403             From: <sip:probe@127.0.0.1>;tag=opt\r\n\
1404             To: <sip:gemini@{target}>\r\n\
1405             Call-ID: options-1@127.0.0.1\r\n\
1406             CSeq: 1 OPTIONS\r\n\
1407             Content-Length: 0\r\n\r\n"
1408        );
1409        uac.send_to(options.as_bytes(), &target).await.unwrap();
1410        let status = recv_status(&uac, &mut buf).await.expect("OPTIONS response");
1411        assert!(
1412            status.contains("200"),
1413            "expected 200 to OPTIONS, got {status}"
1414        );
1415
1416        // An INVITE with a G.711 offer surfaces as an IncomingCall (after
1417        // 100/180 provisional responses); rejecting it sends a final failure.
1418        let sdp_body = "v=0\r\n\
1419             o=probe 1 1 IN IP4 127.0.0.1\r\n\
1420             s=call\r\nc=IN IP4 127.0.0.1\r\nt=0 0\r\n\
1421             m=audio 40000 RTP/AVP 0\r\n\
1422             a=rtpmap:0 PCMU/8000\r\n";
1423        let invite = format!(
1424            "INVITE sip:gemini@{target} SIP/2.0\r\n\
1425             Via: SIP/2.0/UDP 127.0.0.1:{uac_port};branch=z9hG4bKinv1\r\n\
1426             Max-Forwards: 70\r\n\
1427             From: <sip:probe@127.0.0.1>;tag=inv\r\n\
1428             To: <sip:gemini@{target}>\r\n\
1429             Call-ID: invite-1@127.0.0.1\r\n\
1430             CSeq: 1 INVITE\r\n\
1431             Contact: <sip:probe@127.0.0.1:{uac_port}>\r\n\
1432             Content-Type: application/sdp\r\n\
1433             Content-Length: {}\r\n\r\n{sdp_body}",
1434            sdp_body.len()
1435        );
1436        uac.send_to(invite.as_bytes(), &target).await.unwrap();
1437
1438        let incoming = tokio::time::timeout(Duration::from_secs(3), call_rx)
1439            .await
1440            .expect("call surfaces")
1441            .expect("agent still running");
1442        assert_eq!(incoming.offer.port, 40_000);
1443        assert_eq!(
1444            incoming.offer.g711_payload_type(),
1445            Some(super::super::rtp::PT_PCMU)
1446        );
1447        assert!(incoming.from.contains("probe"), "from: {}", incoming.from);
1448        incoming.reject();
1449
1450        // Drain provisional responses until the final failure arrives.
1451        let mut saw_final = false;
1452        for _ in 0..6 {
1453            match recv_status(&uac, &mut buf).await {
1454                Some(status) => {
1455                    let code: u32 = status
1456                        .split_whitespace()
1457                        .nth(1)
1458                        .and_then(|c| c.parse().ok())
1459                        .unwrap_or(0);
1460                    if code >= 400 {
1461                        saw_final = true;
1462                        break;
1463                    }
1464                }
1465                None => break,
1466            }
1467        }
1468        assert!(
1469            saw_final,
1470            "expected a final failure response to the rejected INVITE"
1471        );
1472    }
1473}