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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! This module provides an implementation of routing netlink structures and the routing attributes
//! that are at the end of most routing netlink responses.
//!
//! # Design decisions
//!
//! This module is based very heavily on the information in `man 7 rtnetlink` so it is mainly a
//! series of structs organized in a style similar to the rest of the library with implementations
//! of `Nl` for each.

use std::mem;

use buffering::copy::{StreamReadBuffer, StreamWriteBuffer};
use libc;

use crate::{
    consts::rtnl::*,
    err::{DeError, SerError},
    Nl,
};

impl<T, P> Nl for Vec<Rtattr<T, P>>
where
    T: RtaType,
    P: Nl,
{
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        for item in self.iter() {
            item.serialize(buf)?;
        }
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        let mut size_hint = buf
            .take_size_hint()
            .ok_or_else(|| DeError::new("Vec of Rtattr requires a size hint to deserialize"))?;
        let mut vec = Vec::new();
        while size_hint > 0 {
            let attr: Rtattr<T, P> = Rtattr::deserialize(buf)?;
            size_hint = size_hint.checked_sub(attr.asize()).ok_or_else(|| {
                DeError::new(&format!(
                    "Rtattr size {} overflowed buffer size {}",
                    attr.size(),
                    size_hint
                ))
            })?;
            vec.push(attr);
        }
        Ok(vec)
    }

    fn size(&self) -> usize {
        self.iter().fold(0, |acc, item| acc + item.asize())
    }
}

/// Struct representing interface information messages
pub struct Ifinfomsg<T> {
    /// Interface address family
    pub ifi_family: RtAddrFamily,
    /// Interface type
    pub ifi_type: Arphrd,
    /// Interface index
    pub ifi_index: libc::c_int,
    /// Interface flags
    pub ifi_flags: Vec<Iff>,
    ifi_change: libc::c_uint,
    /// Payload of `Rtattr`s
    pub rtattrs: Vec<Rtattr<T, Vec<u8>>>,
}

impl<T> Ifinfomsg<T>
where
    T: RtaType,
{
    /// Create a fully initialized interface info struct
    pub fn new(
        ifi_family: RtAddrFamily,
        ifi_type: Arphrd,
        ifi_index: libc::c_int,
        ifi_flags: Vec<Iff>,
        rtattrs: Vec<Rtattr<T, Vec<u8>>>,
    ) -> Self {
        Ifinfomsg {
            ifi_family,
            ifi_type,
            ifi_index,
            ifi_flags,
            ifi_change: 0xffff_ffff,
            rtattrs,
        }
    }
}

impl<T> Nl for Ifinfomsg<T>
where
    T: RtaType,
{
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.ifi_family.serialize(buf)?;
        0u8.serialize(buf)?; // padding
        self.ifi_type.serialize(buf)?;
        self.ifi_index.serialize(buf)?;
        self.ifi_flags
            .iter()
            .fold(0, |acc: libc::c_uint, next| {
                let next_uint: libc::c_uint = next.into();
                acc | next_uint
            })
            .serialize(buf)?;
        self.ifi_change.serialize(buf)?;
        self.rtattrs.serialize(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        let mut size_hint = buf
            .take_size_hint()
            .ok_or_else(|| DeError::new("Ifinfomsg requires a size hint to deserialize"))?;
        let ifi_family = RtAddrFamily::deserialize(buf)?;
        let padding = u8::deserialize(buf)?;
        let ifi_type = Arphrd::deserialize(buf)?;
        let ifi_index = libc::c_int::deserialize(buf)?;
        let ifi_flags = {
            let flags = libc::c_uint::deserialize(buf)?;
            let mut nl_flags = Vec::new();
            for i in 0..mem::size_of::<libc::c_int>() * 8 {
                let bit = 1 << i;
                if bit & flags == bit {
                    nl_flags.push(bit.into());
                }
            }
            nl_flags
        };
        let ifi_change = libc::c_uint::deserialize(buf)?;

        size_hint = size_hint
            .checked_sub(
                ifi_family.size()
                    + padding.size()
                    + ifi_type.size()
                    + ifi_index.size()
                    + mem::size_of::<libc::c_int>()
                    + ifi_change.size(),
            )
            .ok_or_else(|| DeError::new(&format!("Truncated Ifinfomsg size_hint {}", size_hint)))?;
        buf.set_size_hint(size_hint);
        let rtattrs = Vec::<Rtattr<T, Vec<u8>>>::deserialize(buf)?;

        Ok(Ifinfomsg {
            ifi_family,
            ifi_type,
            ifi_index,
            ifi_flags,
            ifi_change,
            rtattrs,
        })
    }

    fn size(&self) -> usize {
        self.ifi_family.size() +
        // padding byte
        0u8.size() +
        self.ifi_type.size() + self.ifi_index.size() +
        // flags
        mem::size_of::<libc::c_uint>() +
        self.ifi_change.size() +
        self.rtattrs.asize()
    }
}

