1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
4use std::{fmt::Display, iter};
5
6use either::Either;
7use itertools::Itertools as _;
8use serde::{Deserialize, Serialize};
9
10#[derive(Clone, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)]
24#[serde(try_from = "CustomizableListen", into = "CustomizableListen")]
25pub struct Listen(CustomizableListen);
26
27impl Listen {
28 pub fn new_none() -> Listen {
30 CustomizableListen::Disabled
31 .try_into()
32 .expect("'disabled' should be valid")
33 }
34
35 pub fn new_localhost(port: u16) -> Listen {
39 CustomizableListen::One(ListenItem::Port(port))
40 .try_into()
41 .expect("a standalone port (including 0) should be valid")
42 }
43
44 pub fn new_localhost_optional(port: Option<u16>) -> Listen {
48 Self::new_localhost(port.unwrap_or_default())
49 }
50
51 pub fn new_auto() -> Listen {
53 CustomizableListen::One(ListenItem::Auto)
54 .try_into()
55 .expect("An auto port should always be valid")
56 }
57
58 pub fn is_empty(&self) -> bool {
60 self.ip_addrs_internal().count() == 0
61 }
62
63 pub fn using_auto(&self) -> bool {
67 self.0.items().any(ListenItem::is_auto)
68 }
69
70 pub fn using_port_zero(&self) -> bool {
74 self.0.items().any(ListenItem::is_port_zero)
75 }
76
77 pub fn ip_addrs(
90 &self,
91 ) -> Result<impl Iterator<Item = impl Iterator<Item = SocketAddr> + '_> + '_, ListenUnsupported>
92 {
93 Ok(self.ip_addrs_internal())
94 }
95
96 fn ip_addrs_internal(
100 &self,
101 ) -> impl Iterator<Item = impl Iterator<Item = SocketAddr> + '_> + '_ {
102 let ips = [Ipv6Addr::LOCALHOST.into(), Ipv4Addr::LOCALHOST.into()];
104 self.0.items().map(move |item| item.iter(ips))
105 }
106
107 #[deprecated(since = "0.38.0")]
114 pub fn localhost_port_legacy(&self) -> Result<Option<u16>, ListenUnsupported> {
115 Ok(match self.to_singleton_legacy()? {
116 None => None,
117 Some(ListenItem::Port(port)) => Some(*port),
118 Some(ListenItem::Auto) => return Err(ListenUnsupported {}),
119 Some(ListenItem::AutoPort(_)) => return Err(ListenUnsupported {}),
120 Some(ListenItem::General(_)) => return Err(ListenUnsupported {}),
121 })
122 }
123
124 pub fn single_address_legacy(&self) -> Result<Option<SocketAddr>, ListenUnsupported> {
137 Ok(match self.to_singleton_legacy()? {
138 None => None,
139 Some(ListenItem::Port(port)) => Some((Ipv4Addr::LOCALHOST, *port).into()),
140 Some(ListenItem::Auto) => Some((Ipv4Addr::LOCALHOST, 0).into()),
141 Some(ListenItem::AutoPort(addr)) => Some((*addr, 0).into()),
142 Some(ListenItem::General(addr)) => Some(*addr),
143 })
144 }
145
146 fn to_singleton_legacy(&self) -> Result<Option<&ListenItem>, ListenUnsupported> {
152 use CustomizableListen as CL;
153 match &self.0 {
154 CL::Disabled => Ok(None),
155 CL::One(li) => Ok(Some(li)),
156 CL::List(lst) => match lst.as_slice() {
157 [] => Ok(None),
158 [li] => Ok(Some(li)),
159 [_, _, ..] => Err(ListenUnsupported {}),
160 },
161 }
162 }
163
164 pub fn is_loopback_only(&self) -> bool {
169 self.ip_addrs_internal()
170 .flatten()
171 .all(|a| a.ip().is_loopback())
172 }
173
174 #[deprecated(since = "0.37.0", note = "please use `is_loopback_only` instead")]
178 pub fn is_localhost_only(&self) -> bool {
179 self.is_loopback_only()
180 }
181}
182
183impl Default for Listen {
184 fn default() -> Self {
185 Self::new_none()
186 }
187}
188
189impl Display for Listen {
190 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
191 let mut sep = "";
192 for item in self.0.items() {
193 match item {
194 ListenItem::Port(_) => {
195 write!(f, "{sep}localhost {item}")?;
196 sep = ", ";
197 }
198 _other => {
199 write!(f, "{sep}{item}")?;
200 sep = ", ";
201 }
202 }
203 }
204 Ok(())
205 }
206}
207
208impl TryFrom<CustomizableListen> for Listen {
209 type Error = InvalidListen;
210
211 fn try_from(l: CustomizableListen) -> Result<Self, Self::Error> {
212 match &l {
213 CustomizableListen::Disabled | CustomizableListen::One(ListenItem::Port(0)) => {
214 Ok(Self(CustomizableListen::Disabled))
216 }
217 CustomizableListen::One(li) => {
218 if li.is_port_zero() {
219 tracing::warn!(
220 "Configured to listen on port zero via {li}. \
221 This is deprecated. Instead, replace '0' with 'auto'."
222 );
223 }
224 Ok(Self(l))
225 }
226 CustomizableListen::List(list) => {
227 if list.iter().any(|item| matches!(item, ListenItem::Port(0))) {
229 return Err(InvalidListen::ZeroPortInList);
230 }
231 if let Some(zero_li) = list.iter().find(|li| li.is_port_zero()) {
233 tracing::warn!(
234 "Configured to listen on port zero via {zero_li}. \
235 This is deprecated. Instead, replace '0' with 'auto'."
236 );
237 }
238 Ok(Self(l))
239 }
240 }
241 }
242}
243
244impl From<Listen> for CustomizableListen {
245 fn from(l: Listen) -> Self {
246 l.0
247 }
248}
249
250#[derive(thiserror::Error, Debug, Clone)]
252#[non_exhaustive]
253#[error("Unsupported listening configuration")]
254pub struct ListenUnsupported {}
255
256#[derive(thiserror::Error, Debug, Clone)]
258#[non_exhaustive]
259enum InvalidListen {
260 #[error("Invalid listen specification: zero (for no port) not permitted in list")]
262 ZeroPortInList,
263}
264
265#[derive(Clone, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)]
273#[serde(try_from = "ListenSerde", into = "ListenSerde")]
274enum CustomizableListen {
275 Disabled,
277 One(ListenItem),
279 List(Vec<ListenItem>),
281}
282
283impl CustomizableListen {
284 fn items(&self) -> impl Iterator<Item = &ListenItem> {
286 match self {
287 Self::Disabled => Either::Right(std::slice::Iter::default()),
288 Self::One(one) => Either::Left(iter::once(one)),
289 Self::List(many) => Either::Right(many.iter()),
290 }
291 }
292}
293
294#[derive(Clone, Hash, Debug, Ord, PartialOrd, Eq, PartialEq)]
309#[allow(clippy::exhaustive_enums)]
312enum ListenItem {
313 Port(u16),
315
316 Auto,
318
319 AutoPort(IpAddr),
321
322 General(SocketAddr),
324}
325
326impl ListenItem {
327 fn iter<'a>(
332 &'a self,
333 ips_for_port: impl IntoIterator<Item = IpAddr> + 'a,
334 ) -> impl Iterator<Item = SocketAddr> + 'a {
335 use ListenItem as LI;
336 let with_ips = |portnum| {
337 Either::Left({
338 ips_for_port
339 .into_iter()
340 .map(move |ip| SocketAddr::new(ip, portnum))
341 })
342 };
343
344 match self {
345 &LI::Port(port) => with_ips(port),
346 LI::Auto => with_ips(0),
347 LI::AutoPort(addr) => Either::Right(iter::once((*addr, 0).into())),
348 LI::General(addr) => Either::Right(iter::once(*addr)),
349 }
350 }
351
352 fn is_auto(&self) -> bool {
354 use ListenItem as LI;
355 match self {
356 LI::Port(_) => false,
357 LI::Auto => true,
358 LI::AutoPort(_) => true,
359 LI::General(_) => false,
360 }
361 }
362
363 fn is_port_zero(&self) -> bool {
365 use ListenItem as LI;
366
367 match self {
368 LI::Port(port) => *port == 0,
369 LI::Auto => false,
370 LI::AutoPort(_) => false,
371 LI::General(addr) => addr.port() == 0,
372 }
373 }
374}
375
376impl Display for ListenItem {
377 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
378 match self {
379 ListenItem::Port(port) => write!(f, "port {}", port)?,
380 ListenItem::Auto => write!(f, "auto")?,
381 ListenItem::AutoPort(addr) => write!(f, "{addr}:auto")?,
382 ListenItem::General(addr) => write!(f, "{}", addr)?,
383 }
384 Ok(())
385 }
386}
387#[derive(Serialize, Deserialize)]
389#[serde(untagged)]
390#[serde(expecting = "value was not a bool, `u16` integer, string, or list of integers/strings")]
392enum ListenSerde {
393 Bool(bool),
395
396 One(ListenItemSerde),
398
399 List(Vec<ListenItemSerde>),
401}
402
403#[derive(Serialize, Deserialize)]
405#[serde(untagged)]
406#[serde(expecting = "item was not a `u16` integer or string")]
408enum ListenItemSerde {
409 Port(u16),
411
412 String(String),
414}
415
416impl From<CustomizableListen> for ListenSerde {
417 fn from(l: CustomizableListen) -> Self {
418 match l {
419 CustomizableListen::Disabled => ListenSerde::Bool(false),
420 CustomizableListen::One(item) => ListenSerde::One(item.into()),
421 CustomizableListen::List(list) => match list.as_slice() {
422 [] => ListenSerde::List(Vec::new()),
423 [one] => ListenSerde::List(vec![one.clone().into()]),
424 list => ListenSerde::List(list.iter().cloned().map(Into::into).collect()),
425 },
426 }
427 }
428}
429impl From<ListenItem> for ListenItemSerde {
430 fn from(i: ListenItem) -> Self {
431 use ListenItem as LI;
432 match i {
433 LI::Port(port) => Self::Port(port),
434 LI::Auto => Self::String("auto".to_string()),
435 LI::AutoPort(addr) => Self::String(format!("{addr}:auto")),
436 LI::General(addr) => Self::String(addr.to_string()),
437 }
438 }
439}
440
441#[derive(thiserror::Error, Debug, Clone)]
443#[non_exhaustive]
444enum InvalidCustomizableListen {
445 #[error("Invalid listen specification: need actual addr/port, or `false`; not `true`")]
447 InvalidBool,
448
449 #[error("Invalid listen specification: failed to parse string: {0}")]
451 InvalidString(#[from] std::net::AddrParseError),
452}
453impl TryFrom<ListenSerde> for CustomizableListen {
454 type Error = InvalidCustomizableListen;
455
456 fn try_from(l: ListenSerde) -> Result<CustomizableListen, Self::Error> {
457 use ListenSerde as LS;
458 Ok(match l {
459 LS::Bool(false) => CustomizableListen::Disabled,
461 LS::Bool(true) => return Err(InvalidCustomizableListen::InvalidBool),
462 LS::One(ListenItemSerde::String(s)) if s.is_empty() => CustomizableListen::List(vec![]),
464 LS::One(i) => CustomizableListen::One(i.try_into()?),
465 LS::List(l) => {
466 CustomizableListen::List(l.into_iter().map(|i| i.try_into()).try_collect()?)
467 }
468 })
469 }
470}
471impl ListenItemSerde {}
472impl TryFrom<ListenItemSerde> for ListenItem {
473 type Error = InvalidCustomizableListen;
474
475 fn try_from(i: ListenItemSerde) -> Result<ListenItem, Self::Error> {
476 use ListenItem as LI;
477 use ListenItemSerde as LIS;
478 Ok(match i {
479 LIS::String(a) => {
480 if a == "auto" {
481 LI::Auto
482 } else if let Some(ip_addr) = a.strip_suffix(":auto") {
483 LI::AutoPort(ip_addr.parse()?)
484 } else {
485 LI::General(a.parse()?)
486 }
487 }
488 LIS::Port(p) => LI::Port(p),
489 })
490 }
491}
492
493#[cfg(test)]
494mod test {
495 #![allow(clippy::bool_assert_comparison)]
497 #![allow(clippy::clone_on_copy)]
498 #![allow(clippy::dbg_macro)]
499 #![allow(clippy::mixed_attributes_style)]
500 #![allow(clippy::print_stderr)]
501 #![allow(clippy::print_stdout)]
502 #![allow(clippy::single_char_pattern)]
503 #![allow(clippy::unwrap_used)]
504 #![allow(clippy::unchecked_time_subtraction)]
505 #![allow(clippy::useless_vec)]
506 #![allow(clippy::needless_pass_by_value)]
507 #![allow(clippy::string_slice)] use super::*;
510
511 #[derive(Debug, Default, Deserialize, Serialize)]
512 struct TestConfigFile {
513 #[serde(default)]
514 listen: Option<Listen>,
515 }
516
517 #[test]
518 fn listen_parse() {
519 use ListenItem as LI;
520
521 let localhost6 = |p| SocketAddr::new(Ipv6Addr::LOCALHOST.into(), p);
522 let localhost4 = |p| SocketAddr::new(Ipv4Addr::LOCALHOST.into(), p);
523 let unspec6 = |p| SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), p);
524
525 #[allow(clippy::needless_pass_by_value)] fn chk(
527 exp_i: Vec<ListenItem>,
528 exp_addrs: Result<Vec<Vec<SocketAddr>>, ()>,
529 exp_lpd: Result<Option<u16>, ()>,
530 s: &str,
531 ) {
532 let tc: TestConfigFile = toml::from_str(s).expect(s);
533 let ll = tc.listen.unwrap();
534 eprintln!("s={:?} ll={:?}", s, ll);
535 assert_eq!(ll.0.items().cloned().collect::<Vec<_>>(), exp_i);
536 assert_eq!(
537 ll.ip_addrs()
538 .map(|a| a.map(|l| l.collect_vec()).collect_vec())
539 .map_err(|_| ()),
540 exp_addrs
541 );
542 #[allow(deprecated)]
543 {
544 assert_eq!(ll.localhost_port_legacy().map_err(|_| ()), exp_lpd);
545 }
546 }
547
548 let chk_err = |exp, s: &str| {
549 let got: Result<TestConfigFile, _> = toml::from_str(s);
550 let got = got.expect_err(s).to_string();
551 assert!(got.contains(exp), "s={:?} got={:?} exp={:?}", s, got, exp);
552 };
553
554 let chk_none = |s: &str| {
555 chk(vec![], Ok(vec![]), Ok(None), &format!("listen = {}", s));
556 chk_err(
557 "", &format!("listen = [ {} ]", s),
559 );
560 };
561
562 let chk_1 = |v: ListenItem, addrs: Vec<Vec<SocketAddr>>, port, s| {
563 chk(
564 vec![v.clone()],
565 Ok(addrs.clone()),
566 port,
567 &format!("listen = {}", s),
568 );
569 chk(
570 vec![v.clone()],
571 Ok(addrs.clone()),
572 port,
573 &format!("listen = [ {} ]", s),
574 );
575 chk(
576 vec![v, LI::Port(23.try_into().unwrap())],
577 Ok([addrs, vec![vec![localhost6(23), localhost4(23)]]]
578 .into_iter()
579 .flatten()
580 .collect()),
581 Err(()),
582 &format!("listen = [ {}, 23 ]", s),
583 );
584 };
585
586 chk_none(r#""""#);
587 chk_none(r#"0"#);
588 chk_none(r#"false"#);
589 chk(vec![], Ok(vec![]), Ok(None), r#"listen = []"#);
590
591 chk_1(
592 LI::Port(42.try_into().unwrap()),
593 vec![vec![localhost6(42), localhost4(42)]],
594 Ok(Some(42)),
595 "42",
596 );
597 chk_1(
598 LI::General(unspec6(56)),
599 vec![vec![unspec6(56)]],
600 Err(()),
601 r#""[::]:56""#,
602 );
603
604 let chk_err_1 = |e, el, s| {
605 chk_err(e, &format!("listen = {}", s));
606 chk_err(el, &format!("listen = [ {} ]", s));
607 chk_err(el, &format!("listen = [ 23, {}, 77 ]", s));
608 };
609
610 chk_err_1(
611 "need actual addr/port",
612 "value was not a bool, `u16` integer, string, or list of integers/strings",
613 "true",
614 );
615 chk_err(
616 "value was not a bool, `u16` integer, string, or list of integers/strings",
617 r#"listen = [ [] ]"#,
618 );
619
620 chk_1(
621 LI::Auto,
622 vec![vec![localhost6(0), localhost4(0)]],
623 Err(()),
624 r#" "auto" "#,
625 );
626
627 chk_1(
628 LI::AutoPort("1.2.3.4".parse().unwrap()),
629 vec![vec!["1.2.3.4:0".parse().unwrap()]],
630 Err(()),
631 r#" "1.2.3.4:auto" "#,
632 );
633 }
634
635 #[test]
636 fn more_parsing_checks() {
637 let config: TestConfigFile = toml::from_str(r#"listen = false"#).unwrap();
638 assert!(config.listen.unwrap().is_empty());
639
640 let config: TestConfigFile = toml::from_str(r#"listen = 0"#).unwrap();
641 assert!(config.listen.unwrap().is_empty());
642
643 let config: TestConfigFile = toml::from_str(r#"listen = 1"#).unwrap();
644 #[rustfmt::skip]
645 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 2);
646
647 let config: TestConfigFile = toml::from_str(r#"listen = """#).unwrap();
648 assert!(config.listen.unwrap().is_empty());
649
650 let config: TestConfigFile = toml::from_str(r#"listen = "127.0.0.1:8080""#).unwrap();
651 #[rustfmt::skip]
652 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 1);
653
654 let config: TestConfigFile = toml::from_str(r#"listen = ["127.0.0.1:8080"]"#).unwrap();
655 #[rustfmt::skip]
656 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 1);
657
658 let config: TestConfigFile = toml::from_str(r#"listen = "127.0.0.1:0""#).unwrap();
659 #[rustfmt::skip]
660 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 1);
661
662 let config: TestConfigFile = toml::from_str(r#"listen = ["127.0.0.1:0"]"#).unwrap();
663 #[rustfmt::skip]
664 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 1);
665
666 let config: TestConfigFile = toml::from_str(r#"listen = [1]"#).unwrap();
667 #[rustfmt::skip]
668 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 2);
669
670 let config: TestConfigFile = toml::from_str(r#"listen = [1, 2]"#).unwrap();
671 #[rustfmt::skip]
672 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 4);
673
674 let config: TestConfigFile = toml::from_str(r#"listen = ["127.0.0.1:8080", 2]"#).unwrap();
675 #[rustfmt::skip]
676 assert_eq!(config.listen.unwrap().ip_addrs().unwrap().flatten().count(), 3);
677
678 assert!(toml::from_str::<TestConfigFile>(r#"listen = [false]"#).is_err());
679 assert!(toml::from_str::<TestConfigFile>(r#"listen = true"#).is_err());
680 assert!(toml::from_str::<TestConfigFile>(r#"listen = [true]"#).is_err());
681 assert!(toml::from_str::<TestConfigFile>(r#"listen = [0]"#).is_err());
682 assert!(toml::from_str::<TestConfigFile>(r#"listen = ["127.0.0.1:8080", 0]"#).is_err());
683 assert!(toml::from_str::<TestConfigFile>(r#"listen = ["foo"]"#).is_err());
684 assert!(toml::from_str::<TestConfigFile>(r#"listen = ["127.0.0.1:8080", "foo"]"#).is_err());
685 assert!(toml::from_str::<TestConfigFile>(r#"listen = [""]"#).is_err());
686 assert!(toml::from_str::<TestConfigFile>(r#"listen = ["127.0.0.1:8080", ""]"#).is_err());
687 }
688
689 #[test]
690 fn constructor() {
691 let l = Listen::new_none();
692 assert!(l.is_empty());
693 assert_eq!(l.ip_addrs().unwrap().flatten().count(), 0);
694
695 let l = Listen::new_localhost(1234);
696 assert!(!l.is_empty());
697 assert_eq!(l.ip_addrs().unwrap().flatten().count(), 2);
698
699 let l = Listen::new_localhost(0);
700 assert!(l.is_empty());
701 assert_eq!(l.ip_addrs().unwrap().flatten().count(), 0);
702
703 let l = Listen::new_localhost_optional(Some(1234));
704 assert!(!l.is_empty());
705 assert_eq!(l.ip_addrs().unwrap().flatten().count(), 2);
706
707 let l = Listen::new_localhost_optional(Some(0));
708 assert!(l.is_empty());
709 assert_eq!(l.ip_addrs().unwrap().flatten().count(), 0);
710
711 let l = Listen::new_localhost_optional(None);
712 assert!(l.is_empty());
713 assert_eq!(l.ip_addrs().unwrap().flatten().count(), 0);
714 }
715
716 #[test]
717 fn display_listen() {
718 let empty = Listen::new_none();
719 assert_eq!(empty.to_string(), "");
720
721 let one_port = Listen::new_localhost(1234);
722 assert_eq!(one_port.to_string(), "localhost port 1234");
723
724 let multi_port = Listen(CustomizableListen::List(vec![
725 ListenItem::Port(1111.try_into().unwrap()),
726 ListenItem::Port(2222.try_into().unwrap()),
727 ]));
728 assert_eq!(
729 multi_port.to_string(),
730 "localhost port 1111, localhost port 2222"
731 );
732
733 let multi_addr = Listen(CustomizableListen::List(vec![
734 ListenItem::Port(1234.try_into().unwrap()),
735 ListenItem::General("1.2.3.4:5678".parse().unwrap()),
736 ]));
737 assert_eq!(multi_addr.to_string(), "localhost port 1234, 1.2.3.4:5678");
738
739 let multi_addr = Listen(CustomizableListen::List(vec![
740 ListenItem::Auto,
741 ListenItem::AutoPort("1.2.3.4".parse().unwrap()),
742 ]));
743 assert_eq!(multi_addr.to_string(), "auto, 1.2.3.4:auto");
744 }
745
746 #[test]
747 fn is_localhost() {
748 fn localhost_only(s: &str) -> bool {
749 let tc: TestConfigFile = toml::from_str(s).expect(s);
750 tc.listen.unwrap().is_loopback_only()
751 }
752
753 assert_eq!(localhost_only(r#"listen = [ ]"#), true);
754 assert_eq!(localhost_only(r#"listen = [ 3 ]"#), true);
755 assert_eq!(localhost_only(r#"listen = [ 3, 10 ]"#), true);
756 assert_eq!(localhost_only(r#"listen = [ "127.0.0.1:9050" ]"#), true);
757 assert_eq!(localhost_only(r#"listen = [ "[::1]:9050" ]"#), true);
758 assert_eq!(
759 localhost_only(r#"listen = [ "[::1]:9050", "192.168.0.1:1234" ]"#),
760 false
761 );
762 assert_eq!(localhost_only(r#"listen = [ "192.168.0.1:1234" ]"#), false);
763 }
764}