summaryrefslogtreecommitdiff
path: root/src/redirecting_i2p.rs
blob: 3feef831adc73671bd4b6d66e185d657f71bf04d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use serde::Deserialize;
use std::fs;

#[derive(Debug, Deserialize)]
pub struct I2ProxySettings {
    pub i2p_port: Option<isize>,
    pub panel_port: Option<isize>,
}

#[derive(Deserialize, Debug)]
struct I2pdConfigFile {
    httpproxy: Option<HttpProxySection>,
    http: Option<HttpSection>,
}

#[derive(Deserialize, Debug)]
struct HttpProxySection {
    enabled: Option<bool>,
    port: Option<isize>,
    address: Option<String>,
}

#[derive(Deserialize, Debug)]
struct HttpSection {
    enabled: Option<bool>,
    port: Option<isize>,
    address: Option<String>,
}

impl I2ProxySettings {
    pub fn default() -> I2ProxySettings {
        I2ProxySettings {
            i2p_port: Some(4444),
            panel_port: Some(7070),
        }
    }

    const DEFAULT_I2PD_CONFIG_PATH: &'static str = "/etc/i2pd/i2pd.conf";

    pub fn from_i2pd_config(
        config_path: Option<&str>,
    ) -> Result<I2ProxySettings, Box<dyn std::error::Error>> {
        let path = config_path.unwrap_or(Self::DEFAULT_I2PD_CONFIG_PATH);
        let content = fs::read_to_string(path)?;

        let parsed_config: I2pdConfigFile = serde_ini::from_str(&content)?;

        let i2p_port = parsed_config.httpproxy.and_then(|proxy| proxy.port);
        let panel_port = parsed_config.http.and_then(|http| http.port);

        Ok(I2ProxySettings {
            i2p_port,
            panel_port,
        })
    }

    fn parse_url(url: &str) -> url::Url {
        url::Url::parse(url).expect("Failed to parse URL")
    }

    pub fn redirecting_i2p(&mut self, url: &str) -> String {
        if self.i2p_port.is_none() {
            self.i2p_port = Some(4444);
        }

        let parsed_url = Self::parse_url(url);
        let host = parsed_url.host_str().unwrap_or("");
        let path = parsed_url.path();
        // Wrong logic, unused, now used the proxy, not webpath
        let combined = format!("{}{}", host, path);
        let i2p_url = format!("http://127.0.0.1:{}/{}", self.i2p_port.unwrap(), combined);
        let i2p_url = I2ProxySettings::parse_url(&i2p_url);

        i2p_url.to_string()
    }
}