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

use std::collections::{hash_map::Entry, HashMap, HashSet};

use log::{debug, error};
use serde::{Deserialize, Serialize};

use crate::{
    ip::{is_ipv6_addr, sanitize_ip_network},
    ErrorKind, NmstateError,
};

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
/// IP routing status
pub struct Routes {
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Running effected routes containing route from universe or link scope,
    /// and only from these protocols:
    ///  * boot (often used by `iproute` command)
    ///  * static
    ///  * ra
    ///  * dhcp
    ///  * mrouted
    ///  * keepalived
    ///  * babel
    ///
    /// Ignored when applying.
    pub running: Option<Vec<RouteEntry>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Static routes containing route from universe or link scope,
    /// and only from these protocols:
    ///  * boot (often used by `iproute` command)
    ///  * static
    ///
    /// When applying, `None` means preserve current routes.
    /// This property is not overriding but adding specified routes to
    /// existing routes. To delete a route entry, please [RouteEntry.state] as
    /// [RouteState::Absent]. Any property of absent [RouteEntry] set to
    /// `None` means wildcard. For example, this [crate::NetworkState] could
    /// remove all routes next hop to interface eth1(showing in yaml):
    /// ```yaml
    /// routes:
    ///   config:
    ///   - next-hop-interface: eth1
    ///     state: absent
    /// ```
    ///
    /// To change a route entry, you need to delete old one and add new one(can
    /// be in single transaction).
    pub config: Option<Vec<RouteEntry>>,
}

impl Routes {
    pub fn new() -> Self {
        Self::default()
    }

    /// TODO: hide it, internal only
    pub fn is_empty(&self) -> bool {
        self.running.is_none() && self.config.is_none()
    }

    pub fn validate(&self) -> Result<(), NmstateError> {
        // All desire non-absent route should have next hop interface
        if let Some(config_routes) = self.config.as_ref() {
            for route in config_routes.iter().filter(|r| !r.is_absent()) {
                if route.next_hop_iface.is_none() {
                    let e = NmstateError::new(
                        ErrorKind::NotImplementedError,
                        format!(
                            "Route with empty next hop interface \
                        is not supported: {:?}",
                            route
                        ),
                    );
                    error!("{}", e);
                    return Err(e);
                }
            }
        }
        Ok(())
    }

    // RouteEntry been added/removed from specific interface, all(including
    // desire and current) its routes will be included in return hash.
    // Steps:
    //  1. Find out all interface with desired add routes.
    //  2. Find out all interface impacted by desired absent routes.
    //  3. Copy all routes from current which are to changed interface.
    //  4. Remove routes base on absent.
    //  5. Add routes in desire.
    //  6. Sort and remove duplicate route.
    pub(crate) fn gen_changed_ifaces_and_routes(
        &self,
        current: &Self,
    ) -> Result<HashMap<String, Vec<RouteEntry>>, NmstateError> {
        let mut ret: HashMap<String, Vec<RouteEntry>> = HashMap::new();
        let mut desired_routes = Vec::new();
        if let Some(rts) = self.config.as_ref() {
            for rt in rts {
                let mut rt = rt.clone();
                rt.sanitize()?;
                desired_routes.push(rt);
            }
        }
        let des_routes_index =
            create_route_index_by_iface(desired_routes.as_slice());
        let cur_routes_index = current
            .config
            .as_ref()
            .map(|c| create_route_index_by_iface(c.as_slice()))
            .unwrap_or_default();

        let mut iface_names_in_desire: HashSet<&str> =
            des_routes_index.keys().copied().collect();

        // Convert the absent route without iface to multiple routes with
        // iface define.
        let absent_routes = flat_absent_route(
            self.config.as_deref().unwrap_or(&[]),
            current.config.as_deref().unwrap_or(&[]),
        );

        // Include interface which will be impacted by absent routes
        for absent_route in &absent_routes {
            if let Some(i) = absent_route.next_hop_iface.as_ref() {
                debug!(
                    "Interface is impacted by absent route {:?}",
                    absent_route
                );
                iface_names_in_desire.insert(i);
            }
        }

        // Copy current routes next hop to changed interfaces
        for iface_name in &iface_names_in_desire {
            if let Some(cur_routes) = cur_routes_index.get(iface_name) {
                ret.insert(
                    iface_name.to_string(),
                    cur_routes
                        .as_slice()
                        .iter()
                        .map(|r| (*r).clone())
                        .collect::<Vec<RouteEntry>>(),
                );
            }
        }

        // Apply absent routes
        for absent_route in &absent_routes {
            // All absent_route should have interface name here
            if let Some(iface_name) = absent_route.next_hop_iface.as_ref() {
                if let Some(routes) = ret.get_mut(iface_name) {
                    routes.retain(|r| !absent_route.is_match(r));
                }
            }
        }

        // Append desire routes
        for (iface_name, desire_routes) in des_routes_index.iter() {
            let new_routes = desire_routes
                .iter()
                .map(|r| (*r).clone())
                .collect::<Vec<RouteEntry>>();
            match ret.entry(iface_name.to_string()) {
                Entry::Occupied(o) => {
                    o.into_mut().extend(new_routes);
                }
                Entry::Vacant(v) => {
                    v.insert(new_routes);
                }
            };
        }

        // Sort and remove the duplicated routes
        for desire_routes in ret.values_mut() {
            desire_routes.sort_unstable();
            desire_routes.dedup();
        }
        Ok(ret)
    }

