Skip to main content

active_call/
config.rs

1use crate::media::{ambiance::AmbianceOption, recorder::RecorderFormat};
2use crate::useragent::RegisterOption;
3use anyhow::{Error, Result};
4use clap::Parser;
5use rsipstack::dialog::invitation::InviteOption;
6use rsipstack::rsip::uri::{Auth, HostWithPort, Uri};
7use rustrtc::IceServer;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11#[derive(Parser, Debug)]
12#[command(version)]
13pub struct Cli {
14    /// Path to configuration file
15    #[clap(long)]
16    pub conf: Option<String>,
17    /// HTTP listening address
18    #[clap(long)]
19    pub http: Option<String>,
20
21    /// SIP listening port
22    #[clap(long)]
23    pub sip: Option<String>,
24
25    /// SIP invitation handler: URL for webhook (http://...) or playbook file (.md)
26    #[clap(long)]
27    pub handler: Option<String>,
28
29    /// Call a SIP address immediately and use the handler for the call
30    #[clap(long)]
31    pub call: Option<String>,
32
33    /// External IP address for SIP/RTP
34    #[clap(long)]
35    pub external_ip: Option<String>,
36
37    /// Supported codecs (e.g., pcmu,pcma,g722,g729,opus)
38    #[clap(long, value_delimiter = ',')]
39    pub codecs: Option<Vec<String>>,
40
41    /// Download models (sensevoice, supertonic, or all)
42    #[cfg(feature = "offline")]
43    #[clap(long)]
44    pub download_models: Option<String>,
45
46    /// Models directory for offline inference
47    #[cfg(feature = "offline")]
48    #[clap(long, default_value = "./models")]
49    pub models_dir: String,
50
51    /// Exit after downloading models
52    #[cfg(feature = "offline")]
53    #[clap(long)]
54    pub exit_after_download: bool,
55}
56
57pub(crate) fn default_config_recorder_path() -> String {
58    #[cfg(target_os = "windows")]
59    return "./config/recorders".to_string();
60    #[cfg(not(target_os = "windows"))]
61    return "./config/recorders".to_string();
62}
63
64fn default_config_media_cache_path() -> String {
65    #[cfg(target_os = "windows")]
66    return "./config/mediacache".to_string();
67    #[cfg(not(target_os = "windows"))]
68    return "./config/mediacache".to_string();
69}
70
71fn default_config_http_addr() -> String {
72    "0.0.0.0:8080".to_string()
73}
74
75fn default_sip_addr() -> String {
76    "0.0.0.0".to_string()
77}
78
79fn default_sip_port() -> u16 {
80    25060
81}
82
83fn default_config_rtp_start_port() -> Option<u16> {
84    Some(12000)
85}
86
87fn default_config_rtp_end_port() -> Option<u16> {
88    Some(42000)
89}
90
91fn default_config_rtp_latching() -> Option<bool> {
92    Some(true)
93}
94
95fn default_graceful_shutdown() -> Option<bool> {
96    Some(true)
97}
98
99fn default_graceful_shutdown_timeout() -> Option<u64> {
100    Some(30)
101}
102
103fn default_config_useragent() -> Option<String> {
104    Some(format!(
105        "active-call({} miuda.ai)",
106        env!("CARGO_PKG_VERSION")
107    ))
108}
109
110fn default_enable_options_response() -> Option<bool> {
111    Some(true)
112}
113
114fn default_options_allow_registered_servers() -> Option<bool> {
115    Some(true)
116}
117
118fn default_options_auto_learn() -> Option<bool> {
119    Some(true)
120}
121
122fn default_options_learn_ttl() -> Option<String> {
123    Some("7d".to_string())
124}
125
126fn default_codecs() -> Option<Vec<String>> {
127    let codecs = vec![
128        "pcmu".to_string(),
129        "pcma".to_string(),
130        "g722".to_string(),
131        "g729".to_string(),
132        "opus".to_string(),
133        "telephone_event".to_string(),
134    ];
135    Some(codecs)
136}
137
138#[derive(Debug, Clone, Deserialize, Serialize, Default)]
139#[serde(rename_all = "snake_case")]
140pub struct RecordingPolicy {
141    #[serde(default)]
142    pub enabled: bool,
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub auto_start: Option<bool>,
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub filename_pattern: Option<String>,
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub samplerate: Option<u32>,
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub ptime: Option<u32>,
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub path: Option<String>,
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub format: Option<RecorderFormat>,
155    /// Record at the source's native sample rate instead of resampling to
156    /// 16 kHz. The actual rate is detected from the caller leg's codec.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub native_samplerate: Option<bool>,
159}
160
161impl RecordingPolicy {
162    pub fn recorder_path(&self) -> String {
163        self.path
164            .as_ref()
165            .map(|p| p.trim())
166            .filter(|p| !p.is_empty())
167            .map(|p| p.to_string())
168            .unwrap_or_else(default_config_recorder_path)
169    }
170
171    pub fn recorder_format(&self) -> RecorderFormat {
172        self.format.unwrap_or_default()
173    }
174
175    pub fn ensure_defaults(&mut self) -> bool {
176        if self
177            .path
178            .as_ref()
179            .map(|p| p.trim().is_empty())
180            .unwrap_or(true)
181        {
182            self.path = Some(default_config_recorder_path());
183        }
184
185        false
186    }
187}
188
189#[derive(Debug, Clone, Deserialize, Serialize)]
190pub struct RewriteRule {
191    pub r#match: String,
192    pub rewrite: String,
193}
194
195/// Trunk-like SIP INVITE/REFER rewriting rule.
196///
197/// Rules are evaluated in declaration order and the first rule whose `match`
198/// conditions all hold (AND) is applied via its `rewrite` actions
199/// (first-match-wins). A rule with an empty `match` section always matches and
200/// therefore acts as a catch-all default.
201///
202/// ```toml
203/// [[trunk_rules]]
204/// rule.match.to.host = "^172\\.25\\."
205/// rule.rewrite.contact.host = "172.25.225.2"
206/// ```
207#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
208#[serde(rename_all = "snake_case")]
209pub struct TrunkRule {
210    pub rule: TrunkRuleDef,
211}
212
213#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
214#[serde(rename_all = "snake_case")]
215pub struct TrunkRuleDef {
216    #[serde(default, rename = "match")]
217    pub r#match: TrunkMatch,
218    pub rewrite: TrunkRewrite,
219}
220
221/// Match conditions for a trunk rule. All non-None fields must match (AND).
222/// `from` matches the SIP From header (caller), `to` matches the SIP To header
223/// and Request-URI (callee) of the outgoing INVITE/REFER.
224#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
225#[serde(rename_all = "snake_case")]
226pub struct TrunkMatch {
227    pub from: Option<UriMatch>,
228    pub to: Option<UriMatch>,
229}
230
231/// Matches a URI against optional regex patterns on its user and host parts.
232/// `user` matches the username before `@`; `host` matches the host after `@`.
233#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
234#[serde(rename_all = "snake_case")]
235pub struct UriMatch {
236    /// Regex matched against the SIP URI user part (before `@`).
237    pub user: Option<String>,
238    /// Regex matched against the SIP URI host part (after `@`).
239    pub host: Option<String>,
240}
241
242/// Rewrite actions applied once a rule matches. All non-None fields are applied.
243#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
244#[serde(rename_all = "snake_case")]
245pub struct TrunkRewrite {
246    pub from: Option<UriRewrite>,
247    pub to: Option<UriRewrite>,
248    pub contact: Option<UriRewrite>,
249}
250
251/// Rewrites the user and/or host of a SIP URI. When a `host` value carries no
252/// port (e.g. `"172.25.225.2"`), the original URI port is preserved; include a
253/// port (e.g. `"172.25.225.2:15060"`) to also change it.
254#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
255#[serde(rename_all = "snake_case")]
256pub struct UriRewrite {
257    pub user: Option<String>,
258    pub host: Option<String>,
259}
260
261impl TrunkRule {
262    fn matches(&self, invite: &InviteOption) -> bool {
263        self.rule.r#match.matches(invite)
264    }
265
266    fn apply(&self, invite: &mut InviteOption) {
267        self.rule.rewrite.apply(invite);
268    }
269}
270
271impl TrunkMatch {
272    fn matches(&self, invite: &InviteOption) -> bool {
273        let from_ok = self
274            .from
275            .as_ref()
276            .map(|from| from.matches(&invite.caller))
277            .unwrap_or(true);
278        let to_ok = self
279            .to
280            .as_ref()
281            .map(|to| to.matches(&invite.callee))
282            .unwrap_or(true);
283        from_ok && to_ok
284    }
285}
286
287impl UriMatch {
288    fn matches(&self, uri: &Uri) -> bool {
289        let user_ok = self
290            .user
291            .as_ref()
292            .map(|user| {
293                uri.auth
294                    .as_ref()
295                    .map(|auth| regex_is_match(user, &auth.user))
296                    .unwrap_or(false)
297            })
298            .unwrap_or(true);
299        let host_ok = self
300            .host
301            .as_ref()
302            .map(|host| regex_is_match(host, &uri.host_with_port.host.to_string()))
303            .unwrap_or(true);
304        user_ok && host_ok
305    }
306}
307
308impl TrunkRewrite {
309    fn apply(&self, invite: &mut InviteOption) {
310        if let Some(from) = &self.from {
311            from.apply(&mut invite.caller);
312        }
313        if let Some(to) = &self.to {
314            to.apply(&mut invite.callee);
315        }
316        if let Some(contact) = &self.contact {
317            contact.apply(&mut invite.contact);
318        }
319    }
320}
321
322impl UriRewrite {
323    fn apply(&self, uri: &mut Uri) {
324        if let Some(user) = &self.user {
325            let auth = uri.auth.get_or_insert_with(|| Auth {
326                user: String::new(),
327                password: None,
328            });
329            auth.user = user.clone();
330        }
331        if let Some(host) = &self.host
332            && let Ok(mut host_with_port) = HostWithPort::try_from(host.as_str())
333        {
334            // Preserve the original port when the rewrite value omits one.
335            if host_with_port.port.is_none() {
336                host_with_port.port = uri.host_with_port.port;
337            }
338            uri.host_with_port = host_with_port;
339        }
340    }
341}
342
343fn regex_is_match(pattern: &str, value: &str) -> bool {
344    regex::Regex::new(pattern)
345        .map(|re| re.is_match(value))
346        .unwrap_or(false)
347}
348
349/// Extracts the host part of a `register_users[].server` value, which may be
350/// `host`, `host:port`, or `[ipv6]:port`.
351fn host_of_server(server: &str) -> Option<String> {
352    let server = server.trim();
353    if server.is_empty() {
354        return None;
355    }
356    if let Some(rest) = server.strip_prefix('[') {
357        // [ipv6]:port or [ipv6]
358        return rest.split(']').next().map(|h| h.to_ascii_lowercase());
359    }
360    // A bare ipv6 literal without brackets contains multiple colons; keep it whole.
361    if server.matches(':').count() > 1 {
362        return Some(server.to_ascii_lowercase());
363    }
364    server.split(':').next().map(|h| h.to_ascii_lowercase())
365}
366
367/// One parsed `[options_response].allow` entry: an exact IP, a CIDR block, or
368/// a hostname.
369#[derive(Debug, Clone, PartialEq)]
370pub enum OptionsAclEntry {
371    Ip(std::net::IpAddr),
372    Cidr(ipnet::IpNet),
373    Host(String),
374}
375
376impl OptionsAclEntry {
377    fn parse(raw: &str) -> Option<Self> {
378        let raw = raw.trim();
379        if raw.is_empty() {
380            return None;
381        }
382        if let Ok(ip) = raw.parse::<std::net::IpAddr>() {
383            return Some(Self::Ip(ip));
384        }
385        if let Ok(cidr) = raw.parse::<ipnet::IpNet>() {
386            return Some(Self::Cidr(cidr));
387        }
388        Some(Self::Host(raw.to_ascii_lowercase()))
389    }
390
391    pub fn matches(&self, source_ip: Option<std::net::IpAddr>, source_host: &str) -> bool {
392        match self {
393            Self::Ip(ip) => source_ip == Some(*ip),
394            Self::Cidr(net) => source_ip.map(|ip| net.contains(&ip)).unwrap_or(false),
395            Self::Host(host) => host.eq_ignore_ascii_case(source_host),
396        }
397    }
398}
399
400/// `[options_response]` — customizes the 200 OK answers to out-of-dialog
401/// OPTIONS keep-alive probes and restricts which sources are answered.
402///
403/// A probe is answered only when its source (top Via header) matches the
404/// static `allow` ACL, a `register_users[].server` host, or a peer address
405/// learned from call traffic (`auto_learn`). Everything else is dropped
406/// silently.
407#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
408#[serde(rename_all = "snake_case")]
409pub struct OptionsResponseConfig {
410    /// Answer out-of-dialog OPTIONS probes; falls back to the legacy
411    /// `enable_options_response` field, defaulting to `true`.
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    pub enabled: Option<bool>,
414    /// Static ACL entries: exact IP (`139.224.72.64`), CIDR (`10.0.0.0/8`),
415    /// or hostname (`sip.ccc.aliyuncs.com`).
416    #[serde(default, skip_serializing_if = "Vec::is_empty")]
417    pub allow: Vec<String>,
418    /// Also answer probes coming from the hosts of `register_users[].server`.
419    #[serde(default = "default_options_allow_registered_servers")]
420    pub allow_registered_servers: Option<bool>,
421    /// Learn peer addresses from call traffic — inbound INVITEs and responses
422    /// to our outbound INVITEs — and answer probes from those sources within
423    /// `learn_ttl` (strict mode: until the first peer is learned, only the
424    /// static ACL and registered hosts apply).
425    #[serde(default = "default_options_auto_learn")]
426    pub auto_learn: Option<bool>,
427    /// How long a learned peer address stays valid, e.g. `"7d"` (default).
428    #[serde(default = "default_options_learn_ttl")]
429    pub learn_ttl: Option<String>,
430    /// Extra headers appended to the OPTIONS 200 OK response.
431    #[serde(default, skip_serializing_if = "Vec::is_empty")]
432    pub extra_headers: Vec<(String, String)>,
433}
434
435#[derive(Debug, Deserialize, Serialize)]
436pub struct Config {
437    #[serde(default = "default_config_http_addr")]
438    pub http_addr: String,
439    pub addr: String,
440    pub udp_port: u16,
441    pub auto_learn_public_address: Option<bool>,
442
443    pub log_level: Option<String>,
444    pub log_file: Option<String>,
445    #[serde(default, skip_serializing_if = "Vec::is_empty")]
446    pub http_access_skip_paths: Vec<String>,
447
448    /// Peer active-call nodes ("ip:port" of their HTTP/WS endpoint).
449    ///
450    /// When a websocket client connects with a session id that is not hosted on
451    /// this node, the originator (empty `forward`) polls each peer once
452    /// (`forward=true`) and tunnels the websocket to the peer that hosts the
453    /// call. Any request whose `forward` is set must not hop further.
454    #[serde(default, skip_serializing_if = "Vec::is_empty")]
455    pub peers: Vec<String>,
456
457    #[serde(default = "default_config_useragent")]
458    pub useragent: Option<String>,
459    pub register_users: Option<Vec<RegisterOption>>,
460    #[serde(default = "default_graceful_shutdown")]
461    pub graceful_shutdown: Option<bool>,
462    /// Total seconds to wait during graceful shutdown before forcing exit.
463    /// SIP de-registration and active call draining run in parallel, both with this timeout.
464    #[serde(default = "default_graceful_shutdown_timeout")]
465    pub graceful_shutdown_timeout: Option<u64>,
466    pub handler: Option<InviteHandlerConfig>,
467    pub accept_timeout: Option<String>,
468    #[serde(default = "default_codecs")]
469    pub codecs: Option<Vec<String>>,
470    pub external_ip: Option<String>,
471    #[serde(default = "default_config_rtp_start_port")]
472    pub rtp_start_port: Option<u16>,
473    #[serde(default = "default_config_rtp_end_port")]
474    pub rtp_end_port: Option<u16>,
475    #[serde(default = "default_config_rtp_latching")]
476    pub enable_rtp_latching: Option<bool>,
477    pub enable_ice_lite: Option<bool>,
478    /// How long a WebRTC connection may stay ICE-disconnected before its media
479    /// is torn down and the call hung up, e.g. "15s". The call carries on if
480    /// ICE recovers within it. Unset or unparsable: rustrtc's default (60s).
481    pub ice_disconnect_grace: Option<String>,
482    pub rtp_bind_ip: Option<String>,
483    pub tls_port: Option<u16>,
484    pub tls_cert_file: Option<String>,
485    pub tls_key_file: Option<String>,
486
487    pub enable_srtp: Option<bool>,
488
489    pub callrecord: Option<CallRecordConfig>,
490    #[serde(default = "default_config_media_cache_path")]
491    pub media_cache_path: String,
492    pub ambiance: Option<AmbianceOption>,
493    pub ice_servers: Option<Vec<IceServer>>,
494    #[serde(default)]
495    pub recording: Option<RecordingPolicy>,
496    pub rewrites: Option<Vec<RewriteRule>>,
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub trunk_rules: Option<Vec<TrunkRule>>,
499    #[serde(default = "default_enable_options_response")]
500    pub enable_options_response: Option<bool>,
501    #[serde(default, skip_serializing_if = "Option::is_none")]
502    pub options_response: Option<OptionsResponseConfig>,
503
504    /// Follow incoming in-dialog REFER automatically: dial the Refer-To
505    /// target and bridge media (transfer). The `transferRequest` session
506    /// event is always emitted regardless; when disabled the RFC 3515
507    /// implicit subscription is terminated with a 403 NOTIFY instead.
508    #[serde(default, skip_serializing_if = "Option::is_none")]
509    pub auto_refer: Option<bool>,
510    /// Timeout in seconds for the INVITE handshake of an auto-refer leg.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub auto_refer_timeout: Option<u32>,
513    /// In-process SIP signaling capture and post-call JSONL upload
514    /// (rustpbx-style "sipflow", lightweight in-memory flavour).
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    pub sipflow: Option<crate::sipflow::SipFlowConfig>,
517}
518
519impl Config {
520    /// Whether incoming in-dialog REFERs are followed automatically
521    /// (defaults to true).
522    pub fn auto_refer(&self) -> bool {
523        self.auto_refer.unwrap_or(true)
524    }
525
526    /// INVITE handshake timeout in seconds for auto-refer legs (default 30).
527    pub fn auto_refer_timeout(&self) -> u32 {
528        self.auto_refer_timeout.unwrap_or(30)
529    }
530}
531
532#[derive(Debug, Deserialize, Clone, Serialize)]
533#[serde(rename_all = "snake_case")]
534#[serde(tag = "type")]
535pub enum InviteHandlerConfig {
536    Webhook {
537        url: Option<String>,
538        urls: Option<Vec<String>>,
539        method: Option<String>,
540        headers: Option<Vec<(String, String)>>,
541    },
542    Playbook {
543        rules: Option<Vec<PlaybookRule>>,
544        default: Option<String>,
545    },
546}
547
548#[derive(Debug, Deserialize, Clone, Serialize)]
549#[serde(rename_all = "snake_case")]
550pub struct PlaybookRule {
551    pub caller: Option<String>,
552    pub callee: Option<String>,
553    pub playbook: String,
554}
555
556#[derive(Debug, Deserialize, Clone, Serialize)]
557#[serde(rename_all = "snake_case")]
558pub enum S3Vendor {
559    Aliyun,
560    Tencent,
561    Minio,
562    AWS,
563    GCP,
564    Azure,
565    DigitalOcean,
566}
567
568#[derive(Debug, Deserialize, Clone, Serialize)]
569#[serde(tag = "type")]
570#[serde(rename_all = "snake_case")]
571pub enum CallRecordConfig {
572    Local {
573        root: String,
574    },
575    S3 {
576        vendor: S3Vendor,
577        bucket: String,
578        region: String,
579        access_key: String,
580        secret_key: String,
581        endpoint: String,
582        root: String,
583        with_media: Option<bool>,
584        keep_media_copy: Option<bool>,
585    },
586    Http {
587        url: String,
588        headers: Option<HashMap<String, String>>,
589        with_media: Option<bool>,
590        keep_media_copy: Option<bool>,
591    },
592}
593
594impl Default for CallRecordConfig {
595    fn default() -> Self {
596        Self::Local {
597            #[cfg(target_os = "windows")]
598            root: "./config/cdr".to_string(),
599            #[cfg(not(target_os = "windows"))]
600            root: "./config/cdr".to_string(),
601        }
602    }
603}
604
605impl Default for Config {
606    fn default() -> Self {
607        Self {
608            http_addr: default_config_http_addr(),
609            log_level: None,
610            log_file: None,
611            http_access_skip_paths: Vec::new(),
612            peers: Vec::new(),
613            addr: default_sip_addr(),
614            udp_port: default_sip_port(),
615            auto_learn_public_address: None,
616            useragent: None,
617            register_users: None,
618            graceful_shutdown: Some(true),
619            graceful_shutdown_timeout: default_graceful_shutdown_timeout(),
620            handler: None,
621            accept_timeout: Some("50s".to_string()),
622            media_cache_path: default_config_media_cache_path(),
623            ambiance: None,
624            callrecord: None,
625            ice_servers: None,
626            codecs: None,
627            external_ip: None,
628            rtp_start_port: default_config_rtp_start_port(),
629            rtp_end_port: default_config_rtp_end_port(),
630            enable_rtp_latching: Some(true),
631            rtp_bind_ip: None,
632            enable_ice_lite: None,
633            ice_disconnect_grace: None,
634            tls_port: None,
635            tls_cert_file: None,
636            tls_key_file: None,
637            enable_srtp: None,
638            recording: None,
639            rewrites: None,
640            trunk_rules: None,
641            enable_options_response: default_enable_options_response(),
642            options_response: None,
643            auto_refer: None,
644            auto_refer_timeout: None,
645            sipflow: None,
646        }
647    }
648}
649
650impl Clone for Config {
651    fn clone(&self) -> Self {
652        // This is a bit expensive but Config is not cloned often in hot paths
653        // and implementing Clone manually for all nested structs is tedious
654        let s = toml::to_string(self).unwrap();
655        toml::from_str(&s).unwrap()
656    }
657}
658
659impl Config {
660    pub fn load(path: &str) -> Result<Self, Error> {
661        let config: Self = toml::from_str(
662            &std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("{}: {}", e, path))?,
663        )?;
664        Ok(config)
665    }
666
667    /// Parsed `ice_disconnect_grace`; None keeps rustrtc's default.
668    pub fn ice_disconnect_grace(&self) -> Option<std::time::Duration> {
669        self.ice_disconnect_grace
670            .as_deref()
671            .and_then(|raw| humantime::parse_duration(raw).ok())
672    }
673
674    /// Whether out-of-dialog OPTIONS probes should be answered at all.
675    pub fn options_response_enabled(&self) -> bool {
676        self.options_response
677            .as_ref()
678            .and_then(|o| o.enabled)
679            .or(self.enable_options_response)
680            .unwrap_or(true)
681    }
682
683    /// Whether peer addresses should be learned from call traffic.
684    pub fn options_auto_learn(&self) -> bool {
685        self.options_response
686            .as_ref()
687            .and_then(|o| o.auto_learn)
688            .unwrap_or(true)
689    }
690
691    /// TTL for learned peer addresses; unparsable/missing values default to 7 days.
692    pub fn options_learn_ttl(&self) -> std::time::Duration {
693        const DEFAULT: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
694        self.options_response
695            .as_ref()
696            .and_then(|o| o.learn_ttl.as_deref())
697            .map(|raw| humantime::parse_duration(raw).unwrap_or(DEFAULT))
698            .unwrap_or(DEFAULT)
699    }
700
701    /// Parsed static ACL entries for OPTIONS probing.
702    pub fn options_acl_entries(&self) -> Vec<OptionsAclEntry> {
703        self.options_response
704            .as_ref()
705            .map(|o| {
706                o.allow
707                    .iter()
708                    .filter_map(|raw| OptionsAclEntry::parse(raw))
709                    .collect()
710            })
711            .unwrap_or_default()
712    }
713
714    /// Hosts of `register_users[].server` when `allow_registered_servers` is
715    /// on (the default); empty otherwise.
716    pub fn options_registered_hosts(&self) -> Vec<String> {
717        let enabled = self
718            .options_response
719            .as_ref()
720            .and_then(|o| o.allow_registered_servers)
721            .unwrap_or(true);
722        if !enabled {
723            return vec![];
724        }
725        self.register_users
726            .as_ref()
727            .map(|users| {
728                users
729                    .iter()
730                    .filter_map(|user| host_of_server(&user.server))
731                    .collect()
732            })
733            .unwrap_or_default()
734    }
735
736    /// Extra headers appended to OPTIONS 200 OK responses.
737    pub fn options_extra_headers(&self) -> Vec<(String, String)> {
738        self.options_response
739            .as_ref()
740            .map(|o| o.extra_headers.clone())
741            .unwrap_or_default()
742    }
743
744    /// Whether `source_ip`/`source_host` matches the static ACL or the
745    /// registered-server hosts (the configured, non-learned allow sets).
746    pub fn options_matches_static(
747        &self,
748        source_ip: Option<std::net::IpAddr>,
749        source_host: &str,
750    ) -> bool {
751        self.options_acl_entries()
752            .iter()
753            .any(|entry| entry.matches(source_ip, source_host))
754            || self
755                .options_registered_hosts()
756                .iter()
757                .any(|host| host.eq_ignore_ascii_case(source_host))
758    }
759
760    pub fn recorder_path(&self) -> String {
761        self.recording
762            .as_ref()
763            .map(|policy| policy.recorder_path())
764            .unwrap_or_else(default_config_recorder_path)
765    }
766
767    pub fn recorder_format(&self) -> RecorderFormat {
768        self.recording
769            .as_ref()
770            .map(|policy| policy.recorder_format())
771            .unwrap_or_default()
772    }
773
774    pub fn recorder_native_samplerate(&self) -> bool {
775        self.recording
776            .as_ref()
777            .and_then(|policy| policy.native_samplerate)
778            .unwrap_or(false)
779    }
780
781    pub fn ensure_recording_defaults(&mut self) -> bool {
782        let mut fallback = false;
783
784        if let Some(policy) = self.recording.as_mut() {
785            fallback |= policy.ensure_defaults();
786        }
787
788        fallback
789    }
790
791    /// Apply the first matching trunk rule to an outgoing SIP INVITE/REFER.
792    ///
793    /// Rules are evaluated in declaration order; the first rule whose `match`
794    /// conditions (all AND) hold is applied and later rules are skipped
795    /// (first-match-wins). A rule with an empty `match` section always matches
796    /// and acts as a catch-all default. If no rule matches, the invite is left
797    /// untouched. Does nothing when [`Config::trunk_rules`] is not configured.
798    pub fn apply_trunk_rules(&self, invite: &mut InviteOption) {
799        if let Some(rules) = &self.trunk_rules {
800            for rule in rules {
801                if rule.matches(invite) {
802                    rule.apply(invite);
803                    break;
804                }
805            }
806        }
807    }
808
809    /// Normalize a configured peer to a `ws://` (or `wss://`) base URL.
810    ///
811    /// Accepts bare `ip:port`, or an explicit `ws://`, `wss://`, `http://` or
812    /// `https://` scheme. Returns `None` when the value is empty or unusable.
813    pub fn peer_ws_endpoint(peer: &str) -> Option<String> {
814        let peer = peer.trim();
815        if peer.is_empty() {
816            return None;
817        }
818        if peer.starts_with("wss://") {
819            return Some(peer.to_string());
820        }
821        if peer.starts_with("ws://") {
822            return Some(peer.to_string());
823        }
824        if peer.starts_with("https://") {
825            return Some(peer.replacen("https://", "wss://", 1));
826        }
827        if peer.starts_with("http://") {
828            return Some(peer.replacen("http://", "ws://", 1));
829        }
830        Some(format!("ws://{}", peer))
831    }
832}
833
834#[cfg(test)]
835mod tests {
836    use super::*;
837
838    #[test]
839    fn test_playbook_handler_config_parsing() {
840        let toml_config = r#"
841http_addr = "0.0.0.0:8080"
842addr = "0.0.0.0"
843udp_port = 25060
844
845[handler]
846type = "playbook"
847default = "default.md"
848
849[[handler.rules]]
850caller = "^\\+1\\d{10}$"
851callee = "^sip:support@.*"
852playbook = "support.md"
853
854[[handler.rules]]
855caller = "^\\+86\\d+"
856playbook = "chinese.md"
857
858[[handler.rules]]
859callee = "^sip:sales@.*"
860playbook = "sales.md"
861"#;
862
863        let config: Config = toml::from_str(toml_config).unwrap();
864
865        assert!(config.handler.is_some());
866        if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
867            assert_eq!(default, Some("default.md".to_string()));
868            let rules = rules.unwrap();
869            assert_eq!(rules.len(), 3);
870
871            assert_eq!(rules[0].caller, Some(r"^\+1\d{10}$".to_string()));
872            assert_eq!(rules[0].callee, Some("^sip:support@.*".to_string()));
873            assert_eq!(rules[0].playbook, "support.md");
874
875            assert_eq!(rules[1].caller, Some(r"^\+86\d+".to_string()));
876            assert_eq!(rules[1].callee, None);
877            assert_eq!(rules[1].playbook, "chinese.md");
878
879            assert_eq!(rules[2].caller, None);
880            assert_eq!(rules[2].callee, Some("^sip:sales@.*".to_string()));
881            assert_eq!(rules[2].playbook, "sales.md");
882        } else {
883            panic!("Expected Playbook handler config");
884        }
885    }
886
887    #[test]
888    fn test_playbook_handler_config_without_default() {
889        let toml_config = r#"
890http_addr = "0.0.0.0:8080"
891addr = "0.0.0.0"
892udp_port = 25060
893
894[handler]
895type = "playbook"
896
897[[handler.rules]]
898caller = "^\\+1.*"
899playbook = "us.md"
900"#;
901
902        let config: Config = toml::from_str(toml_config).unwrap();
903
904        if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
905            assert_eq!(default, None);
906            let rules = rules.unwrap();
907            assert_eq!(rules.len(), 1);
908        } else {
909            panic!("Expected Playbook handler config");
910        }
911    }
912
913    #[test]
914    fn test_webhook_handler_config_still_works() {
915        let toml_config = r#"
916http_addr = "0.0.0.0:8080"
917addr = "0.0.0.0"
918udp_port = 25060
919
920[handler]
921type = "webhook"
922url = "http://example.com/webhook"
923"#;
924
925        let config: Config = toml::from_str(toml_config).unwrap();
926
927        if let Some(InviteHandlerConfig::Webhook { url, .. }) = config.handler {
928            assert_eq!(url, Some("http://example.com/webhook".to_string()));
929        } else {
930            panic!("Expected Webhook handler config");
931        }
932    }
933
934    // ---------------------------------------------------------------------------
935    // options_response: config parsing + accessors
936    // ---------------------------------------------------------------------------
937
938    #[test]
939    fn test_options_response_defaults() {
940        let config: Config = toml::from_str(
941            r#"
942http_addr = "0.0.0.0:8080"
943addr = "0.0.0.0"
944udp_port = 25060
945"#,
946        )
947        .unwrap();
948
949        assert!(config.options_response.is_none());
950        // Section absent: enabled via the legacy field/default, auto-learn on,
951        // 7d TTL, no static entries, no extra headers.
952        assert!(config.options_response_enabled());
953        assert!(config.options_auto_learn());
954        assert_eq!(
955            config.options_learn_ttl(),
956            std::time::Duration::from_secs(7 * 24 * 3600)
957        );
958        assert!(config.options_acl_entries().is_empty());
959        assert!(config.options_registered_hosts().is_empty());
960        assert!(config.options_extra_headers().is_empty());
961    }
962
963    #[test]
964    fn test_options_response_config_parsing() {
965        let toml_config = r#"
966http_addr = "0.0.0.0:8080"
967addr = "0.0.0.0"
968udp_port = 25060
969
970[options_response]
971enabled = true
972allow = ["139.224.72.64", "10.0.0.0/8", "SIP.CCC.AliyunCS.com"]
973allow_registered_servers = false
974auto_learn = false
975learn_ttl = "1h"
976extra_headers = [["X-Node-Id", "node-1"], ["User-Agent", "ActiveCall-Test"]]
977"#;
978
979        let config: Config = toml::from_str(toml_config).unwrap();
980        let options = config.options_response.as_ref().unwrap();
981        assert_eq!(options.enabled, Some(true));
982        assert_eq!(options.allow_registered_servers, Some(false));
983        assert_eq!(options.auto_learn, Some(false));
984
985        assert!(!config.options_auto_learn());
986        assert_eq!(
987            config.options_learn_ttl(),
988            std::time::Duration::from_secs(3600)
989        );
990
991        let entries = config.options_acl_entries();
992        assert_eq!(entries.len(), 3);
993        assert_eq!(
994            entries[0],
995            OptionsAclEntry::Ip("139.224.72.64".parse().unwrap())
996        );
997        assert!(matches!(entries[1], OptionsAclEntry::Cidr(_)));
998        assert_eq!(
999            entries[2],
1000            OptionsAclEntry::Host("sip.ccc.aliyuncs.com".to_string())
1001        );
1002
1003        let headers = config.options_extra_headers();
1004        assert_eq!(headers.len(), 2);
1005        assert_eq!(headers[0], ("X-Node-Id".to_string(), "node-1".to_string()));
1006    }
1007
1008    #[test]
1009    fn test_options_response_enabled_fallback_chain() {
1010        // Legacy field only.
1011        let config: Config = toml::from_str(
1012            r#"
1013addr = "0.0.0.0"
1014udp_port = 25060
1015enable_options_response = false
1016"#,
1017        )
1018        .unwrap();
1019        assert!(!config.options_response_enabled());
1020
1021        // New section wins over the legacy field.
1022        let config: Config = toml::from_str(
1023            r#"
1024addr = "0.0.0.0"
1025udp_port = 25060
1026enable_options_response = false
1027
1028[options_response]
1029enabled = true
1030"#,
1031        )
1032        .unwrap();
1033        assert!(config.options_response_enabled());
1034
1035        // New section with enabled unset falls back to the legacy field.
1036        let config: Config = toml::from_str(
1037            r#"
1038addr = "0.0.0.0"
1039udp_port = 25060
1040enable_options_response = false
1041
1042[options_response]
1043extra_headers = [["X-A", "1"]]
1044"#,
1045        )
1046        .unwrap();
1047        assert!(!config.options_response_enabled());
1048    }
1049
1050    #[test]
1051    fn test_options_acl_matching() {
1052        let toml_config = r#"
1053addr = "0.0.0.0"
1054udp_port = 25060
1055
1056[options_response]
1057allow = ["139.224.72.64", "10.0.0.0/8", "sip.ccc.aliyuncs.com"]
1058"#;
1059        let config: Config = toml::from_str(toml_config).unwrap();
1060        let ip = |s: &str| Some(s.parse::<std::net::IpAddr>().unwrap());
1061
1062        // Exact IP.
1063        assert!(config.options_matches_static(ip("139.224.72.64"), "139.224.72.64"));
1064        assert!(!config.options_matches_static(ip("139.224.72.65"), "139.224.72.65"));
1065        // CIDR.
1066        assert!(config.options_matches_static(ip("10.1.2.3"), "10.1.2.3"));
1067        assert!(!config.options_matches_static(ip("192.168.1.1"), "192.168.1.1"));
1068        // Hostname, case-insensitive.
1069        assert!(config.options_matches_static(None, "SIP.CCC.ALIYUNCS.COM"));
1070        assert!(!config.options_matches_static(None, "sip.example.com"));
1071        // An IP source does not match the hostname entry and vice versa.
1072        assert!(!config.options_matches_static(None, "139.224.72.64"));
1073    }
1074
1075    #[test]
1076    fn test_options_registered_hosts() {
1077        let toml_config = r#"
1078addr = "0.0.0.0"
1079udp_port = 25060
1080
1081[[register_users]]
1082server = "sip.example.com:5060"
1083username = "1001"
1084
1085[[register_users]]
1086server = "10.0.0.5"
1087username = "1002"
1088"#;
1089        let config: Config = toml::from_str(toml_config).unwrap();
1090        // Default: registered servers are allowed.
1091        assert_eq!(
1092            config.options_registered_hosts(),
1093            vec!["sip.example.com".to_string(), "10.0.0.5".to_string()]
1094        );
1095        assert!(config.options_matches_static(None, "SIP.EXAMPLE.COM"));
1096        assert!(config.options_matches_static(Some("10.0.0.5".parse().unwrap()), "10.0.0.5"));
1097
1098        // Opt out via allow_registered_servers = false.
1099        let toml_config_off = r#"
1100addr = "0.0.0.0"
1101udp_port = 25060
1102
1103[[register_users]]
1104server = "sip.example.com"
1105username = "1001"
1106
1107[options_response]
1108allow_registered_servers = false
1109"#;
1110        let config: Config = toml::from_str(toml_config_off).unwrap();
1111        assert!(config.options_registered_hosts().is_empty());
1112        assert!(!config.options_matches_static(None, "sip.example.com"));
1113    }
1114
1115    #[test]
1116    fn test_host_of_server() {
1117        assert_eq!(
1118            host_of_server("sip.example.com:5060"),
1119            Some("sip.example.com".to_string())
1120        );
1121        assert_eq!(
1122            host_of_server("SIP.Example.COM"),
1123            Some("sip.example.com".to_string())
1124        );
1125        assert_eq!(
1126            host_of_server("[2001:db8::1]:5060"),
1127            Some("2001:db8::1".to_string())
1128        );
1129        assert_eq!(
1130            host_of_server("2001:db8::1"),
1131            Some("2001:db8::1".to_string())
1132        );
1133        assert_eq!(host_of_server(""), None);
1134    }
1135
1136    // ---------------------------------------------------------------------------
1137    // trunk_rules: config parsing
1138    // ---------------------------------------------------------------------------
1139
1140    #[test]
1141    fn test_trunk_rules_config_parsing() {
1142        let toml_config = r#"
1143http_addr = "0.0.0.0:8080"
1144addr = "0.0.0.0"
1145udp_port = 25060
1146
1147[[trunk_rules]]
1148rule.match.to.host = "^172\\.25\\."
1149rule.rewrite.contact.host = "172.25.225.2"
1150
1151[[trunk_rules]]
1152rule.match.from.user = "^\\+86.*"
1153rule.match.to.host = "^10\\."
1154rule.rewrite.from.user = "10086"
1155rule.rewrite.to.host = "10.0.0.1"
1156rule.rewrite.contact.user = "active-call"
1157rule.rewrite.contact.host = "10.0.0.1:25060"
1158
1159[[trunk_rules]]
1160rule.rewrite.contact.host = "116.62.75.161"
1161"#;
1162
1163        let config: Config = toml::from_str(toml_config).unwrap();
1164        let rules = config.trunk_rules.expect("trunk_rules should be parsed");
1165
1166        assert_eq!(rules.len(), 3);
1167
1168        // Rule 1: match to.host, rewrite contact.host
1169        let m = &rules[0].rule.r#match;
1170        assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^172\\.25\\."));
1171        assert_eq!(m.to.as_ref().unwrap().user, None);
1172        assert_eq!(m.from, None);
1173        let w = &rules[0].rule.rewrite;
1174        assert_eq!(
1175            w.contact.as_ref().unwrap().host.as_deref(),
1176            Some("172.25.225.2")
1177        );
1178        assert_eq!(w.from, None);
1179        assert_eq!(w.to, None);
1180
1181        // Rule 2: combined match + all rewrites
1182        let m = &rules[1].rule.r#match;
1183        assert_eq!(m.from.as_ref().unwrap().user.as_deref(), Some("^\\+86.*"));
1184        assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^10\\."));
1185        let w = &rules[1].rule.rewrite;
1186        assert_eq!(w.from.as_ref().unwrap().user.as_deref(), Some("10086"));
1187        assert_eq!(w.to.as_ref().unwrap().host.as_deref(), Some("10.0.0.1"));
1188        assert_eq!(
1189            w.contact.as_ref().unwrap().user.as_deref(),
1190            Some("active-call")
1191        );
1192        assert_eq!(
1193            w.contact.as_ref().unwrap().host.as_deref(),
1194            Some("10.0.0.1:25060")
1195        );
1196
1197        // Rule 3: catch-all (empty match)
1198        assert_eq!(rules[2].rule.r#match.from, None);
1199        assert_eq!(rules[2].rule.r#match.to, None);
1200        assert_eq!(
1201            rules[2]
1202                .rule
1203                .rewrite
1204                .contact
1205                .as_ref()
1206                .unwrap()
1207                .host
1208                .as_deref(),
1209            Some("116.62.75.161")
1210        );
1211    }
1212
1213    #[test]
1214    fn test_trunk_rules_absent_by_default() {
1215        let config = Config::default();
1216        assert!(config.trunk_rules.is_none());
1217    }
1218
1219    // ---------------------------------------------------------------------------
1220    // trunk_rules: match + rewrite behaviour
1221    // ---------------------------------------------------------------------------
1222
1223    fn invite_option(caller: &str, callee: &str, contact: &str) -> InviteOption {
1224        InviteOption {
1225            caller: caller.try_into().unwrap(),
1226            callee: callee.try_into().unwrap(),
1227            contact: contact.try_into().unwrap(),
1228            ..Default::default()
1229        }
1230    }
1231
1232    #[test]
1233    fn test_trunk_rule_matches_on_to_host() {
1234        let config: Config = toml::from_str(
1235            r#"
1236addr = "0.0.0.0"
1237udp_port = 25060
1238
1239[[trunk_rules]]
1240rule.match.to.host = "^172\\.25\\."
1241rule.rewrite.contact.host = "172.25.225.2"
1242"#,
1243        )
1244        .unwrap();
1245
1246        // Internal target -> matched, contact host rewritten.
1247        let mut invite = invite_option(
1248            "sip:ai@116.62.75.161:13050",
1249            "sip:agent1@172.25.225.3:15060",
1250            "sip:ai@127.0.0.1:13050",
1251        );
1252        config.apply_trunk_rules(&mut invite);
1253        assert_eq!(
1254            invite.contact.host_with_port.host.to_string(),
1255            "172.25.225.2"
1256        );
1257
1258        // External target -> no match, contact untouched.
1259        let mut invite = invite_option(
1260            "sip:ai@116.62.75.161:13050",
1261            "sip:+8613800138000@sbc.example.com:5060",
1262            "sip:ai@127.0.0.1:13050",
1263        );
1264        config.apply_trunk_rules(&mut invite);
1265        assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1266    }
1267
1268    #[test]
1269    fn test_trunk_rule_matches_on_from_user_and_to_host() {
1270        let config: Config = toml::from_str(
1271            r#"
1272addr = "0.0.0.0"
1273udp_port = 25060
1274
1275[[trunk_rules]]
1276rule.match.from.user = "^anonymous$"
1277rule.match.to.host = "^sbc\\."
1278rule.rewrite.contact.host = "116.62.75.161"
1279"#,
1280        )
1281        .unwrap();
1282
1283        // from.user + to.host both match -> rewritten.
1284        let mut invite = invite_option(
1285            "sip:anonymous@116.62.75.161:13050",
1286            "sip:+8613800138000@sbc.example.com:5060",
1287            "sip:ai@127.0.0.1:13050",
1288        );
1289        config.apply_trunk_rules(&mut invite);
1290        assert_eq!(
1291            invite.contact.host_with_port.host.to_string(),
1292            "116.62.75.161"
1293        );
1294
1295        // from.user does not match -> no rewrite.
1296        let mut invite = invite_option(
1297            "sip:alice@116.62.75.161:13050",
1298            "sip:+8613800138000@sbc.example.com:5060",
1299            "sip:ai@127.0.0.1:13050",
1300        );
1301        config.apply_trunk_rules(&mut invite);
1302        assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1303    }
1304
1305    #[test]
1306    fn test_trunk_rule_rewrites_from_to_contact() {
1307        let config: Config = toml::from_str(
1308            r#"
1309addr = "0.0.0.0"
1310udp_port = 25060
1311
1312[[trunk_rules]]
1313rule.match.to.host = "^10\\."
1314rule.rewrite.from.user = "10086"
1315rule.rewrite.from.host = "116.62.75.161"
1316rule.rewrite.to.user = "30000"
1317rule.rewrite.to.host = "10.0.0.1:25060"
1318rule.rewrite.contact.user = "active-call"
1319rule.rewrite.contact.host = "10.0.0.1"
1320"#,
1321        )
1322        .unwrap();
1323
1324        let mut invite = invite_option(
1325            "sip:ai@127.0.0.1:13050",
1326            "sip:agent1@10.0.0.2:25060",
1327            "sip:ai@127.0.0.1:13050",
1328        );
1329        config.apply_trunk_rules(&mut invite);
1330
1331        // caller (from)
1332        assert_eq!(invite.caller.auth.as_ref().unwrap().user, "10086");
1333        assert_eq!(
1334            invite.caller.host_with_port.host.to_string(),
1335            "116.62.75.161"
1336        );
1337
1338        // callee (to)
1339        assert_eq!(invite.callee.auth.as_ref().unwrap().user, "30000");
1340        assert_eq!(invite.callee.host_with_port.host.to_string(), "10.0.0.1");
1341        assert_eq!(invite.callee.host_with_port.port.unwrap().0, 25060);
1342
1343        // contact: host rewritten without port -> original port preserved
1344        assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1345        assert_eq!(invite.contact.host_with_port.host.to_string(), "10.0.0.1");
1346        assert_eq!(invite.contact.host_with_port.port.unwrap().0, 13050);
1347    }
1348
1349    #[test]
1350    fn test_trunk_rule_catch_all_default() {
1351        let config: Config = toml::from_str(
1352            r#"
1353addr = "0.0.0.0"
1354udp_port = 25060
1355
1356[[trunk_rules]]
1357rule.match.to.host = "^172\\.25\\."
1358rule.rewrite.contact.host = "172.25.225.2"
1359
1360[[trunk_rules]]
1361rule.rewrite.contact.host = "116.62.75.161"
1362"#,
1363        )
1364        .unwrap();
1365
1366        // Not matched by rule 1 -> falls through to catch-all rule 2.
1367        let mut invite = invite_option(
1368            "sip:ai@116.62.75.161:13050",
1369            "sip:+8613800138000@sbc.example.com:5060",
1370            "sip:ai@127.0.0.1:13050",
1371        );
1372        config.apply_trunk_rules(&mut invite);
1373        assert_eq!(
1374            invite.contact.host_with_port.host.to_string(),
1375            "116.62.75.161"
1376        );
1377    }
1378
1379    #[test]
1380    fn test_trunk_rule_first_match_wins() {
1381        let config: Config = toml::from_str(
1382            r#"
1383addr = "0.0.0.0"
1384udp_port = 25060
1385
1386[[trunk_rules]]
1387rule.match.to.host = ".*"
1388rule.rewrite.contact.host = "1.1.1.1"
1389
1390[[trunk_rules]]
1391rule.match.to.host = ".*"
1392rule.rewrite.contact.host = "2.2.2.2"
1393"#,
1394        )
1395        .unwrap();
1396
1397        let mut invite = invite_option(
1398            "sip:ai@116.62.75.161:13050",
1399            "sip:any@example.com:5060",
1400            "sip:ai@127.0.0.1:13050",
1401        );
1402        config.apply_trunk_rules(&mut invite);
1403        // Only the first rule applies.
1404        assert_eq!(invite.contact.host_with_port.host.to_string(), "1.1.1.1");
1405    }
1406
1407    #[test]
1408    fn test_trunk_rule_no_config_noop() {
1409        let config = Config::default();
1410        let mut invite = invite_option(
1411            "sip:ai@116.62.75.161:13050",
1412            "sip:agent1@172.25.225.3:15060",
1413            "sip:ai@127.0.0.1:13050",
1414        );
1415        let before = invite.contact.to_string();
1416        config.apply_trunk_rules(&mut invite);
1417        assert_eq!(invite.contact.to_string(), before);
1418    }
1419
1420    #[test]
1421    fn test_trunk_rule_rewrite_missing_auth_creates_user() {
1422        let config: Config = toml::from_str(
1423            r#"
1424addr = "0.0.0.0"
1425udp_port = 25060
1426
1427[[trunk_rules]]
1428rule.match.to.host = ".*"
1429rule.rewrite.contact.user = "active-call"
1430"#,
1431        )
1432        .unwrap();
1433
1434        // A contact without a user part (e.g. "sip:127.0.0.1:13050").
1435        let mut invite = InviteOption {
1436            caller: "sip:ai@127.0.0.1:13050".try_into().unwrap(),
1437            callee: "sip:agent1@172.25.225.3:15060".try_into().unwrap(),
1438            contact: "sip:127.0.0.1:13050".try_into().unwrap(),
1439            ..Default::default()
1440        };
1441        config.apply_trunk_rules(&mut invite);
1442        assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1443    }
1444}