rtnetlink 0.21.0

manipulate linux networking resources via netlink
Documentation
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
// SPDX-License-Identifier: MIT

use std::{
    marker::PhantomData,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

#[cfg(not(target_os = "android"))]
use netlink_packet_route::route::{
    MplsLabel, RouteLwEnCapType, RouteLwTunnelEncap, RouteMplsIpTunnel,
};
use netlink_packet_route::{
    route::{
        RouteAddress, RouteAttribute, RouteFlags, RouteHeader, RouteMessage,
        RouteNextHop, RouteNextHopFlags, RouteProtocol, RouteScope, RouteType,
        RouteVia,
    },
    AddressFamily,
};

#[derive(Debug, Clone)]
pub struct RouteMessageBuilder<T = IpAddr> {
    message: RouteMessage,
    _phantom: PhantomData<T>,
}

#[derive(Debug, Clone)]
pub struct RouteNextHopBuilder {
    address_family: AddressFamily,
    nexthop: RouteNextHop,
}

impl<T> RouteMessageBuilder<T> {
    /// Create default RouteMessage with header set to:
    ///  * route: [RouteHeader::RT_TABLE_MAIN]
    ///  * protocol: [RouteProtocol::Static]
    ///  * scope: [RouteScope::Universe]
    ///  * kind: [RouteType::Unicast]
    ///
    /// For using this message in querying routes, these settings
    /// are ignored unless `NETLINK_GET_STRICT_CHK` been enabled.
    fn new_no_address_family() -> Self {
        let mut message = RouteMessage::default();
        message.header.table = RouteHeader::RT_TABLE_MAIN;
        message.header.protocol = RouteProtocol::Static;
        message.header.scope = RouteScope::Universe;
        message.header.kind = RouteType::Unicast;
        Self {
            message,
            _phantom: Default::default(),
        }
    }

    /// Sets the input interface index.
    pub fn input_interface(mut self, index: u32) -> Self {
        self.message.attributes.push(RouteAttribute::Iif(index));
        self
    }

    /// Sets the output interface index.
    pub fn output_interface(mut self, index: u32) -> Self {
        self.message.attributes.push(RouteAttribute::Oif(index));
        self
    }

    /// Sets the output MPLS encapsulation labels.
    #[cfg(not(target_os = "android"))]
    pub fn output_mpls(mut self, labels: Vec<MplsLabel>) -> Self {
        if labels.is_empty() {
            return self;
        }
        if self.message.header.address_family == AddressFamily::Mpls {
            self.message
                .attributes
                .push(RouteAttribute::NewDestination(labels));
        } else {
            self.message
                .attributes
                .push(RouteAttribute::EncapType(RouteLwEnCapType::Mpls));
            let encap = RouteLwTunnelEncap::Mpls(
                RouteMplsIpTunnel::Destination(labels),
            );
            self.message
                .attributes
                .push(RouteAttribute::Encap(vec![encap]));
        }
        self
    }

    /// Sets multiple nexthop entries for the route.
    pub fn multipath(mut self, nexthops: Vec<RouteNextHop>) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::MultiPath(nexthops));
        self
    }

    /// Sets the route priority (metric)
    pub fn priority(mut self, priority: u32) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::Priority(priority));
        self
    }

    /// Sets the route table ID.
    ///
    /// Default is main route table.
    pub fn table_id(mut self, table: u32) -> Self {
        if table > 255 {
            self.message.attributes.push(RouteAttribute::Table(table));
        } else {
            self.message.header.table = table as u8;
        }
        self
    }

    #[cfg(not(target_os = "android"))]
    /// Sets mark value on route.
    pub fn mark(mut self, mark: u32) -> Self {
        self.message.attributes.push(RouteAttribute::Mark(mark));
        self
    }

    /// Sets the route protocol.
    ///
    /// Default is static route protocol.
    pub fn protocol(mut self, protocol: RouteProtocol) -> Self {
        self.message.header.protocol = protocol;
        self
    }

    /// Sets the route scope.
    ///
    /// Default is universe route scope.
    pub fn scope(mut self, scope: RouteScope) -> Self {
        self.message.header.scope = scope;
        self
    }

    /// Sets the route kind.
    ///
    /// Default is unicast route kind.
    pub fn kind(mut self, kind: RouteType) -> Self {
        self.message.header.kind = kind;
        self
    }

    /// Marks the next hop as directly reachable (on-link).
    ///
    /// Indicates that the next hop is reachable without passing through a
    /// connected subnet.
    pub fn onlink(mut self) -> Self {
        self.message.header.flags.insert(RouteFlags::Onlink);
        self
    }

    /// Return a mutable reference to the request message.
    pub fn get_mut(&mut self) -> &mut RouteMessage {
        &mut self.message
    }

    pub fn build(self) -> RouteMessage {
        self.message
    }
}