    pub(crate) fn get_config_routes_of_iface(
        &self,
        iface_name: &str,
    ) -> Option<Vec<RouteEntry>> {
        self.config.as_ref().map(|rts| {
            rts.iter()
                .filter(|r| r.next_hop_iface.as_deref() == Some(iface_name))
                .cloned()
                .collect()
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum RouteState {
    /// Mark a route entry as absent to remove it.
    Absent,
}

impl Default for RouteState {
    fn default() -> Self {
        Self::Absent
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
#[serde(deny_unknown_fields)]
/// Route entry
pub struct RouteEntry {
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Only used for delete route when applying.
    pub state: Option<RouteState>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Route destination address or network
    pub destination: Option<String>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "next-hop-interface"
    )]
    /// Route next hop interface name.
    /// Serialize and deserialize to/from `next-hop-interface`.
    pub next_hop_iface: Option<String>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "next-hop-address"
    )]
    /// Route next hop IP address.
    /// Serialize and deserialize to/from `next-hop-address`.
    pub next_hop_addr: Option<String>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        deserialize_with = "crate::deserializer::option_i64_or_string"
    )]
    /// Route metric. [RouteEntry::USE_DEFAULT_METRIC] for default
    /// setting of network backend.
    pub metric: Option<i64>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        deserialize_with = "crate::deserializer::option_u32_or_string"
    )]
    /// Route table id. [RouteEntry::USE_DEFAULT_ROUTE_TABLE] for main
    /// route table 254.
    pub table_id: Option<u32>,
}

impl RouteEntry {
    pub const USE_DEFAULT_METRIC: i64 = -1;
    pub const USE_DEFAULT_ROUTE_TABLE: u32 = 0;

    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn is_absent(&self) -> bool {
        matches!(self.state, Some(RouteState::Absent))
    }

    pub(crate) fn is_match(&self, other: &Self) -> bool {
        if self.destination.as_ref().is_some()
            && self.destination != other.destination
        {
            return false;
        }
        if self.next_hop_iface.as_ref().is_some()
            && self.next_hop_iface != other.next_hop_iface
        {
            return false;
        }

        if self.next_hop_addr.as_ref().is_some()
            && self.next_hop_addr != other.next_hop_addr
        {
            return false;
        }
        if self.table_id.is_some()
            && self.table_id != Some(RouteEntry::USE_DEFAULT_ROUTE_TABLE)
            && self.table_id != other.table_id
        {
            return false;
        }
        true
    }

    // Return tuple of (no_absent, is_ipv4, table_id, next_hop_iface,
    // destination, next_hop_addr)
    fn sort_key(&self) -> (bool, bool, u32, &str, &str, &str) {
        (
            !matches!(self.state, Some(RouteState::Absent)),
            !self
                .destination
                .as_ref()
                .map(|d| is_ipv6_addr(d.as_str()))
                .unwrap_or_default(),
            self.table_id.unwrap_or(RouteEntry::USE_DEFAULT_ROUTE_TABLE),
            self.next_hop_iface.as_deref().unwrap_or(""),
            self.destination.as_deref().unwrap_or(""),
            self.next_hop_addr.as_deref().unwrap_or(""),
        )
    }

    pub(crate) fn sanitize(&mut self) -> Result<(), NmstateError> {
        if let Some(dst) = self.destination.as_ref() {
            let new_dst = sanitize_ip_network(dst)?;
            if dst != &new_dst {
                log::warn!(
                    "Route destination {} sanitized to {}",
                    dst,
                    new_dst
                );
                self.destination = Some(new_dst);
            }
        }
        if let Some(via) = self.next_hop_addr.as_ref() {
            let new_via = format!("{}", via.parse::<std::net::IpAddr>()?);
            if via != &new_via {
                log::warn!(
                    "Route next-hop-address {} sanitized to {}",
                    via,
                    new_via
                );
                self.next_hop_addr = Some(new_via);
            }
        }
        Ok(())
    }
}

// For Vec::dedup()
impl PartialEq for RouteEntry {
    fn eq(&self, other: &Self) -> bool {
        self.sort_key() == other.sort_key()
    }
}

// For Vec::sort_unstable()
impl Ord for RouteEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.sort_key().cmp(&other.sort_key())
    }
}

// For ord
impl Eq for RouteEntry {}

// For ord
impl PartialOrd for RouteEntry {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

// Absent route will be ignored
fn create_route_index_by_iface(
    routes: &[RouteEntry],
) -> HashMap<&str, Vec<&RouteEntry>> {
    let mut ret: HashMap<&str, Vec<&RouteEntry>> = HashMap::new();
    for route in routes {
        if route.is_absent() {
            continue;
        }
        let next_hop_iface = route.next_hop_iface.as_deref().unwrap_or("");
        match ret.entry(next_hop_iface) {
            Entry::Occupied(o) => {
                o.into_mut().push(route);
            }
            Entry::Vacant(v) => {
                v.insert(vec![route]);
            }
        };
    }
    ret
}

// All the routes sending to this function has no interface defined.
fn flat_absent_route(
    desire_routes: &[RouteEntry],
    cur_routes: &[RouteEntry],
) -> Vec<RouteEntry> {
    let mut ret: Vec<RouteEntry> = Vec::new();
    for absent_route in desire_routes.iter().filter(|r| r.is_absent()) {
        if absent_route.next_hop_iface.is_none() {
            for cur_route in cur_routes {
                if absent_route.is_match(cur_route) {
                    let mut new_absent_route = absent_route.clone();
                    new_absent_route.next_hop_iface =
                        cur_route.next_hop_iface.as_ref().cloned();
                    ret.push(new_absent_route);
                }
            }
        } else {
            ret.push(absent_route.clone());
        }
    }
    ret
}