/// Struct representing interface address messages
pub struct Ifaddrmsg<T> {
    /// Interface address family
    pub ifa_family: RtAddrFamily,
    /// Interface address prefix length
    pub ifa_prefixlen: libc::c_uchar,
    /// Interface address flags
    pub ifa_flags: Vec<IfaF>,
    /// Interface address scope
    pub ifa_scope: libc::c_uchar,
    /// Interface address index
    pub ifa_index: libc::c_int,
    /// Payload of `Rtattr`s
    pub rtattrs: Vec<Rtattr<T, Vec<u8>>>,
}

impl<T> Nl for Ifaddrmsg<T>
where
    T: RtaType,
{
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.ifa_family.serialize(buf)?;
        self.ifa_prefixlen.serialize(buf)?;
        self.ifa_flags
            .iter()
            .fold(0u8, |acc: libc::c_uchar, next| {
                let next_uint: u8 = u32::from(next) as u8;
                acc | next_uint as libc::c_uchar
            })
            .serialize(buf)?;
        self.ifa_scope.serialize(buf)?;
        self.ifa_index.serialize(buf)?;
        self.rtattrs.serialize(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        let mut result = Ifaddrmsg {
            ifa_family: RtAddrFamily::deserialize(buf)?,
            ifa_prefixlen: libc::c_uchar::deserialize(buf)?,
            ifa_flags: {
                let flags = libc::c_uchar::deserialize(buf)?;
                let mut nl_flags = Vec::new();
                for i in 0..mem::size_of::<libc::c_uchar>() * 8 {
                    let bit = 1 << i;
                    if bit & flags == bit {
                        nl_flags.push((u32::from(bit)).into());
                    }
                }
                nl_flags
            },
            ifa_scope: libc::c_uchar::deserialize(buf)?,
            ifa_index: libc::c_int::deserialize(buf)?,
            rtattrs: vec![],
        };

        let size_hint = buf
            .take_size_hint()
            .ok_or_else(|| DeError::new("Ifinfomsg requires a size hint to deserialize"))?
            - result.asize();
        buf.set_size_hint(size_hint);

        result.rtattrs = Vec::deserialize(buf)?;
        Ok(result)
    }

    fn size(&self) -> usize {
        self.ifa_family.size()
            + self.ifa_prefixlen.size()
            + mem::size_of::<libc::c_uchar>()
            + self.ifa_scope.size()
            + self.ifa_index.size()
    }
}

/// General form of address family dependent message.  Used for requesting things from via rtnetlink.
pub struct Rtgenmsg {
    /// Address family for the request
    pub rtgen_family: RtAddrFamily,
}

impl Nl for Rtgenmsg {
    fn serialize(&self, m: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.rtgen_family.serialize(m)
    }

    fn deserialize<T>(m: &mut StreamReadBuffer<T>) -> Result<Self, DeError>
    where
        T: AsRef<[u8]>,
    {
        Ok(Self {
            rtgen_family: RtAddrFamily::deserialize(m)?,
        })
    }

