igd/
search.rs

1use attohttpc::Method;
2use attohttpc::RequestBuilder;
3use std::collections::HashMap;
4use std::net::{SocketAddrV4, UdpSocket};
5use std::str;
6
7use crate::common::{messages, parsing, SearchOptions};
8use crate::errors::SearchError;
9use crate::gateway::Gateway;
10
11/// Search gateway, using the given `SearchOptions`.
12///
13/// The default `SearchOptions` should suffice in most cases.
14/// It can be created with `Default::default()` or `SearchOptions::default()`.
15///
16/// # Example
17/// ```no_run
18/// use igd::{search_gateway, SearchOptions, Result};
19///
20/// fn main() -> Result {
21///     let gateway = search_gateway(Default::default())?;
22///     let ip = gateway.get_external_ip()?;
23///     println!("External IP address: {}", ip);
24///     Ok(())
25/// }
26/// ```
27pub fn search_gateway(options: SearchOptions) -> Result<Gateway, SearchError> {
28    let socket = UdpSocket::bind(options.bind_addr)?;
29    socket.set_read_timeout(options.timeout)?;
30
31    socket.send_to(messages::SEARCH_REQUEST.as_bytes(), options.broadcast_address)?;
32
33    loop {
34        let mut buf = [0u8; 1500];
35        let (read, _) = socket.recv_from(&mut buf)?;
36        let text = str::from_utf8(&buf[..read])?;
37
38        let (addr, root_url) = parsing::parse_search_result(text)?;
39
40        let (control_schema_url, control_url) = match get_control_urls(&addr, &root_url) {
41            Ok(o) => o,
42            Err(e) => {
43                debug!(
44                    "Error has occurred while getting control urls. error: {}, addr: {}, root_url: {}",
45                    e, addr, root_url
46                );
47                continue;
48            }
49        };
50
51        let control_schema = match get_schemas(&addr, &control_schema_url) {
52            Ok(o) => o,
53            Err(e) => {
54                debug!(
55                    "Error has occurred while getting schemas. error: {}, addr: {}, control_schema_url: {}",
56                    e, addr, control_schema_url
57                );
58                continue;
59            }
60        };
61
62        return Ok(Gateway {
63            addr,
64            root_url,
65            control_url,
66            control_schema_url,
67            control_schema,
68        });
69    }
70}
71
72fn get_control_urls(addr: &SocketAddrV4, root_url: &str) -> Result<(String, String), SearchError> {
73    let url = format!("http://{}:{}{}", addr.ip(), addr.port(), root_url);
74
75    match RequestBuilder::try_new(Method::GET, &url) {
76        Ok(request_builder) => {
77            let response = request_builder.send()?;
78            parsing::parse_control_urls(&response.bytes()?[..])
79        }
80        Err(error) => Err(SearchError::HttpError(error)),
81    }
82}
83
84fn get_schemas(addr: &SocketAddrV4, control_schema_url: &str) -> Result<HashMap<String, Vec<String>>, SearchError> {
85    let url = format!("http://{}:{}{}", addr.ip(), addr.port(), control_schema_url);
86
87    match RequestBuilder::try_new(Method::GET, &url) {
88        Ok(request_builder) => {
89            let response = request_builder.send()?;
90            parsing::parse_schemas(&response.bytes()?[..])
91        }
92        Err(error) => Err(SearchError::HttpError(error)),
93    }
94}