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 #[clap(long)]
16 pub conf: Option<String>,
17 #[clap(long)]
19 pub http: Option<String>,
20
21 #[clap(long)]
23 pub sip: Option<String>,
24
25 #[clap(long)]
27 pub handler: Option<String>,
28
29 #[clap(long)]
31 pub call: Option<String>,
32
33 #[clap(long)]
35 pub external_ip: Option<String>,
36
37 #[clap(long, value_delimiter = ',')]
39 pub codecs: Option<Vec<String>>,
40
41 #[cfg(feature = "offline")]
43 #[clap(long)]
44 pub download_models: Option<String>,
45
46 #[cfg(feature = "offline")]
48 #[clap(long, default_value = "./models")]
49 pub models_dir: String,
50
51 #[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 env_number<T: std::str::FromStr>(key: &str) -> Option<T> {
129 let raw = std::env::var(key).ok()?;
130 let raw = raw.trim();
131 if raw.is_empty() {
132 return None;
133 }
134 raw.parse::<T>().ok()
135}
136
137
138fn default_codecs() -> Option<Vec<String>> {
139 let codecs = vec![
140 "pcmu".to_string(),
141 "pcma".to_string(),
142 "g722".to_string(),
143 "g729".to_string(),
144 "opus".to_string(),
145 "telephone_event".to_string(),
146 ];
147 Some(codecs)
148}
149
150#[derive(Debug, Clone, Deserialize, Serialize, Default)]
151#[serde(rename_all = "snake_case")]
152pub struct JitterBufferConfig {
153 pub webrtc: Option<bool>,
155 pub sip: Option<bool>,
159}
160
161#[derive(Debug, Clone, Default, Deserialize, Serialize)]
169#[serde(rename_all = "snake_case")]
170pub struct AdmissionConfig {
171 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub max_active_calls: Option<usize>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub wait_ms: Option<u64>,
177}
178
179#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
183#[serde(rename_all = "snake_case")]
184pub struct ModuleToggle {
185 #[serde(default)]
186 pub enabled: bool,
187}
188
189impl Default for ModuleToggle {
190 fn default() -> Self {
191 Self { enabled: true }
192 }
193}
194
195#[derive(Debug, Clone, Default, Deserialize, Serialize)]
203#[serde(rename_all = "snake_case")]
204pub struct ModulesConfig {
205 pub denoise: Option<ModuleToggle>,
206 pub vad: Option<ModuleToggle>,
207 pub eou: Option<ModuleToggle>,
208 pub ringback_detection: Option<ModuleToggle>,
209 pub sipflow: Option<ModuleToggle>,
210 pub playbooks: Option<ModuleToggle>,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215pub enum RuntimeModule {
216 Denoise,
217 Vad,
218 Eou,
219 RingbackDetection,
220 Sipflow,
221 Playbooks,
222}
223
224impl RuntimeModule {
225 pub fn toggle_key(self) -> Option<&'static str> {
227 match self {
228 RuntimeModule::Denoise => Some("DENOISE_ENABLED"),
229 RuntimeModule::Eou => Some("EOU_ENABLED"),
230 RuntimeModule::RingbackDetection => Some("RINGBACK_DETECTION_ENABLED"),
231 _ => None,
232 }
233 }
234
235 pub fn as_str(self) -> &'static str {
236 match self {
237 RuntimeModule::Denoise => "denoise",
238 RuntimeModule::Vad => "vad",
239 RuntimeModule::Eou => "eou",
240 RuntimeModule::RingbackDetection => "ringback_detection",
241 RuntimeModule::Sipflow => "sipflow",
242 RuntimeModule::Playbooks => "playbooks",
243 }
244 }
245}
246
247#[derive(Debug, Clone, Default, Deserialize, Serialize)]
249#[serde(rename_all = "snake_case")]
250pub struct ReloadConfig {
251 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub token: Option<String>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub watch: Option<bool>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub watch_interval_ms: Option<u64>,
263}
264
265#[derive(Debug, Clone, Deserialize, Serialize, Default)]
266#[serde(rename_all = "snake_case")]
267pub struct RecordingPolicy {
268 #[serde(default)]
269 pub enabled: bool,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub auto_start: Option<bool>,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub filename_pattern: Option<String>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub samplerate: Option<u32>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub ptime: Option<u32>,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub path: Option<String>,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub format: Option<RecorderFormat>,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub native_samplerate: Option<bool>,
286}
287
288impl RecordingPolicy {
289 pub fn recorder_path(&self) -> String {
290 self.path
291 .as_ref()
292 .map(|p| p.trim())
293 .filter(|p| !p.is_empty())
294 .map(|p| p.to_string())
295 .unwrap_or_else(default_config_recorder_path)
296 }
297
298 pub fn recorder_format(&self) -> RecorderFormat {
299 self.format.unwrap_or_default()
300 }
301
302 pub fn ensure_defaults(&mut self) -> bool {
303 if self
304 .path
305 .as_ref()
306 .map(|p| p.trim().is_empty())
307 .unwrap_or(true)
308 {
309 self.path = Some(default_config_recorder_path());
310 }
311
312 false
313 }
314}
315
316#[derive(Debug, Clone, Deserialize, Serialize)]
317pub struct RewriteRule {
318 pub r#match: String,
319 pub rewrite: String,
320}
321
322#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
335#[serde(rename_all = "snake_case")]
336pub struct TrunkRule {
337 pub rule: TrunkRuleDef,
338}
339
340#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
341#[serde(rename_all = "snake_case")]
342pub struct TrunkRuleDef {
343 #[serde(default, rename = "match")]
344 pub r#match: TrunkMatch,
345 pub rewrite: TrunkRewrite,
346}
347
348#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
352#[serde(rename_all = "snake_case")]
353pub struct TrunkMatch {
354 pub from: Option<UriMatch>,
355 pub to: Option<UriMatch>,
356}
357
358#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
361#[serde(rename_all = "snake_case")]
362pub struct UriMatch {
363 pub user: Option<String>,
365 pub host: Option<String>,
367}
368
369#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
371#[serde(rename_all = "snake_case")]
372pub struct TrunkRewrite {
373 pub from: Option<UriRewrite>,
374 pub to: Option<UriRewrite>,
375 pub contact: Option<UriRewrite>,
376}
377
378#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
382#[serde(rename_all = "snake_case")]
383pub struct UriRewrite {
384 pub user: Option<String>,
385 pub host: Option<String>,
386}
387
388impl TrunkRule {
389 fn matches(&self, invite: &InviteOption) -> bool {
390 self.rule.r#match.matches(invite)
391 }
392
393 fn apply(&self, invite: &mut InviteOption) {
394 self.rule.rewrite.apply(invite);
395 }
396}
397
398impl TrunkMatch {
399 fn matches(&self, invite: &InviteOption) -> bool {
400 let from_ok = self
401 .from
402 .as_ref()
403 .map(|from| from.matches(&invite.caller))
404 .unwrap_or(true);
405 let to_ok = self
406 .to
407 .as_ref()
408 .map(|to| to.matches(&invite.callee))
409 .unwrap_or(true);
410 from_ok && to_ok
411 }
412}
413
414impl UriMatch {
415 fn matches(&self, uri: &Uri) -> bool {
416 let user_ok = self
417 .user
418 .as_ref()
419 .map(|user| {
420 uri.auth
421 .as_ref()
422 .map(|auth| regex_is_match(user, &auth.user))
423 .unwrap_or(false)
424 })
425 .unwrap_or(true);
426 let host_ok = self
427 .host
428 .as_ref()
429 .map(|host| regex_is_match(host, &uri.host_with_port.host.to_string()))
430 .unwrap_or(true);
431 user_ok && host_ok
432 }
433}
434
435impl TrunkRewrite {
436 fn apply(&self, invite: &mut InviteOption) {
437 if let Some(from) = &self.from {
438 from.apply(&mut invite.caller);
439 }
440 if let Some(to) = &self.to {
441 to.apply(&mut invite.callee);
442 }
443 if let Some(contact) = &self.contact {
444 contact.apply(&mut invite.contact);
445 }
446 }
447}
448
449impl UriRewrite {
450 fn apply(&self, uri: &mut Uri) {
451 if let Some(user) = &self.user {
452 let auth = uri.auth.get_or_insert_with(|| Auth {
453 user: String::new(),
454 password: None,
455 });
456 auth.user = user.clone();
457 }
458 if let Some(host) = &self.host
459 && let Ok(mut host_with_port) = HostWithPort::try_from(host.as_str())
460 {
461 if host_with_port.port.is_none() {
463 host_with_port.port = uri.host_with_port.port;
464 }
465 uri.host_with_port = host_with_port;
466 }
467 }
468}
469
470fn regex_is_match(pattern: &str, value: &str) -> bool {
471 regex::Regex::new(pattern)
472 .map(|re| re.is_match(value))
473 .unwrap_or(false)
474}
475
476fn host_of_server(server: &str) -> Option<String> {
479 let server = server.trim();
480 if server.is_empty() {
481 return None;
482 }
483 if let Some(rest) = server.strip_prefix('[') {
484 return rest.split(']').next().map(|h| h.to_ascii_lowercase());
486 }
487 if server.matches(':').count() > 1 {
489 return Some(server.to_ascii_lowercase());
490 }
491 server.split(':').next().map(|h| h.to_ascii_lowercase())
492}
493
494#[derive(Debug, Clone, PartialEq)]
497pub enum OptionsAclEntry {
498 Ip(std::net::IpAddr),
499 Cidr(ipnet::IpNet),
500 Host(String),
501}
502
503impl OptionsAclEntry {
504 fn parse(raw: &str) -> Option<Self> {
505 let raw = raw.trim();
506 if raw.is_empty() {
507 return None;
508 }
509 if let Ok(ip) = raw.parse::<std::net::IpAddr>() {
510 return Some(Self::Ip(ip));
511 }
512 if let Ok(cidr) = raw.parse::<ipnet::IpNet>() {
513 return Some(Self::Cidr(cidr));
514 }
515 Some(Self::Host(raw.to_ascii_lowercase()))
516 }
517
518 pub fn matches(&self, source_ip: Option<std::net::IpAddr>, source_host: &str) -> bool {
519 match self {
520 Self::Ip(ip) => source_ip == Some(*ip),
521 Self::Cidr(net) => source_ip.map(|ip| net.contains(&ip)).unwrap_or(false),
522 Self::Host(host) => host.eq_ignore_ascii_case(source_host),
523 }
524 }
525}
526
527#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
535#[serde(rename_all = "snake_case")]
536pub struct OptionsResponseConfig {
537 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub enabled: Option<bool>,
541 #[serde(default, skip_serializing_if = "Vec::is_empty")]
544 pub allow: Vec<String>,
545 #[serde(default = "default_options_allow_registered_servers")]
547 pub allow_registered_servers: Option<bool>,
548 #[serde(default = "default_options_auto_learn")]
553 pub auto_learn: Option<bool>,
554 #[serde(default = "default_options_learn_ttl")]
556 pub learn_ttl: Option<String>,
557 #[serde(default, skip_serializing_if = "Vec::is_empty")]
559 pub extra_headers: Vec<(String, String)>,
560}
561
562#[derive(Debug, Deserialize, Serialize)]
563pub struct Config {
564 #[serde(default = "default_config_http_addr")]
565 pub http_addr: String,
566 pub addr: String,
567 pub udp_port: u16,
568 pub auto_learn_public_address: Option<bool>,
569
570 pub log_level: Option<String>,
571 pub log_file: Option<String>,
572 #[serde(default, skip_serializing_if = "Vec::is_empty")]
573 pub http_access_skip_paths: Vec<String>,
574
575 #[serde(default, skip_serializing_if = "Vec::is_empty")]
582 pub peers: Vec<String>,
583
584 #[serde(default = "default_config_useragent")]
585 pub useragent: Option<String>,
586 pub register_users: Option<Vec<RegisterOption>>,
587 #[serde(default = "default_graceful_shutdown")]
588 pub graceful_shutdown: Option<bool>,
589 #[serde(default = "default_graceful_shutdown_timeout")]
592 pub graceful_shutdown_timeout: Option<u64>,
593 pub handler: Option<InviteHandlerConfig>,
594 pub accept_timeout: Option<String>,
595 #[serde(default = "default_codecs")]
596 pub codecs: Option<Vec<String>>,
597 pub external_ip: Option<String>,
598 #[serde(default = "default_config_rtp_start_port")]
599 pub rtp_start_port: Option<u16>,
600 #[serde(default = "default_config_rtp_end_port")]
601 pub rtp_end_port: Option<u16>,
602 #[serde(default = "default_config_rtp_latching")]
603 pub enable_rtp_latching: Option<bool>,
604 pub enable_ice_lite: Option<bool>,
605 pub ice_disconnect_grace: Option<String>,
609 pub rtp_bind_ip: Option<String>,
610 pub tls_port: Option<u16>,
611 pub tls_cert_file: Option<String>,
612 pub tls_key_file: Option<String>,
613
614 pub enable_srtp: Option<bool>,
615
616 pub callrecord: Option<CallRecordConfig>,
617 #[serde(default = "default_config_media_cache_path")]
618 pub media_cache_path: String,
619 pub ambiance: Option<AmbianceOption>,
620 pub ice_servers: Option<Vec<IceServer>>,
621 pub jitter_buffer: Option<JitterBufferConfig>,
625 #[serde(default)]
626 pub recording: Option<RecordingPolicy>,
627 pub rewrites: Option<Vec<RewriteRule>>,
628 #[serde(default, skip_serializing_if = "Option::is_none")]
629 pub trunk_rules: Option<Vec<TrunkRule>>,
630 #[serde(default = "default_enable_options_response")]
631 pub enable_options_response: Option<bool>,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub options_response: Option<OptionsResponseConfig>,
634
635 #[serde(default, skip_serializing_if = "Option::is_none")]
640 pub auto_refer: Option<bool>,
641 #[serde(default, skip_serializing_if = "Option::is_none")]
643 pub auto_refer_timeout: Option<u32>,
644 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub sipflow: Option<crate::sipflow::SipFlowConfig>,
648
649 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub admission: Option<AdmissionConfig>,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
654 pub modules: Option<ModulesConfig>,
655 #[serde(default, skip_serializing_if = "Option::is_none")]
657 pub reload: Option<ReloadConfig>,
658}
659
660impl Config {
661 pub fn auto_refer(&self) -> bool {
664 self.auto_refer.unwrap_or(true)
665 }
666
667 pub fn auto_refer_timeout(&self) -> u32 {
669 self.auto_refer_timeout.unwrap_or(30)
670 }
671}
672
673#[derive(Debug, Deserialize, Clone, Serialize)]
674#[serde(rename_all = "snake_case")]
675#[serde(tag = "type")]
676pub enum InviteHandlerConfig {
677 Webhook {
678 url: Option<String>,
679 urls: Option<Vec<String>>,
680 method: Option<String>,
681 headers: Option<Vec<(String, String)>>,
682 },
683 Playbook {
684 rules: Option<Vec<PlaybookRule>>,
685 default: Option<String>,
686 },
687}
688
689#[derive(Debug, Deserialize, Clone, Serialize)]
690#[serde(rename_all = "snake_case")]
691pub struct PlaybookRule {
692 pub caller: Option<String>,
693 pub callee: Option<String>,
694 pub playbook: String,
695}
696
697#[derive(Debug, Deserialize, Clone, Serialize)]
698#[serde(rename_all = "snake_case")]
699pub enum S3Vendor {
700 Aliyun,
701 Tencent,
702 Minio,
703 AWS,
704 GCP,
705 Azure,
706 DigitalOcean,
707}
708
709#[derive(Debug, Deserialize, Clone, Serialize)]
710#[serde(tag = "type")]
711#[serde(rename_all = "snake_case")]
712pub enum CallRecordConfig {
713 Local {
714 root: String,
715 },
716 S3 {
717 vendor: S3Vendor,
718 bucket: String,
719 region: String,
720 access_key: String,
721 secret_key: String,
722 endpoint: String,
723 root: String,
724 with_media: Option<bool>,
725 keep_media_copy: Option<bool>,
726 part_size_mb: Option<u64>,
728 delete_after_upload: Option<bool>,
730 },
731 Http {
732 url: String,
733 headers: Option<HashMap<String, String>>,
734 with_media: Option<bool>,
735 keep_media_copy: Option<bool>,
736 part_size_mb: Option<u64>,
738 delete_after_upload: Option<bool>,
740 },
741}
742
743impl Default for CallRecordConfig {
744 fn default() -> Self {
745 Self::Local {
746 #[cfg(target_os = "windows")]
747 root: "./config/cdr".to_string(),
748 #[cfg(not(target_os = "windows"))]
749 root: "./config/cdr".to_string(),
750 }
751 }
752}
753
754impl Default for Config {
755 fn default() -> Self {
756 Self {
757 http_addr: default_config_http_addr(),
758 log_level: None,
759 log_file: None,
760 http_access_skip_paths: Vec::new(),
761 peers: Vec::new(),
762 addr: default_sip_addr(),
763 udp_port: default_sip_port(),
764 auto_learn_public_address: None,
765 useragent: None,
766 register_users: None,
767 graceful_shutdown: Some(true),
768 graceful_shutdown_timeout: default_graceful_shutdown_timeout(),
769 handler: None,
770 accept_timeout: Some("50s".to_string()),
771 media_cache_path: default_config_media_cache_path(),
772 ambiance: None,
773 callrecord: None,
774 ice_servers: None,
775 jitter_buffer: None,
776 codecs: None,
777 external_ip: None,
778 rtp_start_port: default_config_rtp_start_port(),
779 rtp_end_port: default_config_rtp_end_port(),
780 enable_rtp_latching: Some(true),
781 rtp_bind_ip: None,
782 enable_ice_lite: None,
783 ice_disconnect_grace: None,
784 tls_port: None,
785 tls_cert_file: None,
786 tls_key_file: None,
787 enable_srtp: None,
788 recording: None,
789 rewrites: None,
790 trunk_rules: None,
791 enable_options_response: default_enable_options_response(),
792 options_response: None,
793 auto_refer: None,
794 auto_refer_timeout: None,
795 sipflow: None,
796 admission: None,
797 modules: None,
798 reload: None,
799 }
800 }
801}
802
803impl Clone for Config {
804 fn clone(&self) -> Self {
805 let s = toml::to_string(self).unwrap();
808 toml::from_str(&s).unwrap()
809 }
810}
811
812impl Config {
813 pub fn load(path: &str) -> Result<Self, Error> {
814 let mut config: Self = toml::from_str(
815 &std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("{}: {}", e, path))?,
816 )?;
817 config.apply_env_overrides();
818 Ok(config)
819 }
820
821 pub fn apply_env_overrides(&mut self) {
827 if let Some(v) = env_number::<usize>("MAX_ACTIVE_CALLS") {
828 self.admission
829 .get_or_insert_with(AdmissionConfig::default)
830 .max_active_calls = Some(v);
831 tracing::info!(max_active_calls = v, "MAX_ACTIVE_CALLS override applied from env");
832 }
833 if let Some(v) = env_number::<u64>("MAX_CALLS_WAIT_MS") {
834 self.admission
835 .get_or_insert_with(AdmissionConfig::default)
836 .wait_ms = Some(v);
837 tracing::info!(wait_ms = v, "MAX_CALLS_WAIT_MS override applied from env");
838 }
839 if let Ok(token) = std::env::var("PBX_RELOAD_TOKEN")
840 && !token.trim().is_empty()
841 {
842 self.reload
843 .get_or_insert_with(ReloadConfig::default)
844 .token = Some(token.trim().to_string());
845 }
846 }
847
848 pub fn admission_max_calls(&self) -> usize {
850 self.admission
851 .as_ref()
852 .and_then(|a| a.max_active_calls)
853 .unwrap_or(0)
854 }
855
856 pub fn admission_wait_ms(&self) -> u64 {
858 self.admission
859 .as_ref()
860 .and_then(|a| a.wait_ms)
861 .unwrap_or(5_000)
862 }
863
864 pub fn module_enabled(&self, module: RuntimeModule) -> bool {
870 let configured = match module {
871 RuntimeModule::Denoise => self.modules.as_ref().and_then(|m| m.denoise),
872 RuntimeModule::Vad => self.modules.as_ref().and_then(|m| m.vad),
873 RuntimeModule::Eou => self.modules.as_ref().and_then(|m| m.eou),
874 RuntimeModule::RingbackDetection => {
875 self.modules.as_ref().and_then(|m| m.ringback_detection)
876 }
877 RuntimeModule::Sipflow => self.modules.as_ref().and_then(|m| m.sipflow),
878 RuntimeModule::Playbooks => self.modules.as_ref().and_then(|m| m.playbooks),
879 }
880 .unwrap_or_default()
881 .enabled;
882
883 match module.toggle_key() {
884 Some(key) => crate::runtime::toggle_value(key).unwrap_or(configured),
885 None => configured,
886 }
887 }
888
889 pub fn reload_token(&self) -> Option<&str> {
891 self.reload
892 .as_ref()
893 .and_then(|r| r.token.as_deref())
894 .map(str::trim)
895 .filter(|t| !t.is_empty())
896 }
897
898 pub fn reload_watch(&self) -> bool {
899 self.reload
900 .as_ref()
901 .and_then(|r| r.watch)
902 .unwrap_or(false)
903 }
904
905 pub fn reload_watch_interval(&self) -> std::time::Duration {
906 std::time::Duration::from_millis(
907 self.reload
908 .as_ref()
909 .and_then(|r| r.watch_interval_ms)
910 .unwrap_or(2_000)
911 .clamp(200, 60_000),
912 )
913 }
914
915 pub fn ice_disconnect_grace(&self) -> Option<std::time::Duration> {
917 self.ice_disconnect_grace
918 .as_deref()
919 .and_then(|raw| humantime::parse_duration(raw).ok())
920 }
921
922 pub fn options_response_enabled(&self) -> bool {
924 self.options_response
925 .as_ref()
926 .and_then(|o| o.enabled)
927 .or(self.enable_options_response)
928 .unwrap_or(true)
929 }
930
931 pub fn options_auto_learn(&self) -> bool {
933 self.options_response
934 .as_ref()
935 .and_then(|o| o.auto_learn)
936 .unwrap_or(true)
937 }
938
939 pub fn options_learn_ttl(&self) -> std::time::Duration {
941 const DEFAULT: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
942 self.options_response
943 .as_ref()
944 .and_then(|o| o.learn_ttl.as_deref())
945 .map(|raw| humantime::parse_duration(raw).unwrap_or(DEFAULT))
946 .unwrap_or(DEFAULT)
947 }
948
949 pub fn options_acl_entries(&self) -> Vec<OptionsAclEntry> {
951 self.options_response
952 .as_ref()
953 .map(|o| {
954 o.allow
955 .iter()
956 .filter_map(|raw| OptionsAclEntry::parse(raw))
957 .collect()
958 })
959 .unwrap_or_default()
960 }
961
962 pub fn options_registered_hosts(&self) -> Vec<String> {
965 let enabled = self
966 .options_response
967 .as_ref()
968 .and_then(|o| o.allow_registered_servers)
969 .unwrap_or(true);
970 if !enabled {
971 return vec![];
972 }
973 self.register_users
974 .as_ref()
975 .map(|users| {
976 users
977 .iter()
978 .filter_map(|user| host_of_server(&user.server))
979 .collect()
980 })
981 .unwrap_or_default()
982 }
983
984 pub fn options_extra_headers(&self) -> Vec<(String, String)> {
986 self.options_response
987 .as_ref()
988 .map(|o| o.extra_headers.clone())
989 .unwrap_or_default()
990 }
991
992 pub fn options_matches_static(
995 &self,
996 source_ip: Option<std::net::IpAddr>,
997 source_host: &str,
998 ) -> bool {
999 self.options_acl_entries()
1000 .iter()
1001 .any(|entry| entry.matches(source_ip, source_host))
1002 || self
1003 .options_registered_hosts()
1004 .iter()
1005 .any(|host| host.eq_ignore_ascii_case(source_host))
1006 }
1007
1008 pub fn recorder_path(&self) -> String {
1009 self.recording
1010 .as_ref()
1011 .map(|policy| policy.recorder_path())
1012 .unwrap_or_else(default_config_recorder_path)
1013 }
1014
1015 pub fn recorder_format(&self) -> RecorderFormat {
1016 self.recording
1017 .as_ref()
1018 .map(|policy| policy.recorder_format())
1019 .unwrap_or_default()
1020 }
1021
1022 pub fn recorder_native_samplerate(&self) -> bool {
1023 self.recording
1024 .as_ref()
1025 .and_then(|policy| policy.native_samplerate)
1026 .unwrap_or(false)
1027 }
1028
1029 pub fn ensure_recording_defaults(&mut self) -> bool {
1030 let mut fallback = false;
1031
1032 if let Some(policy) = self.recording.as_mut() {
1033 fallback |= policy.ensure_defaults();
1034 }
1035
1036 fallback
1037 }
1038
1039 pub fn apply_trunk_rules(&self, invite: &mut InviteOption) {
1047 if let Some(rules) = &self.trunk_rules {
1048 for rule in rules {
1049 if rule.matches(invite) {
1050 rule.apply(invite);
1051 break;
1052 }
1053 }
1054 }
1055 }
1056
1057 pub fn peer_ws_endpoint(peer: &str) -> Option<String> {
1062 let peer = peer.trim();
1063 if peer.is_empty() {
1064 return None;
1065 }
1066 if peer.starts_with("wss://") {
1067 return Some(peer.to_string());
1068 }
1069 if peer.starts_with("ws://") {
1070 return Some(peer.to_string());
1071 }
1072 if peer.starts_with("https://") {
1073 return Some(peer.replacen("https://", "wss://", 1));
1074 }
1075 if peer.starts_with("http://") {
1076 return Some(peer.replacen("http://", "ws://", 1));
1077 }
1078 Some(format!("ws://{}", peer))
1079 }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 use super::*;
1085
1086 #[test]
1087 fn test_playbook_handler_config_parsing() {
1088 let toml_config = r#"
1089http_addr = "0.0.0.0:8080"
1090addr = "0.0.0.0"
1091udp_port = 25060
1092
1093[handler]
1094type = "playbook"
1095default = "default.md"
1096
1097[[handler.rules]]
1098caller = "^\\+1\\d{10}$"
1099callee = "^sip:support@.*"
1100playbook = "support.md"
1101
1102[[handler.rules]]
1103caller = "^\\+86\\d+"
1104playbook = "chinese.md"
1105
1106[[handler.rules]]
1107callee = "^sip:sales@.*"
1108playbook = "sales.md"
1109"#;
1110
1111 let config: Config = toml::from_str(toml_config).unwrap();
1112
1113 assert!(config.handler.is_some());
1114 if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
1115 assert_eq!(default, Some("default.md".to_string()));
1116 let rules = rules.unwrap();
1117 assert_eq!(rules.len(), 3);
1118
1119 assert_eq!(rules[0].caller, Some(r"^\+1\d{10}$".to_string()));
1120 assert_eq!(rules[0].callee, Some("^sip:support@.*".to_string()));
1121 assert_eq!(rules[0].playbook, "support.md");
1122
1123 assert_eq!(rules[1].caller, Some(r"^\+86\d+".to_string()));
1124 assert_eq!(rules[1].callee, None);
1125 assert_eq!(rules[1].playbook, "chinese.md");
1126
1127 assert_eq!(rules[2].caller, None);
1128 assert_eq!(rules[2].callee, Some("^sip:sales@.*".to_string()));
1129 assert_eq!(rules[2].playbook, "sales.md");
1130 } else {
1131 panic!("Expected Playbook handler config");
1132 }
1133 }
1134
1135 #[test]
1136 fn test_playbook_handler_config_without_default() {
1137 let toml_config = r#"
1138http_addr = "0.0.0.0:8080"
1139addr = "0.0.0.0"
1140udp_port = 25060
1141
1142[handler]
1143type = "playbook"
1144
1145[[handler.rules]]
1146caller = "^\\+1.*"
1147playbook = "us.md"
1148"#;
1149
1150 let config: Config = toml::from_str(toml_config).unwrap();
1151
1152 if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
1153 assert_eq!(default, None);
1154 let rules = rules.unwrap();
1155 assert_eq!(rules.len(), 1);
1156 } else {
1157 panic!("Expected Playbook handler config");
1158 }
1159 }
1160
1161 #[test]
1162 fn test_webhook_handler_config_still_works() {
1163 let toml_config = r#"
1164http_addr = "0.0.0.0:8080"
1165addr = "0.0.0.0"
1166udp_port = 25060
1167
1168[handler]
1169type = "webhook"
1170url = "http://example.com/webhook"
1171"#;
1172
1173 let config: Config = toml::from_str(toml_config).unwrap();
1174
1175 if let Some(InviteHandlerConfig::Webhook { url, .. }) = config.handler {
1176 assert_eq!(url, Some("http://example.com/webhook".to_string()));
1177 } else {
1178 panic!("Expected Webhook handler config");
1179 }
1180 }
1181
1182 #[test]
1187 fn test_options_response_defaults() {
1188 let config: Config = toml::from_str(
1189 r#"
1190http_addr = "0.0.0.0:8080"
1191addr = "0.0.0.0"
1192udp_port = 25060
1193"#,
1194 )
1195 .unwrap();
1196
1197 assert!(config.options_response.is_none());
1198 assert!(config.options_response_enabled());
1201 assert!(config.options_auto_learn());
1202 assert_eq!(
1203 config.options_learn_ttl(),
1204 std::time::Duration::from_secs(7 * 24 * 3600)
1205 );
1206 assert!(config.options_acl_entries().is_empty());
1207 assert!(config.options_registered_hosts().is_empty());
1208 assert!(config.options_extra_headers().is_empty());
1209 }
1210
1211 #[test]
1212 fn test_options_response_config_parsing() {
1213 let toml_config = r#"
1214http_addr = "0.0.0.0:8080"
1215addr = "0.0.0.0"
1216udp_port = 25060
1217
1218[options_response]
1219enabled = true
1220allow = ["139.224.72.64", "10.0.0.0/8", "SIP.CCC.AliyunCS.com"]
1221allow_registered_servers = false
1222auto_learn = false
1223learn_ttl = "1h"
1224extra_headers = [["X-Node-Id", "node-1"], ["User-Agent", "ActiveCall-Test"]]
1225"#;
1226
1227 let config: Config = toml::from_str(toml_config).unwrap();
1228 let options = config.options_response.as_ref().unwrap();
1229 assert_eq!(options.enabled, Some(true));
1230 assert_eq!(options.allow_registered_servers, Some(false));
1231 assert_eq!(options.auto_learn, Some(false));
1232
1233 assert!(!config.options_auto_learn());
1234 assert_eq!(
1235 config.options_learn_ttl(),
1236 std::time::Duration::from_secs(3600)
1237 );
1238
1239 let entries = config.options_acl_entries();
1240 assert_eq!(entries.len(), 3);
1241 assert_eq!(
1242 entries[0],
1243 OptionsAclEntry::Ip("139.224.72.64".parse().unwrap())
1244 );
1245 assert!(matches!(entries[1], OptionsAclEntry::Cidr(_)));
1246 assert_eq!(
1247 entries[2],
1248 OptionsAclEntry::Host("sip.ccc.aliyuncs.com".to_string())
1249 );
1250
1251 let headers = config.options_extra_headers();
1252 assert_eq!(headers.len(), 2);
1253 assert_eq!(headers[0], ("X-Node-Id".to_string(), "node-1".to_string()));
1254 }
1255
1256 #[test]
1257 fn test_options_response_enabled_fallback_chain() {
1258 let config: Config = toml::from_str(
1260 r#"
1261addr = "0.0.0.0"
1262udp_port = 25060
1263enable_options_response = false
1264"#,
1265 )
1266 .unwrap();
1267 assert!(!config.options_response_enabled());
1268
1269 let config: Config = toml::from_str(
1271 r#"
1272addr = "0.0.0.0"
1273udp_port = 25060
1274enable_options_response = false
1275
1276[options_response]
1277enabled = true
1278"#,
1279 )
1280 .unwrap();
1281 assert!(config.options_response_enabled());
1282
1283 let config: Config = toml::from_str(
1285 r#"
1286addr = "0.0.0.0"
1287udp_port = 25060
1288enable_options_response = false
1289
1290[options_response]
1291extra_headers = [["X-A", "1"]]
1292"#,
1293 )
1294 .unwrap();
1295 assert!(!config.options_response_enabled());
1296 }
1297
1298 #[test]
1299 fn test_options_acl_matching() {
1300 let toml_config = r#"
1301addr = "0.0.0.0"
1302udp_port = 25060
1303
1304[options_response]
1305allow = ["139.224.72.64", "10.0.0.0/8", "sip.ccc.aliyuncs.com"]
1306"#;
1307 let config: Config = toml::from_str(toml_config).unwrap();
1308 let ip = |s: &str| Some(s.parse::<std::net::IpAddr>().unwrap());
1309
1310 assert!(config.options_matches_static(ip("139.224.72.64"), "139.224.72.64"));
1312 assert!(!config.options_matches_static(ip("139.224.72.65"), "139.224.72.65"));
1313 assert!(config.options_matches_static(ip("10.1.2.3"), "10.1.2.3"));
1315 assert!(!config.options_matches_static(ip("192.168.1.1"), "192.168.1.1"));
1316 assert!(config.options_matches_static(None, "SIP.CCC.ALIYUNCS.COM"));
1318 assert!(!config.options_matches_static(None, "sip.example.com"));
1319 assert!(!config.options_matches_static(None, "139.224.72.64"));
1321 }
1322
1323 #[test]
1324 fn test_options_registered_hosts() {
1325 let toml_config = r#"
1326addr = "0.0.0.0"
1327udp_port = 25060
1328
1329[[register_users]]
1330server = "sip.example.com:5060"
1331username = "1001"
1332
1333[[register_users]]
1334server = "10.0.0.5"
1335username = "1002"
1336"#;
1337 let config: Config = toml::from_str(toml_config).unwrap();
1338 assert_eq!(
1340 config.options_registered_hosts(),
1341 vec!["sip.example.com".to_string(), "10.0.0.5".to_string()]
1342 );
1343 assert!(config.options_matches_static(None, "SIP.EXAMPLE.COM"));
1344 assert!(config.options_matches_static(Some("10.0.0.5".parse().unwrap()), "10.0.0.5"));
1345
1346 let toml_config_off = r#"
1348addr = "0.0.0.0"
1349udp_port = 25060
1350
1351[[register_users]]
1352server = "sip.example.com"
1353username = "1001"
1354
1355[options_response]
1356allow_registered_servers = false
1357"#;
1358 let config: Config = toml::from_str(toml_config_off).unwrap();
1359 assert!(config.options_registered_hosts().is_empty());
1360 assert!(!config.options_matches_static(None, "sip.example.com"));
1361 }
1362
1363 #[test]
1364 fn test_host_of_server() {
1365 assert_eq!(
1366 host_of_server("sip.example.com:5060"),
1367 Some("sip.example.com".to_string())
1368 );
1369 assert_eq!(
1370 host_of_server("SIP.Example.COM"),
1371 Some("sip.example.com".to_string())
1372 );
1373 assert_eq!(
1374 host_of_server("[2001:db8::1]:5060"),
1375 Some("2001:db8::1".to_string())
1376 );
1377 assert_eq!(
1378 host_of_server("2001:db8::1"),
1379 Some("2001:db8::1".to_string())
1380 );
1381 assert_eq!(host_of_server(""), None);
1382 }
1383
1384 #[test]
1389 fn test_trunk_rules_config_parsing() {
1390 let toml_config = r#"
1391http_addr = "0.0.0.0:8080"
1392addr = "0.0.0.0"
1393udp_port = 25060
1394
1395[[trunk_rules]]
1396rule.match.to.host = "^172\\.25\\."
1397rule.rewrite.contact.host = "172.25.225.2"
1398
1399[[trunk_rules]]
1400rule.match.from.user = "^\\+86.*"
1401rule.match.to.host = "^10\\."
1402rule.rewrite.from.user = "10086"
1403rule.rewrite.to.host = "10.0.0.1"
1404rule.rewrite.contact.user = "active-call"
1405rule.rewrite.contact.host = "10.0.0.1:25060"
1406
1407[[trunk_rules]]
1408rule.rewrite.contact.host = "116.62.75.161"
1409"#;
1410
1411 let config: Config = toml::from_str(toml_config).unwrap();
1412 let rules = config.trunk_rules.expect("trunk_rules should be parsed");
1413
1414 assert_eq!(rules.len(), 3);
1415
1416 let m = &rules[0].rule.r#match;
1418 assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^172\\.25\\."));
1419 assert_eq!(m.to.as_ref().unwrap().user, None);
1420 assert_eq!(m.from, None);
1421 let w = &rules[0].rule.rewrite;
1422 assert_eq!(
1423 w.contact.as_ref().unwrap().host.as_deref(),
1424 Some("172.25.225.2")
1425 );
1426 assert_eq!(w.from, None);
1427 assert_eq!(w.to, None);
1428
1429 let m = &rules[1].rule.r#match;
1431 assert_eq!(m.from.as_ref().unwrap().user.as_deref(), Some("^\\+86.*"));
1432 assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^10\\."));
1433 let w = &rules[1].rule.rewrite;
1434 assert_eq!(w.from.as_ref().unwrap().user.as_deref(), Some("10086"));
1435 assert_eq!(w.to.as_ref().unwrap().host.as_deref(), Some("10.0.0.1"));
1436 assert_eq!(
1437 w.contact.as_ref().unwrap().user.as_deref(),
1438 Some("active-call")
1439 );
1440 assert_eq!(
1441 w.contact.as_ref().unwrap().host.as_deref(),
1442 Some("10.0.0.1:25060")
1443 );
1444
1445 assert_eq!(rules[2].rule.r#match.from, None);
1447 assert_eq!(rules[2].rule.r#match.to, None);
1448 assert_eq!(
1449 rules[2]
1450 .rule
1451 .rewrite
1452 .contact
1453 .as_ref()
1454 .unwrap()
1455 .host
1456 .as_deref(),
1457 Some("116.62.75.161")
1458 );
1459 }
1460
1461 #[test]
1462 fn test_trunk_rules_absent_by_default() {
1463 let config = Config::default();
1464 assert!(config.trunk_rules.is_none());
1465 }
1466
1467 fn invite_option(caller: &str, callee: &str, contact: &str) -> InviteOption {
1472 InviteOption {
1473 caller: caller.try_into().unwrap(),
1474 callee: callee.try_into().unwrap(),
1475 contact: contact.try_into().unwrap(),
1476 ..Default::default()
1477 }
1478 }
1479
1480 #[test]
1481 fn test_trunk_rule_matches_on_to_host() {
1482 let config: Config = toml::from_str(
1483 r#"
1484addr = "0.0.0.0"
1485udp_port = 25060
1486
1487[[trunk_rules]]
1488rule.match.to.host = "^172\\.25\\."
1489rule.rewrite.contact.host = "172.25.225.2"
1490"#,
1491 )
1492 .unwrap();
1493
1494 let mut invite = invite_option(
1496 "sip:ai@116.62.75.161:13050",
1497 "sip:agent1@172.25.225.3:15060",
1498 "sip:ai@127.0.0.1:13050",
1499 );
1500 config.apply_trunk_rules(&mut invite);
1501 assert_eq!(
1502 invite.contact.host_with_port.host.to_string(),
1503 "172.25.225.2"
1504 );
1505
1506 let mut invite = invite_option(
1508 "sip:ai@116.62.75.161:13050",
1509 "sip:+8613800138000@sbc.example.com:5060",
1510 "sip:ai@127.0.0.1:13050",
1511 );
1512 config.apply_trunk_rules(&mut invite);
1513 assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1514 }
1515
1516 #[test]
1517 fn test_trunk_rule_matches_on_from_user_and_to_host() {
1518 let config: Config = toml::from_str(
1519 r#"
1520addr = "0.0.0.0"
1521udp_port = 25060
1522
1523[[trunk_rules]]
1524rule.match.from.user = "^anonymous$"
1525rule.match.to.host = "^sbc\\."
1526rule.rewrite.contact.host = "116.62.75.161"
1527"#,
1528 )
1529 .unwrap();
1530
1531 let mut invite = invite_option(
1533 "sip:anonymous@116.62.75.161:13050",
1534 "sip:+8613800138000@sbc.example.com:5060",
1535 "sip:ai@127.0.0.1:13050",
1536 );
1537 config.apply_trunk_rules(&mut invite);
1538 assert_eq!(
1539 invite.contact.host_with_port.host.to_string(),
1540 "116.62.75.161"
1541 );
1542
1543 let mut invite = invite_option(
1545 "sip:alice@116.62.75.161:13050",
1546 "sip:+8613800138000@sbc.example.com:5060",
1547 "sip:ai@127.0.0.1:13050",
1548 );
1549 config.apply_trunk_rules(&mut invite);
1550 assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1551 }
1552
1553 #[test]
1554 fn test_trunk_rule_rewrites_from_to_contact() {
1555 let config: Config = toml::from_str(
1556 r#"
1557addr = "0.0.0.0"
1558udp_port = 25060
1559
1560[[trunk_rules]]
1561rule.match.to.host = "^10\\."
1562rule.rewrite.from.user = "10086"
1563rule.rewrite.from.host = "116.62.75.161"
1564rule.rewrite.to.user = "30000"
1565rule.rewrite.to.host = "10.0.0.1:25060"
1566rule.rewrite.contact.user = "active-call"
1567rule.rewrite.contact.host = "10.0.0.1"
1568"#,
1569 )
1570 .unwrap();
1571
1572 let mut invite = invite_option(
1573 "sip:ai@127.0.0.1:13050",
1574 "sip:agent1@10.0.0.2:25060",
1575 "sip:ai@127.0.0.1:13050",
1576 );
1577 config.apply_trunk_rules(&mut invite);
1578
1579 assert_eq!(invite.caller.auth.as_ref().unwrap().user, "10086");
1581 assert_eq!(
1582 invite.caller.host_with_port.host.to_string(),
1583 "116.62.75.161"
1584 );
1585
1586 assert_eq!(invite.callee.auth.as_ref().unwrap().user, "30000");
1588 assert_eq!(invite.callee.host_with_port.host.to_string(), "10.0.0.1");
1589 assert_eq!(invite.callee.host_with_port.port.unwrap().0, 25060);
1590
1591 assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1593 assert_eq!(invite.contact.host_with_port.host.to_string(), "10.0.0.1");
1594 assert_eq!(invite.contact.host_with_port.port.unwrap().0, 13050);
1595 }
1596
1597 #[test]
1598 fn test_trunk_rule_catch_all_default() {
1599 let config: Config = toml::from_str(
1600 r#"
1601addr = "0.0.0.0"
1602udp_port = 25060
1603
1604[[trunk_rules]]
1605rule.match.to.host = "^172\\.25\\."
1606rule.rewrite.contact.host = "172.25.225.2"
1607
1608[[trunk_rules]]
1609rule.rewrite.contact.host = "116.62.75.161"
1610"#,
1611 )
1612 .unwrap();
1613
1614 let mut invite = invite_option(
1616 "sip:ai@116.62.75.161:13050",
1617 "sip:+8613800138000@sbc.example.com:5060",
1618 "sip:ai@127.0.0.1:13050",
1619 );
1620 config.apply_trunk_rules(&mut invite);
1621 assert_eq!(
1622 invite.contact.host_with_port.host.to_string(),
1623 "116.62.75.161"
1624 );
1625 }
1626
1627 #[test]
1628 fn test_trunk_rule_first_match_wins() {
1629 let config: Config = toml::from_str(
1630 r#"
1631addr = "0.0.0.0"
1632udp_port = 25060
1633
1634[[trunk_rules]]
1635rule.match.to.host = ".*"
1636rule.rewrite.contact.host = "1.1.1.1"
1637
1638[[trunk_rules]]
1639rule.match.to.host = ".*"
1640rule.rewrite.contact.host = "2.2.2.2"
1641"#,
1642 )
1643 .unwrap();
1644
1645 let mut invite = invite_option(
1646 "sip:ai@116.62.75.161:13050",
1647 "sip:any@example.com:5060",
1648 "sip:ai@127.0.0.1:13050",
1649 );
1650 config.apply_trunk_rules(&mut invite);
1651 assert_eq!(invite.contact.host_with_port.host.to_string(), "1.1.1.1");
1653 }
1654
1655 #[test]
1656 fn test_trunk_rule_no_config_noop() {
1657 let config = Config::default();
1658 let mut invite = invite_option(
1659 "sip:ai@116.62.75.161:13050",
1660 "sip:agent1@172.25.225.3:15060",
1661 "sip:ai@127.0.0.1:13050",
1662 );
1663 let before = invite.contact.to_string();
1664 config.apply_trunk_rules(&mut invite);
1665 assert_eq!(invite.contact.to_string(), before);
1666 }
1667
1668 #[test]
1669 fn test_trunk_rule_rewrite_missing_auth_creates_user() {
1670 let config: Config = toml::from_str(
1671 r#"
1672addr = "0.0.0.0"
1673udp_port = 25060
1674
1675[[trunk_rules]]
1676rule.match.to.host = ".*"
1677rule.rewrite.contact.user = "active-call"
1678"#,
1679 )
1680 .unwrap();
1681
1682 let mut invite = InviteOption {
1684 caller: "sip:ai@127.0.0.1:13050".try_into().unwrap(),
1685 callee: "sip:agent1@172.25.225.3:15060".try_into().unwrap(),
1686 contact: "sip:127.0.0.1:13050".try_into().unwrap(),
1687 ..Default::default()
1688 };
1689 config.apply_trunk_rules(&mut invite);
1690 assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1691 }
1692
1693 #[test]
1694 fn test_jitter_buffer_section() {
1695 let config: Config = toml::from_str(
1696 r#"
1697addr = "0.0.0.0"
1698udp_port = 25060
1699"#,
1700 )
1701 .unwrap();
1702 assert!(config.jitter_buffer.is_none());
1703
1704 let config: Config = toml::from_str(
1705 r#"
1706addr = "0.0.0.0"
1707udp_port = 25060
1708
1709[jitter_buffer]
1710sip = true
1711"#,
1712 )
1713 .unwrap();
1714 let jitter_buffer = config.jitter_buffer.unwrap();
1715 assert_eq!(jitter_buffer.webrtc, None);
1716 assert_eq!(jitter_buffer.sip, Some(true));
1717 }
1718}