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
// SPDX-License-Identifier: MIT

/// Nat action
///
/// The nat action maps one IP prefix to another
use std::net::Ipv4Addr;

use netlink_packet_utils::{
    nla::{DefaultNla, Nla, NlaBuffer},
    traits::{Emitable, Parseable},
    DecodeError,
};

use super::{nat_flag::TcNatFlags, TcActionGeneric, TcActionGenericBuffer};

const TCA_NAT_PARMS: u16 = 1;
const TCA_NAT_TM: u16 = 2;

/// Network address translation action.
#[derive(Debug, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub struct TcActionNat {}

impl TcActionNat {
    pub(crate) const KIND: &'static str = "nat";
}

/// Options for the [`TcActionNat`] action.
#[derive(Debug, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub enum TcActionNatOption {
    /// TODO: document this after we make it something better than `Vec<u8>`
    Tm(Vec<u8>),
    /// Parameters for the nat action.
    Parms(TcNat),
    /// Other attributes unknown at the time of writing.
    Other(DefaultNla),
}

impl Nla for TcActionNatOption {
    fn value_len(&self) -> usize {
        match self {
            Self::Tm(bytes) => bytes.len(),
            Self::Parms(v) => v.buffer_len(),
            Self::Other(attr) => attr.value_len(),
        }
    }

    fn emit_value(&self, buffer: &mut [u8]) {
        match self {
            Self::Tm(bytes) => buffer.copy_from_slice(bytes.as_slice()),
            Self::Parms(p) => p.emit(buffer),
            Self::Other(attr) => attr.emit_value(buffer),
        }
    }
    fn kind(&self) -> u16 {
        match self {
            Self::Tm(_) => TCA_NAT_TM,
            Self::Parms(_) => TCA_NAT_PARMS,
            Self::Other(nla) => nla.kind(),
        }
    }
}

impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<NlaBuffer<&'a T>>
    for TcActionNatOption
{
    fn parse(buf: &NlaBuffer<&'a T>) -> Result<Self, DecodeError> {
        let payload = buf.value();
        Ok(match buf.kind() {
            TCA_NAT_TM => Self::Tm(payload.to_vec()),
            TCA_NAT_PARMS => {
                Self::Parms(TcNat::parse(&TcNatBuffer::new_checked(payload)?)?)
            }
            _ => Self::Other(DefaultNla::parse(buf)?),
        })
    }
}

const TC_NAT_BUF_LEN: usize = TcActionGeneric::BUF_LEN + 16;

/// Network address translation action.
#[derive(Debug, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub struct TcNat {
    /// Common attributes for all actions.
    pub generic: TcActionGeneric,
    /// Original address.
    pub old_addr: Ipv4Addr,
    /// New address.
    pub new_addr: Ipv4Addr,
    /// Mask of the old address
    pub mask: Ipv4Addr,
    /// Flags for the NAT action.
    pub flags: TcNatFlags,
}

impl Default for TcNat {
    fn default() -> Self {
        Self {
            generic: TcActionGeneric::default(),
            old_addr: Ipv4Addr::UNSPECIFIED,
            new_addr: Ipv4Addr::UNSPECIFIED,
            mask: Ipv4Addr::UNSPECIFIED,
            flags: TcNatFlags::empty(),
        }
    }
}

buffer!(TcNatBuffer(TC_NAT_BUF_LEN) {
    generic: (slice, 0..TcActionGeneric::BUF_LEN),
    old_addr: (slice, TcActionGeneric::BUF_LEN..(TcActionGeneric::BUF_LEN+4)),
    new_addr: (slice, (TcActionGeneric::BUF_LEN+4)..(TcActionGeneric::BUF_LEN+8)),
    mask: (slice, (TcActionGeneric::BUF_LEN+8)..(TcActionGeneric::BUF_LEN+12)),
    flags: (u32, (TcActionGeneric::BUF_LEN+12)..TC_NAT_BUF_LEN),
});

impl Emitable for TcNat {
    fn buffer_len(&self) -> usize {
        TC_NAT_BUF_LEN
    }

    fn emit(&self, buffer: &mut [u8]) {
        let mut packet = TcNatBuffer::new(buffer);
        self.generic.emit(packet.generic_mut());
        packet
            .old_addr_mut()
            .copy_from_slice(&self.old_addr.octets());
        packet
            .new_addr_mut()
            .copy_from_slice(&self.new_addr.octets());
        packet.mask_mut().copy_from_slice(&self.mask.octets());
        packet.set_flags(self.flags.bits());
    }
}

impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<TcNatBuffer<&'a T>> for TcNat {
    fn parse(buf: &TcNatBuffer<&T>) -> Result<Self, DecodeError> {
        Ok(Self {
            generic: TcActionGeneric::parse(&TcActionGenericBuffer::new(
                buf.generic(),
            ))?,
            old_addr: parse_ipv4(buf.old_addr())?,
            new_addr: parse_ipv4(buf.new_addr())?,
            mask: parse_ipv4(buf.mask())?,
            flags: TcNatFlags::from_bits_retain(buf.flags()),
        })
    }
}

fn parse_ipv4(data: &[u8]) -> Result<Ipv4Addr, DecodeError> {
    if data.len() != 4 {
        Err(DecodeError::from(format!(
            "Invalid length of IPv4 Address, expecting 4 bytes, but got {:?}",
            data
        )))
    } else {
        Ok(Ipv4Addr::new(data[0], data[1], data[2], data[3]))
    }
}