summaryrefslogtreecommitdiffhomepage
path: root/mullvad-cli/src/cmds/status.rs
blob: 11e436d34aff99d3c45f00fbbdb08e2b88f746c0 (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
use clap;
use new_rpc_client;
use Command;
use Result;

use mullvad_ipc_client::DaemonRpcClient;
use talpid_types::tunnel::TunnelStateTransition::{self, *};

pub struct Status;

impl Command for Status {
    fn name(&self) -> &'static str {
        "status"
    }

    fn clap_subcommand(&self) -> clap::App<'static, 'static> {
        clap::SubCommand::with_name(self.name())
            .about("View the state of the VPN tunnel")
            .subcommand(
                clap::SubCommand::with_name("listen").about("Listen for VPN tunnel state changes"),
            )
    }

    fn run(&self, matches: &clap::ArgMatches) -> Result<()> {
        let mut rpc = new_rpc_client()?;
        let state = rpc.get_state()?;

        print_state(&state);
        print_location(&mut rpc)?;
        if matches.subcommand_matches("listen").is_some() {
            for new_state in rpc.new_state_subscribe()? {
                print_state(&new_state);

                if new_state == Connected || new_state == Disconnected {
                    print_location(&mut rpc)?;
                }
            }
        }
        Ok(())
    }
}

fn print_state(state: &TunnelStateTransition) {
    print!("Tunnel status: ");
    match state {
        Blocked(reason) => println!("Blocked ({})", reason),
        Connected => println!("Connected"),
        Connecting => println!("Connecting..."),
        Disconnected => println!("Disconnected"),
        Disconnecting(_) => println!("Disconnecting..."),
    }
}

fn print_location(rpc: &mut DaemonRpcClient) -> Result<()> {
    let location = rpc.get_current_location()?;
    let city_and_country = if let Some(city) = location.city {
        format!("{}, {}", city, location.country)
    } else {
        format!("{}", location.country)
    };
    if let Some(hostname) = location.hostname {
        println!("Relay: {}", hostname);
    }
    println!("Location: {}", city_and_country);
    println!(
        "Position: {:.5}°N, {:.5}°W",
        location.latitude, location.longitude
    );
    Ok(())
}