    fn size(&self) -> usize {
        self.rtgen_family.size()
    }
}

/// Route message
pub struct Rtmsg<T> {
    /// Address family of route
    pub rtm_family: RtAddrFamily,
    /// Length of destination
    pub rtm_dst_len: libc::c_uchar,
    /// Length of source
    pub rtm_src_len: libc::c_uchar,
    /// TOS filter
    pub rtm_tos: libc::c_uchar,
    /// Routing table ID
    pub rtm_table: RtTable,
    /// Routing protocol
    pub rtm_protocol: Rtprot,
    /// Routing scope
    pub rtm_scope: RtScope,
    /// Routing type
    pub rtm_type: Rtn,
    /// Routing flags
    pub rtm_flags: Vec<RtmF>,
    /// Payload of `Rtattr`s
    pub rtattrs: Vec<Rtattr<T, Vec<u8>>>,
}

impl<T> Nl for Rtmsg<T>
where
    T: RtaType,
{
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.rtm_family.serialize(buf)?;
        self.rtm_dst_len.serialize(buf)?;
        self.rtm_src_len.serialize(buf)?;
        self.rtm_tos.serialize(buf)?;
        self.rtm_table.serialize(buf)?;
        self.rtm_protocol.serialize(buf)?;
        self.rtm_scope.serialize(buf)?;
        self.rtm_type.serialize(buf)?;
        self.rtm_flags
            .iter()
            .fold(0, |acc: libc::c_uint, next| {
                let next_uint: libc::c_uint = next.into();
                acc | next_uint
            })
            .serialize(buf)?;
        self.rtattrs.serialize(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        let size_hint = buf
            .take_size_hint()
            .ok_or_else(|| DeError::new("Must provide size hint to deserialize Rtmsg"))?;

        let rtm_family = RtAddrFamily::deserialize(buf)?;
        let rtm_dst_len = libc::c_uchar::deserialize(buf)?;
        let rtm_src_len = libc::c_uchar::deserialize(buf)?;
        let rtm_tos = libc::c_uchar::deserialize(buf)?;
        let rtm_table = RtTable::deserialize(buf)?;
        let rtm_protocol = Rtprot::deserialize(buf)?;
        let rtm_scope = RtScope::deserialize(buf)?;
        let rtm_type = Rtn::deserialize(buf)?;
        let rtm_flags = {
            let flags = libc::c_int::deserialize(buf)?;
            let mut rtm_flags = Vec::new();
            for i in 0..mem::size_of::<libc::c_uint>() * 8 {
                let bit = 1 << i;
                if bit & flags == bit {
                    rtm_flags.push((bit as libc::c_uint).into());
                }
            }
            rtm_flags
        };

        buf.set_size_hint(
            size_hint
                - rtm_family.size()
                - rtm_dst_len.size()
                - rtm_src_len.size()
                - rtm_tos.size()
                - rtm_table.size()
                - rtm_protocol.size()
                - rtm_scope.size()
                - rtm_type.size()
                - mem::size_of::<libc::c_int>(),
        );
        let rtattrs = Vec::<Rtattr<T, Vec<u8>>>::deserialize(buf)?;

        Ok(Rtmsg {
            rtm_family,
            rtm_dst_len,
            rtm_src_len,
            rtm_tos,
            rtm_table,
            rtm_protocol,
            rtm_scope,
            rtm_type,
            rtm_flags,
            rtattrs,
        })
    }

    fn size(&self) -> usize {
        self.rtm_family.size()
            + self.rtm_dst_len.size()
            + self.rtm_src_len.size()
            + self.rtm_tos.size()
            + self.rtm_table.size()
            + self.rtm_protocol.size()
            + self.rtm_scope.size()
            + self.rtm_type.size()
            + mem::size_of::<libc::c_uint>()
            + self.rtattrs.asize()
    }
}