impl RouteMessageBuilder<Ipv4Addr> {
    /// Create default RouteMessage with header set to:
    ///  * route: [RouteHeader::RT_TABLE_MAIN]
    ///  * protocol: [RouteProtocol::Static]
    ///  * scope: [RouteScope::Universe]
    ///  * kind: [RouteType::Unicast]
    ///  * address_family: [AddressFamily::Inet4]
    ///
    /// For using this message in querying routes, these settings
    /// are ignored unless `NETLINK_GET_STRICT_CHK` been enabled.
    pub fn new() -> Self {
        let mut builder = Self::new_no_address_family();
        builder.get_mut().header.address_family = AddressFamily::Inet;
        builder
    }

    /// Sets the source address prefix.
    pub fn source_prefix(mut self, addr: Ipv4Addr, prefix_length: u8) -> Self {
        self.message.header.source_prefix_length = prefix_length;
        self.message
            .attributes
            .push(RouteAttribute::Source(RouteAddress::Inet(addr)));
        self
    }

    /// Sets the preferred source address.
    pub fn pref_source(mut self, addr: Ipv4Addr) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::PrefSource(RouteAddress::Inet(addr)));
        self
    }

    /// Sets the destination address prefix.
    pub fn destination_prefix(
        mut self,
        addr: Ipv4Addr,
        prefix_length: u8,
    ) -> Self {
        self.message.header.destination_prefix_length = prefix_length;
        self.message
            .attributes
            .push(RouteAttribute::Destination(RouteAddress::Inet(addr)));
        self
    }

    /// Sets the gateway (via) address.
    pub fn gateway(mut self, addr: Ipv4Addr) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::Gateway(RouteAddress::Inet(addr)));
        self
    }

    /// Sets the IPv6 gateway (via) address.
    pub fn via(mut self, addr: Ipv6Addr) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::Via(RouteVia::Inet6(addr)));
        self
    }
}

impl Default for RouteMessageBuilder<Ipv4Addr> {
    fn default() -> Self {
        Self::new()
    }
}

impl RouteMessageBuilder<Ipv6Addr> {
    /// Create default RouteMessage with header set to:
    ///  * route: [RouteHeader::RT_TABLE_MAIN]
    ///  * protocol: [RouteProtocol::Static]
    ///  * scope: [RouteScope::Universe]
    ///  * kind: [RouteType::Unicast]
    ///  * address_family: [AddressFamily::Inet6]
    ///
    /// For using this message in querying routes, these settings
    /// are ignored unless `NETLINK_GET_STRICT_CHK` been enabled.
    pub fn new() -> Self {
        let mut builder = Self::new_no_address_family();
        builder.get_mut().header.address_family = AddressFamily::Inet6;
        builder
    }

    /// Sets the source address prefix.
    pub fn source_prefix(mut self, addr: Ipv6Addr, prefix_length: u8) -> Self {
        self.message.header.source_prefix_length = prefix_length;
        self.message
            .attributes
            .push(RouteAttribute::Source(RouteAddress::Inet6(addr)));
        self
    }

    /// Sets the preferred source address.
    pub fn pref_source(mut self, addr: Ipv6Addr) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::PrefSource(RouteAddress::Inet6(addr)));
        self
    }

    /// Sets the destination address prefix.
    pub fn destination_prefix(
        mut self,
        addr: Ipv6Addr,
        prefix_length: u8,
    ) -> Self {
        self.message.header.destination_prefix_length = prefix_length;
        self.message
            .attributes
            .push(RouteAttribute::Destination(RouteAddress::Inet6(addr)));
        self
    }

    /// Sets the gateway (via) address.
    pub fn gateway(mut self, addr: Ipv6Addr) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::Gateway(RouteAddress::Inet6(addr)));
        self
    }
}

impl Default for RouteMessageBuilder<Ipv6Addr> {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, thiserror::Error)]
pub enum InvalidRouteMessage {
    #[error("invalid address family {:?}", _0)]
    AddressFamily(AddressFamily),

    #[error("invalid gateway {}", _0)]
    Gateway(IpAddr),

    #[error("invalid preferred source {}", _0)]
    PrefSource(IpAddr),

    #[error("invalid source prefix {}/{}", _0, _1)]
    SourcePrefix(IpAddr, u8),

