1use std::collections::HashSet;
2use std::fmt;
3use std::net::IpAddr;
4use std::ops::Deref;
5
6use crate::address::{
7 address_to_int, expand_ipv6_address, get_mask_ipv4, get_mask_ipv6,
8 is_valid_ipv4_address, is_valid_ipv6_address, masked_bits, parse_port,
9};
10use crate::error::{Error, Result};
11
12const PRIVATE_ADDRESSES: [&str; 6] = [
13 "0.0.0.0/8",
14 "169.254.0.0/16",
15 "127.0.0.0/8",
16 "192.168.0.0/16",
17 "10.0.0.0/8",
18 "172.16.0.0/12",
19];
20
21const DEFAULT_POLICY_RULES: [&str; 11] = [
22 "reject *:25",
23 "reject *:119",
24 "reject *:135-139",
25 "reject *:445",
26 "reject *:563",
27 "reject *:1214",
28 "reject *:4661-4666",
29 "reject *:6346-6429",
30 "reject *:6699",
31 "reject *:6881-6999",
32 "accept *:*",
33];
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum AddressType {
37 Wildcard,
38 Ipv4,
39 Ipv6,
40}
41
42#[derive(Debug, Clone)]
43pub struct ExitPolicyRule {
44 pub is_accept: bool,
45 pub address: Option<String>,
46 pub min_port: u16,
47 pub max_port: u16,
48 address_type: AddressType,
49 masked_bits: Option<u32>,
50 mask: Option<String>,
51 mask_value: u128,
52 address_value: u128,
53 skip_rule: bool,
54 is_private: bool,
55 is_default_suffix: bool,
56}
57
58impl PartialEq for ExitPolicyRule {
59 fn eq(&self, other: &Self) -> bool {
60 self.is_accept == other.is_accept
61 && self.address == other.address
62 && self.min_port == other.min_port
63 && self.max_port == other.max_port
64 && self.mask == other.mask
65 }
66}
67
68impl Eq for ExitPolicyRule {}
69
70fn port_spec(rule: &str, spec: &str) -> Result<(u16, u16)> {
71 if spec == "*" {
72 return Ok((1, 65535));
73 }
74 if !spec.is_empty() && spec.bytes().all(|byte| byte.is_ascii_digit()) {
75 return match parse_port(spec, true) {
76 Some(port) => Ok((port, port)),
77 None => Err(Error::parse(format!(
78 "'{spec}' isn't within a valid port range: {rule}"
79 ))),
80 };
81 }
82 let Some((first, last)) = spec.split_once('-') else {
83 return Err(Error::parse(format!(
84 "Port value isn't a wildcard, integer, or range: {rule}"
85 )));
86 };
87 let (Some(min_port), Some(max_port)) =
88 (parse_port(first, true), parse_port(last, true))
89 else {
90 return Err(Error::parse(format!("Malformed port range: {rule}")));
91 };
92 if min_port > max_port {
93 return Err(Error::parse(format!(
94 "Port range has a lower bound that's greater than its upper bound: {rule}"
95 )));
96 }
97 Ok((min_port, max_port))
98}
99
100impl ExitPolicyRule {
101 pub fn new(rule: &str) -> Result<Self> {
102 let is_accept = rule.starts_with("accept");
103 let is_ipv6_only = rule.starts_with("accept6") || rule.starts_with("reject6");
104 let pattern = if is_ipv6_only {
105 &rule[7..]
106 } else if is_accept || rule.starts_with("reject") {
107 &rule[6..]
108 } else {
109 return Err(Error::parse(format!(
110 "An exit policy must start with either 'accept[6]' or 'reject[6]': {rule}"
111 )));
112 };
113 if !pattern.starts_with(' ') {
114 return Err(Error::parse(format!(
115 "An exit policy should have a space separating its accept/reject from \
116 the exit pattern: {rule}"
117 )));
118 }
119 let pattern = pattern.trim_start();
120 let well_formed = pattern
121 .rsplit_once(':')
122 .is_some_and(|(_, ports)| !ports.contains(']'));
123 if !well_formed {
124 return Err(Error::parse(format!(
125 "An exitpattern must be of the form 'addrspec:portspec': {rule}"
126 )));
127 }
128 let (address_spec, port_text) = pattern.rsplit_once(':').expect("checked above");
129 let (min_port, max_port) = port_spec(rule, port_text)?;
130 let mut parsed = Self {
131 is_accept,
132 address: None,
133 min_port,
134 max_port,
135 address_type: AddressType::Wildcard,
136 masked_bits: None,
137 mask: None,
138 mask_value: 0,
139 address_value: 0,
140 skip_rule: false,
141 is_private: false,
142 is_default_suffix: false,
143 };
144 parsed.apply_address_spec(rule, address_spec, is_ipv6_only)?;
145 Ok(parsed)
146 }
147
148 pub fn from_ports(is_accept: bool, min_port: u16, max_port: u16) -> Self {
149 Self {
150 is_accept,
151 address: None,
152 min_port,
153 max_port,
154 address_type: AddressType::Wildcard,
155 masked_bits: None,
156 mask: None,
157 mask_value: 0,
158 address_value: 0,
159 skip_rule: false,
160 is_private: false,
161 is_default_suffix: false,
162 }
163 }
164
165 fn apply_address_spec(
166 &mut self,
167 rule: &str,
168 address_spec: &str,
169 ipv6_only: bool,
170 ) -> Result<()> {
171 let spec = match address_spec {
172 "*4" => "0.0.0.0/0",
173 "*6" => "[0000:0000:0000:0000:0000:0000:0000:0000]/0",
174 "*" if ipv6_only => "[0000:0000:0000:0000:0000:0000:0000:0000]/0",
175 other => other,
176 };
177 let (address, extra) = match spec.split_once('/') {
178 Some((address, extra)) => (address, Some(extra)),
179 None => (spec, None),
180 };
181 if spec == "*" {
182 self.address_type = AddressType::Wildcard;
183 return Ok(());
184 }
185 if is_valid_ipv4_address(address) {
186 return self.apply_ipv4(rule, address, extra, ipv6_only);
187 }
188 let inner = address
189 .strip_prefix('[')
190 .and_then(|rest| rest.strip_suffix(']'));
191 match inner {
192 Some(inner) if is_valid_ipv6_address(inner, false) => {
193 self.apply_ipv6(rule, inner, extra)
194 }
195 _ => Err(Error::parse(format!(
196 "'{address_spec}' isn't a wildcard, IPv4, or IPv6 address: {rule}"
197 ))),
198 }
199 }
200
201 fn apply_ipv4(
202 &mut self,
203 rule: &str,
204 address: &str,
205 extra: Option<&str>,
206 ipv6_only: bool,
207 ) -> Result<()> {
208 self.skip_rule = ipv6_only;
209 self.address_type = AddressType::Ipv4;
210 self.address = Some(address.to_string());
211 match extra {
212 None => self.masked_bits = Some(32),
213 Some(extra) if is_valid_ipv4_address(extra) => match masked_bits(extra) {
214 Ok(bits) => self.masked_bits = Some(bits),
215 Err(_) => {
216 self.mask = Some(extra.to_string());
217 self.mask_value = address_to_int(extra)?;
218 }
219 },
220 Some(extra)
221 if !extra.is_empty()
222 && extra.bytes().all(|byte| byte.is_ascii_digit()) =>
223 {
224 let bits: u32 = extra.parse().unwrap_or(u32::MAX);
225 if bits > 32 {
226 return Err(Error::parse(
227 "IPv4 masks must be in the range of 0-32 bits",
228 ));
229 }
230 self.masked_bits = Some(bits);
231 }
232 Some(extra) => {
233 return Err(Error::parse(format!(
234 "The '{extra}' isn't a mask nor number of bits: {rule}"
235 )));
236 }
237 }
238 if let Some(bits) = self.masked_bits {
239 self.mask = Some(get_mask_ipv4(bits)?);
240 self.mask_value = address_to_int(self.mask.as_deref().unwrap_or_default())?;
241 }
242 self.address_value = address_to_int(address)? & self.mask_value;
243 Ok(())
244 }
245
246 fn apply_ipv6(
247 &mut self,
248 rule: &str,
249 address: &str,
250 extra: Option<&str>,
251 ) -> Result<()> {
252 self.address_type = AddressType::Ipv6;
253 self.address = Some(expand_ipv6_address(address)?.to_uppercase());
254 let bits = match extra {
255 None => 128,
256 Some(extra)
257 if !extra.is_empty()
258 && extra.bytes().all(|byte| byte.is_ascii_digit()) =>
259 {
260 let bits: u32 = extra.parse().unwrap_or(u32::MAX);
261 if bits > 128 {
262 return Err(Error::parse(
263 "IPv6 masks must be in the range of 0-128 bits",
264 ));
265 }
266 bits
267 }
268 Some(extra) => {
269 return Err(Error::parse(format!(
270 "The '{extra}' isn't a number of bits: {rule}"
271 )));
272 }
273 };
274 self.masked_bits = Some(bits);
275 let mask = get_mask_ipv6(bits)?;
276 self.mask_value = address_to_int(&mask)?;
277 self.mask = Some(mask);
278 self.address_value = address_to_int(self.address.as_deref().unwrap_or_default())?
279 & self.mask_value;
280 Ok(())
281 }
282
283 pub fn is_address_wildcard(&self) -> bool {
284 self.address_type == AddressType::Wildcard
285 }
286
287 pub fn is_port_wildcard(&self) -> bool {
288 matches!(self.min_port, 0 | 1) && self.max_port == 65535
289 }
290
291 pub fn address_type(&self) -> AddressType {
292 self.address_type
293 }
294
295 pub fn mask(&self) -> Option<&str> {
296 self.mask.as_deref()
297 }
298
299 pub fn masked_bits(&self) -> Option<u32> {
300 self.masked_bits
301 }
302
303 pub fn is_private(&self) -> bool {
304 self.is_private
305 }
306
307 pub fn is_default(&self) -> bool {
308 self.is_default_suffix
309 }
310
311 pub fn is_match(
312 &self,
313 address: Option<&str>,
314 port: Option<u16>,
315 strict: bool,
316 ) -> Result<bool> {
317 if self.skip_rule {
318 return Ok(false);
319 }
320 let parsed_address = address.map(parse_exit_address).transpose()?;
321 if let Some(parsed) = &parsed_address {
322 let mismatched = matches!(
323 (self.address_type, parsed),
324 (AddressType::Ipv6, IpAddr::V4(_)) | (AddressType::Ipv4, IpAddr::V6(_))
325 );
326 if mismatched {
327 return Ok(false);
328 }
329 }
330 if let Some(0) = port {
331 return Err(Error::invalid_input("'0' isn't a valid port"));
332 }
333 let mut fuzzy_match = false;
334 if !self.is_address_wildcard() {
335 match &parsed_address {
336 None => fuzzy_match = true,
337 Some(parsed) => {
338 let comparison = ip_to_integer(parsed) & self.mask_value;
339 if self.address_value != comparison {
340 return Ok(false);
341 }
342 }
343 }
344 }
345 if !self.is_port_wildcard() {
346 match port {
347 None => fuzzy_match = true,
348 Some(port) if port < self.min_port || port > self.max_port => {
349 return Ok(false);
350 }
351 Some(_) => {}
352 }
353 }
354 Ok(match fuzzy_match {
355 true => strict != self.is_accept,
356 false => true,
357 })
358 }
359}
360
361fn ip_to_integer(address: &IpAddr) -> u128 {
362 match address {
363 IpAddr::V4(address) => u128::from(u32::from(*address)),
364 IpAddr::V6(address) => u128::from(*address),
365 }
366}
367
368fn parse_exit_address(address: &str) -> Result<IpAddr> {
369 let unwrapped = address
370 .strip_prefix('[')
371 .and_then(|rest| rest.strip_suffix(']'))
372 .unwrap_or(address);
373 unwrapped.parse().map_err(|_| {
374 Error::invalid_input(format!("'{address}' isn't a valid IPv4 or IPv6 address"))
375 })
376}
377
378impl fmt::Display for ExitPolicyRule {
379 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
380 write!(
381 formatter,
382 "{} ",
383 if self.is_accept { "accept" } else { "reject" }
384 )?;
385 match (self.address_type, self.address.as_deref()) {
386 (AddressType::Wildcard, _) | (_, None) => write!(formatter, "*:")?,
387 (kind, Some(address)) => {
388 match kind {
389 AddressType::Ipv4 => write!(formatter, "{address}")?,
390 _ => write!(formatter, "[{address}]")?,
391 }
392 let is_full = matches!(
393 (kind, self.masked_bits),
394 (AddressType::Ipv4, Some(32)) | (AddressType::Ipv6, Some(128))
395 );
396 match (is_full, self.masked_bits) {
397 (true, _) => write!(formatter, ":")?,
398 (false, Some(bits)) => write!(formatter, "/{bits}:")?,
399 (false, None) => {
400 write!(formatter, "/{}:", self.mask.as_deref().unwrap_or(""))?
401 }
402 }
403 }
404 }
405 match (self.is_port_wildcard(), self.min_port == self.max_port) {
406 (true, _) => write!(formatter, "*"),
407 (false, true) => write!(formatter, "{}", self.min_port),
408 (false, false) => write!(formatter, "{}-{}", self.min_port, self.max_port),
409 }
410 }
411}
412
413fn flag_private_rules(rules: &mut [ExitPolicyRule]) {
414 let describe = |rule: &ExitPolicyRule| {
415 format!(
416 "{}/{}",
417 rule.address.as_deref().unwrap_or("None"),
418 rule.masked_bits
419 .map_or("None".to_string(), |bits| bits.to_string())
420 )
421 };
422 let starts: Vec<usize> = (0..rules.len())
423 .take_while(|index| index + PRIVATE_ADDRESSES.len() <= rules.len())
424 .filter(|index| describe(&rules[*index]) == PRIVATE_ADDRESSES[0])
425 .collect();
426 for start in starts {
427 let end = start + PRIVATE_ADDRESSES.len();
428 let (min_port, max_port, is_accept) = {
429 let first = &rules[start];
430 (first.min_port, first.max_port, first.is_accept)
431 };
432 let is_match = rules[start..end].iter().enumerate().all(|(offset, rule)| {
433 describe(rule) == PRIVATE_ADDRESSES[offset]
434 && rule.min_port == min_port
435 && rule.max_port == max_port
436 && rule.is_accept == is_accept
437 });
438 if !is_match {
439 continue;
440 }
441 rules[start..end]
442 .iter_mut()
443 .for_each(|rule| rule.is_private = true);
444 if let Some(last) = rules.get_mut(end)
445 && !last.is_address_wildcard()
446 && last.min_port == min_port
447 && last.max_port == max_port
448 && last.is_accept == is_accept
449 {
450 last.is_private = true;
451 }
452 }
453}
454
455fn flag_default_rules(rules: &mut [ExitPolicyRule]) {
456 if rules.len() < DEFAULT_POLICY_RULES.len() {
457 return;
458 }
459 let split = rules.len() - DEFAULT_POLICY_RULES.len();
460 let defaults: Vec<ExitPolicyRule> = DEFAULT_POLICY_RULES
461 .iter()
462 .map(|rule| ExitPolicyRule::new(rule).expect("default rules are valid"))
463 .collect();
464 if rules[split..] == defaults[..] {
465 rules[split..]
466 .iter_mut()
467 .for_each(|rule| rule.is_default_suffix = true);
468 }
469}
470
471#[derive(Debug, Clone)]
472pub struct ExitPolicy {
473 rules: Vec<ExitPolicyRule>,
474 is_allowed_default: bool,
475}
476
477impl ExitPolicy {
478 pub fn new<S: AsRef<str>>(rules: &[S]) -> Result<Self> {
479 let parsed = rules
480 .iter()
481 .map(AsRef::as_ref)
482 .map(str::trim)
483 .filter(|rule| !rule.is_empty())
484 .map(ExitPolicyRule::new)
485 .collect::<Result<Vec<_>>>()?;
486 Ok(Self::from_rules(parsed, true))
487 }
488
489 pub fn from_rules(input: Vec<ExitPolicyRule>, is_allowed_default: bool) -> Self {
490 let mut rules = Vec::new();
491 let (mut is_all_accept, mut is_all_reject) = (true, true);
492 for rule in input {
493 match rule.is_accept {
494 true => is_all_reject = false,
495 false => is_all_accept = false,
496 }
497 let is_final = rule.is_address_wildcard() && rule.is_port_wildcard();
498 rules.push(rule);
499 if is_final {
500 break;
501 }
502 }
503 let ends_with_wildcard = rules
504 .last()
505 .is_some_and(|rule| rule.is_address_wildcard() && rule.is_port_wildcard());
506 if ends_with_wildcard && (is_all_accept || is_all_reject) {
507 let wildcard = if is_all_accept {
508 "accept *:*"
509 } else {
510 "reject *:*"
511 };
512 rules = vec![ExitPolicyRule::new(wildcard).expect("literal rule is valid")];
513 }
514 flag_private_rules(&mut rules);
515 flag_default_rules(&mut rules);
516 Self {
517 rules,
518 is_allowed_default,
519 }
520 }
521
522 pub fn rules(&self) -> &[ExitPolicyRule] {
523 &self.rules
524 }
525
526 pub fn len(&self) -> usize {
527 self.rules.len()
528 }
529
530 pub fn is_empty(&self) -> bool {
531 self.rules.is_empty()
532 }
533
534 pub fn iter(&self) -> std::slice::Iter<'_, ExitPolicyRule> {
535 self.rules.iter()
536 }
537
538 pub fn can_exit_to(
539 &self,
540 address: Option<&str>,
541 port: Option<u16>,
542 strict: bool,
543 ) -> Result<bool> {
544 if !self.is_exiting_allowed() {
545 return Ok(false);
546 }
547 for rule in &self.rules {
548 if rule.is_match(address, port, strict)? {
549 return Ok(rule.is_accept);
550 }
551 }
552 Ok(self.is_allowed_default)
553 }
554
555 pub fn is_exiting_allowed(&self) -> bool {
556 let mut rejected_ports: HashSet<u16> = HashSet::new();
557 for rule in &self.rules {
558 if rule.is_accept {
559 if (rule.min_port..=rule.max_port)
560 .any(|port| !rejected_ports.contains(&port))
561 {
562 return true;
563 }
564 } else if rule.is_address_wildcard() {
565 if rule.is_port_wildcard() {
566 return false;
567 }
568 rejected_ports.extend(rule.min_port..=rule.max_port);
569 }
570 }
571 self.is_allowed_default
572 }
573
574 pub fn summary(&self) -> String {
575 let mut is_whitelist = !self.is_allowed_default;
576 if let Some(rule) = self
577 .rules
578 .iter()
579 .find(|rule| rule.is_address_wildcard() && rule.is_port_wildcard())
580 {
581 is_whitelist = !rule.is_accept;
582 }
583 let mut display_ports: Vec<u16> = Vec::new();
584 let mut skip_ports: HashSet<u16> = HashSet::new();
585 for rule in &self.rules {
586 if !rule.is_address_wildcard() {
587 continue;
588 }
589 if rule.is_port_wildcard() {
590 break;
591 }
592 for port in rule.min_port..=rule.max_port {
593 if skip_ports.insert(port) && rule.is_accept == is_whitelist {
594 display_ports.push(port);
595 }
596 }
597 }
598 let ranges = match display_ports.is_empty() {
599 true => {
600 is_whitelist = !is_whitelist;
601 vec!["1-65535".to_string()]
602 }
603 false => port_ranges(display_ports),
604 };
605 let prefix = if is_whitelist { "accept " } else { "reject " };
606 format!("{prefix}{}", ranges.join(", ")).trim().to_string()
607 }
608
609 pub fn has_private(&self) -> bool {
610 self.rules.iter().any(ExitPolicyRule::is_private)
611 }
612
613 pub fn strip_private(&self) -> Self {
614 let kept = self
615 .rules
616 .iter()
617 .filter(|rule| !rule.is_private())
618 .cloned()
619 .collect();
620 Self::from_rules(kept, self.is_allowed_default)
621 }
622
623 pub fn has_default(&self) -> bool {
624 self.rules.iter().any(ExitPolicyRule::is_default)
625 }
626
627 pub fn strip_default(&self) -> Self {
628 let kept = self
629 .rules
630 .iter()
631 .filter(|rule| !rule.is_default())
632 .cloned()
633 .collect();
634 Self::from_rules(kept, self.is_allowed_default)
635 }
636}
637
638fn port_ranges(mut ports: Vec<u16>) -> Vec<String> {
639 ports.sort_unstable();
640 let mut ranges = Vec::new();
641 let mut run: Vec<u16> = Vec::new();
642 for port in ports {
643 if run.last().is_none_or(|last| *last + 1 == port) {
644 run.push(port);
645 continue;
646 }
647 ranges.push(format_run(&run));
648 run = vec![port];
649 }
650 if !run.is_empty() {
651 ranges.push(format_run(&run));
652 }
653 ranges
654}
655
656fn format_run(run: &[u16]) -> String {
657 match run {
658 [single] => single.to_string(),
659 [first, .., last] => format!("{first}-{last}"),
660 [] => String::new(),
661 }
662}
663
664impl PartialEq for ExitPolicy {
665 fn eq(&self, other: &Self) -> bool {
666 self.rules == other.rules
667 }
668}
669
670impl Eq for ExitPolicy {}
671
672impl serde::Serialize for ExitPolicy {
673 fn serialize<S: serde::Serializer>(
674 &self,
675 serializer: S,
676 ) -> std::result::Result<S::Ok, S::Error> {
677 serializer.collect_str(self)
678 }
679}
680
681impl fmt::Display for ExitPolicy {
682 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
683 let rules: Vec<String> = self.rules.iter().map(ToString::to_string).collect();
684 formatter.write_str(&rules.join(", "))
685 }
686}
687
688impl<'a> IntoIterator for &'a ExitPolicy {
689 type Item = &'a ExitPolicyRule;
690 type IntoIter = std::slice::Iter<'a, ExitPolicyRule>;
691
692 fn into_iter(self) -> Self::IntoIter {
693 self.rules.iter()
694 }
695}
696
697#[derive(Debug, Clone)]
698pub struct MicroExitPolicy {
699 policy: ExitPolicy,
700 text: String,
701 pub is_accept: bool,
702}
703
704impl MicroExitPolicy {
705 pub fn new(policy: &str) -> Result<Self> {
706 let is_accept = match policy {
707 text if text.starts_with("accept") => true,
708 text if text.starts_with("reject") => false,
709 _ => {
710 return Err(Error::parse(format!(
711 "A microdescriptor exit policy must start with either 'accept' or \
712 'reject': {policy}"
713 )));
714 }
715 };
716 let ports = &policy[6..];
717 if !ports.starts_with(' ') {
718 return Err(Error::parse(format!(
719 "A microdescriptor exit policy should have a space separating \
720 accept/reject from its port list: {policy}"
721 )));
722 }
723 let mut rules = Vec::new();
724 for entry in ports.trim_start().split(',') {
725 let (first, last) = entry.split_once('-').unwrap_or((entry, entry));
726 let (Some(min_port), Some(max_port)) =
727 (parse_port(first, false), parse_port(last, false))
728 else {
729 return Err(Error::parse(format!("'{entry}' is an invalid port range")));
730 };
731 rules.push(ExitPolicyRule::from_ports(is_accept, min_port, max_port));
732 }
733 Ok(Self {
734 policy: ExitPolicy::from_rules(rules, !is_accept),
735 text: policy.to_string(),
736 is_accept,
737 })
738 }
739}
740
741impl Deref for MicroExitPolicy {
742 type Target = ExitPolicy;
743
744 fn deref(&self) -> &ExitPolicy {
745 &self.policy
746 }
747}
748
749impl PartialEq for MicroExitPolicy {
750 fn eq(&self, other: &Self) -> bool {
751 self.text == other.text
752 }
753}
754
755impl Eq for MicroExitPolicy {}
756
757impl serde::Serialize for MicroExitPolicy {
758 fn serialize<S: serde::Serializer>(
759 &self,
760 serializer: S,
761 ) -> std::result::Result<S::Ok, S::Error> {
762 serializer.collect_str(self)
763 }
764}
765
766impl fmt::Display for MicroExitPolicy {
767 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
768 formatter.write_str(&self.text)
769 }
770}
771
772fn local_host_address() -> Option<String> {
773 let hostname = std::fs::read_to_string("/proc/sys/kernel/hostname")
774 .or_else(|_| std::fs::read_to_string("/etc/hostname"))
775 .ok()?;
776 let target = format!("{}:0", hostname.trim());
777 std::net::ToSocketAddrs::to_socket_addrs(&target)
778 .ok()?
779 .find(|address| address.is_ipv4())
780 .map(|address| address.ip().to_string())
781}
782
783pub fn get_config_policy(rules: &str, ip_address: Option<&str>) -> Result<ExitPolicy> {
784 let entries: Vec<&str> = rules.split(',').collect();
785 get_config_policy_from(&entries, ip_address)
786}
787
788pub fn get_config_policy_from<S: AsRef<str>>(
789 rules: &[S],
790 ip_address: Option<&str>,
791) -> Result<ExitPolicy> {
792 let ip_address = match ip_address {
793 Some(address) if is_valid_ipv4_address(address) => Some(address.to_string()),
794 Some(address) if is_valid_ipv6_address(address, true) => {
795 let bare = address.trim_start_matches('[').trim_end_matches(']');
796 Some(format!("[{bare}]"))
797 }
798 Some(address) => {
799 return Err(Error::invalid_input(format!(
800 "{address} isn't a valid IP address"
801 )));
802 }
803 None => None,
804 };
805 let has_port_suffix = |rule: &str| {
806 rule.rsplit_once(':').is_some_and(|(_, suffix)| {
807 !suffix.is_empty()
808 && suffix
809 .bytes()
810 .all(|byte| byte.is_ascii_digit() || byte == b'-' || byte == b'*')
811 })
812 };
813 let mut result = Vec::new();
814 for rule in rules.iter().map(|rule| rule.as_ref().trim()) {
815 if rule.is_empty() {
816 continue;
817 }
818 let rule = match has_port_suffix(rule) {
819 true => rule.to_string(),
820 false => format!("{rule}:*"),
821 };
822 if !rule.contains("private") {
823 result.push(ExitPolicyRule::new(&rule)?);
824 continue;
825 }
826 let acceptance = rule.split(' ').next().unwrap_or_default();
827 let port = rule.rsplit_once(':').map_or("*", |(_, port)| port);
828 let mut addresses: Vec<String> =
829 PRIVATE_ADDRESSES.iter().map(|a| a.to_string()).collect();
830 match &ip_address {
831 Some(address) => addresses.push(address.clone()),
832 None => addresses.extend(local_host_address()),
833 }
834 for private_address in addresses {
835 result.push(ExitPolicyRule::new(&format!(
836 "{acceptance} {private_address}:{port}"
837 ))?);
838 }
839 }
840 Ok(ExitPolicy::from_rules(result, true))
841}