/// Represents an ARP (neighbor table) entry
pub struct Ndmsg {
    /// Address family of entry
    pub ndm_family: RtAddrFamily,
    /// Index of entry
    pub ndm_index: libc::c_int,
    /// State of entry
    pub ndm_state: Vec<Nud>,
    /// Flags for entry
    pub ndm_flags: Vec<Ntf>,
    /// Type of entry
    pub ndm_type: Rtn,
}

impl Nl for Ndmsg {
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.ndm_family.serialize(buf)?;
        self.ndm_index.serialize(buf)?;
        self.ndm_state
            .iter()
            .fold(0, |acc: u16, next| {
                let next_uint: u16 = next.into();
                acc | next_uint
            })
            .serialize(buf)?;
        self.ndm_flags
            .iter()
            .fold(0, |acc: u8, next| {
                let next_uint: u8 = next.into();
                acc | next_uint
            })
            .serialize(buf)?;
        self.ndm_type.serialize(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        Ok(Ndmsg {
            ndm_family: RtAddrFamily::deserialize(buf)?,
            ndm_index: libc::c_int::deserialize(buf)?,
            ndm_state: {
                let state = u16::deserialize(buf)?;
                let mut ndm_state = Vec::new();
                for i in 0..mem::size_of::<u16>() * 8 {
                    let bit = 1 << i;
                    if bit & state == bit {
                        ndm_state.push((bit as u16).into());
                    }
                }
                ndm_state
            },
            ndm_flags: {
                let flags = u8::deserialize(buf)?;
                let mut ndm_flags = Vec::new();
                for i in 0..mem::size_of::<u8>() * 8 {
                    let bit = 1 << i;
                    if bit & flags == bit {
                        ndm_flags.push((bit as u8).into());
                    }
                }
                ndm_flags
            },
            ndm_type: Rtn::deserialize(buf)?,
        })
    }

    fn size(&self) -> usize {
        self.ndm_family.size()
            + self.ndm_index.size()
            + mem::size_of::<u16>()
            + mem::size_of::<u8>()
            + self.ndm_type.size()
    }
}

/// Struct representing ARP cache info
pub struct NdaCacheinfo {
    /// Confirmed
    pub ndm_confirmed: u32,
    /// Used
    pub ndm_used: u32,
    /// Updated
    pub ndm_updated: u32,
    /// Reference count
    pub ndm_refcnt: u32,
}

impl Nl for NdaCacheinfo {
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.ndm_confirmed.serialize(buf)?;
        self.ndm_used.serialize(buf)?;
        self.ndm_updated.serialize(buf)?;
        self.ndm_refcnt.serialize(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        Ok(NdaCacheinfo {
            ndm_confirmed: u32::deserialize(buf)?,
            ndm_used: u32::deserialize(buf)?,
            ndm_updated: u32::deserialize(buf)?,
            ndm_refcnt: u32::deserialize(buf)?,
        })
    }

    fn size(&self) -> usize {
        self.ndm_confirmed.size()
            + self.ndm_used.size()
            + self.ndm_updated.size()
            + self.ndm_refcnt.size()
    }
}

/// Message in response to queuing discipline operations
pub struct Tcmsg<T> {
    /// Family
    pub tcm_family: libc::c_uchar,
    /// Interface index
    pub tcm_ifindex: libc::c_int,
    /// Queuing discipline handle
    pub tcm_handle: u32,
    /// Parent queuing discipline
    pub tcm_parent: u32,
    /// Info
    pub tcm_info: u32,
    /// Payload of `Rtattr`s
    pub rtattrs: Vec<Rtattr<T, Vec<u8>>>,
}

