Skip to main content

tor_config/
listen.rs

1//! Configuration for ports and addresses to listen on.
2
3use 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/// Specification of (possibly) something to listen on (eg, a port, or some addresses/ports)
11///
12/// Can represent, at least:
13///  * "do not listen"
14///  * Listen on the following port on localhost (IPv6 and IPv4)
15///  * Listen on precisely the following address and port
16///  * Listen on several addresses/ports
17///
18/// Currently only IP (v6 and v4) is supported.
19//
20// NOTE: If you're adding or changing functionality for this type,
21// make sure that all existing users of this type (for example all config options in arti and
22// arti-relay which use this) want that functionality.
23#[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    /// Create a new `Listen` specifying no addresses (no listening)
29    pub fn new_none() -> Listen {
30        CustomizableListen::Disabled
31            .try_into()
32            .expect("'disabled' should be valid")
33    }
34
35    /// Create a new `Listen` specifying listening on a port on localhost
36    ///
37    /// Special case: if `port` is zero, specifies no listening.
38    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    /// Create a new `Listen`, possibly specifying listening on a port on localhost
45    ///
46    /// Special case: if `port` is `Some(0)`, also specifies no listening.
47    pub fn new_localhost_optional(port: Option<u16>) -> Listen {
48        Self::new_localhost(port.unwrap_or_default())
49    }
50
51    /// Create a new `Listen` specifying an arbitrarily chosen IPv4 or IPv6 port.
52    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    /// Return true if no listening addresses have been configured
59    pub fn is_empty(&self) -> bool {
60        self.ip_addrs_internal().count() == 0
61    }
62
63    /// Return true if there are any "auto" addresses in this Listen.
64    ///
65    /// See also [`using_port_zero()`](Self::using_port_zero).
66    pub fn using_auto(&self) -> bool {
67        self.0.items().any(ListenItem::is_auto)
68    }
69
70    /// Return true if there are any port-zero addresses in this Listen.
71    ///
72    /// See also [`using_auto()`](Self::using_auto).
73    pub fn using_port_zero(&self) -> bool {
74        self.0.items().any(ListenItem::is_port_zero)
75    }
76
77    /// List the network socket addresses to listen on
78    ///
79    /// Each returned item is a list of `SocketAddr`,
80    /// of which *at least one* must be successfully bound.
81    /// It is OK if the others (up to all but one of them)
82    /// fail with `EAFNOSUPPORT` ("Address family not supported").
83    /// This allows handling of support, or non-support,
84    /// for particular address families, eg IPv6 vs IPv4 localhost.
85    /// Other errors (eg, `EADDRINUSE`) should always be treated as serious problems.
86    ///
87    /// Fails if the listen spec involves listening on things other than IP addresses.
88    /// (Currently that is not possible.)
89    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    /// List the network socket addresses to listen on.
97    ///
98    /// See [`Self::ip_addrs`], which wraps this result in an `Ok`.
99    fn ip_addrs_internal(
100        &self,
101    ) -> impl Iterator<Item = impl Iterator<Item = SocketAddr> + '_> + '_ {
102        // We interpret standalone ports to be localhost addresses.
103        let ips = [Ipv6Addr::LOCALHOST.into(), Ipv4Addr::LOCALHOST.into()];
104        self.0.items().map(move |item| item.iter(ips))
105    }
106
107    /// Get the localhost port to listen on
108    ///
109    /// Returns `None` if listening is configured to be disabled.
110    ///
111    /// Fails, giving an unsupported error, if the configuration
112    /// isn't just "listen on a single localhost port in all address families"
113    #[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    /// Get a single address to listen on
125    ///
126    /// Returns `None` if listening is configured to be disabled.
127    ///
128    /// If the configuration is "listen on a single port",
129    /// treats this as a request to listening on IPv4 only.
130    /// Use of this function implies a bug:
131    /// lack of proper support for the current internet protocol IPv6.
132    /// It should only be used if an underlying library or facility is likewise buggy.
133    ///
134    /// Fails, giving an unsupported error, if the configuration
135    /// isn't just "listen on a single port on one address family".
136    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    /// Helper: return a ListenItem if this Listen has exactly one.
147    ///
148    /// Return None if there are multiple items, or an error if there are multiple items.
149    ///
150    /// (Note that all users of this function are, or should be, deprecated.)
151    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    /// Return true if this `Listen` only configures listening on loopback addresses (`127.0.0.0/8`
165    /// and `::1`).
166    ///
167    /// Returns true if there are no addresses configured.
168    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.
175    /// Use [`Self::is_loopback_only`] instead,
176    /// which behaves the same but has the correct method name.
177    #[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                // A non-list standalone 0 means "none".
215                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                // We don't support a standalone 0 port in a list item.
228                if list.iter().any(|item| matches!(item, ListenItem::Port(0))) {
229                    return Err(InvalidListen::ZeroPortInList);
230                }
231                // We warn on e.g. "127.0.0.1:0"
232                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/// [`Listen`] configuration specified something not supported by application code
251#[derive(thiserror::Error, Debug, Clone)]
252#[non_exhaustive]
253#[error("Unsupported listening configuration")]
254pub struct ListenUnsupported {}
255
256/// Listen configuration is invalid
257#[derive(thiserror::Error, Debug, Clone)]
258#[non_exhaustive]
259enum InvalidListen {
260    /// Specified listen was a list containing a zero integer
261    #[error("Invalid listen specification: zero (for no port) not permitted in list")]
262    ZeroPortInList,
263}
264
265/// A general structure for configuring listening ports.
266///
267/// This is meant to provide some basic parsing without being too opinionated.
268/// If you have further requirements, you should wrap this in a new type.
269/// For example if `CustomizableListen` supports keywords or flags in the future such as "auto",
270/// any config options that don't want to support them should use a wrapper type that handles them
271/// and returns an error.
272#[derive(Clone, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)]
273#[serde(try_from = "ListenSerde", into = "ListenSerde")]
274enum CustomizableListen {
275    /// Explicitly disabled with `false`.
276    Disabled,
277    /// A single item not in a list.
278    One(ListenItem),
279    /// A list of items.
280    List(Vec<ListenItem>),
281}
282
283impl CustomizableListen {
284    /// All configured listen options.
285    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/// One item in the [`CustomizableListen`].
295///
296/// This type defines a common format for parsing.
297/// We don't assign any particular meaning to the variants.
298/// For example a standalone port doesn't imply anything about what IP address should be used.
299/// Similarly, a port of 0 doesn't have any inherent meaning.
300/// For example a port of 0 might mean "don't listen" (when network addresses are optional)
301/// or might mean "raise an error" (when network addresses are required).
302/// It's up to the user of this type to assign meaning to the values given.
303///
304/// We distinguish a standalone port,
305/// rather than just storing two `net:SocketAddr`,
306/// so that we can handle localhost (which means two address families) specially
307/// in order to implement `localhost_port_legacy()`.
308#[derive(Clone, Hash, Debug, Ord, PartialOrd, Eq, PartialEq)]
309// If we add new variants, it *is* a breaking change.
310// We want a compile-time error, not a runtime error.
311#[allow(clippy::exhaustive_enums)]
312enum ListenItem {
313    /// One port, both IPv6 and IPv4
314    Port(u16),
315
316    /// IPv6 and/or IPv4, arbitrarily chosen ports.
317    Auto,
318
319    /// Specific address, arbitrarily chosen port.
320    AutoPort(IpAddr),
321
322    /// Any other single socket address
323    General(SocketAddr),
324}
325
326impl ListenItem {
327    /// Return the `SocketAddr`s implied by this item
328    ///
329    /// If the item is a standalone port, then the returned iterator will return a socket address
330    /// using that port for each IP address in `ips_for_port`.
331    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    /// Return true if this ListenItem is "addr:auto" or "auto"
353    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    /// Return true if this ListenItem is using an explicit (deprecated) port value of 0.
364    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/// How we (de) serialize a [`Listen`]
388#[derive(Serialize, Deserialize)]
389#[serde(untagged)]
390// the default error message from serde's "untagged" is useless for users, so we provide our own
391#[serde(expecting = "value was not a bool, `u16` integer, string, or list of integers/strings")]
392enum ListenSerde {
393    /// for `listen = false` (in TOML syntax)
394    Bool(bool),
395
396    /// A bare item
397    One(ListenItemSerde),
398
399    /// An item in a list
400    List(Vec<ListenItemSerde>),
401}
402
403/// One item in the list of a list-ish `Listen`, or the plain value
404#[derive(Serialize, Deserialize)]
405#[serde(untagged)]
406// the default error message from serde's "untagged" is useless for users, so we provide our own
407#[serde(expecting = "item was not a `u16` integer or string")]
408enum ListenItemSerde {
409    /// An integer.
410    Port(u16),
411
412    /// A string.
413    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/// Listen configuration is invalid
442#[derive(thiserror::Error, Debug, Clone)]
443#[non_exhaustive]
444enum InvalidCustomizableListen {
445    /// Bool was `true` but that's not an address.
446    #[error("Invalid listen specification: need actual addr/port, or `false`; not `true`")]
447    InvalidBool,
448
449    /// Specified listen was a string but couldn't parse to a [`SocketAddr`].
450    #[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            // A false value not in a list is interpreted as "none".
460            LS::Bool(false) => CustomizableListen::Disabled,
461            LS::Bool(true) => return Err(InvalidCustomizableListen::InvalidBool),
462            // An empty string not in a list is interpreted as "none".
463            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    // @@ begin test lint list maintained by maint/add_warning @@
496    #![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)] // See arti#2571
508    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
509    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)] // we do this for consistency
526        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                "", /* any error will do */
558                &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}