Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ http-body-util = "0.1"
hyper = { version = "1", features = ["http1", "client"] }
hyper-util = { version = "0.1", features = ["http1", "client"] }
log = "0.4"
rand = "0.8"
rand = "0.9"
reqwest = { version = "0.12.9", default-features = false, features = ["blocking", "rustls-tls"] }
thiserror = "2.0.4"
tokio = {version = "1", optional = true, features = ["net", "macros"]}
Expand Down
6 changes: 3 additions & 3 deletions examples/add_any_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate igd;

fn main() {
match igd::search_gateway(Default::default()) {
Err(ref err) => println!("Error: {}", err),
Err(ref err) => println!("Error: {err}"),
Ok(gateway) => {
let local_addr = match std::env::args().nth(1) {
Some(local_addr) => local_addr,
Expand All @@ -15,10 +15,10 @@ fn main() {

match gateway.add_any_port(igd::PortMappingProtocol::TCP, local_addr, 60, "add_port example") {
Err(ref err) => {
println!("There was an error! {}", err);
println!("There was an error! {err}");
}
Ok(port) => {
println!("It worked! Got port {}", port);
println!("It worked! Got port {port}");
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/add_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate igd;

fn main() {
match igd::search_gateway(Default::default()) {
Err(ref err) => println!("Error: {}", err),
Err(ref err) => println!("Error: {err}"),
Ok(gateway) => {
let local_addr = match std::env::args().nth(1) {
Some(local_addr) => local_addr,
Expand All @@ -15,7 +15,7 @@ fn main() {

match gateway.add_port(igd::PortMappingProtocol::TCP, 80, local_addr, 60, "add_port example") {
Err(ref err) => {
println!("There was an error! {}", err);
println!("There was an error! {err}");
}
Ok(()) => {
println!("It worked");
Expand Down
8 changes: 4 additions & 4 deletions examples/add_remove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ extern crate igd;
fn main() {
match igd::search_gateway(Default::default()) {
Err(ref err) => match *err {
igd::SearchError::IoError(ref ioe) => println!("IoError: {}", ioe),
_ => println!("{:?}", err),
igd::SearchError::IoError(ref ioe) => println!("IoError: {ioe}"),
_ => println!("{err:?}"),
},
Ok(gateway) => {
let args: Vec<_> = env::args().collect();
Expand All @@ -22,11 +22,11 @@ fn main() {
let local_addr = SocketAddrV4::new(local_ip, local_port);

match gateway.add_port(igd::PortMappingProtocol::TCP, remote_port, local_addr, 60, "crust") {
Err(ref err) => println!("{:?}", err),
Err(ref err) => println!("{err:?}"),
Ok(()) => {
println!("AddPortMapping successful.");
match gateway.remove_port(igd::PortMappingProtocol::TCP, remote_port) {
Err(ref err) => println!("Error removing: {:?}", err),
Err(ref err) => println!("Error removing: {err:?}"),
Ok(_) => println!("DeletePortMapping successful."),
}
}
Expand Down
10 changes: 5 additions & 5 deletions examples/aio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,26 +33,26 @@ async fn main() {

let gateway = match search_gateway(Default::default()).await {
Ok(g) => g,
Err(err) => return println!("Faild to find IGD: {}", err),
Err(err) => return println!("Faild to find IGD: {err}"),
};
let pub_ip = match gateway.get_external_ip().await {
Ok(ip) => ip,
Err(err) => return println!("Failed to get external IP: {}", err),
Err(err) => return println!("Failed to get external IP: {err}"),
};
println!("Our public IP is {}", pub_ip);
println!("Our public IP is {pub_ip}");
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 1234, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
println!("Failed to add port mapping: {e}");
}
println!("New port mapping was successfully added.");

if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 2345, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
println!("Failed to add port mapping: {e}");
}
println!("New port mapping was successfully added.");

Expand Down
6 changes: 3 additions & 3 deletions examples/external_ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ extern crate igd;

fn main() {
match igd::search_gateway(Default::default()) {
Err(ref err) => println!("Error: {}", err),
Err(ref err) => println!("Error: {err}"),
Ok(gateway) => match gateway.get_external_ip() {
Err(ref err) => {
println!("There was an error! {}", err);
println!("There was an error! {err}");
}
Ok(ext_addr) => {
println!("Local gateway: {}, External ip address: {}", gateway, ext_addr);
println!("Local gateway: {gateway}, External ip address: {ext_addr}");
}
},
}
Expand Down
4 changes: 2 additions & 2 deletions examples/remove_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ extern crate igd;

fn main() {
match igd::search_gateway(Default::default()) {
Err(ref err) => println!("Error: {}", err),
Err(ref err) => println!("Error: {err}"),
Ok(gateway) => match gateway.remove_port(igd::PortMappingProtocol::TCP, 80) {
Err(ref err) => {
println!("There was an error! {}", err);
println!("There was an error! {err}");
}
Ok(()) => {
println!("It worked");
Expand Down
2 changes: 1 addition & 1 deletion src/aio/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub struct Gateway {

impl Gateway {
async fn perform_request(&self, header: &str, body: &str, ok: &str) -> Result<RequestReponse, RequestError> {
let url = format!("{}", self);
let url = format!("{self}");
let text = soap::send_async(&url, soap::Action::new(header), body).await?;
parsing::parse_response(text, ok)
}
Expand Down
24 changes: 10 additions & 14 deletions src/aio/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn search_gateway(options: SearchOptions) -> Result<Gateway, SearchErr
let addr_v4 = match addr {
SocketAddr::V4(a) => Ok(a),
_ => {
warn!("unsupported IPv6 gateway response from addr: {}", addr);
warn!("unsupported IPv6 gateway response from addr: {addr}");
Err(SearchError::InvalidResponse)
}
}?;
Expand Down Expand Up @@ -85,13 +85,13 @@ async fn send_search_request(socket: &mut UdpSocket, addr: SocketAddr) -> Result
async fn receive_search_response(socket: &mut UdpSocket) -> Result<(Vec<u8>, SocketAddr), SearchError> {
let mut buff = [0u8; MAX_RESPONSE_SIZE];
let (n, from) = socket.recv_from(&mut buff).await?;
debug!("received broadcast response from: {}", from);
debug!("received broadcast response from: {from}");
Ok((buff[..n].to_vec(), from))
}

// Handle a UDP response message
fn handle_broadcast_resp(from: &SocketAddr, data: &[u8]) -> Result<(SocketAddr, String), SearchError> {
debug!("handling broadcast response from: {}", from);
debug!("handling broadcast response from: {from}");

// Convert response to text
let text = std::str::from_utf8(data).map_err(SearchError::from)?;
Expand All @@ -103,27 +103,27 @@ fn handle_broadcast_resp(from: &SocketAddr, data: &[u8]) -> Result<(SocketAddr,
}

async fn get_control_urls(addr: &SocketAddr, path: &str) -> Result<(String, String), SearchError> {
debug!("requesting control url from: http://{}{}", addr, path);
debug!("requesting control url from: http://{addr}{path}");
let body = http_get_bounded(addr, path, MAX_HTTP_RESPONSE_SIZE).await?;
debug!("handling control response from: {}", addr);
debug!("handling control response from: {addr}");
parsing::parse_control_urls(std::io::Cursor::new(body))
}

async fn get_control_schemas(
addr: &SocketAddr,
control_schema_url: &str,
) -> Result<HashMap<String, Vec<String>>, SearchError> {
debug!("requesting control schema from: http://{}{}", addr, control_schema_url);
debug!("requesting control schema from: http://{addr}{control_schema_url}");
let body = http_get_bounded(addr, control_schema_url, MAX_HTTP_RESPONSE_SIZE).await?;
debug!("handling schema response from: {}", addr);
debug!("handling schema response from: {addr}");
parsing::parse_schemas(std::io::Cursor::new(body))
}

async fn http_get_bounded(addr: &SocketAddr, path: &str, memory_upper_bound: usize) -> Result<Vec<u8>, SearchError> {
use http_body_util::BodyExt;

let authority = addr.to_string();
let uri: Uri = format!("http://{}{}", addr, path).parse()?;
let uri: Uri = format!("http://{addr}{path}").parse()?;

let url: url::Url = uri.to_string().parse()?;
validate_url(addr.ip(), &url)?;
Expand Down Expand Up @@ -188,18 +188,14 @@ mod tests {
service::service_fn,
};
use hyper_util::rt::TokioIo;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use rand::{distr::Alphanumeric, rng, Rng};
use tokio::net::TcpListener;
use tokio_stream::wrappers::ReceiverStream;

use super::*;

fn generate_random_body(n: usize) -> Vec<u8> {
let s: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(n)
.map(char::from)
.collect();
let s: String = rng().sample_iter(&Alphanumeric).take(n).map(char::from).collect();
s.into_bytes()
}

Expand Down
40 changes: 12 additions & 28 deletions src/common/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const MESSAGE_TAIL: &str = r#"</s:Body>
</s:Envelope>"#;

fn format_message(body: String) -> String {
format!("{}{}{}", MESSAGE_HEAD, body, MESSAGE_TAIL)
format!("{MESSAGE_HEAD}{body}{MESSAGE_TAIL}")
}

pub fn format_get_external_ip_message() -> String {
Expand Down Expand Up @@ -62,24 +62,19 @@ pub fn format_add_any_port_mapping_message(
"NewProtocol" => protocol.to_string(),
"NewRemoteHost" => "".to_string(),
unknown => {
warn!("Unknown argument: {}", unknown);
warn!("Unknown argument: {unknown}");
return None;
}
};
Some(format!(
"<{argument}>{value}</{argument}>",
argument = argument,
value = value
))
Some(format!("<{argument}>{value}</{argument}>"))
})
.collect::<Vec<_>>()
.join("\n");

format_message(format!(
r#"<u:AddAnyPortMapping xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
{}
{args}
</u:AddAnyPortMapping>"#,
args,
))
}

Expand All @@ -104,24 +99,19 @@ pub fn format_add_port_mapping_message(
"NewProtocol" => protocol.to_string(),
"NewRemoteHost" => "".to_string(),
unknown => {
warn!("Unknown argument: {}", unknown);
warn!("Unknown argument: {unknown}");
return None;
}
};
Some(format!(
"<{argument}>{value}</{argument}>",
argument = argument,
value = value
))
Some(format!("<{argument}>{value}</{argument}>"))
})
.collect::<Vec<_>>()
.join("\n");

format_message(format!(
r#"<u:AddPortMapping xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
{}
{args}
</u:AddPortMapping>"#,
args,
))
}

Expand All @@ -134,32 +124,26 @@ pub fn format_delete_port_message(schema: &[String], protocol: PortMappingProtoc
"NewProtocol" => protocol.to_string(),
"NewRemoteHost" => "".to_string(),
unknown => {
warn!("Unknown argument: {}", unknown);
warn!("Unknown argument: {unknown}");
return None;
}
};
Some(format!(
"<{argument}>{value}</{argument}>",
argument = argument,
value = value
))
Some(format!("<{argument}>{value}</{argument}>"))
})
.collect::<Vec<_>>()
.join("\n");

format_message(format!(
r#"<u:DeletePortMapping xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
{}
{args}
</u:DeletePortMapping>"#,
args,
))
}

pub fn formate_get_generic_port_mapping_entry_message(port_mapping_index: u32) -> String {
format_message(format!(
r#"<u:GetGenericPortMappingEntry xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
<NewPortMappingIndex>{}</NewPortMappingIndex>
</u:GetGenericPortMappingEntry>"#,
port_mapping_index
<NewPortMappingIndex>{port_mapping_index}</NewPortMappingIndex>
</u:GetGenericPortMappingEntry>"#
))
}
2 changes: 1 addition & 1 deletion src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ pub use self::options::SearchOptions;
use rand::{self, Rng};

pub fn random_port() -> u16 {
rand::thread_rng().gen_range(32_768_u16..65_535_u16)
rand::rng().random_range(32_768_u16..65_535_u16)
}
5 changes: 1 addition & 4 deletions src/common/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,10 +329,7 @@ pub fn parse_get_generic_port_mapping_entry(
let response = result?;
let xml = response.xml;
let make_err = |msg: String| || GetGenericPortMappingEntryError::RequestError(RequestError::InvalidResponse(msg));
let extract_field = |field: &str| {
xml.get_child(field)
.ok_or_else(make_err(format!("{} is missing", field)))
};
let extract_field = |field: &str| xml.get_child(field).ok_or_else(make_err(format!("{field} is missing")));
let remote_host = extract_field("NewRemoteHost")?
.get_text()
.map(|c| c.into_owned())
Expand Down
Loading
Loading