    #[error("invalid destination prefix {}/{}", _0, _1)]
    DestinationPrefix(IpAddr, u8),
}

impl RouteMessageBuilder<IpAddr> {
    pub fn new() -> Self {
        Self::new_no_address_family()
    }

    /// Sets the source address prefix.
    pub fn source_prefix(
        mut self,
        addr: IpAddr,
        prefix_length: u8,
    ) -> Result<Self, InvalidRouteMessage> {
        self.set_address_family_from_ip_addr(addr);
        match self.message.header.address_family {
            AddressFamily::Inet => {
                if addr.is_ipv6() || prefix_length > 32 {
                    return Err(InvalidRouteMessage::SourcePrefix(
                        addr,
                        prefix_length,
                    ));
                }
            }
            AddressFamily::Inet6 => {
                if addr.is_ipv4() || prefix_length > 128 {
                    return Err(InvalidRouteMessage::SourcePrefix(
                        addr,
                        prefix_length,
                    ));
                }
            }
            af => return Err(InvalidRouteMessage::AddressFamily(af)),
        };
        self.message
            .attributes
            .push(RouteAttribute::Source(addr.into()));
        self.message.header.source_prefix_length = prefix_length;
        Ok(self)
    }

    /// Sets the preferred source address.
    pub fn pref_source(
        mut self,
        addr: IpAddr,
    ) -> Result<Self, InvalidRouteMessage> {
        self.set_address_family_from_ip_addr(addr);
        match self.message.header.address_family {
            AddressFamily::Inet => {
                if addr.is_ipv6() {
                    return Err(InvalidRouteMessage::PrefSource(addr));
                };
            }
            AddressFamily::Inet6 => {
                if addr.is_ipv4() {
                    return Err(InvalidRouteMessage::PrefSource(addr));
                };
            }
            af => {
                return Err(InvalidRouteMessage::AddressFamily(af));
            }
        }
        self.message
            .attributes
            .push(RouteAttribute::PrefSource(addr.into()));
        Ok(self)
    }

    /// Sets the destination address prefix.
    pub fn destination_prefix(
        mut self,
        addr: IpAddr,
        prefix_length: u8,
    ) -> Result<Self, InvalidRouteMessage> {
        self.set_address_family_from_ip_addr(addr);
        match self.message.header.address_family {
            AddressFamily::Inet => {
                if addr.is_ipv6() || prefix_length > 32 {
                    return Err(InvalidRouteMessage::DestinationPrefix(
                        addr,
                        prefix_length,
                    ));
                }
            }
            AddressFamily::Inet6 => {
                if addr.is_ipv4() || prefix_length > 128 {
                    return Err(InvalidRouteMessage::DestinationPrefix(
                        addr,
                        prefix_length,
                    ));
                }
            }
            af => {
                return Err(InvalidRouteMessage::AddressFamily(af));
            }
        };
        self.message.header.destination_prefix_length = prefix_length;
        self.message
            .attributes
            .push(RouteAttribute::Destination(addr.into()));
        Ok(self)
    }

    /// Sets the gateway (via) address.
    pub fn gateway(
        mut self,
        addr: IpAddr,
    ) -> Result<Self, InvalidRouteMessage> {
        let attr = match (self.message.header.address_family, addr) {
            (AddressFamily::Inet, addr @ IpAddr::V4(_))
            | (AddressFamily::Inet6, addr @ IpAddr::V6(_)) => {
                RouteAttribute::Gateway(addr.into())
            }
            (AddressFamily::Inet, IpAddr::V6(v6)) => {
                RouteAttribute::Via(RouteVia::Inet6(v6))
            }
            (af, _) => return Err(InvalidRouteMessage::AddressFamily(af)),
        };
        self.message.attributes.push(attr);
        Ok(self)
    }

    /// If it is not set already, set the address family based on the
    /// given IP address. This is a noop is the address family is
    /// already set.
    fn set_address_family_from_ip_addr(&mut self, addr: IpAddr) {
        if self.message.header.address_family != AddressFamily::Unspec {
            return;
        }
        if addr.is_ipv4() {
            self.message.header.address_family = AddressFamily::Inet;
        } else {
            self.message.header.address_family = AddressFamily::Inet6;
        }
    }
}

