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