Skip to main content

active_call/
app.rs

1use crate::{
2    call::{ActiveCallRef, refer_headers::ReferHeaderResolver, sip::Invitation},
3    callrecord::{
4        CallRecordFormatter, CallRecordManagerBuilder, CallRecordSender, DefaultCallRecordFormatter,
5    },
6    config::Config,
7    locator::RewriteTargetLocator,
8    sipflow::{SipFlow, SipFlowUploadHook},
9    useragent::{
10        RegisterOption,
11        invitation::{
12            FnCreateInvitationHandler, PendingDialog, PendingDialogGuard,
13            default_create_invite_handler,
14        },
15        peer_learning::{PeerAddressLearner, SharedLearnedPeers},
16        public_address::{
17            LearningMessageInspector, SharedPublicAddress, build_contact, build_public_contact_uri,
18            find_local_addr_for_uri,
19        },
20        registration::{RegistrationHandle, UserCredential},
21    },
22};
23
24use crate::media::{cache::set_cache_dir, engine::StreamEngine};
25use anyhow::Result;
26use arc_swap::ArcSwap;
27use async_trait::async_trait;
28use chrono::{DateTime, Local};
29use futures::FutureExt;
30use humantime::parse_duration;
31use rsipstack::rsip::prelude::HeadersExt;
32use rsipstack::rsip::{Accept, Method, typed};
33use rsipstack::transaction::{
34    Endpoint, TransactionReceiver,
35    endpoint::{TargetLocator, TransportEventInspector},
36};
37use rsipstack::transport::transport_layer::DomainResolver;
38use rsipstack::{dialog::dialog_layer::DialogLayer, transaction::endpoint::MessageInspector};
39use rsipstack::{
40    rsip::{Host, HostWithPort},
41    transport::SipAddr,
42};
43use std::future::pending;
44use std::panic::{AssertUnwindSafe, catch_unwind};
45use std::str::FromStr;
46use std::sync::{Arc, RwLock};
47use std::time::Duration;
48use std::{collections::HashMap, net::SocketAddr};
49use std::{collections::HashSet, time::Instant};
50use std::{
51    path::Path,
52    sync::atomic::{AtomicBool, AtomicU64, Ordering},
53};
54use tokio::select;
55use tokio::sync::Mutex;
56use tokio_util::sync::CancellationToken;
57use tracing::{debug, info, warn};
58
59/// Generates a short unique session id for incoming calls, e.g. `s.3f9a2b1c4d5e`,
60/// instead of reusing the raw SIP dialog-id string. Collisions with live
61/// sessions are retried (practically impossible with 48 bits of randomness).
62fn generate_short_session_id(invitation: &Invitation) -> String {
63    loop {
64        let uuid = uuid::Uuid::new_v4().simple().to_string();
65        let session_id = format!("s.{}", &uuid);
66        if !invitation.session_exists(&session_id) {
67            return session_id;
68        }
69    }
70}
71
72/// Extracts the network source of a received request from its top Via header:
73/// the IP comes from the `received` parameter (populated by our transport for
74/// NAT'd peers) or the sent-by host when it is an IP literal; the hostname is
75/// the sent-by host as written. Port is intentionally ignored (carrier source
76/// ports change between probes).
77fn extract_via_source(request: &rsipstack::rsip::Request) -> (Option<std::net::IpAddr>, String) {
78    use rsipstack::rsip::ToTypedHeader;
79    let Ok(via) = request.via_header().and_then(|v| v.typed()) else {
80        return (None, String::new());
81    };
82    let source_ip = via
83        .received()
84        .and_then(|r| r.ok())
85        .or_else(|| match &via.sent_by().host {
86            rsipstack::rsip::Host::IpAddr(ip) => Some(*ip),
87            _ => None,
88        });
89    (source_ip, via.sent_by().host.to_string())
90}
91
92pub struct AppStateInner {
93    /// Live configuration snapshot, hot-swappable via
94    /// [`AppStateInner::apply_config`]. Reads go through
95    /// [`AppStateInner::config`]: a call captures one snapshot at construction
96    /// and keeps it for its lifetime, so a reload never changes a call that is
97    /// already running.
98    config: ArcSwap<Config>,
99    /// Path recorded at startup; used by the reload endpoint and the watcher.
100    pub config_path: Option<Arc<str>>,
101    pub token: CancellationToken,
102    pub stream_engine: Arc<StreamEngine>,
103    pub callrecord_sender: Option<CallRecordSender>,
104    pub endpoint: Endpoint,
105    pub registration_handles: Mutex<HashMap<String, CancellationToken>>,
106    pub alive_users: Arc<RwLock<HashSet<String>>>,
107    pub dialog_layer: Arc<DialogLayer>,
108    pub create_invitation_handler: Option<FnCreateInvitationHandler>,
109    pub invitation: Invitation,
110    pub routing_state: Arc<crate::call::RoutingState>,
111    pub pending_playbooks: Arc<Mutex<HashMap<String, (String, Instant)>>>,
112    /// In-process SIP signaling capture ([`crate::sipflow`]); `None` when
113    /// the `[sipflow]` section is absent/disabled.
114    pub sip_flow: Option<Arc<SipFlow>>,
115    pub learned_public_address: SharedPublicAddress,
116    /// Peer source addresses learned from call traffic, used by the OPTIONS
117    /// ACL (`[options_response]`).
118    pub learned_peers: crate::useragent::peer_learning::SharedLearnedPeers,
119    /// Optional hook that rewrites the custom headers an incoming REFER
120    /// carries onto the transfer INVITE; `None` forwards them unchanged.
121    pub refer_header_resolver: Option<std::sync::Arc<dyn ReferHeaderResolver>>,
122
123    pub active_calls: Arc<std::sync::Mutex<HashMap<String, ActiveCallRef>>>,
124    pub total_calls: AtomicU64,
125    pub total_failed_calls: AtomicU64,
126    pub uptime: DateTime<Local>,
127    pub shutting_down: Arc<AtomicBool>,
128}
129
130pub type AppState = Arc<AppStateInner>;
131
132pub struct AppStateBuilder {
133    pub config: Option<Config>,
134    pub stream_engine: Option<Arc<StreamEngine>>,
135    pub callrecord_sender: Option<CallRecordSender>,
136    pub callrecord_formatter: Option<Arc<dyn CallRecordFormatter>>,
137    pub cancel_token: Option<CancellationToken>,
138    pub create_invitation_handler: Option<FnCreateInvitationHandler>,
139    pub config_path: Option<String>,
140
141    pub message_inspector: Option<Box<dyn MessageInspector>>,
142    pub target_locator: Option<Box<dyn TargetLocator>>,
143    pub transport_inspector: Option<Box<dyn TransportEventInspector>>,
144    pub refer_header_resolver: Option<std::sync::Arc<dyn ReferHeaderResolver>>,
145    /// Externally created signaling recorder; when set it takes precedence
146    /// over `[sipflow]` config (used by embedders that need the same
147    /// `SipFlow` handle in their own callrecord manager).
148    pub sip_flow: Option<Arc<SipFlow>>,
149}
150
151impl AppStateInner {
152    pub fn auto_learn_public_address_enabled(&self) -> bool {
153        self.config().auto_learn_public_address.unwrap_or(false)
154    }
155
156    /// Whether an OPTIONS probe from `source_ip`/`source_host` (as extracted
157    /// from the top Via header) should be answered: the source must match the
158    /// static ACL, a registered-server host, or a peer address learned from
159    /// call traffic within the configured TTL.
160    pub fn options_source_allowed(
161        &self,
162        source_ip: Option<std::net::IpAddr>,
163        source_host: &str,
164    ) -> bool {
165        if self.config().options_matches_static(source_ip, source_host) {
166            return true;
167        }
168        if !self.config().options_auto_learn() {
169            return false;
170        }
171        let ttl = self.config().options_learn_ttl();
172        match source_ip {
173            Some(ip) => self.learned_peers.contains_within(&ip, ttl),
174            None => false,
175        }
176    }
177
178    pub fn get_dump_events_file(&self, session_id: &String) -> String {
179        let recorder_root = self.config().recorder_path();
180        let root = Path::new(&recorder_root);
181        if !root.exists() {
182            match std::fs::create_dir_all(root) {
183                Ok(_) => {
184                    info!("created dump events root: {}", root.to_string_lossy());
185                }
186                Err(e) => {
187                    warn!(
188                        "Failed to create dump events root: {} {}",
189                        e,
190                        root.to_string_lossy()
191                    );
192                }
193            }
194        }
195        root.join(format!("{}.events.jsonl", session_id))
196            .to_string_lossy()
197            .to_string()
198    }
199
200    pub fn get_recorder_file(&self, session_id: &String) -> String {
201        let recorder_root = self.config().recorder_path();
202        let root = Path::new(&recorder_root);
203        if !root.exists() {
204            match std::fs::create_dir_all(root) {
205                Ok(_) => {
206                    info!("created recorder root: {}", root.to_string_lossy());
207                }
208                Err(e) => {
209                    warn!(
210                        "Failed to create recorder root: {} {}",
211                        e,
212                        root.to_string_lossy()
213                    );
214                }
215            }
216        }
217        let desired_ext = self.config().recorder_format().extension();
218        let mut filename = session_id.clone();
219        if !filename
220            .to_lowercase()
221            .ends_with(&format!(".{}", desired_ext.to_lowercase()))
222        {
223            filename = format!("{}.{}", filename, desired_ext);
224        }
225        root.join(filename).to_string_lossy().to_string()
226    }
227
228    pub async fn serve(self: Arc<Self>) -> Result<()> {
229        let incoming_txs = self.endpoint.incoming_transactions()?;
230        let token = self.token.child_token();
231        let endpoint_inner = self.endpoint.inner.clone();
232        let dialog_layer = self.dialog_layer.clone();
233        let app_state_clone = self.clone();
234
235        match self.start_registration().await {
236            Ok(count) => {
237                info!("registration started, count: {}", count);
238            }
239            Err(e) => {
240                warn!("failed to start registration: {:?}", e);
241            }
242        }
243
244        let pending_cleanup_state = self.clone();
245        let pending_cleanup_token = token.clone();
246        crate::spawn(async move {
247            let mut interval = tokio::time::interval(Duration::from_secs(60));
248            let ttl = Duration::from_secs(300);
249            loop {
250                tokio::select! {
251                    _ = pending_cleanup_token.cancelled() => break,
252                    _ = interval.tick() => {
253                        let mut pending = pending_cleanup_state.pending_playbooks.lock().await;
254                        let before = pending.len();
255                        pending.retain(|_, (_, created_at)| created_at.elapsed() < ttl);
256                        let removed = before - pending.len();
257                        if removed > 0 {
258                            info!(removed, remaining = pending.len(), "cleaned up stale pending_playbooks entries");
259                        }
260                    }
261                }
262            }
263        });
264
265        tokio::select! {
266            _ = token.cancelled() => {
267                info!("cancelled");
268            }
269            result = endpoint_inner.serve() => {
270                if let Err(e) = result {
271                    info!("endpoint serve error: {:?}", e);
272                }
273            }
274            result = app_state_clone.process_incoming_request(dialog_layer.clone(), incoming_txs) => {
275                if let Err(e) = result {
276                    info!("process incoming request error: {:?}", e);
277                }
278            },
279        }
280
281        let total_secs = self.config().graceful_shutdown_timeout.unwrap_or(30);
282        let timeout = self.config()
283            .graceful_shutdown
284            .map(|_| Duration::from_secs(total_secs));
285
286        match self.stop_registration(timeout).await {
287            Ok(_) => {
288                info!("registration stopped, waiting for clear");
289            }
290            Err(e) => {
291                warn!("failed to stop registration: {:?}", e);
292            }
293        }
294        info!("stopping");
295        Ok(())
296    }
297
298    async fn process_incoming_request(
299        self: Arc<Self>,
300        dialog_layer: Arc<DialogLayer>,
301        mut incoming: TransactionReceiver,
302    ) -> Result<()> {
303        while let Some(mut tx) = incoming.recv().await {
304            let key: &rsipstack::transaction::key::TransactionKey = &tx.key;
305            info!(?key, "received transaction");
306            if tx.original.to_header()?.tag()?.as_ref().is_some() {
307                match dialog_layer.match_dialog(&tx) {
308                    Some(mut d) => {
309                        crate::spawn(async move {
310                            match d.handle(&mut tx).await {
311                                Ok(_) => (),
312                                Err(e) => {
313                                    info!("error handling transaction: {:?}", e);
314                                }
315                            }
316                        });
317                        continue;
318                    }
319                    None => {
320                        info!("dialog not found: {}", tx.original);
321                        match tx
322                            .reply(rsipstack::rsip::StatusCode::CallTransactionDoesNotExist)
323                            .await
324                        {
325                            Ok(_) => (),
326                            Err(e) => {
327                                info!("error replying to request: {:?}", e);
328                            }
329                        }
330                        continue;
331                    }
332                }
333            }
334            // out dialog, new server dialog
335            let (state_sender, state_receiver) = dialog_layer.new_dialog_state_channel();
336            match tx.original.method {
337                rsipstack::rsip::Method::Invite | rsipstack::rsip::Method::Ack => {
338                    // Reject new INVITEs during graceful shutdown
339                    if self.shutting_down.load(Ordering::Relaxed) {
340                        info!(?key, "rejecting INVITE during graceful shutdown");
341                        match tx
342                            .reply_with(
343                                rsipstack::rsip::StatusCode::ServiceUnavailable,
344                                vec![rsipstack::rsip::Header::Other(
345                                    "Reason".into(),
346                                    "SIP;cause=503;text=\"Server shutting down\"".into(),
347                                )],
348                                None,
349                            )
350                            .await
351                        {
352                            Ok(_) => (),
353                            Err(e) => {
354                                info!("error replying to request: {:?}", e);
355                            }
356                        }
357                        continue;
358                    }
359
360                    let invitation_handler = match self.create_invitation_handler {
361                        Some(ref create_invitation_handler) => {
362                            create_invitation_handler(self.config().handler.as_ref()).ok()
363                        }
364                        _ => default_create_invite_handler(
365                            self.config().handler.as_ref(),
366                            Some(self.clone()),
367                        ),
368                    };
369                    let invitation_handler = match invitation_handler {
370                        Some(h) => h,
371                        None => {
372                            info!(?key, "no invite handler configured, rejecting INVITE");
373                            match tx
374                                .reply_with(
375                                    rsipstack::rsip::StatusCode::ServiceUnavailable,
376                                    vec![rsipstack::rsip::Header::Other(
377                                        "Reason".into(),
378                                        "SIP;cause=503;text=\"No invite handler configured\""
379                                            .into(),
380                                    )],
381                                    None,
382                                )
383                                .await
384                            {
385                                Ok(_) => (),
386                                Err(e) => {
387                                    info!("error replying to request: {:?}", e);
388                                }
389                            }
390                            continue;
391                        }
392                    };
393                    let local_addr = tx
394                        .connection
395                        .as_ref()
396                        .map(|connection| connection.get_addr().clone())
397                        .or_else(|| dialog_layer.endpoint.get_addrs().first().cloned());
398                    let contact_username =
399                        tx.original.uri.auth.as_ref().map(|auth| auth.user.as_str());
400                    let contact = local_addr.as_ref().map(|addr| {
401                        build_public_contact_uri(
402                            &self.learned_public_address,
403                            self.auto_learn_public_address_enabled(),
404                            addr,
405                            contact_username,
406                            None,
407                        )
408                    });
409
410                    let dialog = match dialog_layer.get_or_create_server_invite(
411                        &tx,
412                        state_sender,
413                        None,
414                        contact,
415                    ) {
416                        Ok(d) => d,
417                        Err(e) => {
418                            // 481 Dialog/Transaction Does Not Exist
419                            info!("failed to obtain dialog: {:?}", e);
420                            match tx
421                                .reply(rsipstack::rsip::StatusCode::CallTransactionDoesNotExist)
422                                .await
423                            {
424                                Ok(_) => (),
425                                Err(e) => {
426                                    info!("error replying to request: {:?}", e);
427                                }
428                            }
429                            continue;
430                        }
431                    };
432
433                    let dialog_id = dialog.id();
434                    let dialog_id_str = dialog_id.to_string();
435                    let session_id = if dialog_id_str.len() > 64 { generate_short_session_id(&self.invitation) } else { dialog_id_str.clone() };
436                    // Register the dialog's SIP Call-ID under this session so
437                    // sipflow can merge its signaling at hangup.
438                    if let Some(flow) = self.sip_flow.as_ref() {
439                        flow.associate(&session_id, &dialog_id.call_id);
440                    }
441                    let dialog_id_for_cleanup = dialog_id.clone();
442                    let token = self.token.child_token();
443                    let pending_dialog = PendingDialog {
444                        token: token.clone(),
445                        dialog: dialog.clone(),
446                        state_receiver,
447                    };
448
449                    let guard = Arc::new(PendingDialogGuard::new_with_session(
450                        self.invitation.clone(),
451                        dialog_id,
452                        session_id.clone(),
453                        pending_dialog,
454                    ));
455
456                    let accept_timeout = self
457                        .config()
458                        .accept_timeout
459                        .as_ref()
460                        .and_then(|t| parse_duration(t).ok())
461                        .unwrap_or_else(|| Duration::from_secs(60));
462
463                    let mut dialog_ref = dialog.clone();
464                    let routing_state = self.routing_state.clone();
465                    let dialog_for_reject = dialog.clone();
466                    let invitation_for_cleanup = self.invitation.clone();
467                    let active_calls_for_task = self.active_calls.clone();
468                    let session_id_for_task = session_id.clone();
469                    crate::spawn(async move {
470                        info!(
471                            session_id = session_id_for_task,
472                            id = dialog_id_str,
473                            "incoming invite task started"
474                        );
475                        let _pending_guard = guard;
476                        let token_ref = token.clone();
477                        let accept_timeout_sleep = tokio::time::sleep(accept_timeout);
478                        let invite_handler = invitation_handler.on_invite(
479                            session_id_for_task.clone(),
480                            token.clone(),
481                            dialog.clone(),
482                            routing_state,
483                        );
484                        let dialog_handle = dialog_ref.handle(&mut tx);
485                        tokio::pin!(accept_timeout_sleep);
486                        tokio::pin!(invite_handler);
487                        tokio::pin!(dialog_handle);
488
489                        let mut cancel_done = false;
490                        let mut accept_timeout_done = false;
491                        let mut invite_done = false;
492                        loop {
493                            let mut reject_request = None;
494
495                            select! {
496                                _ = token_ref.cancelled(), if !cancel_done => {
497                                    cancel_done = true;
498                                    reject_request = Some((
499                                        rsipstack::rsip::StatusCode::ServiceUnavailable,
500                                        "invite cancelled".to_string(),
501                                        "cancelled",
502                                    ));
503                                }
504                                _ = &mut accept_timeout_sleep, if !accept_timeout_done
505                                    && dialog_for_reject.state().can_cancel() => {
506                                    accept_timeout_done = true;
507                                    reject_request = Some((
508                                        rsipstack::rsip::StatusCode::RequestTimeout,
509                                        "accept timeout".to_string(),
510                                        "accept timeout",
511                                    ));
512                                }
513                                result = &mut invite_handler, if !invite_done => {
514                                    invite_done = true;
515                                    match result {
516                                        Ok(_) => {
517                                            info!(id = dialog_id_str, "invite handler completed");
518                                        }
519                                        Err(e) => {
520                                            info!(id = dialog_id_str, "error handling invite: {:?}", e);
521                                            reject_request = Some((
522                                                rsipstack::rsip::StatusCode::ServiceUnavailable,
523                                                format!("Failed to process invite: {}", e),
524                                                "invite handler error",
525                                            ));
526                                        }
527                                    }
528                                }
529                                result = &mut dialog_handle => {
530                                    match result {
531                                        Ok(_) => {
532                                            info!(id = dialog_id_str, "dialog handling finished");
533                                        }
534                                        Err(e) => {
535                                            info!(
536                                                id = dialog_id_str,
537                                                "dialog handling ended with error: {:?}", e
538                                            );
539                                        }
540                                    }
541                                    if let rsipstack::dialog::dialog::DialogState::Terminated(
542                                        _,
543                                        reason,
544                                    ) = dialog_for_reject.state()
545                                    {
546                                        info!(
547                                            id = dialog_id_str,
548                                            "terminated invite dialog finished, cancelling invite token"
549                                        );
550                                        token_ref.cancel();
551
552                                        // A websocket client may already have
553                                        // attached an ActiveCall for this session,
554                                        // but that call only starts watching the
555                                        // dialog state on its first command
556                                        // (Ringing/Accept). A far-end CANCEL before
557                                        // that command would otherwise leave the
558                                        // call in `active_calls` forever. Propagate
559                                        // the termination: report the hangup and
560                                        // tear the call down.
561                                        let maybe_call = active_calls_for_task
562                                            .lock()
563                                            .unwrap()
564                                            .get(&session_id_for_task)
565                                            .cloned();
566                                        if let Some(call) = maybe_call {
567                                            let has_reason = call
568                                                .progress
569                                                .load_full()
570                                                .hangup_reason
571                                                .is_some();
572                                            if !has_reason {
573                                                let term =
574                                                    crate::call::state::CallProgress::termination(
575                                                        Some(&reason),
576                                                    );
577                                                call.leg().update_progress(|p| {
578                                                    p.last_status_code = term.status_code;
579                                                    p.set_hangup_reason(
580                                                        term.hangup_reason.clone(),
581                                                    );
582                                                });
583                                                let event = call.leg().build_hangup_event(
584                                                    call.session_id.clone(),
585                                                    Some(term.initiator.to_string()),
586                                                );
587                                                call.event_sender.send(event).ok();
588                                            }
589                                            call.cancel_token.cancel();
590                                        }
591                                    }
592                                    info!(id = dialog_id_str, "incoming invite task finished");
593                                    break;
594                                }
595                            }
596
597                            if let Some((code, reason, source)) = reject_request {
598                                if dialog_for_reject.state().can_cancel() {
599                                    info!(
600                                        id = dialog_id_str,
601                                        ?code,
602                                        %reason,
603                                        source,
604                                        "rejecting invite"
605                                    );
606                                    if let Err(e) =
607                                        dialog_for_reject.reject(Some(code), Some(reason))
608                                    {
609                                        info!(
610                                            id = dialog_id_str,
611                                            "error rejecting invite: {:?}", e
612                                        );
613                                    }
614                                    invitation_for_cleanup.get_pending_call(&dialog_id_for_cleanup);
615                                    invitation_for_cleanup
616                                        .dialog_layer
617                                        .remove_dialog(&dialog_id_for_cleanup);
618                                }
619                            }
620                        }
621                    });
622                }
623                rsipstack::rsip::Method::Options => {
624                    if self.config().options_response_enabled() {
625                        let (source_ip, source_host) = extract_via_source(&tx.original);
626                        if self.options_source_allowed(source_ip, &source_host) {
627                            info!(?key, %source_host, "responding to out-of-dialog OPTIONS request");
628                            let mut headers = vec![
629                                {
630                                    let allow_header: rsipstack::rsip::Header =
631                                        typed::Allow::from(Method::all()).into();
632                                    allow_header
633                                },
634                                rsipstack::rsip::Header::Accept(Accept::new("application/sdp")),
635                            ];
636                            let extra_headers = self.config().options_extra_headers();
637                            if !extra_headers.is_empty() {
638                                headers.extend(crate::sip_util::sip_headers_from_map(
639                                    &extra_headers.into_iter().collect::<HashMap<_, _>>(),
640                                ));
641                            }
642                            match tx
643                                .reply_with(rsipstack::rsip::StatusCode::OK, headers, None)
644                                .await
645                            {
646                                Ok(_) => (),
647                                Err(e) => {
648                                    info!("error replying to OPTIONS: {:?}", e);
649                                }
650                            }
651                        } else {
652                            debug!(
653                                ?key,
654                                %source_host,
655                                "dropping OPTIONS probe from non-allowed source"
656                            );
657                        }
658                    } else {
659                        info!(?key, "ignoring out-of-dialog OPTIONS request");
660                    }
661                    continue;
662                }
663                rsipstack::rsip::Method::Refer => {
664                    info!(?key, "ignoring out-of-dialog REFER");
665                    match tx.reply(rsipstack::rsip::StatusCode::BadRequest).await {
666                        Ok(_) => (),
667                        Err(e) => {
668                            info!("error replying to out-of-dialog REFER: {:?}", e);
669                        }
670                    }
671                    continue;
672                }
673                _ => {
674                    info!(?key, "received request: {:?}", tx.original.method);
675                    match tx.reply(rsipstack::rsip::StatusCode::OK).await {
676                        Ok(_) => (),
677                        Err(e) => {
678                            info!("error replying to request: {:?}", e);
679                        }
680                    }
681                }
682            }
683        }
684        Ok(())
685    }
686
687    pub fn stop(&self) {
688        if self.shutting_down.swap(true, Ordering::Relaxed) {
689            return;
690        }
691        info!("stopping, marking as shutting down");
692        self.token.cancel();
693    }
694
695    pub async fn graceful_stop(&self, total_timeout_secs: u64) -> Result<()> {
696        if self.shutting_down.swap(true, Ordering::Relaxed) {
697            return Ok(());
698        }
699
700        info!("graceful stopping, marking as shutting down");
701        let timeout = Duration::from_secs(total_timeout_secs);
702
703        let (reg_result, ()) = tokio::join!(
704            self.stop_registration(Some(timeout)),
705            self.wait_for_active_calls(timeout),
706        );
707        if let Err(e) = reg_result {
708            warn!("stop_registration error: {}", e);
709        }
710        self.token.cancel();
711        Ok(())
712    }
713
714    async fn wait_for_active_calls(&self, timeout: Duration) {
715        let active_calls = self.active_calls.clone();
716        let check_loop = async move {
717            let mut last_count = usize::MAX;
718            loop {
719                let count = active_calls.lock().unwrap().len();
720                if count == 0 {
721                    break;
722                }
723                if count != last_count {
724                    info!(active_calls = count, "waiting for active calls to finish");
725                    last_count = count;
726                }
727                tokio::time::sleep(Duration::from_millis(500)).await;
728            }
729        };
730        match tokio::time::timeout(timeout, check_loop).await {
731            Ok(()) => info!("all active calls finished"),
732            Err(_) => warn!("timed out waiting for active calls to finish, forcing shutdown"),
733        }
734    }
735
736    pub async fn start_registration(&self) -> Result<usize> {
737        let mut count = 0;
738        let config = self.config();
739        if let Some(register_users) = &config.register_users {
740            for option in register_users.iter() {
741                if option.disabled.unwrap_or(false) {
742                    info!(user = option.aor(), "registration disabled, skipping");
743                    continue;
744                }
745                match self.register(option.clone()).await {
746                    Ok(_) => {
747                        count += 1;
748                    }
749                    Err(e) => {
750                        warn!("failed to register user: {:?} {:?}", e, option);
751                    }
752                }
753            }
754        }
755        Ok(count)
756    }
757
758    pub fn find_credentials_for_callee(&self, callee: &str) -> Option<UserCredential> {
759        let callee_uri = crate::sip_util::ensure_sip_scheme(callee.to_string());
760
761        let parsed_callee = match rsipstack::rsip::Uri::try_from(callee_uri.as_str()) {
762            Ok(uri) => uri,
763            Err(e) => {
764                warn!("failed to parse callee URI: {} {:?}", callee, e);
765                return None;
766            }
767        };
768
769        // Matching is host-kind-homogeneous: a domain callee matches domain
770        // servers, an IP callee matches IP servers.
771        match &parsed_callee.host_with_port.host {
772            rsipstack::rsip::Host::Domain(domain) => {
773                let domain = domain.0.clone();
774                self.find_credentials(
775                    callee,
776                    &format!("domain {}", domain),
777                    |host| matches!(host, rsipstack::rsip::Host::Domain(d) if d.0 == domain),
778                )
779            }
780            rsipstack::rsip::Host::IpAddr(ip) => {
781                let ip = *ip;
782                self.find_credentials(callee, "IP match", move |host| {
783                    matches!(host, rsipstack::rsip::Host::IpAddr(server_ip) if *server_ip == ip)
784                })
785            }
786        }
787    }
788
789    /// Scan registered users for the first server matching `pred` that has a
790    /// credential.
791    fn find_credentials(
792        &self,
793        callee: &str,
794        match_type: &str,
795        pred: impl Fn(&rsipstack::rsip::Host) -> bool,
796    ) -> Option<UserCredential> {
797        let config = self.config();
798        let register_users = config.register_users.as_ref()?;
799        for option in register_users.iter() {
800            let server = crate::sip_util::ensure_sip_scheme(option.server.clone());
801
802            let parsed_server = match rsipstack::rsip::Uri::try_from(server.as_str()) {
803                Ok(uri) => uri,
804                Err(e) => {
805                    warn!("failed to parse server URI: {} {:?}", option.server, e);
806                    continue;
807                }
808            };
809
810            if pred(&parsed_server.host_with_port.host) {
811                if let Some(cred) = &option.credential {
812                    info!(
813                        callee,
814                        username = cred.username,
815                        server = option.server,
816                        match_type,
817                        "Auto-injecting credentials from registered user for outbound call"
818                    );
819                    return Some(cred.clone());
820                }
821            }
822        }
823        None
824    }
825
826    pub async fn stop_registration(&self, wait_for_clear: Option<Duration>) -> Result<()> {
827        {
828            let mut handles = self.registration_handles.lock().await;
829            for (_, cancel_token) in handles.drain() {
830                cancel_token.cancel();
831            }
832        }
833
834        if let Some(duration) = wait_for_clear {
835            let live_users = self.alive_users.clone();
836            let check_loop = async move {
837                loop {
838                    let is_empty = {
839                        let users = live_users
840                            .read()
841                            .map_err(|_| anyhow::anyhow!("Lock poisoned"))?;
842                        users.is_empty()
843                    };
844                    if is_empty {
845                        break;
846                    }
847                    tokio::time::sleep(Duration::from_millis(50)).await;
848                }
849                Ok::<(), anyhow::Error>(())
850            };
851            match tokio::time::timeout(duration, check_loop).await {
852                Ok(_) => {}
853                Err(e) => {
854                    warn!("failed to wait for clear: {}", e);
855                    return Err(anyhow::anyhow!("failed to wait for clear: {}", e));
856                }
857            }
858        }
859        Ok(())
860    }
861
862    pub async fn register(&self, option: RegisterOption) -> Result<()> {
863        let user = option.aor();
864        let server = crate::sip_util::ensure_sip_scheme(option.server.clone());
865        let sip_server = match rsipstack::rsip::Uri::try_from(server) {
866            Ok(uri) => uri,
867            Err(e) => {
868                warn!("failed to parse server: {} {:?}", e, option.server);
869                return Err(anyhow::anyhow!("failed to parse server: {}", e));
870            }
871        };
872        let cancel_token = self.token.child_token();
873        let credential = option.credential.clone().map(|c| c.into());
874        let registration = rsipstack::dialog::registration::Registration::new(
875            self.endpoint.inner.clone(),
876            credential,
877        );
878        let mut handle = RegistrationHandle {
879            registration,
880            option,
881            cancel_token: cancel_token.clone(),
882            start_time: Instant::now(),
883            last_update: Instant::now(),
884            last_response: None,
885        };
886        self.registration_handles
887            .lock()
888            .await
889            .insert(user.clone(), cancel_token);
890        tracing::debug!(user = user.as_str(), "starting registration task");
891        let alive_users = self.alive_users.clone();
892
893        crate::spawn(async move {
894            handle.start_time = Instant::now();
895            let cancel_token = handle.cancel_token.clone();
896            let addrs = handle.registration.endpoint.get_addrs();
897            let local_bind_addr = if let Some(addr) = find_local_addr_for_uri(&addrs, &sip_server) {
898                addr
899            } else {
900                warn!(
901                    user = user.as_str(),
902                    server = %sip_server,
903                    "failed to get local bind address for registration transport"
904                );
905                alive_users.write().unwrap().remove(&user);
906                return;
907            };
908            let user = handle.option.aor();
909            alive_users.write().unwrap().remove(&user);
910            let mut contact_address = local_bind_addr.addr.clone();
911            let mut contact = build_contact(
912                &local_bind_addr,
913                Some(contact_address.clone()),
914                Some(handle.option.username.as_str()),
915                None,
916            );
917            let mut should_register = true;
918            let mut timer = pending().boxed();
919
920            loop {
921                select! {
922                    _ = cancel_token.cancelled() => {
923                        break;
924                    }
925                    _ = timer.as_mut(), if !should_register => {
926                        should_register = true;
927                        timer = Box::pin(pending());
928                    }
929                    result = handle.do_register(&sip_server, None, &contact), if should_register => {
930                        match result {
931                            Ok((expires, new_addr)) => {
932                                if handle
933                                    .should_retry_registration_now(
934                                        &local_bind_addr,
935                                        &contact_address,
936                                        new_addr.as_ref(),
937                                    )
938                                {
939                                    if let Some(next_contact_address) = new_addr {
940                                        info!(
941                                            user = user.as_str(),
942                                            current_contact = %contact_address,
943                                            next_contact = %next_contact_address,
944                                            "public address changed, retrying registration immediately",
945                                        );
946                                        contact_address = next_contact_address;
947                                        contact = build_contact(
948                                            &local_bind_addr,
949                                            Some(contact_address.clone()),
950                                            Some(handle.option.username.as_str()),
951                                            None,
952                                        );
953                                        continue;
954                                    }
955                                }
956                                info!(
957                                    user = user.as_str(),
958                                    expires = expires,
959                                    contact = %contact_address,
960                                    alive_users = alive_users.read().unwrap().len(),
961                                    "registration refreshed",
962                                );
963                                alive_users.write().unwrap().insert(user.clone());
964                                should_register = false;
965                                timer = Box::pin(tokio::time::sleep(Duration::from_secs(
966                                    (expires * 3 / 4) as u64,
967                                )));
968                            }
969                            Err(e) => {
970                                warn!(
971                                    user = user.as_str(),
972                                    alive_users = alive_users.read().unwrap().len(),
973                                    "registration failed: {:?}", e
974                                );
975                                should_register = false;
976                                timer = Box::pin(tokio::time::sleep(Duration::from_secs(60)));
977                            }
978                        }
979                    }
980                }
981            }
982            handle
983                .do_register(&sip_server, Some(0), &contact)
984                .await
985                .ok();
986            alive_users.write().unwrap().remove(&user);
987        });
988        Ok(())
989    }
990}
991
992impl AppStateInner {
993    /// Current config snapshot. Cheap (`Arc` clone); call sites that make
994    /// several decisions from one consistent view should bind it first.
995    #[inline]
996    pub fn config(&self) -> Arc<Config> {
997        self.config.load_full()
998    }
999
1000    /// Path of the config file this process was started with, if any.
1001    pub fn config_path(&self) -> Option<&str> {
1002        self.config_path.as_deref()
1003    }
1004
1005    /// Re-read the config file recorded at startup and apply it.
1006    pub async fn reload_from_disk(&self) -> Result<ReloadReport, ReloadError> {
1007        let Some(path) = self.config_path() else {
1008            return Err(ReloadError::NoPath);
1009        };
1010        // `Config::load` also re-applies env overrides, so the precedence
1011        // (env > file > default) is identical to startup.
1012        let proposed = Config::load(path)
1013            .map_err(|e| ReloadError::Invalid(format!("{path}: {e}")))?;
1014        Ok(self.apply_config(proposed))
1015    }
1016
1017    /// Validate a proposed snapshot without installing it (`mode=check`).
1018    pub fn preview_config(&self, proposed: Config) -> ReloadReport {
1019        self.diff_report(&proposed)
1020    }
1021
1022    /// Validate and install a new config snapshot.
1023    ///
1024    /// Applying is atomic: the snapshot is swapped in one store, after which
1025    /// the module switches and the media cache directory are re-derived. The
1026    /// report classifies every changed top-level section so the caller can see
1027    /// which changes are live (`applied`), which wait for the next call
1028    /// (`deferred`) and which need a restart (`requires_restart`).
1029    pub fn apply_config(&self, proposed: Config) -> ReloadReport {
1030        let report = self.diff_report(&proposed);
1031        if report.status == "error" {
1032            return report;
1033        }
1034
1035        // Swap first, then derive the side effects from the new snapshot so a
1036        // concurrent call sees either the old or the new world, never a mix.
1037        self.config.store(Arc::new(proposed));
1038        let current = self.config.load_full();
1039        apply_side_effects(&current);
1040        report
1041    }
1042
1043    fn diff_report(&self, proposed: &Config) -> ReloadReport {
1044        diff_configs(&self.config.load_full(), proposed)
1045    }
1046}
1047
1048/// Classify the differences between two snapshots into the reload report.
1049fn diff_configs(old: &Config, proposed: &Config) -> ReloadReport {
1050    let old_json = serde_json::to_value(old).unwrap_or_default();
1051    let new_json = serde_json::to_value(proposed).unwrap_or_default();
1052
1053    let mut applied = Vec::new();
1054    let mut deferred = Vec::new();
1055    let mut requires_restart = Vec::new();
1056    let (Some(old_map), Some(new_map)) = (old_json.as_object(), new_json.as_object()) else {
1057        return ReloadReport {
1058            status: "error",
1059            revision: String::new(),
1060            applied,
1061            deferred,
1062            requires_restart,
1063        };
1064    };
1065
1066    let mut keys: Vec<&String> = old_map.keys().chain(new_map.keys()).collect();
1067    keys.sort();
1068    keys.dedup();
1069    for key in keys {
1070        let before = old_map.get(key).unwrap_or(&serde_json::Value::Null);
1071        let after = new_map.get(key).unwrap_or(&serde_json::Value::Null);
1072        if before == after {
1073            continue;
1074        }
1075        match classify_field(key) {
1076            FieldClass::Hot => applied.push(key.clone()),
1077            FieldClass::Deferred => deferred.push(key.clone()),
1078            FieldClass::Restart => requires_restart.push(key.clone()),
1079        }
1080    }
1081
1082    ReloadReport {
1083        status: if applied.is_empty() && deferred.is_empty() && requires_restart.is_empty() {
1084            "unchanged"
1085        } else {
1086            "ok"
1087        },
1088        revision: chrono::Utc::now().to_rfc3339(),
1089        applied,
1090        deferred,
1091        requires_restart,
1092    }
1093}
1094
1095/// How a changed top-level config section takes effect.
1096#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1097enum FieldClass {
1098    /// Read live from the snapshot (per request / per admission check).
1099    Hot,
1100    /// Read when a call, track or upload is set up.
1101    Deferred,
1102    /// Captured at build time; only a process restart applies it.
1103    Restart,
1104}
1105
1106fn classify_field(key: &str) -> FieldClass {
1107    match key {
1108        // Live per request/admission check.
1109        "admission" | "modules" | "reload" | "auto_learn_public_address"
1110        | "enable_options_response" | "options_response" | "peers" | "rewrites"
1111        | "trunk_rules" | "http_access_skip_paths" => FieldClass::Hot,
1112        // Read when a call/track/upload is set up.
1113        "callrecord" | "recording" | "media_cache_path" | "codecs" | "ice_servers"
1114        | "ambiance" | "jitter_buffer" | "enable_rtp_latching" | "enable_ice_lite"
1115        | "ice_disconnect_grace" | "enable_srtp" | "external_ip" | "rtp_bind_ip"
1116        | "auto_refer" | "auto_refer_timeout" | "accept_timeout" => FieldClass::Deferred,
1117        // Listener/UA/allocator/engine wiring built at startup.
1118        _ => FieldClass::Restart,
1119    }
1120}
1121
1122/// Re-derive the process-wide state that mirrors the config snapshot.
1123fn apply_side_effects(config: &Config) {
1124    crate::runtime::apply_config(config);
1125    if let Err(e) = crate::media::cache::set_cache_dir(&config.media_cache_path) {
1126        tracing::warn!(error = %e, "failed to update media cache dir on reload");
1127    }
1128}
1129
1130/// Outcome of one reload attempt.
1131#[derive(Debug, Clone, serde::Serialize)]
1132pub struct ReloadReport {
1133    /// `ok` (changed), `unchanged`, or `error`.
1134    pub status: &'static str,
1135    /// RFC 3339 timestamp of the snapshot this report describes.
1136    pub revision: String,
1137    /// Live immediately.
1138    pub applied: Vec<String>,
1139    /// Applies from the next call onwards.
1140    pub deferred: Vec<String>,
1141    /// Requires a process restart.
1142    pub requires_restart: Vec<String>,
1143}
1144
1145#[derive(Debug)]
1146pub enum ReloadError {
1147    /// The process was started without a config file path.
1148    NoPath,
1149    /// The file could not be read or parsed; the old snapshot stays live.
1150    Invalid(String),
1151}
1152
1153impl std::fmt::Display for ReloadError {
1154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1155        match self {
1156            ReloadError::NoPath => write!(
1157                f,
1158                "no config path recorded at startup; start with --conf or with_config_metadata"
1159            ),
1160            ReloadError::Invalid(e) => write!(f, "invalid configuration: {e}"),
1161        }
1162    }
1163}
1164
1165impl std::error::Error for ReloadError {}
1166
1167impl Drop for AppStateInner {
1168    fn drop(&mut self) {
1169        self.stop();
1170    }
1171}
1172
1173struct SimpleDomainResolver;
1174
1175#[async_trait]
1176impl DomainResolver for SimpleDomainResolver {
1177    async fn resolve(&self, target: &SipAddr) -> rsipstack::Result<SipAddr> {
1178        match &target.addr.host {
1179            Host::Domain(domain) => {
1180                let port: u16 = target.addr.port.map(|p| p.value()).unwrap_or(5060);
1181                let addr_str = format!("{}:{}", domain, port);
1182                match tokio::net::lookup_host(&addr_str).await {
1183                    Ok(mut addrs) => {
1184                        if let Some(addr) = addrs.next() {
1185                            Ok(SipAddr {
1186                                r#type: target.r#type,
1187                                addr: HostWithPort {
1188                                    host: Host::IpAddr(addr.ip()),
1189                                    port: Some(rsipstack::rsip::Port(addr.port())),
1190                                },
1191                            })
1192                        } else {
1193                            Err(rsipstack::Error::DnsResolutionError(format!(
1194                                "no addresses found for {}",
1195                                domain
1196                            )))
1197                        }
1198                    }
1199                    Err(e) => Err(rsipstack::Error::DnsResolutionError(format!(
1200                        "DNS resolution failed for {}: {}",
1201                        domain, e
1202                    ))),
1203                }
1204            }
1205            _ => Ok(target.clone()),
1206        }
1207    }
1208}
1209
1210impl AppStateBuilder {
1211    pub fn new() -> Self {
1212        Self {
1213            config: None,
1214            stream_engine: None,
1215            callrecord_sender: None,
1216            callrecord_formatter: None,
1217            cancel_token: None,
1218            create_invitation_handler: None,
1219            config_path: None,
1220            message_inspector: None,
1221            target_locator: None,
1222            transport_inspector: None,
1223            refer_header_resolver: None,
1224            sip_flow: None,
1225        }
1226    }
1227
1228    pub fn with_config(mut self, config: Config) -> Self {
1229        self.config = Some(config);
1230        self
1231    }
1232
1233    pub fn with_stream_engine(mut self, stream_engine: Arc<StreamEngine>) -> Self {
1234        self.stream_engine = Some(stream_engine);
1235        self
1236    }
1237
1238    pub fn with_callrecord_sender(mut self, sender: CallRecordSender) -> Self {
1239        self.callrecord_sender = Some(sender);
1240        self
1241    }
1242
1243    pub fn with_cancel_token(mut self, token: CancellationToken) -> Self {
1244        self.cancel_token = Some(token);
1245        self
1246    }
1247
1248    pub fn with_config_metadata(mut self, path: Option<String>) -> Self {
1249        self.config_path = path;
1250        self
1251    }
1252
1253    pub fn with_inspector(&mut self, inspector: Box<dyn MessageInspector>) -> &mut Self {
1254        self.message_inspector = Some(inspector);
1255        self
1256    }
1257    pub fn with_target_locator(&mut self, locator: Box<dyn TargetLocator>) -> &mut Self {
1258        self.target_locator = Some(locator);
1259        self
1260    }
1261
1262    pub fn with_transport_inspector(
1263        &mut self,
1264        inspector: Box<dyn TransportEventInspector>,
1265    ) -> &mut Self {
1266        self.transport_inspector = Some(inspector);
1267        self
1268    }
1269
1270    /// Install a hook that rewrites the custom headers an incoming REFER
1271    /// carries onto the transfer INVITE. Without one the REFER headers are
1272    /// forwarded unchanged.
1273    pub fn with_refer_header_resolver(
1274        mut self,
1275        resolver: std::sync::Arc<dyn ReferHeaderResolver>,
1276    ) -> Self {
1277        self.refer_header_resolver = Some(resolver);
1278        self
1279    }
1280
1281    /// Inject an externally created signaling recorder (see
1282    /// [`crate::sipflow`]). Takes precedence over `[sipflow]` config.
1283    pub fn with_sipflow(mut self, sip_flow: Arc<SipFlow>) -> Self {
1284        self.sip_flow = Some(sip_flow);
1285        self
1286    }
1287
1288    pub async fn build(mut self) -> Result<AppState> {
1289        let config: Arc<Config> = Arc::new(self.config.unwrap_or_default());
1290        // Publish the module switches before the first call can be set up.
1291        crate::runtime::apply_config(&config);
1292        let token = self
1293            .cancel_token
1294            .unwrap_or_else(|| CancellationToken::new());
1295        let _ = set_cache_dir(&config.media_cache_path);
1296        let local_ip = if !config.addr.is_empty() {
1297            std::net::IpAddr::from_str(config.addr.as_str())?
1298        } else {
1299            crate::net_tool::get_first_non_loopback_interface()?
1300        };
1301        let transport_layer = match catch_unwind(AssertUnwindSafe(|| {
1302            rsipstack::transport::TransportLayer::new(token.clone())
1303        })) {
1304            Ok(tl) => tl,
1305            Err(_) => {
1306                warn!(
1307                    "failed to initialize default DNS resolver with hickory-resolver, falling back to simple resolver via tokio::net::lookup_host"
1308                );
1309                rsipstack::transport::TransportLayer::new_with_domain_resolver(
1310                    token.clone(),
1311                    Box::new(SimpleDomainResolver),
1312                )
1313            }
1314        };
1315        let local_addr: SocketAddr = format!("{}:{}", local_ip, config.udp_port).parse()?;
1316
1317        // Create UDP socket with SO_REUSEPORT for graceful restarts
1318        #[cfg(unix)]
1319        let std_socket = {
1320            use socket2::{Domain, Protocol, SockAddr, Socket, Type};
1321
1322            let domain = if local_addr.is_ipv4() {
1323                Domain::IPV4
1324            } else {
1325                Domain::IPV6
1326            };
1327            let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))
1328                .map_err(|err| anyhow::anyhow!("Failed to create UDP socket: {}", err))?;
1329
1330            socket
1331                .set_reuse_address(true)
1332                .map_err(|err| anyhow::anyhow!("Failed to set SO_REUSEADDR: {}", err))?;
1333
1334            // SO_REUSEPORT (Linux/BSD)
1335            #[cfg(not(any(target_os = "solaris", target_os = "illumos", target_os = "cygwin")))]
1336            socket
1337                .set_reuse_port(true)
1338                .map_err(|err| anyhow::anyhow!("Failed to set SO_REUSEPORT: {}", err))?;
1339
1340            socket
1341                .bind(&SockAddr::from(local_addr))
1342                .map_err(|err| anyhow::anyhow!("Failed to bind UDP socket: {}", err))?;
1343
1344            let std_socket: std::net::UdpSocket = socket.into();
1345            std_socket
1346        };
1347
1348        #[cfg(not(unix))]
1349        let std_socket = std::net::UdpSocket::bind(local_addr)?;
1350
1351        std_socket.set_nonblocking(true)?;
1352        let tokio_socket = tokio::net::UdpSocket::from_std(std_socket)?;
1353        // Use the actual bound address (important when port=0 lets OS assign a port)
1354        let actual_addr = tokio_socket.local_addr()?;
1355        let bind_addr = rsipstack::transport::SipConnection::resolve_bind_address(actual_addr);
1356        let mut learned_public_address: SharedPublicAddress =
1357            Arc::new(ArcSwap::from_pointee(bind_addr.into()));
1358        let learned_peers =
1359            SharedLearnedPeers::new(crate::useragent::peer_learning::LEARNED_PEERS_CAPACITY);
1360
1361        let udp_inner = rsipstack::transport::udp::UdpInner {
1362            conn: std::sync::Arc::new(tokio_socket),
1363            addr: rsipstack::transport::SipAddr {
1364                r#type: Some(rsipstack::rsip::transport::Transport::Udp),
1365                addr: bind_addr.into(),
1366            },
1367        };
1368
1369        let external = config
1370            .external_ip
1371            .as_ref()
1372            .map(|ip| {
1373                format!("{}:{}", ip, actual_addr.port())
1374                    .parse()
1375                    .map_err(|e| anyhow::anyhow!("Failed to parse external address: {}", e))
1376            })
1377            .transpose()?;
1378
1379        let udp_conn = rsipstack::transport::udp::UdpConnection::attach(
1380            udp_inner,
1381            external,
1382            Some(token.child_token()),
1383        )
1384        .await;
1385
1386        info!(
1387            "start useragent, addr: {} (SO_REUSEPORT enabled)",
1388            udp_conn.get_addr()
1389        );
1390
1391        transport_layer.add_transport(udp_conn.into());
1392
1393        // Optional SIP over TLS transport
1394        if let Some(tls_port) = config.tls_port {
1395            let tls_addr: std::net::SocketAddr = format!("{}:{}", local_ip, tls_port).parse()?;
1396            let mut tls_cfg = rsipstack::transport::tls::TlsConfig::default();
1397            if let Some(ref cert_path) = config.tls_cert_file {
1398                tls_cfg.cert = Some(
1399                    std::fs::read(cert_path)
1400                        .map_err(|e| anyhow::anyhow!("tls_cert_file: {}", e))?,
1401                );
1402            }
1403            if let Some(ref key_path) = config.tls_key_file {
1404                tls_cfg.key = Some(
1405                    std::fs::read(key_path).map_err(|e| anyhow::anyhow!("tls_key_file: {}", e))?,
1406                );
1407            }
1408            let external_tls_addr = config
1409                .external_ip
1410                .as_ref()
1411                .and_then(|ip| format!("{}:{}", ip, tls_port).parse().ok());
1412            match rsipstack::transport::tls::TlsListenerConnection::new(
1413                tls_addr,
1414                external_tls_addr,
1415                tls_cfg,
1416            )
1417            .await
1418            {
1419                Ok(tls_conn) => {
1420                    transport_layer.add_transport(tls_conn.into());
1421                    info!("TLS SIP transport started on {}:{}", local_ip, tls_port);
1422                }
1423                Err(e) => {
1424                    return Err(anyhow::anyhow!("Failed to start TLS SIP transport: {}", e));
1425                }
1426            }
1427        }
1428
1429        let endpoint_option = rsipstack::transaction::endpoint::EndpointOption::default();
1430        let mut endpoint_builder = rsipstack::EndpointBuilder::new();
1431        if let Some(ref user_agent) = config.useragent {
1432            endpoint_builder.with_user_agent(user_agent.as_str());
1433        }
1434
1435        let mut endpoint_builder = endpoint_builder
1436            .with_cancel_token(token.child_token())
1437            .with_transport_layer(transport_layer)
1438            .with_option(endpoint_option);
1439
1440        // Inspector chain (outermost runs first): public-address learning
1441        // (opt-in) -> call-traffic peer learning (for the OPTIONS ACL) ->
1442        // any caller-provided inspector.
1443        let mut next_inspector = self.message_inspector.take();
1444        if config.options_auto_learn() {
1445            info!("learning call-traffic peer addresses for OPTIONS ACL");
1446            next_inspector = Some(Box::new(PeerAddressLearner::new_with_next(
1447                learned_peers.clone(),
1448                next_inspector,
1449            )));
1450        }
1451        if config.auto_learn_public_address.unwrap_or_default() {
1452            let inspector = LearningMessageInspector::new(bind_addr.into(), next_inspector);
1453            learned_public_address = inspector.shared_public_address();
1454            next_inspector = Some(Box::new(inspector));
1455        }
1456
1457        // [sipflow] in-process signaling capture — outermost inspector so
1458        // every message (both directions, REFER transfer dialogs included)
1459        // is recorded before any other inspector sees it. An injected
1460        // recorder takes precedence over the config section.
1461        let sip_flow = match self.sip_flow.take() {
1462            Some(flow) => Some(flow),
1463            None => match config.sipflow.as_ref().filter(|c| c.enabled()) {
1464                Some(sipflow_config) => {
1465                    info!(
1466                        max_calls = sipflow_config.max_calls(),
1467                        max_items_per_call = sipflow_config.max_items_per_call(),
1468                        upload = sipflow_config.upload.is_some(),
1469                        "sipflow signaling capture enabled"
1470                    );
1471                    Some(Arc::new(SipFlow::new(
1472                        sipflow_config.clone(),
1473                        bind_addr.to_string(),
1474                        None,
1475                    )))
1476                }
1477                None => None,
1478            },
1479        };
1480        if let Some(flow) = sip_flow.as_ref() {
1481            flow.set_next(next_inspector.take());
1482            next_inspector = Some(Box::new(SipFlow::clone(flow)));
1483        }
1484
1485        if let Some(inspector) = next_inspector {
1486            endpoint_builder = endpoint_builder.with_inspector(inspector);
1487        }
1488        if let Some(locator) = self.target_locator {
1489            endpoint_builder.with_target_locator(locator);
1490        } else if let Some(ref rules) = config.rewrites {
1491            endpoint_builder
1492                .with_target_locator(Box::new(RewriteTargetLocator::new(rules.clone())));
1493        }
1494
1495        if let Some(inspector) = self.transport_inspector {
1496            endpoint_builder = endpoint_builder.with_transport_inspector(inspector);
1497        }
1498
1499        let endpoint = endpoint_builder.build();
1500        let dialog_layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
1501
1502        let stream_engine = self.stream_engine.unwrap_or_default();
1503
1504        let callrecord_formatter = if let Some(formatter) = self.callrecord_formatter {
1505            formatter
1506        } else {
1507            let formatter = if let Some(ref callrecord) = config.callrecord {
1508                DefaultCallRecordFormatter::new_with_config(callrecord)
1509            } else {
1510                DefaultCallRecordFormatter::default()
1511            };
1512            Arc::new(formatter)
1513        };
1514
1515        let callrecord_sender = if let Some(sender) = self.callrecord_sender {
1516            Some(sender)
1517        } else if let Some(ref callrecord) = config.callrecord {
1518            let builder = CallRecordManagerBuilder::new()
1519                .with_cancel_token(token.child_token())
1520                .with_config(callrecord.clone())
1521                .with_max_concurrent(32)
1522                .with_formatter(callrecord_formatter.clone());
1523            // Attach the sipflow upload/eviction hook when capture is on.
1524            let builder = match sip_flow.as_ref() {
1525                Some(flow) => builder.with_hook(Arc::new(SipFlowUploadHook {
1526                    flow: flow.clone(),
1527                    upload: config
1528                        .sipflow
1529                        .as_ref()
1530                        .and_then(|c| c.upload.clone()),
1531                })),
1532                None => builder,
1533            };
1534
1535            let mut callrecord_manager = builder.build();
1536            let sender = callrecord_manager.sender.clone();
1537            crate::spawn(async move {
1538                callrecord_manager.serve().await;
1539            });
1540            Some(sender)
1541        } else {
1542            None
1543        };
1544
1545        let app_state = Arc::new(AppStateInner {
1546            config: ArcSwap::from(config),
1547            config_path: self.config_path.map(Arc::from),
1548            token,
1549            stream_engine,
1550            callrecord_sender,
1551            endpoint,
1552            registration_handles: Mutex::new(HashMap::new()),
1553            alive_users: Arc::new(RwLock::new(HashSet::new())),
1554            dialog_layer: dialog_layer.clone(),
1555            create_invitation_handler: self.create_invitation_handler,
1556            invitation: Invitation::new(dialog_layer),
1557            routing_state: Arc::new(crate::call::RoutingState::new()),
1558            pending_playbooks: Arc::new(Mutex::new(HashMap::new())),
1559            sip_flow,
1560            learned_public_address,
1561            learned_peers,
1562            refer_header_resolver: self.refer_header_resolver,
1563            active_calls: Arc::new(std::sync::Mutex::new(HashMap::new())),
1564            total_calls: AtomicU64::new(0),
1565            total_failed_calls: AtomicU64::new(0),
1566            uptime: Local::now(),
1567            shutting_down: Arc::new(AtomicBool::new(false)),
1568        });
1569
1570        if app_state.config().reload_watch() {
1571            crate::spawn(watch_config_file(app_state.clone()));
1572        }
1573
1574        Ok(app_state)
1575    }
1576}
1577
1578/// Poll the config file (mtime + size) and apply changes.
1579///
1580/// Off unless `[reload] watch = true`: deploys should use the explicit
1581/// `mode=check` → `mode=apply` flow. The watcher exists for ops convenience;
1582/// write the file atomically (`.tmp` + rename) to avoid parsing a half-written
1583/// config — a parse failure keeps the previous snapshot live and the next
1584/// change re-triggers it anyway.
1585async fn watch_config_file(state: AppState) {
1586    fn stamp(path: &str) -> Option<(std::time::SystemTime, u64)> {
1587        let meta = std::fs::metadata(path).ok()?;
1588        Some((meta.modified().ok()?, meta.len()))
1589    }
1590
1591    let Some(path) = state.config_path().map(str::to_string) else {
1592        return;
1593    };
1594    let mut last = stamp(&path);
1595    loop {
1596        tokio::time::sleep(state.config().reload_watch_interval()).await;
1597        if state.token.is_cancelled() {
1598            return;
1599        }
1600        let now = stamp(&path);
1601        if now == last {
1602            continue;
1603        }
1604        last = now;
1605        // Let an in-progress write settle before parsing.
1606        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1607        match state.reload_from_disk().await {
1608            Ok(report) => info!(
1609                status = report.status,
1610                applied = ?report.applied,
1611                deferred = ?report.deferred,
1612                requires_restart = ?report.requires_restart,
1613                "config reloaded by file watcher"
1614            ),
1615            Err(e) => warn!(error = %e, "config reload failed; keeping previous snapshot"),
1616        }
1617    }
1618}
1619
1620#[cfg(test)]
1621mod reload_tests {
1622    use super::diff_configs;
1623    use crate::config::{AdmissionConfig, Config, ModuleToggle, ModulesConfig};
1624
1625    #[test]
1626    fn identical_config_is_unchanged() {
1627        let old = Config::default();
1628        let report = diff_configs(&old, &old);
1629        assert_eq!(report.status, "unchanged");
1630        assert!(report.applied.is_empty());
1631        assert!(report.deferred.is_empty());
1632        assert!(report.requires_restart.is_empty());
1633    }
1634
1635    #[test]
1636    fn hot_sections_are_live_and_listener_changes_need_restart() {
1637        let old = Config::default();
1638        let mut new = Config::default();
1639        new.admission = Some(AdmissionConfig {
1640            max_active_calls: Some(10),
1641            wait_ms: Some(250),
1642        });
1643        new.modules = Some(ModulesConfig {
1644            denoise: Some(ModuleToggle { enabled: false }),
1645            ..Default::default()
1646        });
1647        new.udp_port = old.udp_port + 1;
1648
1649        let report = diff_configs(&old, &new);
1650        assert_eq!(report.status, "ok");
1651        assert!(report.applied.contains(&"admission".to_string()));
1652        assert!(report.applied.contains(&"modules".to_string()));
1653        assert!(report.requires_restart.contains(&"udp_port".to_string()));
1654        assert!(report.deferred.is_empty());
1655    }
1656
1657    #[test]
1658    fn per_call_sections_are_deferred() {
1659        let old = Config::default();
1660        let mut new = Config::default();
1661        new.codecs = Some(vec!["pcmu".to_string()]);
1662        let report = diff_configs(&old, &new);
1663        assert_eq!(report.deferred, vec!["codecs".to_string()]);
1664        assert!(report.applied.is_empty());
1665    }
1666
1667    #[test]
1668    fn removing_a_section_is_reported() {
1669        let mut old = Config::default();
1670        old.admission = Some(AdmissionConfig {
1671            max_active_calls: Some(10),
1672            wait_ms: None,
1673        });
1674        let new = Config::default();
1675        let report = diff_configs(&old, &new);
1676        assert!(report.applied.contains(&"admission".to_string()));
1677    }
1678}