aboutsummaryrefslogtreecommitdiff
path: root/src/link.rs
blob: b14d7fd3ca0cacb1a7feed3bcd93840e0c9e7ddd (plain) (blame)
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
use crate::error::{Error, Result};

use futures_util::TryStreamExt;
use netlink_packet_route::rtnl::IFF_UP;
use tokio::runtime::Runtime;

#[derive(Clone, Copy, Debug)]
enum State {
    Up,
    Down,
}

async fn set(link: String, state: State) -> Result<()> {
    let (conn, handle, _) = rtnetlink::new_connection()?;
    tokio::spawn(conn);

    let link = handle
        .link()
        .get()
        .match_name(link.clone())
        .execute()
        .try_next()
        .await?
        .ok_or(Error::LinkNotFound(link))?;

    let id = link.header.index;

    match state {
        State::Up => handle.link().set(id).up(),
        State::Down => handle.link().set(id).down(),
    }
    .execute()
    .await?;

    Ok(())
}

pub fn up(link: String) -> Result<()> {
    Runtime::new()?.block_on(set(link, State::Up))
}

pub fn down(link: String) -> Result<()> {
    Runtime::new()?.block_on(set(link, State::Down))
}

async fn do_is_up(link: String) -> Result<bool> {
    let (conn, handle, _) = rtnetlink::new_connection()?;
    tokio::spawn(conn);

    let link = handle
        .link()
        .get()
        .match_name(link.clone())
        .execute()
        .try_next()
        .await?
        .ok_or(Error::LinkNotFound(link))?;

    let is_up = link.header.flags & IFF_UP == IFF_UP;
    Ok(is_up)
}

pub fn is_up(link: String) -> Result<bool> {
    Runtime::new()?.block_on(do_is_up(link))
}