Skip to content

Commit 2639193

Browse files
authored
feat(client): use non-zero ports resolved by dns resolvers (#148)
If a resolved address sets the port number to something besides `0`, and the port isn't otherwise explicitly asked for, the `HttpConnector` will now use that port. This allows custom resolvers that might lookup SRVB or HTTPSrr records that include a port number. cc seanmonstar/reqwest#2413
1 parent 4a8a261 commit 2639193

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/client/legacy/connect/http.rs

+32-1
Original file line numberDiff line numberDiff line change
@@ -433,7 +433,8 @@ where
433433
.map_err(ConnectError::dns)?;
434434
let addrs = addrs
435435
.map(|mut addr| {
436-
addr.set_port(port);
436+
set_port(&mut addr, port, dst.port().is_some());
437+
437438
addr
438439
})
439440
.collect();
@@ -825,9 +826,19 @@ impl ConnectingTcp<'_> {
825826
}
826827
}
827828

829+
/// Respect explicit ports in the URI, if none, either
830+
/// keep non `0` ports resolved from a custom dns resolver,
831+
/// or use the default port for the scheme.
832+
fn set_port(addr: &mut SocketAddr, host_port: u16, explicit: bool) {
833+
if explicit || addr.port() == 0 {
834+
addr.set_port(host_port)
835+
};
836+
}
837+
828838
#[cfg(test)]
829839
mod tests {
830840
use std::io;
841+
use std::net::SocketAddr;
831842

832843
use ::http::Uri;
833844

@@ -836,6 +847,8 @@ mod tests {
836847
use super::super::sealed::{Connect, ConnectSvc};
837848
use super::{Config, ConnectError, HttpConnector};
838849

850+
use super::set_port;
851+
839852
async fn connect<C>(
840853
connector: C,
841854
dst: Uri,
@@ -1234,4 +1247,22 @@ mod tests {
12341247
panic!("test failed");
12351248
}
12361249
}
1250+
1251+
#[test]
1252+
fn test_set_port() {
1253+
// Respect explicit ports no matter what the resolved port is.
1254+
let mut addr = SocketAddr::from(([0, 0, 0, 0], 6881));
1255+
set_port(&mut addr, 42, true);
1256+
assert_eq!(addr.port(), 42);
1257+
1258+
// Ignore default host port, and use the socket port instead.
1259+
let mut addr = SocketAddr::from(([0, 0, 0, 0], 6881));
1260+
set_port(&mut addr, 443, false);
1261+
assert_eq!(addr.port(), 6881);
1262+
1263+
// Use the default port if the resolved port is `0`.
1264+
let mut addr = SocketAddr::from(([0, 0, 0, 0], 0));
1265+
set_port(&mut addr, 443, false);
1266+
assert_eq!(addr.port(), 443);
1267+
}
12371268
}

0 commit comments

Comments
 (0)