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    pub rtp_bind_ip: Option<String>,
479    pub tls_port: Option<u16>,
480    pub tls_cert_file: Option<String>,
481    pub tls_key_file: Option<String>,
482
483    pub enable_srtp: Option<bool>,
484
485    pub callrecord: Option<CallRecordConfig>,
486    #[serde(default = "default_config_media_cache_path")]
487    pub media_cache_path: String,
488    pub ambiance: Option<AmbianceOption>,
489    pub ice_servers: Option<Vec<IceServer>>,
490    #[serde(default)]
491    pub recording: Option<RecordingPolicy>,
492    pub rewrites: Option<Vec<RewriteRule>>,
493    #[serde(default, skip_serializing_if = "Option::is_none")]
494    pub trunk_rules: Option<Vec<TrunkRule>>,
495    #[serde(default = "default_enable_options_response")]
496    pub enable_options_response: Option<bool>,
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub options_response: Option<OptionsResponseConfig>,
499
500    /// Follow incoming in-dialog REFER automatically: dial the Refer-To
501    /// target and bridge media (transfer). The `transferRequest` session
502    /// event is always emitted regardless; when disabled the RFC 3515
503    /// implicit subscription is terminated with a 403 NOTIFY instead.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub auto_refer: Option<bool>,
506    /// Timeout in seconds for the INVITE handshake of an auto-refer leg.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub auto_refer_timeout: Option<u32>,
509    /// In-process SIP signaling capture and post-call JSONL upload
510    /// (rustpbx-style "sipflow", lightweight in-memory flavour).
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub sipflow: Option<crate::sipflow::SipFlowConfig>,
513}
514
515impl Config {
516    /// Whether incoming in-dialog REFERs are followed automatically
517    /// (defaults to true).
518    pub fn auto_refer(&self) -> bool {
519        self.auto_refer.unwrap_or(true)
520    }
521
522    /// INVITE handshake timeout in seconds for auto-refer legs (default 30).
523    pub fn auto_refer_timeout(&self) -> u32 {
524        self.auto_refer_timeout.unwrap_or(30)
525    }
526}
527
528#[derive(Debug, Deserialize, Clone, Serialize)]
529#[serde(rename_all = "snake_case")]
530#[serde(tag = "type")]
531pub enum InviteHandlerConfig {
532    Webhook {
533        url: Option<String>,
534        urls: Option<Vec<String>>,
535        method: Option<String>,
536        headers: Option<Vec<(String, String)>>,
537    },
538    Playbook {
539        rules: Option<Vec<PlaybookRule>>,
540        default: Option<String>,
541    },
542}
543
544#[derive(Debug, Deserialize, Clone, Serialize)]
545#[serde(rename_all = "snake_case")]
546pub struct PlaybookRule {
547    pub caller: Option<String>,
548    pub callee: Option<String>,
549    pub playbook: String,
550}
551
552#[derive(Debug, Deserialize, Clone, Serialize)]
553#[serde(rename_all = "snake_case")]
554pub enum S3Vendor {
555    Aliyun,
556    Tencent,
557    Minio,
558    AWS,
559    GCP,
560    Azure,
561    DigitalOcean,
562}
563
564#[derive(Debug, Deserialize, Clone, Serialize)]
565#[serde(tag = "type")]
566#[serde(rename_all = "snake_case")]
567pub enum CallRecordConfig {
568    Local {
569        root: String,
570    },
571    S3 {
572        vendor: S3Vendor,
573        bucket: String,
574        region: String,
575        access_key: String,
576        secret_key: String,
577        endpoint: String,
578        root: String,
579        with_media: Option<bool>,
580        keep_media_copy: Option<bool>,
581    },
582    Http {
583        url: String,
584        headers: Option<HashMap<String, String>>,
585        with_media: Option<bool>,
586        keep_media_copy: Option<bool>,
587    },
588}
589
590impl Default for CallRecordConfig {
591    fn default() -> Self {
592        Self::Local {
593            #[cfg(target_os = "windows")]
594            root: "./config/cdr".to_string(),
595            #[cfg(not(target_os = "windows"))]
596            root: "./config/cdr".to_string(),
597        }
598    }
599}
600
601impl Default for Config {
602    fn default() -> Self {
603        Self {
604            http_addr: default_config_http_addr(),
605            log_level: None,
606            log_file: None,
607            http_access_skip_paths: Vec::new(),
608            peers: Vec::new(),
609            addr: default_sip_addr(),
610            udp_port: default_sip_port(),
611            auto_learn_public_address: None,
612            useragent: None,
613            register_users: None,
614            graceful_shutdown: Some(true),
615            graceful_shutdown_timeout: default_graceful_shutdown_timeout(),
616            handler: None,
617            accept_timeout: Some("50s".to_string()),
618            media_cache_path: default_config_media_cache_path(),
619            ambiance: None,
620            callrecord: None,
621            ice_servers: None,
622            codecs: None,
623            external_ip: None,
624            rtp_start_port: default_config_rtp_start_port(),
625            rtp_end_port: default_config_rtp_end_port(),
626            enable_rtp_latching: Some(true),
627            rtp_bind_ip: None,
628            enable_ice_lite: None,
629            tls_port: None,
630            tls_cert_file: None,
631            tls_key_file: None,
632            enable_srtp: None,
633            recording: None,
634            rewrites: None,
635            trunk_rules: None,
636            enable_options_response: default_enable_options_response(),
637            options_response: None,
638            auto_refer: None,
639            auto_refer_timeout: None,
640            sipflow: None,
641        }
642    }
643}
644
645impl Clone for Config {
646    fn clone(&self) -> Self {
647        // This is a bit expensive but Config is not cloned often in hot paths
648        // and implementing Clone manually for all nested structs is tedious
649        let s = toml::to_string(self).unwrap();
650        toml::from_str(&s).unwrap()
651    }
652}
653
654impl Config {
655    pub fn load(path: &str) -> Result<Self, Error> {
656        let config: Self = toml::from_str(
657            &std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("{}: {}", e, path))?,
658        )?;
659        Ok(config)
660    }
661
662    /// Whether out-of-dialog OPTIONS probes should be answered at all.
663    pub fn options_response_enabled(&self) -> bool {
664        self.options_response
665            .as_ref()
666            .and_then(|o| o.enabled)
667            .or(self.enable_options_response)
668            .unwrap_or(true)
669    }
670
671    /// Whether peer addresses should be learned from call traffic.
672    pub fn options_auto_learn(&self) -> bool {
673        self.options_response
674            .as_ref()
675            .and_then(|o| o.auto_learn)
676            .unwrap_or(true)
677    }
678
679    /// TTL for learned peer addresses; unparsable/missing values default to 7 days.
680    pub fn options_learn_ttl(&self) -> std::time::Duration {
681        const DEFAULT: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
682        self.options_response
683            .as_ref()
684            .and_then(|o| o.learn_ttl.as_deref())
685            .map(|raw| humantime::parse_duration(raw).unwrap_or(DEFAULT))
686            .unwrap_or(DEFAULT)
687    }
688
689    /// Parsed static ACL entries for OPTIONS probing.
690    pub fn options_acl_entries(&self) -> Vec<OptionsAclEntry> {
691        self.options_response
692            .as_ref()
693            .map(|o| {
694                o.allow
695                    .iter()
696                    .filter_map(|raw| OptionsAclEntry::parse(raw))
697                    .collect()
698            })
699            .unwrap_or_default()
700    }
701
702    /// Hosts of `register_users[].server` when `allow_registered_servers` is
703    /// on (the default); empty otherwise.
704    pub fn options_registered_hosts(&self) -> Vec<String> {
705        let enabled = self
706            .options_response
707            .as_ref()
708            .and_then(|o| o.allow_registered_servers)
709            .unwrap_or(true);
710        if !enabled {
711            return vec![];
712        }
713        self.register_users
714            .as_ref()
715            .map(|users| {
716                users
717                    .iter()
718                    .filter_map(|user| host_of_server(&user.server))
719                    .collect()
720            })
721            .unwrap_or_default()
722    }
723
724    /// Extra headers appended to OPTIONS 200 OK responses.
725    pub fn options_extra_headers(&self) -> Vec<(String, String)> {
726        self.options_response
727            .as_ref()
728            .map(|o| o.extra_headers.clone())
729            .unwrap_or_default()
730    }
731
732    /// Whether `source_ip`/`source_host` matches the static ACL or the
733    /// registered-server hosts (the configured, non-learned allow sets).
734    pub fn options_matches_static(
735        &self,
736        source_ip: Option<std::net::IpAddr>,
737        source_host: &str,
738    ) -> bool {
739        self.options_acl_entries()
740            .iter()
741            .any(|entry| entry.matches(source_ip, source_host))
742            || self
743                .options_registered_hosts()
744                .iter()
745                .any(|host| host.eq_ignore_ascii_case(source_host))
746    }
747
748    pub fn recorder_path(&self) -> String {
749        self.recording
750            .as_ref()
751            .map(|policy| policy.recorder_path())
752            .unwrap_or_else(default_config_recorder_path)
753    }
754
755    pub fn recorder_format(&self) -> RecorderFormat {
756        self.recording
757            .as_ref()
758            .map(|policy| policy.recorder_format())
759            .unwrap_or_default()
760    }
761
762    pub fn recorder_native_samplerate(&self) -> bool {
763        self.recording
764            .as_ref()
765            .and_then(|policy| policy.native_samplerate)
766            .unwrap_or(false)
767    }
768
769    pub fn ensure_recording_defaults(&mut self) -> bool {
770        let mut fallback = false;
771
772        if let Some(policy) = self.recording.as_mut() {
773            fallback |= policy.ensure_defaults();
774        }
775
776        fallback
777    }
778
779    /// Apply the first matching trunk rule to an outgoing SIP INVITE/REFER.
780    ///
781    /// Rules are evaluated in declaration order; the first rule whose `match`
782    /// conditions (all AND) hold is applied and later rules are skipped
783    /// (first-match-wins). A rule with an empty `match` section always matches
784    /// and acts as a catch-all default. If no rule matches, the invite is left
785    /// untouched. Does nothing when [`Config::trunk_rules`] is not configured.
786    pub fn apply_trunk_rules(&self, invite: &mut InviteOption) {
787        if let Some(rules) = &self.trunk_rules {
788            for rule in rules {
789                if rule.matches(invite) {
790                    rule.apply(invite);
791                    break;
792                }
793            }
794        }
795    }
796
797    /// Normalize a configured peer to a `ws://` (or `wss://`) base URL.
798    ///
799    /// Accepts bare `ip:port`, or an explicit `ws://`, `wss://`, `http://` or
800    /// `https://` scheme. Returns `None` when the value is empty or unusable.
801    pub fn peer_ws_endpoint(peer: &str) -> Option<String> {
802        let peer = peer.trim();
803        if peer.is_empty() {
804            return None;
805        }
806        if peer.starts_with("wss://") {
807            return Some(peer.to_string());
808        }
809        if peer.starts_with("ws://") {
810            return Some(peer.to_string());
811        }
812        if peer.starts_with("https://") {
813            return Some(peer.replacen("https://", "wss://", 1));
814        }
815        if peer.starts_with("http://") {
816            return Some(peer.replacen("http://", "ws://", 1));
817        }
818        Some(format!("ws://{}", peer))
819    }
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825
826    #[test]
827    fn test_playbook_handler_config_parsing() {
828        let toml_config = r#"
829http_addr = "0.0.0.0:8080"
830addr = "0.0.0.0"
831udp_port = 25060
832
833[handler]
834type = "playbook"
835default = "default.md"
836
837[[handler.rules]]
838caller = "^\\+1\\d{10}$"
839callee = "^sip:support@.*"
840playbook = "support.md"
841
842[[handler.rules]]
843caller = "^\\+86\\d+"
844playbook = "chinese.md"
845
846[[handler.rules]]
847callee = "^sip:sales@.*"
848playbook = "sales.md"
849"#;
850
851        let config: Config = toml::from_str(toml_config).unwrap();
852
853        assert!(config.handler.is_some());
854        if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
855            assert_eq!(default, Some("default.md".to_string()));
856            let rules = rules.unwrap();
857            assert_eq!(rules.len(), 3);
858
859            assert_eq!(rules[0].caller, Some(r"^\+1\d{10}$".to_string()));
860            assert_eq!(rules[0].callee, Some("^sip:support@.*".to_string()));
861            assert_eq!(rules[0].playbook, "support.md");
862
863            assert_eq!(rules[1].caller, Some(r"^\+86\d+".to_string()));
864            assert_eq!(rules[1].callee, None);
865            assert_eq!(rules[1].playbook, "chinese.md");
866
867            assert_eq!(rules[2].caller, None);
868            assert_eq!(rules[2].callee, Some("^sip:sales@.*".to_string()));
869            assert_eq!(rules[2].playbook, "sales.md");
870        } else {
871            panic!("Expected Playbook handler config");
872        }
873    }
874
875    #[test]
876    fn test_playbook_handler_config_without_default() {
877        let toml_config = r#"
878http_addr = "0.0.0.0:8080"
879addr = "0.0.0.0"
880udp_port = 25060
881
882[handler]
883type = "playbook"
884
885[[handler.rules]]
886caller = "^\\+1.*"
887playbook = "us.md"
888"#;
889
890        let config: Config = toml::from_str(toml_config).unwrap();
891
892        if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
893            assert_eq!(default, None);
894            let rules = rules.unwrap();
895            assert_eq!(rules.len(), 1);
896        } else {
897            panic!("Expected Playbook handler config");
898        }
899    }
900
901    #[test]
902    fn test_webhook_handler_config_still_works() {
903        let toml_config = r#"
904http_addr = "0.0.0.0:8080"
905addr = "0.0.0.0"
906udp_port = 25060
907
908[handler]
909type = "webhook"
910url = "http://example.com/webhook"
911"#;
912
913        let config: Config = toml::from_str(toml_config).unwrap();
914
915        if let Some(InviteHandlerConfig::Webhook { url, .. }) = config.handler {
916            assert_eq!(url, Some("http://example.com/webhook".to_string()));
917        } else {
918            panic!("Expected Webhook handler config");
919        }
920    }
921
922    // ---------------------------------------------------------------------------
923    // options_response: config parsing + accessors
924    // ---------------------------------------------------------------------------
925
926    #[test]
927    fn test_options_response_defaults() {
928        let config: Config = toml::from_str(
929            r#"
930http_addr = "0.0.0.0:8080"
931addr = "0.0.0.0"
932udp_port = 25060
933"#,
934        )
935        .unwrap();
936
937        assert!(config.options_response.is_none());
938        // Section absent: enabled via the legacy field/default, auto-learn on,
939        // 7d TTL, no static entries, no extra headers.
940        assert!(config.options_response_enabled());
941        assert!(config.options_auto_learn());
942        assert_eq!(
943            config.options_learn_ttl(),
944            std::time::Duration::from_secs(7 * 24 * 3600)
945        );
946        assert!(config.options_acl_entries().is_empty());
947        assert!(config.options_registered_hosts().is_empty());
948        assert!(config.options_extra_headers().is_empty());
949    }
950
951    #[test]
952    fn test_options_response_config_parsing() {
953        let toml_config = r#"
954http_addr = "0.0.0.0:8080"
955addr = "0.0.0.0"
956udp_port = 25060
957
958[options_response]
959enabled = true
960allow = ["139.224.72.64", "10.0.0.0/8", "SIP.CCC.AliyunCS.com"]
961allow_registered_servers = false
962auto_learn = false
963learn_ttl = "1h"
964extra_headers = [["X-Node-Id", "node-1"], ["User-Agent", "ActiveCall-Test"]]
965"#;
966
967        let config: Config = toml::from_str(toml_config).unwrap();
968        let options = config.options_response.as_ref().unwrap();
969        assert_eq!(options.enabled, Some(true));
970        assert_eq!(options.allow_registered_servers, Some(false));
971        assert_eq!(options.auto_learn, Some(false));
972
973        assert!(!config.options_auto_learn());
974        assert_eq!(
975            config.options_learn_ttl(),
976            std::time::Duration::from_secs(3600)
977        );
978
979        let entries = config.options_acl_entries();
980        assert_eq!(entries.len(), 3);
981        assert_eq!(
982            entries[0],
983            OptionsAclEntry::Ip("139.224.72.64".parse().unwrap())
984        );
985        assert!(matches!(entries[1], OptionsAclEntry::Cidr(_)));
986        assert_eq!(
987            entries[2],
988            OptionsAclEntry::Host("sip.ccc.aliyuncs.com".to_string())
989        );
990
991        let headers = config.options_extra_headers();
992        assert_eq!(headers.len(), 2);
993        assert_eq!(headers[0], ("X-Node-Id".to_string(), "node-1".to_string()));
994    }
995
996    #[test]
997    fn test_options_response_enabled_fallback_chain() {
998        // Legacy field only.
999        let config: Config = toml::from_str(
1000            r#"
1001addr = "0.0.0.0"
1002udp_port = 25060
1003enable_options_response = false
1004"#,
1005        )
1006        .unwrap();
1007        assert!(!config.options_response_enabled());
1008
1009        // New section wins over the legacy field.
1010        let config: Config = toml::from_str(
1011            r#"
1012addr = "0.0.0.0"
1013udp_port = 25060
1014enable_options_response = false
1015
1016[options_response]
1017enabled = true
1018"#,
1019        )
1020        .unwrap();
1021        assert!(config.options_response_enabled());
1022
1023        // New section with enabled unset falls back to the legacy field.
1024        let config: Config = toml::from_str(
1025            r#"
1026addr = "0.0.0.0"
1027udp_port = 25060
1028enable_options_response = false
1029
1030[options_response]
1031extra_headers = [["X-A", "1"]]
1032"#,
1033        )
1034        .unwrap();
1035        assert!(!config.options_response_enabled());
1036    }
1037
1038    #[test]
1039    fn test_options_acl_matching() {
1040        let toml_config = r#"
1041addr = "0.0.0.0"
1042udp_port = 25060
1043
1044[options_response]
1045allow = ["139.224.72.64", "10.0.0.0/8", "sip.ccc.aliyuncs.com"]
1046"#;
1047        let config: Config = toml::from_str(toml_config).unwrap();
1048        let ip = |s: &str| Some(s.parse::<std::net::IpAddr>().unwrap());
1049
1050        // Exact IP.
1051        assert!(config.options_matches_static(ip("139.224.72.64"), "139.224.72.64"));
1052        assert!(!config.options_matches_static(ip("139.224.72.65"), "139.224.72.65"));
1053        // CIDR.
1054        assert!(config.options_matches_static(ip("10.1.2.3"), "10.1.2.3"));
1055        assert!(!config.options_matches_static(ip("192.168.1.1"), "192.168.1.1"));
1056        // Hostname, case-insensitive.
1057        assert!(config.options_matches_static(None, "SIP.CCC.ALIYUNCS.COM"));
1058        assert!(!config.options_matches_static(None, "sip.example.com"));
1059        // An IP source does not match the hostname entry and vice versa.
1060        assert!(!config.options_matches_static(None, "139.224.72.64"));
1061    }
1062
1063    #[test]
1064    fn test_options_registered_hosts() {
1065        let toml_config = r#"
1066addr = "0.0.0.0"
1067udp_port = 25060
1068
1069[[register_users]]
1070server = "sip.example.com:5060"
1071username = "1001"
1072
1073[[register_users]]
1074server = "10.0.0.5"
1075username = "1002"
1076"#;
1077        let config: Config = toml::from_str(toml_config).unwrap();
1078        // Default: registered servers are allowed.
1079        assert_eq!(
1080            config.options_registered_hosts(),
1081            vec!["sip.example.com".to_string(), "10.0.0.5".to_string()]
1082        );
1083        assert!(config.options_matches_static(None, "SIP.EXAMPLE.COM"));
1084        assert!(config.options_matches_static(Some("10.0.0.5".parse().unwrap()), "10.0.0.5"));
1085
1086        // Opt out via allow_registered_servers = false.
1087        let toml_config_off = r#"
1088addr = "0.0.0.0"
1089udp_port = 25060
1090
1091[[register_users]]
1092server = "sip.example.com"
1093username = "1001"
1094
1095[options_response]
1096allow_registered_servers = false
1097"#;
1098        let config: Config = toml::from_str(toml_config_off).unwrap();
1099        assert!(config.options_registered_hosts().is_empty());
1100        assert!(!config.options_matches_static(None, "sip.example.com"));
1101    }
1102
1103    #[test]
1104    fn test_host_of_server() {
1105        assert_eq!(
1106            host_of_server("sip.example.com:5060"),
1107            Some("sip.example.com".to_string())
1108        );
1109        assert_eq!(
1110            host_of_server("SIP.Example.COM"),
1111            Some("sip.example.com".to_string())
1112        );
1113        assert_eq!(
1114            host_of_server("[2001:db8::1]:5060"),
1115            Some("2001:db8::1".to_string())
1116        );
1117        assert_eq!(
1118            host_of_server("2001:db8::1"),
1119            Some("2001:db8::1".to_string())
1120        );
1121        assert_eq!(host_of_server(""), None);
1122    }
1123
1124    // ---------------------------------------------------------------------------
1125    // trunk_rules: config parsing
1126    // ---------------------------------------------------------------------------
1127
1128    #[test]
1129    fn test_trunk_rules_config_parsing() {
1130        let toml_config = r#"
1131http_addr = "0.0.0.0:8080"
1132addr = "0.0.0.0"
1133udp_port = 25060
1134
1135[[trunk_rules]]
1136rule.match.to.host = "^172\\.25\\."
1137rule.rewrite.contact.host = "172.25.225.2"
1138
1139[[trunk_rules]]
1140rule.match.from.user = "^\\+86.*"
1141rule.match.to.host = "^10\\."
1142rule.rewrite.from.user = "10086"
1143rule.rewrite.to.host = "10.0.0.1"
1144rule.rewrite.contact.user = "active-call"
1145rule.rewrite.contact.host = "10.0.0.1:25060"
1146
1147[[trunk_rules]]
1148rule.rewrite.contact.host = "116.62.75.161"
1149"#;
1150
1151        let config: Config = toml::from_str(toml_config).unwrap();
1152        let rules = config.trunk_rules.expect("trunk_rules should be parsed");
1153
1154        assert_eq!(rules.len(), 3);
1155
1156        // Rule 1: match to.host, rewrite contact.host
1157        let m = &rules[0].rule.r#match;
1158        assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^172\\.25\\."));
1159        assert_eq!(m.to.as_ref().unwrap().user, None);
1160        assert_eq!(m.from, None);
1161        let w = &rules[0].rule.rewrite;
1162        assert_eq!(
1163            w.contact.as_ref().unwrap().host.as_deref(),
1164            Some("172.25.225.2")
1165        );
1166        assert_eq!(w.from, None);
1167        assert_eq!(w.to, None);
1168
1169        // Rule 2: combined match + all rewrites
1170        let m = &rules[1].rule.r#match;
1171        assert_eq!(m.from.as_ref().unwrap().user.as_deref(), Some("^\\+86.*"));
1172        assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^10\\."));
1173        let w = &rules[1].rule.rewrite;
1174        assert_eq!(w.from.as_ref().unwrap().user.as_deref(), Some("10086"));
1175        assert_eq!(w.to.as_ref().unwrap().host.as_deref(), Some("10.0.0.1"));
1176        assert_eq!(
1177            w.contact.as_ref().unwrap().user.as_deref(),
1178            Some("active-call")
1179        );
1180        assert_eq!(
1181            w.contact.as_ref().unwrap().host.as_deref(),
1182            Some("10.0.0.1:25060")
1183        );
1184
1185        // Rule 3: catch-all (empty match)
1186        assert_eq!(rules[2].rule.r#match.from, None);
1187        assert_eq!(rules[2].rule.r#match.to, None);
1188        assert_eq!(
1189            rules[2]
1190                .rule
1191                .rewrite
1192                .contact
1193                .as_ref()
1194                .unwrap()
1195                .host
1196                .as_deref(),
1197            Some("116.62.75.161")
1198        );
1199    }
1200
1201    #[test]
1202    fn test_trunk_rules_absent_by_default() {
1203        let config = Config::default();
1204        assert!(config.trunk_rules.is_none());
1205    }
1206
1207    // ---------------------------------------------------------------------------
1208    // trunk_rules: match + rewrite behaviour
1209    // ---------------------------------------------------------------------------
1210
1211    fn invite_option(caller: &str, callee: &str, contact: &str) -> InviteOption {
1212        InviteOption {
1213            caller: caller.try_into().unwrap(),
1214            callee: callee.try_into().unwrap(),
1215            contact: contact.try_into().unwrap(),
1216            ..Default::default()
1217        }
1218    }
1219
1220    #[test]
1221    fn test_trunk_rule_matches_on_to_host() {
1222        let config: Config = toml::from_str(
1223            r#"
1224addr = "0.0.0.0"
1225udp_port = 25060
1226
1227[[trunk_rules]]
1228rule.match.to.host = "^172\\.25\\."
1229rule.rewrite.contact.host = "172.25.225.2"
1230"#,
1231        )
1232        .unwrap();
1233
1234        // Internal target -> matched, contact host rewritten.
1235        let mut invite = invite_option(
1236            "sip:ai@116.62.75.161:13050",
1237            "sip:agent1@172.25.225.3:15060",
1238            "sip:ai@127.0.0.1:13050",
1239        );
1240        config.apply_trunk_rules(&mut invite);
1241        assert_eq!(
1242            invite.contact.host_with_port.host.to_string(),
1243            "172.25.225.2"
1244        );
1245
1246        // External target -> no match, contact untouched.
1247        let mut invite = invite_option(
1248            "sip:ai@116.62.75.161:13050",
1249            "sip:+8613800138000@sbc.example.com:5060",
1250            "sip:ai@127.0.0.1:13050",
1251        );
1252        config.apply_trunk_rules(&mut invite);
1253        assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1254    }
1255
1256    #[test]
1257    fn test_trunk_rule_matches_on_from_user_and_to_host() {
1258        let config: Config = toml::from_str(
1259            r#"
1260addr = "0.0.0.0"
1261udp_port = 25060
1262
1263[[trunk_rules]]
1264rule.match.from.user = "^anonymous$"
1265rule.match.to.host = "^sbc\\."
1266rule.rewrite.contact.host = "116.62.75.161"
1267"#,
1268        )
1269        .unwrap();
1270
1271        // from.user + to.host both match -> rewritten.
1272        let mut invite = invite_option(
1273            "sip:anonymous@116.62.75.161:13050",
1274            "sip:+8613800138000@sbc.example.com:5060",
1275            "sip:ai@127.0.0.1:13050",
1276        );
1277        config.apply_trunk_rules(&mut invite);
1278        assert_eq!(
1279            invite.contact.host_with_port.host.to_string(),
1280            "116.62.75.161"
1281        );
1282
1283        // from.user does not match -> no rewrite.
1284        let mut invite = invite_option(
1285            "sip:alice@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!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1291    }
1292
1293    #[test]
1294    fn test_trunk_rule_rewrites_from_to_contact() {
1295        let config: Config = toml::from_str(
1296            r#"
1297addr = "0.0.0.0"
1298udp_port = 25060
1299
1300[[trunk_rules]]
1301rule.match.to.host = "^10\\."
1302rule.rewrite.from.user = "10086"
1303rule.rewrite.from.host = "116.62.75.161"
1304rule.rewrite.to.user = "30000"
1305rule.rewrite.to.host = "10.0.0.1:25060"
1306rule.rewrite.contact.user = "active-call"
1307rule.rewrite.contact.host = "10.0.0.1"
1308"#,
1309        )
1310        .unwrap();
1311
1312        let mut invite = invite_option(
1313            "sip:ai@127.0.0.1:13050",
1314            "sip:agent1@10.0.0.2:25060",
1315            "sip:ai@127.0.0.1:13050",
1316        );
1317        config.apply_trunk_rules(&mut invite);
1318
1319        // caller (from)
1320        assert_eq!(invite.caller.auth.as_ref().unwrap().user, "10086");
1321        assert_eq!(
1322            invite.caller.host_with_port.host.to_string(),
1323            "116.62.75.161"
1324        );
1325
1326        // callee (to)
1327        assert_eq!(invite.callee.auth.as_ref().unwrap().user, "30000");
1328        assert_eq!(invite.callee.host_with_port.host.to_string(), "10.0.0.1");
1329        assert_eq!(invite.callee.host_with_port.port.unwrap().0, 25060);
1330
1331        // contact: host rewritten without port -> original port preserved
1332        assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1333        assert_eq!(invite.contact.host_with_port.host.to_string(), "10.0.0.1");
1334        assert_eq!(invite.contact.host_with_port.port.unwrap().0, 13050);
1335    }
1336
1337    #[test]
1338    fn test_trunk_rule_catch_all_default() {
1339        let config: Config = toml::from_str(
1340            r#"
1341addr = "0.0.0.0"
1342udp_port = 25060
1343
1344[[trunk_rules]]
1345rule.match.to.host = "^172\\.25\\."
1346rule.rewrite.contact.host = "172.25.225.2"
1347
1348[[trunk_rules]]
1349rule.rewrite.contact.host = "116.62.75.161"
1350"#,
1351        )
1352        .unwrap();
1353
1354        // Not matched by rule 1 -> falls through to catch-all rule 2.
1355        let mut invite = invite_option(
1356            "sip:ai@116.62.75.161:13050",
1357            "sip:+8613800138000@sbc.example.com:5060",
1358            "sip:ai@127.0.0.1:13050",
1359        );
1360        config.apply_trunk_rules(&mut invite);
1361        assert_eq!(
1362            invite.contact.host_with_port.host.to_string(),
1363            "116.62.75.161"
1364        );
1365    }
1366
1367    #[test]
1368    fn test_trunk_rule_first_match_wins() {
1369        let config: Config = toml::from_str(
1370            r#"
1371addr = "0.0.0.0"
1372udp_port = 25060
1373
1374[[trunk_rules]]
1375rule.match.to.host = ".*"
1376rule.rewrite.contact.host = "1.1.1.1"
1377
1378[[trunk_rules]]
1379rule.match.to.host = ".*"
1380rule.rewrite.contact.host = "2.2.2.2"
1381"#,
1382        )
1383        .unwrap();
1384
1385        let mut invite = invite_option(
1386            "sip:ai@116.62.75.161:13050",
1387            "sip:any@example.com:5060",
1388            "sip:ai@127.0.0.1:13050",
1389        );
1390        config.apply_trunk_rules(&mut invite);
1391        // Only the first rule applies.
1392        assert_eq!(invite.contact.host_with_port.host.to_string(), "1.1.1.1");
1393    }
1394
1395    #[test]
1396    fn test_trunk_rule_no_config_noop() {
1397        let config = Config::default();
1398        let mut invite = invite_option(
1399            "sip:ai@116.62.75.161:13050",
1400            "sip:agent1@172.25.225.3:15060",
1401            "sip:ai@127.0.0.1:13050",
1402        );
1403        let before = invite.contact.to_string();
1404        config.apply_trunk_rules(&mut invite);
1405        assert_eq!(invite.contact.to_string(), before);
1406    }
1407
1408    #[test]
1409    fn test_trunk_rule_rewrite_missing_auth_creates_user() {
1410        let config: Config = toml::from_str(
1411            r#"
1412addr = "0.0.0.0"
1413udp_port = 25060
1414
1415[[trunk_rules]]
1416rule.match.to.host = ".*"
1417rule.rewrite.contact.user = "active-call"
1418"#,
1419        )
1420        .unwrap();
1421
1422        // A contact without a user part (e.g. "sip:127.0.0.1:13050").
1423        let mut invite = InviteOption {
1424            caller: "sip:ai@127.0.0.1:13050".try_into().unwrap(),
1425            callee: "sip:agent1@172.25.225.3:15060".try_into().unwrap(),
1426            contact: "sip:127.0.0.1:13050".try_into().unwrap(),
1427            ..Default::default()
1428        };
1429        config.apply_trunk_rules(&mut invite);
1430        assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1431    }
1432}