summaryrefslogtreecommitdiffhomepage
path: root/talpid-routing/src/unix/macos/interface.rs
blob: a6e0bed540a3033f28ad873ff065df13fa85d5dd (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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use futures::channel::mpsc::{self, UnboundedReceiver, UnboundedSender};
use ipnetwork::IpNetwork;
use nix::{
    net::if_::{if_nametoindex, InterfaceFlags},
    sys::socket::{AddressFamily, SockaddrLike, SockaddrStorage},
};
use std::{
    collections::BTreeMap,
    io,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

use super::data::{Destination, RouteMessage};
use system_configuration::{
    core_foundation::{
        array::CFArray,
        base::{CFType, TCFType, ToVoid},
        dictionary::CFDictionary,
        runloop::{kCFRunLoopCommonModes, CFRunLoop},
        string::CFString,
    },
    dynamic_store::{SCDynamicStore, SCDynamicStoreBuilder, SCDynamicStoreCallBackContext},
    network_configuration::SCNetworkSet,
    preferences::SCPreferences,
    sys::schema_definitions::{
        kSCDynamicStorePropNetPrimaryInterface, kSCPropInterfaceName, kSCPropNetIPv4Router,
        kSCPropNetIPv6Router,
    },
};

const STATE_IPV4_KEY: &str = "State:/Network/Global/IPv4";
const STATE_IPV6_KEY: &str = "State:/Network/Global/IPv6";
const STATE_SERVICE_PATTERN: &str = "State:/Network/Service/.*/IP.*";

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Family {
    V4,
    V6,
}

impl std::fmt::Display for Family {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Family::V4 => f.write_str("V4"),
            Family::V6 => f.write_str("V6"),
        }
    }
}

impl Family {
    pub fn default_network(self) -> IpNetwork {
        match self {
            Family::V4 => IpNetwork::new(Ipv4Addr::UNSPECIFIED.into(), 0).unwrap(),
            Family::V6 => IpNetwork::new(Ipv6Addr::UNSPECIFIED.into(), 0).unwrap(),
        }
    }
}

#[derive(Debug)]
struct NetworkServiceDetails {
    name: String,
    router_ip: IpAddr,
}

pub struct PrimaryInterfaceMonitor {
    store: SCDynamicStore,
    prefs: SCPreferences,
}

// FIXME: Implement Send on SCDynamicStore, if it's safe
unsafe impl Send for PrimaryInterfaceMonitor {}

pub enum InterfaceEvent {
    Update,
}

impl PrimaryInterfaceMonitor {
    pub fn new() -> (Self, UnboundedReceiver<InterfaceEvent>) {
        let store = SCDynamicStoreBuilder::new("talpid-routing").build();
        let prefs = SCPreferences::default(&CFString::new("talpid-routing"));

        let (tx, rx) = mpsc::unbounded();
        Self::start_listener(tx);

        (Self { store, prefs }, rx)
    }

    fn start_listener(tx: UnboundedSender<InterfaceEvent>) {
        std::thread::spawn(|| {
            let listener_store = SCDynamicStoreBuilder::new("talpid-routing-listener")
                .callback_context(SCDynamicStoreCallBackContext {
                    callout: Self::store_change_handler,
                    info: tx,
                })
                .build();

            let watch_keys: CFArray<CFString> = CFArray::from_CFTypes(&[
                CFString::new(STATE_IPV4_KEY),
                CFString::new(STATE_IPV6_KEY),
            ]);
            let watch_patterns = CFArray::from_CFTypes(&[CFString::new(STATE_SERVICE_PATTERN)]);

            if !listener_store.set_notification_keys(&watch_keys, &watch_patterns) {
                log::error!("Failed to start interface listener");
                return;
            }

            let run_loop_source = listener_store.create_run_loop_source();
            CFRunLoop::get_current().add_source(&run_loop_source, unsafe { kCFRunLoopCommonModes });
            CFRunLoop::run_current();

            log::debug!("Interface listener exiting");
        });
    }

    fn store_change_handler(
        _store: SCDynamicStore,
        changed_keys: CFArray<CFString>,
        tx: &mut UnboundedSender<InterfaceEvent>,
    ) {
        for k in changed_keys.iter() {
            log::debug!("Interface change, key {}", k.to_string());
        }
        let _ = tx.unbounded_send(InterfaceEvent::Update);
    }

    /// Retrieve the best current default route. This is based on the primary interface, or else
    /// the first active interface in the network service order.
    pub fn get_route(&self, family: Family) -> Option<RouteMessage> {
        let ifaces = self
            .get_primary_interface(family)
            .map(|iface| {
                log::debug!("Found primary interface for {family}");
                vec![iface]
            })
            .unwrap_or_else(|| {
                log::debug!("No primary interface for {family}. Checking service order");
                self.network_services(family)
            });

        let (iface, index) = ifaces
            .into_iter()
            .filter_map(|iface| {
                let index = if_nametoindex(iface.name.as_str()).map_err(|error| {
                    log::error!("Failed to retrieve interface index for \"{}\": {error}", iface.name);
                    error
                }).ok()?;

                let active = is_active_interface(&iface.name, family).unwrap_or_else(|error| {
                    log::error!("is_active_interface() returned an error for interface \"{}\", assuming active. Error: {error}", iface.name);
                    true
                });
                if !active {
                    log::debug!("Skipping inactive interface {}, router IP {}", iface.name, iface.router_ip);
                    return None;
                }
                Some((iface, index))
            })
            .next()?;

        // Synthesize a scoped route for the interface
        let msg = RouteMessage::new_route(Destination::Network(family.default_network()))
            .set_gateway_addr(iface.router_ip)
            .set_interface_index(u16::try_from(index).unwrap());
        Some(msg)
    }

