summaryrefslogtreecommitdiffhomepage
path: root/test/connection-checker/src/main.rs
blob: 6fb0d84843d102d7968302aa38c9f2f01d5bdffa (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
use clap::Parser;
use eyre::{eyre, Context};
use reqwest::blocking::Client;
use serde::Deserialize;
use std::{io::stdin, time::Duration};

use connection_checker::{
    cli::Opt,
    net::{send_ping, send_tcp, send_udp},
};

fn main() -> eyre::Result<()> {
    let opt = Opt::parse();
    color_eyre::install()?;

    if opt.interactive {
        let stdin = stdin();
        for line in stdin.lines() {
            let _ = line.wrap_err("Failed to read from stdin")?;
            test_connection(&opt)?;
        }
    } else {
        test_connection(&opt)?;
    }

    Ok(())
}

fn test_connection(opt: &Opt) -> eyre::Result<bool> {
    if let Some(destination) = opt.leak {
        if opt.leak_tcp {
            let _ = send_tcp(opt, destination);
        }
        if opt.leak_udp {
            let _ = send_udp(opt, destination);
        }
        if opt.leak_icmp {
            let _ = send_ping(opt, destination.ip());
        }
    }
    am_i_mullvad(opt)
}

/// Check if connected to Mullvad and print the result to stdout
fn am_i_mullvad(opt: &Opt) -> eyre::Result<bool> {
    #[derive(Debug, Deserialize)]
    struct Response {
        ip: String,
        mullvad_exit_ip_hostname: Option<String>,
    }

    let url = &opt.url;

    let client = Client::new();
    let response: Response = client
        .get(url)
        .timeout(Duration::from_secs(opt.timeout))
        .send()
        .and_then(|r| r.json())
        .wrap_err_with(|| eyre!("Failed to GET {url}"))?;

    if let Some(server) = &response.mullvad_exit_ip_hostname {
        println!(
            "You are connected to Mullvad (server {}). Your IP address is {}",
            server, response.ip
        );
        Ok(true)
    } else {
        println!(
            "You are not connected to Mullvad. Your IP address is {}",
            response.ip
        );
        Ok(false)
    }
}