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 default_codecs() -> Option<Vec<String>> {
127 let codecs = vec![
128 "pcmu".to_string(),
129 "pcma".to_string(),
130 "g722".to_string(),
131 "g729".to_string(),
132 "opus".to_string(),
133 "telephone_event".to_string(),
134 ];
135 Some(codecs)
136}
137
138#[derive(Debug, Clone, Deserialize, Serialize, Default)]
139#[serde(rename_all = "snake_case")]
140pub struct RecordingPolicy {
141 #[serde(default)]
142 pub enabled: bool,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub auto_start: Option<bool>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub filename_pattern: Option<String>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub samplerate: Option<u32>,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub ptime: Option<u32>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub path: Option<String>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub format: Option<RecorderFormat>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub native_samplerate: Option<bool>,
159}
160
161impl RecordingPolicy {
162 pub fn recorder_path(&self) -> String {
163 self.path
164 .as_ref()
165 .map(|p| p.trim())
166 .filter(|p| !p.is_empty())
167 .map(|p| p.to_string())
168 .unwrap_or_else(default_config_recorder_path)
169 }
170
171 pub fn recorder_format(&self) -> RecorderFormat {
172 self.format.unwrap_or_default()
173 }
174
175 pub fn ensure_defaults(&mut self) -> bool {
176 if self
177 .path
178 .as_ref()
179 .map(|p| p.trim().is_empty())
180 .unwrap_or(true)
181 {
182 self.path = Some(default_config_recorder_path());
183 }
184
185 false
186 }
187}
188
189#[derive(Debug, Clone, Deserialize, Serialize)]
190pub struct RewriteRule {
191 pub r#match: String,
192 pub rewrite: String,
193}
194
195#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
208#[serde(rename_all = "snake_case")]
209pub struct TrunkRule {
210 pub rule: TrunkRuleDef,
211}
212
213#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
214#[serde(rename_all = "snake_case")]
215pub struct TrunkRuleDef {
216 #[serde(default, rename = "match")]
217 pub r#match: TrunkMatch,
218 pub rewrite: TrunkRewrite,
219}
220
221#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
225#[serde(rename_all = "snake_case")]
226pub struct TrunkMatch {
227 pub from: Option<UriMatch>,
228 pub to: Option<UriMatch>,
229}
230
231#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
234#[serde(rename_all = "snake_case")]
235pub struct UriMatch {
236 pub user: Option<String>,
238 pub host: Option<String>,
240}
241
242#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
244#[serde(rename_all = "snake_case")]
245pub struct TrunkRewrite {
246 pub from: Option<UriRewrite>,
247 pub to: Option<UriRewrite>,
248 pub contact: Option<UriRewrite>,
249}
250
251#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
255#[serde(rename_all = "snake_case")]
256pub struct UriRewrite {
257 pub user: Option<String>,
258 pub host: Option<String>,
259}
260
261impl TrunkRule {
262 fn matches(&self, invite: &InviteOption) -> bool {
263 self.rule.r#match.matches(invite)
264 }
265
266 fn apply(&self, invite: &mut InviteOption) {
267 self.rule.rewrite.apply(invite);
268 }
269}
270
271impl TrunkMatch {
272 fn matches(&self, invite: &InviteOption) -> bool {
273 let from_ok = self
274 .from
275 .as_ref()
276 .map(|from| from.matches(&invite.caller))
277 .unwrap_or(true);
278 let to_ok = self
279 .to
280 .as_ref()
281 .map(|to| to.matches(&invite.callee))
282 .unwrap_or(true);
283 from_ok && to_ok
284 }
285}
286
287impl UriMatch {
288 fn matches(&self, uri: &Uri) -> bool {
289 let user_ok = self
290 .user
291 .as_ref()
292 .map(|user| {
293 uri.auth
294 .as_ref()
295 .map(|auth| regex_is_match(user, &auth.user))
296 .unwrap_or(false)
297 })
298 .unwrap_or(true);
299 let host_ok = self
300 .host
301 .as_ref()
302 .map(|host| regex_is_match(host, &uri.host_with_port.host.to_string()))
303 .unwrap_or(true);
304 user_ok && host_ok
305 }
306}
307
308impl TrunkRewrite {
309 fn apply(&self, invite: &mut InviteOption) {
310 if let Some(from) = &self.from {
311 from.apply(&mut invite.caller);
312 }
313 if let Some(to) = &self.to {
314 to.apply(&mut invite.callee);
315 }
316 if let Some(contact) = &self.contact {
317 contact.apply(&mut invite.contact);
318 }
319 }
320}
321
322impl UriRewrite {
323 fn apply(&self, uri: &mut Uri) {
324 if let Some(user) = &self.user {
325 let auth = uri.auth.get_or_insert_with(|| Auth {
326 user: String::new(),
327 password: None,
328 });
329 auth.user = user.clone();
330 }
331 if let Some(host) = &self.host
332 && let Ok(mut host_with_port) = HostWithPort::try_from(host.as_str())
333 {
334 if host_with_port.port.is_none() {
336 host_with_port.port = uri.host_with_port.port;
337 }
338 uri.host_with_port = host_with_port;
339 }
340 }
341}
342
343fn regex_is_match(pattern: &str, value: &str) -> bool {
344 regex::Regex::new(pattern)
345 .map(|re| re.is_match(value))
346 .unwrap_or(false)
347}
348
349fn host_of_server(server: &str) -> Option<String> {
352 let server = server.trim();
353 if server.is_empty() {
354 return None;
355 }
356 if let Some(rest) = server.strip_prefix('[') {
357 return rest.split(']').next().map(|h| h.to_ascii_lowercase());
359 }
360 if server.matches(':').count() > 1 {
362 return Some(server.to_ascii_lowercase());
363 }
364 server.split(':').next().map(|h| h.to_ascii_lowercase())
365}
366
367#[derive(Debug, Clone, PartialEq)]
370pub enum OptionsAclEntry {
371 Ip(std::net::IpAddr),
372 Cidr(ipnet::IpNet),
373 Host(String),
374}
375
376impl OptionsAclEntry {
377 fn parse(raw: &str) -> Option<Self> {
378 let raw = raw.trim();
379 if raw.is_empty() {
380 return None;
381 }
382 if let Ok(ip) = raw.parse::<std::net::IpAddr>() {
383 return Some(Self::Ip(ip));
384 }
385 if let Ok(cidr) = raw.parse::<ipnet::IpNet>() {
386 return Some(Self::Cidr(cidr));
387 }
388 Some(Self::Host(raw.to_ascii_lowercase()))
389 }
390
391 pub fn matches(&self, source_ip: Option<std::net::IpAddr>, source_host: &str) -> bool {
392 match self {
393 Self::Ip(ip) => source_ip == Some(*ip),
394 Self::Cidr(net) => source_ip.map(|ip| net.contains(&ip)).unwrap_or(false),
395 Self::Host(host) => host.eq_ignore_ascii_case(source_host),
396 }
397 }
398}
399
400#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
408#[serde(rename_all = "snake_case")]
409pub struct OptionsResponseConfig {
410 #[serde(default, skip_serializing_if = "Option::is_none")]
413 pub enabled: Option<bool>,
414 #[serde(default, skip_serializing_if = "Vec::is_empty")]
417 pub allow: Vec<String>,
418 #[serde(default = "default_options_allow_registered_servers")]
420 pub allow_registered_servers: Option<bool>,
421 #[serde(default = "default_options_auto_learn")]
426 pub auto_learn: Option<bool>,
427 #[serde(default = "default_options_learn_ttl")]
429 pub learn_ttl: Option<String>,
430 #[serde(default, skip_serializing_if = "Vec::is_empty")]
432 pub extra_headers: Vec<(String, String)>,
433}
434
435#[derive(Debug, Deserialize, Serialize)]
436pub struct Config {
437 #[serde(default = "default_config_http_addr")]
438 pub http_addr: String,
439 pub addr: String,
440 pub udp_port: u16,
441 pub auto_learn_public_address: Option<bool>,
442
443 pub log_level: Option<String>,
444 pub log_file: Option<String>,
445 #[serde(default, skip_serializing_if = "Vec::is_empty")]
446 pub http_access_skip_paths: Vec<String>,
447
448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
455 pub peers: Vec<String>,
456
457 #[serde(default = "default_config_useragent")]
458 pub useragent: Option<String>,
459 pub register_users: Option<Vec<RegisterOption>>,
460 #[serde(default = "default_graceful_shutdown")]
461 pub graceful_shutdown: Option<bool>,
462 #[serde(default = "default_graceful_shutdown_timeout")]
465 pub graceful_shutdown_timeout: Option<u64>,
466 pub handler: Option<InviteHandlerConfig>,
467 pub accept_timeout: Option<String>,
468 #[serde(default = "default_codecs")]
469 pub codecs: Option<Vec<String>>,
470 pub external_ip: Option<String>,
471 #[serde(default = "default_config_rtp_start_port")]
472 pub rtp_start_port: Option<u16>,
473 #[serde(default = "default_config_rtp_end_port")]
474 pub rtp_end_port: Option<u16>,
475 #[serde(default = "default_config_rtp_latching")]
476 pub enable_rtp_latching: Option<bool>,
477 pub enable_ice_lite: Option<bool>,
478 pub rtp_bind_ip: Option<String>,
479 pub tls_port: Option<u16>,
480 pub tls_cert_file: Option<String>,
481 pub tls_key_file: Option<String>,
482
483 pub enable_srtp: Option<bool>,
484
485 pub callrecord: Option<CallRecordConfig>,
486 #[serde(default = "default_config_media_cache_path")]
487 pub media_cache_path: String,
488 pub ambiance: Option<AmbianceOption>,
489 pub ice_servers: Option<Vec<IceServer>>,
490 #[serde(default)]
491 pub recording: Option<RecordingPolicy>,
492 pub rewrites: Option<Vec<RewriteRule>>,
493 #[serde(default, skip_serializing_if = "Option::is_none")]
494 pub trunk_rules: Option<Vec<TrunkRule>>,
495 #[serde(default = "default_enable_options_response")]
496 pub enable_options_response: Option<bool>,
497 #[serde(default, skip_serializing_if = "Option::is_none")]
498 pub options_response: Option<OptionsResponseConfig>,
499
500 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub auto_refer: Option<bool>,
506 #[serde(default, skip_serializing_if = "Option::is_none")]
508 pub auto_refer_timeout: Option<u32>,
509}
510
511impl Config {
512 pub fn auto_refer(&self) -> bool {
515 self.auto_refer.unwrap_or(true)
516 }
517
518 pub fn auto_refer_timeout(&self) -> u32 {
520 self.auto_refer_timeout.unwrap_or(30)
521 }
522}
523
524#[derive(Debug, Deserialize, Clone, Serialize)]
525#[serde(rename_all = "snake_case")]
526#[serde(tag = "type")]
527pub enum InviteHandlerConfig {
528 Webhook {
529 url: Option<String>,
530 urls: Option<Vec<String>>,
531 method: Option<String>,
532 headers: Option<Vec<(String, String)>>,
533 },
534 Playbook {
535 rules: Option<Vec<PlaybookRule>>,
536 default: Option<String>,
537 },
538}
539
540#[derive(Debug, Deserialize, Clone, Serialize)]
541#[serde(rename_all = "snake_case")]
542pub struct PlaybookRule {
543 pub caller: Option<String>,
544 pub callee: Option<String>,
545 pub playbook: String,
546}
547
548#[derive(Debug, Deserialize, Clone, Serialize)]
549#[serde(rename_all = "snake_case")]
550pub enum S3Vendor {
551 Aliyun,
552 Tencent,
553 Minio,
554 AWS,
555 GCP,
556 Azure,
557 DigitalOcean,
558}
559
560#[derive(Debug, Deserialize, Clone, Serialize)]
561#[serde(tag = "type")]
562#[serde(rename_all = "snake_case")]
563pub enum CallRecordConfig {
564 Local {
565 root: String,
566 },
567 S3 {
568 vendor: S3Vendor,
569 bucket: String,
570 region: String,
571 access_key: String,
572 secret_key: String,
573 endpoint: String,
574 root: String,
575 with_media: Option<bool>,
576 keep_media_copy: Option<bool>,
577 },
578 Http {
579 url: String,
580 headers: Option<HashMap<String, String>>,
581 with_media: Option<bool>,
582 keep_media_copy: Option<bool>,
583 },
584}
585
586impl Default for CallRecordConfig {
587 fn default() -> Self {
588 Self::Local {
589 #[cfg(target_os = "windows")]
590 root: "./config/cdr".to_string(),
591 #[cfg(not(target_os = "windows"))]
592 root: "./config/cdr".to_string(),
593 }
594 }
595}
596
597impl Default for Config {
598 fn default() -> Self {
599 Self {
600 http_addr: default_config_http_addr(),
601 log_level: None,
602 log_file: None,
603 http_access_skip_paths: Vec::new(),
604 peers: Vec::new(),
605 addr: default_sip_addr(),
606 udp_port: default_sip_port(),
607 auto_learn_public_address: None,
608 useragent: None,
609 register_users: None,
610 graceful_shutdown: Some(true),
611 graceful_shutdown_timeout: default_graceful_shutdown_timeout(),
612 handler: None,
613 accept_timeout: Some("50s".to_string()),
614 media_cache_path: default_config_media_cache_path(),
615 ambiance: None,
616 callrecord: None,
617 ice_servers: None,
618 codecs: None,
619 external_ip: None,
620 rtp_start_port: default_config_rtp_start_port(),
621 rtp_end_port: default_config_rtp_end_port(),
622 enable_rtp_latching: Some(true),
623 rtp_bind_ip: None,
624 enable_ice_lite: None,
625 tls_port: None,
626 tls_cert_file: None,
627 tls_key_file: None,
628 enable_srtp: None,
629 recording: None,
630 rewrites: None,
631 trunk_rules: None,
632 enable_options_response: default_enable_options_response(),
633 options_response: None,
634 auto_refer: None,
635 auto_refer_timeout: None,
636 }
637 }
638}
639
640impl Clone for Config {
641 fn clone(&self) -> Self {
642 let s = toml::to_string(self).unwrap();
645 toml::from_str(&s).unwrap()
646 }
647}
648
649impl Config {
650 pub fn load(path: &str) -> Result<Self, Error> {
651 let config: Self = toml::from_str(
652 &std::fs::read_to_string(path).map_err(|e| anyhow::anyhow!("{}: {}", e, path))?,
653 )?;
654 Ok(config)
655 }
656
657 pub fn options_response_enabled(&self) -> bool {
659 self.options_response
660 .as_ref()
661 .and_then(|o| o.enabled)
662 .or(self.enable_options_response)
663 .unwrap_or(true)
664 }
665
666 pub fn options_auto_learn(&self) -> bool {
668 self.options_response
669 .as_ref()
670 .and_then(|o| o.auto_learn)
671 .unwrap_or(true)
672 }
673
674 pub fn options_learn_ttl(&self) -> std::time::Duration {
676 const DEFAULT: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
677 self.options_response
678 .as_ref()
679 .and_then(|o| o.learn_ttl.as_deref())
680 .map(|raw| humantime::parse_duration(raw).unwrap_or(DEFAULT))
681 .unwrap_or(DEFAULT)
682 }
683
684 pub fn options_acl_entries(&self) -> Vec<OptionsAclEntry> {
686 self.options_response
687 .as_ref()
688 .map(|o| {
689 o.allow
690 .iter()
691 .filter_map(|raw| OptionsAclEntry::parse(raw))
692 .collect()
693 })
694 .unwrap_or_default()
695 }
696
697 pub fn options_registered_hosts(&self) -> Vec<String> {
700 let enabled = self
701 .options_response
702 .as_ref()
703 .and_then(|o| o.allow_registered_servers)
704 .unwrap_or(true);
705 if !enabled {
706 return vec![];
707 }
708 self.register_users
709 .as_ref()
710 .map(|users| {
711 users
712 .iter()
713 .filter_map(|user| host_of_server(&user.server))
714 .collect()
715 })
716 .unwrap_or_default()
717 }
718
719 pub fn options_extra_headers(&self) -> Vec<(String, String)> {
721 self.options_response
722 .as_ref()
723 .map(|o| o.extra_headers.clone())
724 .unwrap_or_default()
725 }
726
727 pub fn options_matches_static(
730 &self,
731 source_ip: Option<std::net::IpAddr>,
732 source_host: &str,
733 ) -> bool {
734 self.options_acl_entries()
735 .iter()
736 .any(|entry| entry.matches(source_ip, source_host))
737 || self
738 .options_registered_hosts()
739 .iter()
740 .any(|host| host.eq_ignore_ascii_case(source_host))
741 }
742
743 pub fn recorder_path(&self) -> String {
744 self.recording
745 .as_ref()
746 .map(|policy| policy.recorder_path())
747 .unwrap_or_else(default_config_recorder_path)
748 }
749
750 pub fn recorder_format(&self) -> RecorderFormat {
751 self.recording
752 .as_ref()
753 .map(|policy| policy.recorder_format())
754 .unwrap_or_default()
755 }
756
757 pub fn recorder_native_samplerate(&self) -> bool {
758 self.recording
759 .as_ref()
760 .and_then(|policy| policy.native_samplerate)
761 .unwrap_or(false)
762 }
763
764 pub fn ensure_recording_defaults(&mut self) -> bool {
765 let mut fallback = false;
766
767 if let Some(policy) = self.recording.as_mut() {
768 fallback |= policy.ensure_defaults();
769 }
770
771 fallback
772 }
773
774 pub fn apply_trunk_rules(&self, invite: &mut InviteOption) {
782 if let Some(rules) = &self.trunk_rules {
783 for rule in rules {
784 if rule.matches(invite) {
785 rule.apply(invite);
786 break;
787 }
788 }
789 }
790 }
791
792 pub fn peer_ws_endpoint(peer: &str) -> Option<String> {
797 let peer = peer.trim();
798 if peer.is_empty() {
799 return None;
800 }
801 if peer.starts_with("wss://") {
802 return Some(peer.to_string());
803 }
804 if peer.starts_with("ws://") {
805 return Some(peer.to_string());
806 }
807 if peer.starts_with("https://") {
808 return Some(peer.replacen("https://", "wss://", 1));
809 }
810 if peer.starts_with("http://") {
811 return Some(peer.replacen("http://", "ws://", 1));
812 }
813 Some(format!("ws://{}", peer))
814 }
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820
821 #[test]
822 fn test_playbook_handler_config_parsing() {
823 let toml_config = r#"
824http_addr = "0.0.0.0:8080"
825addr = "0.0.0.0"
826udp_port = 25060
827
828[handler]
829type = "playbook"
830default = "default.md"
831
832[[handler.rules]]
833caller = "^\\+1\\d{10}$"
834callee = "^sip:support@.*"
835playbook = "support.md"
836
837[[handler.rules]]
838caller = "^\\+86\\d+"
839playbook = "chinese.md"
840
841[[handler.rules]]
842callee = "^sip:sales@.*"
843playbook = "sales.md"
844"#;
845
846 let config: Config = toml::from_str(toml_config).unwrap();
847
848 assert!(config.handler.is_some());
849 if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
850 assert_eq!(default, Some("default.md".to_string()));
851 let rules = rules.unwrap();
852 assert_eq!(rules.len(), 3);
853
854 assert_eq!(rules[0].caller, Some(r"^\+1\d{10}$".to_string()));
855 assert_eq!(rules[0].callee, Some("^sip:support@.*".to_string()));
856 assert_eq!(rules[0].playbook, "support.md");
857
858 assert_eq!(rules[1].caller, Some(r"^\+86\d+".to_string()));
859 assert_eq!(rules[1].callee, None);
860 assert_eq!(rules[1].playbook, "chinese.md");
861
862 assert_eq!(rules[2].caller, None);
863 assert_eq!(rules[2].callee, Some("^sip:sales@.*".to_string()));
864 assert_eq!(rules[2].playbook, "sales.md");
865 } else {
866 panic!("Expected Playbook handler config");
867 }
868 }
869
870 #[test]
871 fn test_playbook_handler_config_without_default() {
872 let toml_config = r#"
873http_addr = "0.0.0.0:8080"
874addr = "0.0.0.0"
875udp_port = 25060
876
877[handler]
878type = "playbook"
879
880[[handler.rules]]
881caller = "^\\+1.*"
882playbook = "us.md"
883"#;
884
885 let config: Config = toml::from_str(toml_config).unwrap();
886
887 if let Some(InviteHandlerConfig::Playbook { rules, default }) = config.handler {
888 assert_eq!(default, None);
889 let rules = rules.unwrap();
890 assert_eq!(rules.len(), 1);
891 } else {
892 panic!("Expected Playbook handler config");
893 }
894 }
895
896 #[test]
897 fn test_webhook_handler_config_still_works() {
898 let toml_config = r#"
899http_addr = "0.0.0.0:8080"
900addr = "0.0.0.0"
901udp_port = 25060
902
903[handler]
904type = "webhook"
905url = "http://example.com/webhook"
906"#;
907
908 let config: Config = toml::from_str(toml_config).unwrap();
909
910 if let Some(InviteHandlerConfig::Webhook { url, .. }) = config.handler {
911 assert_eq!(url, Some("http://example.com/webhook".to_string()));
912 } else {
913 panic!("Expected Webhook handler config");
914 }
915 }
916
917 #[test]
922 fn test_options_response_defaults() {
923 let config: Config = toml::from_str(
924 r#"
925http_addr = "0.0.0.0:8080"
926addr = "0.0.0.0"
927udp_port = 25060
928"#,
929 )
930 .unwrap();
931
932 assert!(config.options_response.is_none());
933 assert!(config.options_response_enabled());
936 assert!(config.options_auto_learn());
937 assert_eq!(
938 config.options_learn_ttl(),
939 std::time::Duration::from_secs(7 * 24 * 3600)
940 );
941 assert!(config.options_acl_entries().is_empty());
942 assert!(config.options_registered_hosts().is_empty());
943 assert!(config.options_extra_headers().is_empty());
944 }
945
946 #[test]
947 fn test_options_response_config_parsing() {
948 let toml_config = r#"
949http_addr = "0.0.0.0:8080"
950addr = "0.0.0.0"
951udp_port = 25060
952
953[options_response]
954enabled = true
955allow = ["139.224.72.64", "10.0.0.0/8", "SIP.CCC.AliyunCS.com"]
956allow_registered_servers = false
957auto_learn = false
958learn_ttl = "1h"
959extra_headers = [["X-Node-Id", "node-1"], ["User-Agent", "ActiveCall-Test"]]
960"#;
961
962 let config: Config = toml::from_str(toml_config).unwrap();
963 let options = config.options_response.as_ref().unwrap();
964 assert_eq!(options.enabled, Some(true));
965 assert_eq!(options.allow_registered_servers, Some(false));
966 assert_eq!(options.auto_learn, Some(false));
967
968 assert!(!config.options_auto_learn());
969 assert_eq!(
970 config.options_learn_ttl(),
971 std::time::Duration::from_secs(3600)
972 );
973
974 let entries = config.options_acl_entries();
975 assert_eq!(entries.len(), 3);
976 assert_eq!(
977 entries[0],
978 OptionsAclEntry::Ip("139.224.72.64".parse().unwrap())
979 );
980 assert!(matches!(entries[1], OptionsAclEntry::Cidr(_)));
981 assert_eq!(
982 entries[2],
983 OptionsAclEntry::Host("sip.ccc.aliyuncs.com".to_string())
984 );
985
986 let headers = config.options_extra_headers();
987 assert_eq!(headers.len(), 2);
988 assert_eq!(headers[0], ("X-Node-Id".to_string(), "node-1".to_string()));
989 }
990
991 #[test]
992 fn test_options_response_enabled_fallback_chain() {
993 let config: Config = toml::from_str(
995 r#"
996addr = "0.0.0.0"
997udp_port = 25060
998enable_options_response = false
999"#,
1000 )
1001 .unwrap();
1002 assert!(!config.options_response_enabled());
1003
1004 let config: Config = toml::from_str(
1006 r#"
1007addr = "0.0.0.0"
1008udp_port = 25060
1009enable_options_response = false
1010
1011[options_response]
1012enabled = true
1013"#,
1014 )
1015 .unwrap();
1016 assert!(config.options_response_enabled());
1017
1018 let config: Config = toml::from_str(
1020 r#"
1021addr = "0.0.0.0"
1022udp_port = 25060
1023enable_options_response = false
1024
1025[options_response]
1026extra_headers = [["X-A", "1"]]
1027"#,
1028 )
1029 .unwrap();
1030 assert!(!config.options_response_enabled());
1031 }
1032
1033 #[test]
1034 fn test_options_acl_matching() {
1035 let toml_config = r#"
1036addr = "0.0.0.0"
1037udp_port = 25060
1038
1039[options_response]
1040allow = ["139.224.72.64", "10.0.0.0/8", "sip.ccc.aliyuncs.com"]
1041"#;
1042 let config: Config = toml::from_str(toml_config).unwrap();
1043 let ip = |s: &str| Some(s.parse::<std::net::IpAddr>().unwrap());
1044
1045 assert!(config.options_matches_static(ip("139.224.72.64"), "139.224.72.64"));
1047 assert!(!config.options_matches_static(ip("139.224.72.65"), "139.224.72.65"));
1048 assert!(config.options_matches_static(ip("10.1.2.3"), "10.1.2.3"));
1050 assert!(!config.options_matches_static(ip("192.168.1.1"), "192.168.1.1"));
1051 assert!(config.options_matches_static(None, "SIP.CCC.ALIYUNCS.COM"));
1053 assert!(!config.options_matches_static(None, "sip.example.com"));
1054 assert!(!config.options_matches_static(None, "139.224.72.64"));
1056 }
1057
1058 #[test]
1059 fn test_options_registered_hosts() {
1060 let toml_config = r#"
1061addr = "0.0.0.0"
1062udp_port = 25060
1063
1064[[register_users]]
1065server = "sip.example.com:5060"
1066username = "1001"
1067
1068[[register_users]]
1069server = "10.0.0.5"
1070username = "1002"
1071"#;
1072 let config: Config = toml::from_str(toml_config).unwrap();
1073 assert_eq!(
1075 config.options_registered_hosts(),
1076 vec!["sip.example.com".to_string(), "10.0.0.5".to_string()]
1077 );
1078 assert!(config.options_matches_static(None, "SIP.EXAMPLE.COM"));
1079 assert!(config.options_matches_static(Some("10.0.0.5".parse().unwrap()), "10.0.0.5"));
1080
1081 let toml_config_off = r#"
1083addr = "0.0.0.0"
1084udp_port = 25060
1085
1086[[register_users]]
1087server = "sip.example.com"
1088username = "1001"
1089
1090[options_response]
1091allow_registered_servers = false
1092"#;
1093 let config: Config = toml::from_str(toml_config_off).unwrap();
1094 assert!(config.options_registered_hosts().is_empty());
1095 assert!(!config.options_matches_static(None, "sip.example.com"));
1096 }
1097
1098 #[test]
1099 fn test_host_of_server() {
1100 assert_eq!(
1101 host_of_server("sip.example.com:5060"),
1102 Some("sip.example.com".to_string())
1103 );
1104 assert_eq!(
1105 host_of_server("SIP.Example.COM"),
1106 Some("sip.example.com".to_string())
1107 );
1108 assert_eq!(
1109 host_of_server("[2001:db8::1]:5060"),
1110 Some("2001:db8::1".to_string())
1111 );
1112 assert_eq!(
1113 host_of_server("2001:db8::1"),
1114 Some("2001:db8::1".to_string())
1115 );
1116 assert_eq!(host_of_server(""), None);
1117 }
1118
1119 #[test]
1124 fn test_trunk_rules_config_parsing() {
1125 let toml_config = r#"
1126http_addr = "0.0.0.0:8080"
1127addr = "0.0.0.0"
1128udp_port = 25060
1129
1130[[trunk_rules]]
1131rule.match.to.host = "^172\\.25\\."
1132rule.rewrite.contact.host = "172.25.225.2"
1133
1134[[trunk_rules]]
1135rule.match.from.user = "^\\+86.*"
1136rule.match.to.host = "^10\\."
1137rule.rewrite.from.user = "10086"
1138rule.rewrite.to.host = "10.0.0.1"
1139rule.rewrite.contact.user = "active-call"
1140rule.rewrite.contact.host = "10.0.0.1:25060"
1141
1142[[trunk_rules]]
1143rule.rewrite.contact.host = "116.62.75.161"
1144"#;
1145
1146 let config: Config = toml::from_str(toml_config).unwrap();
1147 let rules = config.trunk_rules.expect("trunk_rules should be parsed");
1148
1149 assert_eq!(rules.len(), 3);
1150
1151 let m = &rules[0].rule.r#match;
1153 assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^172\\.25\\."));
1154 assert_eq!(m.to.as_ref().unwrap().user, None);
1155 assert_eq!(m.from, None);
1156 let w = &rules[0].rule.rewrite;
1157 assert_eq!(
1158 w.contact.as_ref().unwrap().host.as_deref(),
1159 Some("172.25.225.2")
1160 );
1161 assert_eq!(w.from, None);
1162 assert_eq!(w.to, None);
1163
1164 let m = &rules[1].rule.r#match;
1166 assert_eq!(m.from.as_ref().unwrap().user.as_deref(), Some("^\\+86.*"));
1167 assert_eq!(m.to.as_ref().unwrap().host.as_deref(), Some("^10\\."));
1168 let w = &rules[1].rule.rewrite;
1169 assert_eq!(w.from.as_ref().unwrap().user.as_deref(), Some("10086"));
1170 assert_eq!(w.to.as_ref().unwrap().host.as_deref(), Some("10.0.0.1"));
1171 assert_eq!(
1172 w.contact.as_ref().unwrap().user.as_deref(),
1173 Some("active-call")
1174 );
1175 assert_eq!(
1176 w.contact.as_ref().unwrap().host.as_deref(),
1177 Some("10.0.0.1:25060")
1178 );
1179
1180 assert_eq!(rules[2].rule.r#match.from, None);
1182 assert_eq!(rules[2].rule.r#match.to, None);
1183 assert_eq!(
1184 rules[2]
1185 .rule
1186 .rewrite
1187 .contact
1188 .as_ref()
1189 .unwrap()
1190 .host
1191 .as_deref(),
1192 Some("116.62.75.161")
1193 );
1194 }
1195
1196 #[test]
1197 fn test_trunk_rules_absent_by_default() {
1198 let config = Config::default();
1199 assert!(config.trunk_rules.is_none());
1200 }
1201
1202 fn invite_option(caller: &str, callee: &str, contact: &str) -> InviteOption {
1207 InviteOption {
1208 caller: caller.try_into().unwrap(),
1209 callee: callee.try_into().unwrap(),
1210 contact: contact.try_into().unwrap(),
1211 ..Default::default()
1212 }
1213 }
1214
1215 #[test]
1216 fn test_trunk_rule_matches_on_to_host() {
1217 let config: Config = toml::from_str(
1218 r#"
1219addr = "0.0.0.0"
1220udp_port = 25060
1221
1222[[trunk_rules]]
1223rule.match.to.host = "^172\\.25\\."
1224rule.rewrite.contact.host = "172.25.225.2"
1225"#,
1226 )
1227 .unwrap();
1228
1229 let mut invite = invite_option(
1231 "sip:ai@116.62.75.161:13050",
1232 "sip:agent1@172.25.225.3:15060",
1233 "sip:ai@127.0.0.1:13050",
1234 );
1235 config.apply_trunk_rules(&mut invite);
1236 assert_eq!(
1237 invite.contact.host_with_port.host.to_string(),
1238 "172.25.225.2"
1239 );
1240
1241 let mut invite = invite_option(
1243 "sip:ai@116.62.75.161:13050",
1244 "sip:+8613800138000@sbc.example.com:5060",
1245 "sip:ai@127.0.0.1:13050",
1246 );
1247 config.apply_trunk_rules(&mut invite);
1248 assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1249 }
1250
1251 #[test]
1252 fn test_trunk_rule_matches_on_from_user_and_to_host() {
1253 let config: Config = toml::from_str(
1254 r#"
1255addr = "0.0.0.0"
1256udp_port = 25060
1257
1258[[trunk_rules]]
1259rule.match.from.user = "^anonymous$"
1260rule.match.to.host = "^sbc\\."
1261rule.rewrite.contact.host = "116.62.75.161"
1262"#,
1263 )
1264 .unwrap();
1265
1266 let mut invite = invite_option(
1268 "sip:anonymous@116.62.75.161:13050",
1269 "sip:+8613800138000@sbc.example.com:5060",
1270 "sip:ai@127.0.0.1:13050",
1271 );
1272 config.apply_trunk_rules(&mut invite);
1273 assert_eq!(
1274 invite.contact.host_with_port.host.to_string(),
1275 "116.62.75.161"
1276 );
1277
1278 let mut invite = invite_option(
1280 "sip:alice@116.62.75.161:13050",
1281 "sip:+8613800138000@sbc.example.com:5060",
1282 "sip:ai@127.0.0.1:13050",
1283 );
1284 config.apply_trunk_rules(&mut invite);
1285 assert_eq!(invite.contact.host_with_port.host.to_string(), "127.0.0.1");
1286 }
1287
1288 #[test]
1289 fn test_trunk_rule_rewrites_from_to_contact() {
1290 let config: Config = toml::from_str(
1291 r#"
1292addr = "0.0.0.0"
1293udp_port = 25060
1294
1295[[trunk_rules]]
1296rule.match.to.host = "^10\\."
1297rule.rewrite.from.user = "10086"
1298rule.rewrite.from.host = "116.62.75.161"
1299rule.rewrite.to.user = "30000"
1300rule.rewrite.to.host = "10.0.0.1:25060"
1301rule.rewrite.contact.user = "active-call"
1302rule.rewrite.contact.host = "10.0.0.1"
1303"#,
1304 )
1305 .unwrap();
1306
1307 let mut invite = invite_option(
1308 "sip:ai@127.0.0.1:13050",
1309 "sip:agent1@10.0.0.2:25060",
1310 "sip:ai@127.0.0.1:13050",
1311 );
1312 config.apply_trunk_rules(&mut invite);
1313
1314 assert_eq!(invite.caller.auth.as_ref().unwrap().user, "10086");
1316 assert_eq!(
1317 invite.caller.host_with_port.host.to_string(),
1318 "116.62.75.161"
1319 );
1320
1321 assert_eq!(invite.callee.auth.as_ref().unwrap().user, "30000");
1323 assert_eq!(invite.callee.host_with_port.host.to_string(), "10.0.0.1");
1324 assert_eq!(invite.callee.host_with_port.port.unwrap().0, 25060);
1325
1326 assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1328 assert_eq!(invite.contact.host_with_port.host.to_string(), "10.0.0.1");
1329 assert_eq!(invite.contact.host_with_port.port.unwrap().0, 13050);
1330 }
1331
1332 #[test]
1333 fn test_trunk_rule_catch_all_default() {
1334 let config: Config = toml::from_str(
1335 r#"
1336addr = "0.0.0.0"
1337udp_port = 25060
1338
1339[[trunk_rules]]
1340rule.match.to.host = "^172\\.25\\."
1341rule.rewrite.contact.host = "172.25.225.2"
1342
1343[[trunk_rules]]
1344rule.rewrite.contact.host = "116.62.75.161"
1345"#,
1346 )
1347 .unwrap();
1348
1349 let mut invite = invite_option(
1351 "sip:ai@116.62.75.161:13050",
1352 "sip:+8613800138000@sbc.example.com:5060",
1353 "sip:ai@127.0.0.1:13050",
1354 );
1355 config.apply_trunk_rules(&mut invite);
1356 assert_eq!(
1357 invite.contact.host_with_port.host.to_string(),
1358 "116.62.75.161"
1359 );
1360 }
1361
1362 #[test]
1363 fn test_trunk_rule_first_match_wins() {
1364 let config: Config = toml::from_str(
1365 r#"
1366addr = "0.0.0.0"
1367udp_port = 25060
1368
1369[[trunk_rules]]
1370rule.match.to.host = ".*"
1371rule.rewrite.contact.host = "1.1.1.1"
1372
1373[[trunk_rules]]
1374rule.match.to.host = ".*"
1375rule.rewrite.contact.host = "2.2.2.2"
1376"#,
1377 )
1378 .unwrap();
1379
1380 let mut invite = invite_option(
1381 "sip:ai@116.62.75.161:13050",
1382 "sip:any@example.com:5060",
1383 "sip:ai@127.0.0.1:13050",
1384 );
1385 config.apply_trunk_rules(&mut invite);
1386 assert_eq!(invite.contact.host_with_port.host.to_string(), "1.1.1.1");
1388 }
1389
1390 #[test]
1391 fn test_trunk_rule_no_config_noop() {
1392 let config = Config::default();
1393 let mut invite = invite_option(
1394 "sip:ai@116.62.75.161:13050",
1395 "sip:agent1@172.25.225.3:15060",
1396 "sip:ai@127.0.0.1:13050",
1397 );
1398 let before = invite.contact.to_string();
1399 config.apply_trunk_rules(&mut invite);
1400 assert_eq!(invite.contact.to_string(), before);
1401 }
1402
1403 #[test]
1404 fn test_trunk_rule_rewrite_missing_auth_creates_user() {
1405 let config: Config = toml::from_str(
1406 r#"
1407addr = "0.0.0.0"
1408udp_port = 25060
1409
1410[[trunk_rules]]
1411rule.match.to.host = ".*"
1412rule.rewrite.contact.user = "active-call"
1413"#,
1414 )
1415 .unwrap();
1416
1417 let mut invite = InviteOption {
1419 caller: "sip:ai@127.0.0.1:13050".try_into().unwrap(),
1420 callee: "sip:agent1@172.25.225.3:15060".try_into().unwrap(),
1421 contact: "sip:127.0.0.1:13050".try_into().unwrap(),
1422 ..Default::default()
1423 };
1424 config.apply_trunk_rules(&mut invite);
1425 assert_eq!(invite.contact.auth.as_ref().unwrap().user, "active-call");
1426 }
1427}