impl Default for RouteMessageBuilder<IpAddr> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_os = "android"))]
impl RouteMessageBuilder<MplsLabel> {
    /// Create default RouteMessage with header set to:
    ///  * route: [RouteHeader::RT_TABLE_MAIN]
    ///  * protocol: [RouteProtocol::Static]
    ///  * scope: [RouteScope::Universe]
    ///  * kind: [RouteType::Unicast]
    ///  * address_family: [AddressFamily::Mpls]
    ///
    /// For using this message in querying routes, these settings
    /// are ignored unless `NETLINK_GET_STRICT_CHK` been enabled.
    pub fn new() -> Self {
        let mut builder = Self::new_no_address_family();
        builder.get_mut().header.address_family = AddressFamily::Mpls;
        builder
    }

    #[cfg(not(target_os = "android"))]
    /// Sets the destination MPLS label.
    pub fn label(mut self, label: MplsLabel) -> Self {
        self.message.header.address_family = AddressFamily::Mpls;
        self.message.header.destination_prefix_length = 20;
        self.message
            .attributes
            .push(RouteAttribute::Destination(RouteAddress::Mpls(label)));
        self
    }

    /// Sets the gateway (via) address.
    pub fn via(mut self, addr: IpAddr) -> Self {
        self.message
            .attributes
            .push(RouteAttribute::Via(addr.into()));
        self
    }
}
#[cfg(not(target_os = "android"))]
impl Default for RouteMessageBuilder<MplsLabel> {
    fn default() -> Self {
        Self::new()
    }
}

impl RouteNextHopBuilder {
    /// Create default RouteNexthop for a route with the given address family.
    pub fn new(address_family: AddressFamily) -> Self {
        Self {
            address_family,
            nexthop: Default::default(),
        }
    }

    /// Create IPv4 RouteNexthop
    pub fn new_ipv4() -> Self {
        Self {
            address_family: AddressFamily::Inet,
            nexthop: Default::default(),
        }
    }

    /// Create IPv6 RouteNexthop
    pub fn new_ipv6() -> Self {
        Self {
            address_family: AddressFamily::Inet6,
            nexthop: Default::default(),
        }
    }

    /// Sets the nexthop interface index.
    pub fn interface(mut self, index: u32) -> Self {
        self.nexthop.interface_index = index;
        self
    }

    /// Sets the nexthop (via) address.
    pub fn via(mut self, addr: IpAddr) -> Result<Self, InvalidRouteMessage> {
        let attr = match (self.address_family, addr) {
            (AddressFamily::Inet, addr @ IpAddr::V4(_))
            | (AddressFamily::Inet6, addr @ IpAddr::V6(_)) => {
                RouteAttribute::Gateway(addr.into())
            }
            (AddressFamily::Inet, IpAddr::V6(v6)) => {
                RouteAttribute::Via(RouteVia::Inet6(v6))
            }
            #[cfg(not(target_os = "android"))]
            (AddressFamily::Mpls, _) => RouteAttribute::Via(addr.into()),
            (af, _) => return Err(InvalidRouteMessage::AddressFamily(af)),
        };
        self.nexthop.attributes.push(attr);
        Ok(self)
    }

    /// Marks the nexthop as directly reachable (on-link).
    ///
    /// Indicates that the nexthop is reachable without passing through a
    /// connected subnet.
    pub fn onlink(mut self) -> Self {
        self.nexthop.flags.insert(RouteNextHopFlags::Onlink);
        self
    }

    /// Sets the nexthop MPLS encapsulation labels.
    #[cfg(not(target_os = "android"))]
    pub fn mpls(mut self, labels: Vec<MplsLabel>) -> Self {
        if labels.is_empty() {
            return self;
        }
        if self.address_family == AddressFamily::Mpls {
            self.nexthop
                .attributes
                .push(RouteAttribute::NewDestination(labels));
        } else {
            self.nexthop
                .attributes
                .push(RouteAttribute::EncapType(RouteLwEnCapType::Mpls));
            let encap = RouteLwTunnelEncap::Mpls(
                RouteMplsIpTunnel::Destination(labels),
            );
            self.nexthop
                .attributes
                .push(RouteAttribute::Encap(vec![encap]));
        }
        self
    }

    /// Set the nexthop weight
    ///
    /// Equal to `weight` property in `ip route`, but please be advised the
    /// number shown in `ip route` command has plus 1. Meaning kernel has
    /// `weight 0`, but `ip route` shows as `weight 1`. This function is using
    /// kernel number from range of 0 to 255.
    pub fn weight(mut self, weight: u8) -> Self {
        self.nexthop.hops = weight;
        self
    }

    /// Set flags for next hop
    pub fn flags(mut self, flags: RouteNextHopFlags) -> Self {
        self.nexthop.flags = flags;
        self
    }

    pub fn build(self) -> RouteNextHop {
        self.nexthop
    }
}