impl<T> Nl for Tcmsg<T>
where
    T: RtaType,
{
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.tcm_family.serialize(buf)?;
        self.tcm_ifindex.serialize(buf)?;
        self.tcm_handle.serialize(buf)?;
        self.tcm_parent.serialize(buf)?;
        self.tcm_info.serialize(buf)?;
        self.rtattrs.serialize(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        Ok(Tcmsg {
            tcm_family: libc::c_uchar::deserialize(buf)?,
            tcm_ifindex: libc::c_int::deserialize(buf)?,
            tcm_handle: u32::deserialize(buf)?,
            tcm_parent: u32::deserialize(buf)?,
            tcm_info: u32::deserialize(buf)?,
            rtattrs: Vec::<Rtattr<T, Vec<u8>>>::deserialize(buf)?,
        })
    }

    fn size(&self) -> usize {
        self.tcm_family.size()
            + self.tcm_ifindex.size()
            + self.tcm_handle.size()
            + self.tcm_parent.size()
            + self.tcm_info.size()
    }
}

/// Struct representing route netlink attributes
pub struct Rtattr<T, P> {
    /// Length of the attribute
    pub rta_len: libc::c_ushort,
    /// Type of the attribute
    pub rta_type: T,
    /// Payload of the attribute
    pub rta_payload: P,
}

impl<T, P> Rtattr<T, P>
where
    T: RtaType,
    P: Nl,
{
    /// Get the size of the payload only
    pub fn payload_size(&self) -> usize {
        self.rta_payload.size()
    }
}

impl<T, P> Nl for Rtattr<T, P>
where
    T: RtaType,
    P: Nl,
{
    fn serialize(&self, buf: &mut StreamWriteBuffer) -> Result<(), SerError> {
        self.rta_len.serialize(buf)?;
        self.rta_type.serialize(buf)?;
        self.rta_payload.serialize(buf)?;
        self.pad(buf)?;
        Ok(())
    }

    fn deserialize<B>(buf: &mut StreamReadBuffer<B>) -> Result<Self, DeError>
    where
        B: AsRef<[u8]>,
    {
        let rta_len = libc::c_ushort::deserialize(buf)?;
        let rta_type = T::deserialize(buf)?;
        buf.set_size_hint(
            (rta_len as usize)
                .checked_sub(rta_len.size() + rta_type.size())
                .ok_or_else(|| {
                    DeError::new(&format!("Invalid size while reading Rtattr: {}", rta_len))
                })?,
        );
        let rta_payload = P::deserialize(buf)?;
        let rtattr = Rtattr {
            rta_len,
            rta_type,
            rta_payload,
        };
        rtattr.strip(buf)?;
        Ok(rtattr)
    }

    fn size(&self) -> usize {
        self.rta_len.size() + self.rta_type.size() + self.rta_payload.size()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::consts::Rta;

    #[test]
    fn test_rta_deserialize() {
        let mut buf = StreamReadBuffer::new(&[4u8, 0, 0, 0]);
        assert!(Rtattr::<Rta, Vec<u8>>::deserialize(&mut buf).is_ok());
    }

    #[test]
    fn test_rta_deserialize_err() {
        // 3 bytes is below minimum length
        let mut buf = StreamReadBuffer::new(&[3u8, 0, 0, 0]);
        assert!(Rtattr::<Rta, Vec<u8>>::deserialize(&mut buf).is_err());
    }

    #[test]
    fn test_rtattr_deserialize_padding() {
        let mut buf = StreamReadBuffer::new(&[5u8, 0, 0, 0, 0, 0, 0, 0, 111]);
        assert!(Rtattr::<Rta, Vec<u8>>::deserialize(&mut buf).is_ok());
        // should have stripped remainder of word
        assert_eq!(u8::deserialize(&mut buf).unwrap(), 111);
    }

    #[test]
    fn test_rtattr_padding() {
        let attr = Rtattr {
            rta_len: 5,
            rta_type: Rta::Unspec,
            rta_payload: vec![0u8],
        };
        let mut buf = StreamWriteBuffer::new_growable(None);

        assert!(attr.serialize(&mut buf).is_ok());
        // padding check
        assert_eq!(buf.as_ref().len(), 8);
    }
}