summaryrefslogtreecommitdiffhomepage
path: root/talpid-routing/src/lib.rs
blob: f1bf28d1a2c8586ff3f625f4633d0bba70f0298c (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//! Manage routing tables on various platforms.

#![deny(missing_docs)]
#![deny(rust_2018_idioms)]

use ipnetwork::IpNetwork;
use std::{fmt, net::IpAddr};

#[cfg(any(target_os = "windows", target_os = "macos"))]
mod debounce;

#[cfg(target_os = "windows")]
#[path = "windows/mod.rs"]
mod imp;

#[cfg(target_os = "windows")]
pub use imp::{get_best_default_route, CallbackHandle, EventType, InterfaceAndGateway};

#[cfg(not(target_os = "windows"))]
#[path = "unix/mod.rs"]
mod imp;

#[cfg(target_os = "linux")]
use netlink_packet_route::rtnl::constants::RT_TABLE_MAIN;

#[cfg(target_os = "macos")]
pub use imp::{DefaultRouteEvent, PlatformError};

pub use imp::{Error, RouteManager};

pub use imp::RouteManagerHandle;

/// A network route with a specific network node, destination and an optional metric.
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct Route {
    node: Node,
    prefix: IpNetwork,
    metric: Option<u32>,
    #[cfg(target_os = "linux")]
    table_id: u32,
    #[cfg(target_os = "linux")]
    mtu: Option<u32>,
}

impl Route {
    /// Construct a new Route
    pub fn new(node: Node, prefix: IpNetwork) -> Self {
        Self {
            node,
            prefix,
            metric: None,
            #[cfg(target_os = "linux")]
            table_id: u32::from(RT_TABLE_MAIN),
            #[cfg(target_os = "linux")]
            mtu: None,
        }
    }

    #[cfg(target_os = "linux")]
    fn table(mut self, new_id: u32) -> Self {
        self.table_id = new_id;
        self
    }

    /// Returns the network node of the route.
    pub fn get_node(&self) -> &Node {
        &self.node
    }
}

impl fmt::Display for Route {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} via {}", self.prefix, self.node)?;
        if let Some(metric) = &self.metric {
            write!(f, " metric {}", *metric)?;
        }
        #[cfg(target_os = "linux")]
        write!(f, " table {}", self.table_id)?;
        #[cfg(target_os = "linux")]
        if let Some(mtu) = self.mtu {
            write!(f, " mtu {mtu}")?;
        }
        Ok(())
    }
}

/// A network route that should be applied by the RouteManager.
/// It can either be routed through a specific network node or it can be routed through the current
/// default route.
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct RequiredRoute {
    /// Route's prefix
    pub prefix: IpNetwork,
    node: NetNode,
    /// Specifies whether the route should be added to the main routing table or not.
    #[cfg(target_os = "linux")]
    main_table: bool,
    /// Specifies route MTU
    #[cfg(target_os = "linux")]
    mtu: Option<u16>,
}

impl RequiredRoute {
    /// Constructs a new required route.
    pub fn new(prefix: IpNetwork, node: impl Into<NetNode>) -> Self {
        Self {
            node: node.into(),
            prefix,
            #[cfg(target_os = "linux")]
            main_table: true,
            #[cfg(target_os = "linux")]
            mtu: None,
        }
    }

    /// Sets the routing table ID of the route.
    #[cfg(target_os = "linux")]
    pub fn use_main_table(mut self, main_table: bool) -> Self {
        self.main_table = main_table;
        self
    }

    /// Set route MTU to the given value.
    #[cfg(target_os = "linux")]
    pub fn mtu(mut self, mtu: u16) -> Self {
        self.mtu = Some(mtu);
        self
    }
}

/// A NetNode represents a network node - either a real one or a symbolic default one.
/// A route with a symbolic default node will be changed whenever a new default route is created.
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub enum NetNode {
    /// A real node will be used to set a regular route that will remain unchanged for the lifetime
    /// of the RouteManager
    RealNode(Node),
    /// A default node is a symbolic node that will resolve to the network node used in the current
    /// most preferable default route
    #[cfg(not(target_os = "linux"))]
    DefaultNode,
}

impl From<Node> for NetNode {
    fn from(node: Node) -> NetNode {
        NetNode::RealNode(node)
    }
}

/// Node represents a real network node - it can be identified by a network interface name, an IP
/// address or both.
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct Node {
    ip: Option<IpAddr>,
    device: Option<String>,
}

impl Node {
    /// Construct an Node with both an IP address and an interface name.
    pub fn new(address: IpAddr, iface_name: String) -> Self {
        Self {
            ip: Some(address),
            device: Some(iface_name),
        }
    }

    /// Construct an Node from an IP address.
    pub fn address(address: IpAddr) -> Node {
        Self {
            ip: Some(address),
            device: None,
        }
    }

    /// Construct a Node from a network interface name.
    pub fn device(iface_name: String) -> Node {
        Self {
            ip: None,
            device: Some(iface_name),
        }
    }

    /// Retrieve a node's IP address
    pub fn get_address(&self) -> Option<IpAddr> {
        self.ip
    }

    /// Retrieve a node's network interface name
    pub fn get_device(&self) -> Option<&str> {
        self.device.as_ref().map(|s| s.as_ref())
    }
}

impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ip) = &self.ip {
            write!(f, "{ip}")?;
        }
        if let Some(device) = &self.device {
            let extra_space = if self.ip.is_some() { " " } else { "" };
            write!(f, "{extra_space}dev {device}")?;
        }
        Ok(())
    }
}