iroh/endpoint/bind.rs
1use std::{
2 convert::Infallible,
3 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
4};
5
6use n0_error::stack_error;
7
8/// Options when configuring binding an IP socket.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct BindOpts {
11 /// Sets the network prefix length of the subnet for this interface.
12 ///
13 /// The prefix length is used in the routing table that is built to decide where
14 /// datagrams without a specific source address are sent. If these number of leading
15 /// bits in the destination IP address match the same number of leading bits in this
16 /// bound socket address, then it matches the subnet and the datagram will be sent
17 /// here. Otherwise the next bound sockets will be checked for a subnet match. Sockets
18 /// are ordered from longest prefix to shortest prefix.
19 ///
20 /// If no bound address has a matching subnet, the bind marked with
21 /// [`Self::is_default_route`] will be used.
22 ///
23 /// Note that most datagrams belonging to a traffic flow are in response to an incoming
24 /// datagram. Those are usually sent on the same bound socket as they were received and
25 /// will not consult the routing table derived from these bound sockets to select the
26 /// socket on which they will be sent.
27 prefix_len: u8,
28 /// If set, binding this interface is required and any errors will abort the
29 /// initialization of the endpoint.
30 ///
31 /// Defaults to `true`.
32 is_required: bool,
33 /// Whether this socket should be used as default route.
34 ///
35 /// The default route is used for outgoing datagrams not belonging to an existing
36 /// traffic flow, which does not fit in any subnet of the bound sockets. It is assumed
37 /// this subnet has a gateway router to route such packets.
38 ///
39 /// See [`Self::prefix_len`] for details of how such routing works.
40 is_default_route: Option<bool>,
41}
42
43impl Default for BindOpts {
44 fn default() -> Self {
45 Self {
46 prefix_len: 0,
47 is_required: true,
48 is_default_route: None,
49 }
50 }
51}
52
53impl BindOpts {
54 /// Sets the network prefix length of the subnet this interface is in.
55 ///
56 ///
57 /// The subnets of bound sockets are used to route outgoing datagrams not belonging to
58 /// an existing traffic flow to the socket they should be sent on. Subnets are ordered
59 /// from longest prefix length to shortest prefix length and the first subnet which
60 /// contains the destination IP address will be chosen. If no subnet matches but there
61 /// is a bound socket marked with [`Self::set_is_default_route`] then this socket will
62 /// be used. In this case it is assumed the attached subnet has a gateway router to
63 /// forward the datagram.
64 ///
65 /// Defaults to `0`, which means *all* IP addresses will belong to the subnet of this
66 /// socket's address. If multiple sockets of the same address family (IPv4 or IPv6) are
67 /// bound with such a `/0` prefix the socket which will be chosen is undefined.
68 ///
69 /// For IPv4 sockets the maximum prefix is `32`. For IPv6 the maximum prefix is `128`.
70 pub fn set_prefix_len(mut self, prefix_len: u8) -> Self {
71 self.prefix_len = prefix_len;
72 self
73 }
74
75 /// Returns the `prefix_len`, see [`Self::set_prefix_len`].
76 pub fn prefix_len(&self) -> u8 {
77 self.prefix_len
78 }
79
80 /// Sets whether bind errors are fatal for this socket.
81 ///
82 /// If `false` and this socket fails to bind, the error will be silently ignored and the
83 /// endpoint will still be created.
84 ///
85 /// Defaults to `true`.
86 pub fn set_is_required(mut self, is_required: bool) -> Self {
87 self.is_required = is_required;
88 self
89 }
90
91 /// Returns the value set by [`Self::set_is_required`].
92 pub fn is_required(&self) -> bool {
93 self.is_required
94 }
95
96 /// Sets whether this is a default route.
97 ///
98 /// The default route is used for outgoing datagrams not belonging to an existing
99 /// traffic flow, which does not fit in any subnet of the bound sockets. It is assumed
100 /// this subnet has a gateway router to route such packets.
101 ///
102 /// See [`Self::set_prefix_len`] for details on how this routing works.
103 ///
104 /// If not set explicitly, then [`Self::is_default_route`] will return `true`
105 /// if the prefix length is set to `0` (the default) and `false` otherwise.
106 pub fn set_is_default_route(mut self, is_default_route: bool) -> Self {
107 self.is_default_route = Some(is_default_route);
108 self
109 }
110
111 /// Returns whether this is a default route.
112 ///
113 /// If [`Self::set_is_default_route`] has been called then that value is returned.
114 /// Otherwise, returns `true` if the [`prefix_len`][`Self::prefix_len`] is `0` and
115 /// `false` otherwise.
116 pub fn is_default_route(&self) -> bool {
117 match self.is_default_route {
118 Some(is_default) => is_default,
119 None => self.prefix_len() == 0,
120 }
121 }
122}
123
124/// A simpler version of [`ToSocketAddrs`], that does not do any DNS resolution.
125///
126/// [`ToSocketAddrs`]: std::net::ToSocketAddrs
127pub trait ToSocketAddr {
128 /// Error type on failed conversion.
129 type Err: std::error::Error;
130
131 /// Tries to convert this type to a [`SocketAddr`].
132 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err>;
133}
134
135impl ToSocketAddr for SocketAddr {
136 type Err = Infallible;
137
138 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
139 Ok(*self)
140 }
141}
142
143impl ToSocketAddr for SocketAddrV4 {
144 type Err = Infallible;
145
146 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
147 Ok(SocketAddr::V4(*self))
148 }
149}
150
151impl ToSocketAddr for SocketAddrV6 {
152 type Err = Infallible;
153
154 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
155 Ok(SocketAddr::V6(*self))
156 }
157}
158
159impl ToSocketAddr for (IpAddr, u16) {
160 type Err = Infallible;
161
162 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
163 let (ip, port) = *self;
164 match ip {
165 IpAddr::V4(ref a) => (*a, port).to_socket_addr(),
166 IpAddr::V6(ref a) => (*a, port).to_socket_addr(),
167 }
168 }
169}
170
171impl ToSocketAddr for (Ipv4Addr, u16) {
172 type Err = Infallible;
173
174 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
175 let (ip, port) = *self;
176 SocketAddrV4::new(ip, port).to_socket_addr()
177 }
178}
179
180impl ToSocketAddr for (Ipv6Addr, u16) {
181 type Err = Infallible;
182
183 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
184 let (ip, port) = *self;
185 SocketAddrV6::new(ip, port, 0, 0).to_socket_addr()
186 }
187}
188
189impl ToSocketAddr for (&str, u16) {
190 type Err = std::net::AddrParseError;
191
192 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
193 let (host, port) = *self;
194
195 let addr = host.parse::<IpAddr>()?;
196 let addr = SocketAddr::new(addr, port);
197 Ok(addr)
198 }
199}
200
201impl ToSocketAddr for (String, u16) {
202 type Err = std::net::AddrParseError;
203
204 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
205 (&*self.0, self.1).to_socket_addr()
206 }
207}
208
209impl ToSocketAddr for str {
210 type Err = std::net::AddrParseError;
211
212 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
213 let addr = self.parse()?;
214 Ok(addr)
215 }
216}
217
218impl<T: ToSocketAddr + ?Sized> ToSocketAddr for &T {
219 type Err = T::Err;
220
221 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
222 (**self).to_socket_addr()
223 }
224}
225
226impl ToSocketAddr for String {
227 type Err = std::net::AddrParseError;
228
229 fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
230 (**self).to_socket_addr()
231 }
232}
233
234#[allow(missing_docs)]
235#[stack_error(derive, add_meta, from_sources)]
236#[non_exhaustive]
237pub enum InvalidSocketAddr {
238 #[error(transparent)]
239 AddrParse {
240 #[error(std_err)]
241 source: std::net::AddrParseError,
242 },
243 #[error("Invalid IP prefix length")]
244 InvalidPrefixLength {},
245 #[error(transparent)]
246 Infallible {
247 #[error(std_err)]
248 source: Infallible,
249 },
250 #[error("Only a single default address can be set per IP family")]
251 DuplicateDefaultAddr,
252}