1use std::io;
15use std::net::IpAddr;
16use std::net::Ipv4Addr;
17use std::net::Ipv6Addr;
18use std::net::SocketAddr;
19
20use tokio::net::TcpListener;
21use tokio::net::TcpStream;
22use tokio::net::UdpSocket;
23
24use crate::gate::GateToken;
25use crate::gate::LocalBoxFuture;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct UdpOpts {
31 pub ipv6_only: bool,
34}
35
36impl UdpOpts {
37 pub fn for_addr(addr: SocketAddr) -> Self {
40 Self {
41 ipv6_only: addr.is_ipv6(),
42 }
43 }
44}
45
46pub trait NetIo {
48 fn bind_udp(
51 &self,
52 token: &GateToken,
53 addr: SocketAddr,
54 opts: UdpOpts,
55 ) -> io::Result<UdpSocket>;
56
57 fn bind_mdns(
63 &self,
64 token: &GateToken,
65 hosts: &[IpAddr],
66 ) -> io::Result<UdpSocket>;
67
68 fn bind_tcp(
71 &self,
72 token: &GateToken,
73 addr: SocketAddr,
74 ) -> io::Result<TcpListener>;
75
76 fn connect_tcp<'a>(
83 &'a self,
84 token: &'a GateToken,
85 bind: Option<IpAddr>,
86 to: SocketAddr,
87 host: Option<&'a str>,
88 ) -> LocalBoxFuture<'a, io::Result<TcpStream>>;
89
90 fn resolve<'a>(
95 &'a self,
96 token: &'a GateToken,
97 host: &'a str,
98 port: u16,
99 ) -> LocalBoxFuture<'a, io::Result<Vec<SocketAddr>>>;
100
101 fn route_probe(&self, peer: IpAddr) -> Option<IpAddr>;
104}
105
106#[derive(Clone, Copy, Debug, Default)]
108pub struct PlainNetIo;
109
110impl NetIo for PlainNetIo {
111 fn bind_udp(
112 &self,
113 _token: &GateToken,
114 addr: SocketAddr,
115 opts: UdpOpts,
116 ) -> io::Result<UdpSocket> {
117 let domain = if addr.is_ipv4() {
118 socket2::Domain::IPV4
119 } else {
120 socket2::Domain::IPV6
121 };
122 let socket = socket2::Socket::new(
123 domain,
124 socket2::Type::DGRAM,
125 Some(socket2::Protocol::UDP),
126 )?;
127 if addr.is_ipv6() && opts.ipv6_only {
128 socket.set_only_v6(true)?;
129 }
130 socket.set_nonblocking(true)?;
131 socket.bind(&addr.into())?;
132 UdpSocket::from_std(socket.into())
133 }
134
135 fn bind_mdns(
136 &self,
137 _token: &GateToken,
138 hosts: &[IpAddr],
139 ) -> io::Result<UdpSocket> {
140 let socket = socket2::Socket::new(
141 socket2::Domain::IPV4,
142 socket2::Type::DGRAM,
143 Some(socket2::Protocol::UDP),
144 )?;
145 mdns_socket(socket, false, hosts)
146 }
147
148 fn bind_tcp(
149 &self,
150 _token: &GateToken,
151 addr: SocketAddr,
152 ) -> io::Result<TcpListener> {
153 let domain = if addr.is_ipv4() {
154 socket2::Domain::IPV4
155 } else {
156 socket2::Domain::IPV6
157 };
158 let socket = socket2::Socket::new(
159 domain,
160 socket2::Type::STREAM,
161 Some(socket2::Protocol::TCP),
162 )?;
163 if addr.is_ipv6() {
164 socket.set_only_v6(true)?;
165 }
166 #[cfg(not(windows))]
167 socket.set_reuse_address(true)?;
168 socket.set_nonblocking(true)?;
169 socket.bind(&addr.into())?;
170 socket.listen(128)?;
171 TcpListener::from_std(socket.into())
172 }
173
174 fn connect_tcp<'a>(
175 &'a self,
176 _token: &'a GateToken,
177 bind: Option<IpAddr>,
178 to: SocketAddr,
179 _host: Option<&'a str>,
180 ) -> LocalBoxFuture<'a, io::Result<TcpStream>> {
181 Box::pin(async move {
182 let Some(ip) = bind else {
183 return TcpStream::connect(to).await;
184 };
185 let socket = if to.is_ipv4() {
186 tokio::net::TcpSocket::new_v4()?
187 } else {
188 tokio::net::TcpSocket::new_v6()?
189 };
190 if ip.is_ipv4() == to.is_ipv4() {
191 socket.bind(SocketAddr::new(ip, 0))?;
192 }
193 socket.connect(to).await
194 })
195 }
196
197 fn resolve<'a>(
198 &'a self,
199 _token: &'a GateToken,
200 host: &'a str,
201 port: u16,
202 ) -> LocalBoxFuture<'a, io::Result<Vec<SocketAddr>>> {
203 Box::pin(async move {
204 let host = lookup_name(host);
205 Ok(tokio::net::lookup_host((host, port)).await?.collect())
206 })
207 }
208
209 fn route_probe(&self, peer: IpAddr) -> Option<IpAddr> {
210 let unspecified: IpAddr = if peer.is_ipv4() {
211 Ipv4Addr::UNSPECIFIED.into()
212 } else {
213 Ipv6Addr::UNSPECIFIED.into()
214 };
215 let probe = std::net::UdpSocket::bind((unspecified, 0)).ok()?;
216 probe.connect((peer, 9)).ok()?;
217 Some(probe.local_addr().ok()?.ip())
218 }
219}
220
221fn lookup_name(host: &str) -> &str {
225 if host.is_empty() {
226 return "0.0.0.0";
227 }
228 let addr = host.trim_start_matches('[').trim_end_matches(']');
229 let name = addr.strip_suffix('.').unwrap_or(addr).to_ascii_lowercase();
230 if name.len() > ".localhost".len() && name.ends_with(".localhost") {
231 return "localhost";
232 }
233 addr
234}
235
236pub fn mdns_socket(
243 socket: socket2::Socket,
244 bound: bool,
245 hosts: &[IpAddr],
246) -> io::Result<UdpSocket> {
247 let mdns_addr =
248 SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), rtci::mdns::MDNS_PORT);
249 if !bound {
250 socket.set_reuse_address(true)?;
251 #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
252 socket.set_reuse_port(true)?;
253 }
254 socket.set_nonblocking(true)?;
255 socket.set_multicast_ttl_v4(255)?;
256 socket.set_multicast_loop_v4(true)?;
257 if !bound {
258 socket.bind(&mdns_addr.into())?;
259 }
260 let group = rtci::mdns::MDNS_MULTICAST_IPV4;
261 let mut joined = false;
262 for ip in hosts {
263 if let IpAddr::V4(iface) = ip
264 && !iface.is_loopback()
265 && socket.join_multicast_v4(&group, iface).is_ok()
266 {
267 joined = true;
268 }
269 }
270 if !joined {
271 socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED)?;
272 }
273 UdpSocket::from_std(socket.into())
274}
275
276#[cfg(test)]
277mod tests {
278 use super::lookup_name;
279
280 #[test]
281 fn lookup_name_matches_deno_resolve_addr() {
282 assert_eq!(lookup_name(""), "0.0.0.0");
283 assert_eq!(lookup_name("[::1]"), "::1");
284 assert_eq!(lookup_name("stun.example"), "stun.example");
285 assert_eq!(lookup_name("app.localhost"), "localhost");
286 assert_eq!(lookup_name("App.Localhost."), "localhost");
287 assert_eq!(lookup_name("localhost"), "localhost");
288 }
289}