    fn get_primary_interface(&self, family: Family) -> Option<NetworkServiceDetails> {
        let global_name = if family == Family::V4 {
            STATE_IPV4_KEY
        } else {
            STATE_IPV6_KEY
        };
        let global_dict = self
            .store
            .get(CFString::new(global_name))
            .and_then(|v| v.downcast_into::<CFDictionary>())?;
        let name = global_dict
            .find(unsafe { kSCDynamicStorePropNetPrimaryInterface }.to_void())
            .map(|s| unsafe { CFType::wrap_under_get_rule(*s) })
            .and_then(|s| s.downcast::<CFString>())
            .map(|s| s.to_string())
            .or_else(|| {
                log::debug!("Missing name for primary interface ({family})");
                None
            })?;

        let router_key = if family == Family::V4 {
            unsafe { kSCPropNetIPv4Router.to_void() }
        } else {
            unsafe { kSCPropNetIPv6Router.to_void() }
        };

        let router_ip = global_dict
            .find(router_key)
            .map(|s| unsafe { CFType::wrap_under_get_rule(*s) })
            .and_then(|s| s.downcast::<CFString>())
            .and_then(|ip| ip.to_string().parse().ok())
            .or_else(|| {
                log::debug!("Missing router IP for primary interface \"{name}\"");
                None
            })?;

        Some(NetworkServiceDetails { name, router_ip })
    }

    fn network_services(&self, family: Family) -> Vec<NetworkServiceDetails> {
        let router_key = if family == Family::V4 {
            unsafe { kSCPropNetIPv4Router.to_void() }
        } else {
            unsafe { kSCPropNetIPv6Router.to_void() }
        };

        SCNetworkSet::new(&self.prefs)
            .service_order()
            .iter()
            .filter_map(|service_id| {
                let service_id_s = service_id.to_string();
                let key = if family == Family::V4 {
                    format!("State:/Network/Service/{service_id_s}/IPv4")
                } else {
                    format!("State:/Network/Service/{service_id_s}/IPv6")
                };

                let ip_dict = self
                    .store
                    .get(CFString::new(&key))
                    .and_then(|v| v.downcast_into::<CFDictionary>())
                    .or_else(|| {
                        log::debug!("No {family} dict for {service_id_s}");
                        None
                    })?;
                let name = ip_dict
                    .find(unsafe { kSCPropInterfaceName }.to_void())
                    .map(|s| unsafe { CFType::wrap_under_get_rule(*s) })
                    .and_then(|s| s.downcast::<CFString>())
                    .map(|s| s.to_string())
                    .or_else(|| {
                        log::debug!("Missing name for service {service_id_s} ({family})");
                        None
                    })?;
                let router_ip = ip_dict
                    .find(router_key)
                    .map(|s| unsafe { CFType::wrap_under_get_rule(*s) })
                    .and_then(|s| s.downcast::<CFString>())
                    .and_then(|ip| ip.to_string().parse().ok())
                    .or_else(|| {
                        log::debug!("Missing router IP for {service_id_s} ({name}, {family})");
                        None
                    })?;

                Some(NetworkServiceDetails { name, router_ip })
            })
            .collect::<Vec<_>>()
    }

    pub fn debug(&self) {
        for family in [Family::V4, Family::V6] {
            log::debug!(
                "Primary interface ({family}): {:?}",
                self.get_primary_interface(family)
            );
            log::debug!(
                "Network services ({family}): {:?}",
                self.network_services(family)
            );
        }
    }
}

/// Return a map from interface name to link addresses (AF_LINK)
pub fn get_interface_link_addresses() -> io::Result<BTreeMap<String, SockaddrStorage>> {
    let mut gateway_link_addrs = BTreeMap::new();
    let addrs = nix::ifaddrs::getifaddrs()?;
    for addr in addrs.into_iter() {
        if addr.address.and_then(|addr| addr.family()) != Some(AddressFamily::Link) {
            continue;
        }
        gateway_link_addrs.insert(addr.interface_name, addr.address.unwrap());
    }
    Ok(gateway_link_addrs)
}

/// Return whether the given interface has an assigned (unicast) IP address.
fn is_active_interface(interface_name: &str, family: Family) -> io::Result<bool> {
    let required_link_flags: InterfaceFlags = InterfaceFlags::IFF_UP | InterfaceFlags::IFF_RUNNING;
    let has_ip_addr = nix::ifaddrs::getifaddrs()?
        .filter(|addr| (addr.flags & required_link_flags) == required_link_flags)
        .filter(|addr| addr.interface_name == interface_name)
        .any(|addr| {
            if let Some(addr) = addr.address {
                // Check if family matches; ignore if link-local address
                match family {
                    Family::V4 => matches!(addr.as_sockaddr_in(), Some(addr_in) if is_routable_v4(&Ipv4Addr::from(addr_in.ip()))),
                    Family::V6 => {
                        matches!(addr.as_sockaddr_in6(), Some(addr_in) if is_routable_v6(&addr_in.ip()))
                    }
                }
            } else {
                false
            }
        });
    Ok(has_ip_addr)
}

fn is_routable_v4(addr: &Ipv4Addr) -> bool {
    !addr.is_unspecified() && !addr.is_loopback() && !addr.is_link_local()
}

fn is_routable_v6(addr: &Ipv6Addr) -> bool {
    !addr.is_unspecified()
    && !addr.is_loopback()
    // !(link local)
    && (addr.segments()[0] & 0xffc0) != 0xfe80
}