interface-rs 0.3.0

Library for reading and writing Linux interfaces(5) files
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
use crate::error::ParserError;
use crate::interface::{Family, Interface, InterfaceOption, Method};
use std::collections::HashMap;

/// A parser for an `interfaces(5)` file.
///
/// The `Parser` struct provides methods to parse the content of the interfaces file
/// and produce a collection of `Interface` instances.
pub struct Parser;

type ParseResult = Result<(HashMap<String, Interface>, Vec<String>, Vec<String>), ParserError>;

impl Default for Parser {
    fn default() -> Self {
        Self::new()
    }
}

impl Parser {
    /// Creates a new `Parser` instance.
    pub fn new() -> Self {
        Parser
    }

    /// Parses the content of the interfaces file.
    ///
    /// # Arguments
    ///
    /// * `content` - A string slice containing the file content.
    ///
    /// # Returns
    ///
    /// A `Result` containing a tuple `(interfaces, comments, sources)` if successful,
    /// or a `ParserError` if parsing fails.
    pub fn parse(&self, content: &str) -> ParseResult {
        let mut interfaces = HashMap::new();
        let mut current_interface: Option<Interface> = None;
        let mut comments = Vec::new();
        let mut sources = Vec::new();

        for (line_number, line) in content.lines().enumerate() {
            let line = line.trim();

            // Collect comments at the top
            if line.starts_with('#') {
                if interfaces.is_empty() && current_interface.is_none() {
                    comments.push(line.to_string());
                }
                continue;
            }

            // Collect source directives
            if line.starts_with("source") {
                sources.push(line.to_string());
                continue;
            }

            // Skip empty lines
            if line.is_empty() {
                continue;
            }

            let tokens: Vec<&str> = line.split_whitespace().collect();
            if tokens.is_empty() {
                continue;
            }

            // Finish the previous interface if necessary
            match tokens[0] {
                "auto" | "mapping" | "iface" => {
                    if let Some(iface) = current_interface.take() {
                        interfaces.insert(iface.name.clone(), iface);
                    }
                }
                s if s.starts_with("allow-") => {
                    if let Some(iface) = current_interface.take() {
                        interfaces.insert(iface.name.clone(), iface);
                    }
                }
                _ => {}
            }

            match tokens[0] {
                "auto" => {
                    for &iface_name in &tokens[1..] {
                        if let Some(iface) = interfaces.get_mut(iface_name) {
                            // If interface exists, set auto to true
                            iface.auto = true;
                        } else {
                            // Interface doesn't exist yet, create it with auto = true
                            interfaces.insert(
                                iface_name.to_string(),
                                Interface::builder(iface_name).with_auto(true).build(),
                            );
                        }
                    }
                }
                s if s.starts_with("allow-") => {
                    // Safe: we just verified the prefix exists with starts_with
                    let allow_type = s.strip_prefix("allow-").expect("prefix verified above");
                    for &iface_name in &tokens[1..] {
                        if let Some(iface) = interfaces.get_mut(iface_name) {
                            // If interface exists, add to allow list
                            iface.allow.push(allow_type.to_string());
                        } else {
                            // Interface doesn't exist yet, create it with allow
                            let mut iface = Interface::builder(iface_name).build();
                            iface.allow.push(allow_type.to_string());
                            interfaces.insert(iface_name.to_string(), iface);
                        }
                    }
                }
                "iface" => {
                    // Start a new interface
                    let iface_name = tokens
                        .get(1)
                        .ok_or_else(|| ParserError::new("Missing interface name in 'iface' stanza", line_number + 1))?
                        .to_string();

                    // Remove existing interface if any
                    let existing_iface = interfaces.remove(&iface_name);

                    // Build the interface using existing settings if available
                    let mut builder = if let Some(existing_iface) = existing_iface {
                        existing_iface.edit()
                    } else {
                        Interface::builder(iface_name.clone())
                    };

                    // Parse family
                    let family = match tokens.get(2) {
                        Some(s) => s.parse::<Family>().ok(),
                        None => None,
                    };

                    // Parse method (Method::from_str is infallible - unwrap cannot panic)
                    let method: Option<Method> = match tokens.len() {
                        // If family is valid, method is the next token
                        4 if family.is_some() => Some(tokens[3].parse().expect("Method parse is infallible")),
                        // If family is absent, interpret the third token as the method
                        3 if family.is_none() => Some(tokens[2].parse().expect("Method parse is infallible")),
                        _ => None,
                    };

                    if let Some(family) = family {
                        builder = builder.with_family(family);
                    }

                    if let Some(method) = method {
                        builder = builder.with_method(method);
                    }

                    current_interface = Some(builder.build());
                }
                "mapping" => {
                    // Handle 'mapping' stanzas if needed
                    // For now, we ignore unknown stanzas
                }
                _ => {
                    // Parse options under 'iface' stanza
                    if let Some(iface) = &mut current_interface {
                        let mut tokens = line.split_whitespace();
                        if let Some(option_name) = tokens.next() {
                            let option_value = tokens.collect::<Vec<&str>>().join(" ");
                            iface.options.push(InterfaceOption::from_key_value(option_name, &option_value));
                        }
                    } else {
                        // Handle global options if needed
                        // For now, we ignore unknown stanzas outside of an 'iface'
                    }
                }
            }
        }

        // Insert the last interface
        if let Some(iface) = current_interface {
            interfaces.insert(iface.name.clone(), iface);
        }

        Ok((interfaces, comments, sources))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interface::{Family, Method};

    #[test]
    fn test_parse_iface_without_family_and_method() {
        let content = r#"
auto eth0
iface eth0
    address 10.130.17.36/255.255.255.128
    vrf mgmt
"#;
        let parser = Parser::new();
        let (interfaces, _comments, _sources) = parser.parse(content).unwrap();
        assert!(interfaces.contains_key("eth0"));
        let iface = &interfaces["eth0"];
        assert_eq!(iface.name, "eth0");
        assert_eq!(iface.family, None);
        assert_eq!(iface.method, None);
        assert!(iface.options.contains(&InterfaceOption::Address(
            "10.130.17.36/255.255.255.128".to_string()
        )));
        assert!(iface
            .options
            .contains(&InterfaceOption::Vrf("mgmt".to_string())));
    }

    #[test]
    fn test_parse_iface_with_family_and_method() {
        let content = r#"
iface eth1 inet static
    address 192.168.1.10
    netmask 255.255.255.0
"#;
        let parser = Parser::new();
        let (interfaces, _comments, _sources) = parser.parse(content).unwrap();
        assert!(interfaces.contains_key("eth1"));
        let iface = &interfaces["eth1"];
        assert_eq!(iface.name, "eth1");
        assert_eq!(iface.family, Some(Family::Inet));
        assert_eq!(iface.method, Some(Method::Static));
        assert!(iface
            .options
            .contains(&InterfaceOption::Address("192.168.1.10".to_string())));
        assert!(iface
            .options
            .contains(&InterfaceOption::Netmask("255.255.255.0".to_string())));
    }

    #[test]
    fn test_parse_multiple_interfaces() {
        let content = r#"
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto wlan0
iface wlan0 inet static
    address 192.168.0.100
    netmask 255.255.255.0
"#;
        let parser = Parser::new();
        let (interfaces, _comments, _sources) = parser.parse(content).unwrap();

        assert_eq!(interfaces.len(), 3);

        // Check 'lo' interface
        let lo_iface = &interfaces["lo"];
        assert_eq!(lo_iface.name, "lo");
        assert!(lo_iface.auto);
        assert_eq!(lo_iface.family, Some(Family::Inet));
        assert_eq!(lo_iface.method, Some(Method::Loopback));

        // Check 'eth0' interface
        let eth0_iface = &interfaces["eth0"];
        assert_eq!(eth0_iface.name, "eth0");
        assert!(eth0_iface.auto);
        assert_eq!(eth0_iface.family, Some(Family::Inet));
        assert_eq!(eth0_iface.method, Some(Method::Dhcp));

        // Check 'wlan0' interface
        let wlan0_iface = &interfaces["wlan0"];
        assert_eq!(wlan0_iface.name, "wlan0");
        assert!(wlan0_iface.auto);
        assert_eq!(wlan0_iface.family, Some(Family::Inet));
        assert_eq!(wlan0_iface.method, Some(Method::Static));
        assert!(wlan0_iface
            .options
            .contains(&InterfaceOption::Address("192.168.0.100".to_string())));
        assert!(wlan0_iface
            .options
            .contains(&InterfaceOption::Netmask("255.255.255.0".to_string())));
    }

    #[test]
    fn test_parse_multiple_interfaces_strange_order() {
        let content = r#"
iface lo inet loopback
iface eth0 inet dhcp
auto eth0

auto wlan0
auto lo
iface wlan0 inet static
    address 192.168.0.100
    netmask 255.255.255.0
"#;
        let parser = Parser::new();
        let (interfaces, _comments, _sources) = parser.parse(content).unwrap();

        assert_eq!(interfaces.len(), 3);

        // Check 'lo' interface
        let lo_iface = &interfaces["lo"];
        assert_eq!(lo_iface.name, "lo");
        assert!(lo_iface.auto);
        assert_eq!(lo_iface.family, Some(Family::Inet));
        assert_eq!(lo_iface.method, Some(Method::Loopback));

        // Check 'eth0' interface
        let eth0_iface = &interfaces["eth0"];
        assert_eq!(eth0_iface.name, "eth0");
        assert!(eth0_iface.auto);
        assert_eq!(eth0_iface.family, Some(Family::Inet));
        assert_eq!(eth0_iface.method, Some(Method::Dhcp));

        // Check 'wlan0' interface
        let wlan0_iface = &interfaces["wlan0"];
        assert_eq!(wlan0_iface.name, "wlan0");
        assert!(wlan0_iface.auto);
        assert_eq!(wlan0_iface.family, Some(Family::Inet));
        assert_eq!(wlan0_iface.method, Some(Method::Static));
        assert!(wlan0_iface
            .options
            .contains(&InterfaceOption::Address("192.168.0.100".to_string())));
        assert!(wlan0_iface
            .options
            .contains(&InterfaceOption::Netmask("255.255.255.0".to_string())));
    }

    #[test]
    fn test_parse_multiple_interfaces_cumulus() {
        let content = r#"
auto swp54
iface swp54
    bridge-access 199
    mstpctl-bpduguard yes
    mstpctl-portadminedge yes
    mtu 9216
    post-down /some/script.sh
    post-up /some/script.sh

auto bridge
iface bridge
    bridge-ports swp1 swp2 swp3 swp4 swp5 swp6 swp7 swp8 swp9 swp10 swp11 swp12 swp13 swp14 swp15 swp16 swp17 swp18 swp19 swp20 swp21 swp22 swp23 swp24 swp31 swp32 swp33 swp34 swp35 swp36 swp37 swp38 swp39 swp40 swp41 swp42 swp43 swp44 swp45 swp46 swp47 swp48 swp49 swp50 swp51 swp52 swp53 swp54
    bridge-pvid 1
    bridge-vids 100-154 199
    bridge-vlan-aware yes

auto mgmt
iface mgmt
    address 127.0.0.1/8
    address ::1/128
    vrf-table auto

auto vlan101
iface vlan101
    mtu 9216
    post-up /some/script.sh
    vlan-id 101
    vlan-raw-device bridge
    "#;
        let parser = Parser::new();
        let (interfaces, _comments, _sources) = parser.parse(content).unwrap();

        assert_eq!(interfaces.len(), 4);

        // Check 'swp54' interface
        let swp54_iface = &interfaces["swp54"];
        assert_eq!(swp54_iface.name, "swp54");
        assert_eq!(swp54_iface.auto, true);
        assert_eq!(swp54_iface.family, None);
        assert_eq!(swp54_iface.method, None);
        // Check options
        assert!(swp54_iface
            .options
            .contains(&InterfaceOption::BridgeAccess(199)));
        assert!(swp54_iface
            .options
            .contains(&InterfaceOption::MstpctlBpduguard(true)));
        assert!(swp54_iface
            .options
            .contains(&InterfaceOption::MstpctlPortadminedge(true)));
        assert!(swp54_iface
            .options
            .contains(&InterfaceOption::Mtu(9216)));
        assert!(swp54_iface
            .options
            .contains(&InterfaceOption::PostDown("/some/script.sh".to_string())));
        assert!(swp54_iface
            .options
            .contains(&InterfaceOption::PostUp("/some/script.sh".to_string())));

        // Check 'bridge' interface
        let bridge_iface = &interfaces["bridge"];
        assert_eq!(bridge_iface.name, "bridge");
        assert_eq!(bridge_iface.auto, true);
        assert_eq!(bridge_iface.family, None);
        assert_eq!(bridge_iface.method, None);
        // Check options
        assert!(bridge_iface.options.contains(&InterfaceOption::BridgePorts(vec![
            "swp1".to_string(), "swp2".to_string(), "swp3".to_string(), "swp4".to_string(),
            "swp5".to_string(), "swp6".to_string(), "swp7".to_string(), "swp8".to_string(),
            "swp9".to_string(), "swp10".to_string(), "swp11".to_string(), "swp12".to_string(),
            "swp13".to_string(), "swp14".to_string(), "swp15".to_string(), "swp16".to_string(),
            "swp17".to_string(), "swp18".to_string(), "swp19".to_string(), "swp20".to_string(),
            "swp21".to_string(), "swp22".to_string(), "swp23".to_string(), "swp24".to_string(),
            "swp31".to_string(), "swp32".to_string(), "swp33".to_string(), "swp34".to_string(),
            "swp35".to_string(), "swp36".to_string(), "swp37".to_string(), "swp38".to_string(),
            "swp39".to_string(), "swp40".to_string(), "swp41".to_string(), "swp42".to_string(),
            "swp43".to_string(), "swp44".to_string(), "swp45".to_string(), "swp46".to_string(),
            "swp47".to_string(), "swp48".to_string(), "swp49".to_string(), "swp50".to_string(),
            "swp51".to_string(), "swp52".to_string(), "swp53".to_string(), "swp54".to_string(),
        ])));
        assert!(bridge_iface
            .options
            .contains(&InterfaceOption::BridgePvid(1)));
        assert!(bridge_iface
            .options
            .contains(&InterfaceOption::BridgeVids("100-154 199".to_string())));
        assert!(bridge_iface
            .options
            .contains(&InterfaceOption::BridgeVlanAware(true)));

        // Check 'mgmt' interface
        let mgmt_iface = &interfaces["mgmt"];
        assert_eq!(mgmt_iface.name, "mgmt");
        assert_eq!(mgmt_iface.auto, true);
        assert_eq!(mgmt_iface.family, None);
        assert_eq!(mgmt_iface.method, None);
        // Check options
        assert!(mgmt_iface
            .options
            .contains(&InterfaceOption::Address("127.0.0.1/8".to_string())));
        assert!(mgmt_iface
            .options
            .contains(&InterfaceOption::Address("::1/128".to_string())));
        assert!(mgmt_iface
            .options
            .contains(&InterfaceOption::VrfTable("auto".to_string())));

        // Check 'vlan101' interface
        let vlan101_iface = &interfaces["vlan101"];
        assert_eq!(vlan101_iface.name, "vlan101");
        assert_eq!(vlan101_iface.auto, true);
        assert_eq!(vlan101_iface.family, None);
        assert_eq!(vlan101_iface.method, None);
        // Check options
        assert!(vlan101_iface
            .options
            .contains(&InterfaceOption::Mtu(9216)));
        assert!(vlan101_iface
            .options
            .contains(&InterfaceOption::PostUp("/some/script.sh".to_string())));
        assert!(vlan101_iface
            .options
            .contains(&InterfaceOption::VlanId(101)));
        assert!(vlan101_iface
            .options
            .contains(&InterfaceOption::VlanRawDevice("bridge".to_string())));

        // Check print/display formatting
        // At the end of the test
        let mut output = String::new();
        output.push_str(&format!("{}\n", swp54_iface));
        output.push_str(&format!("{}\n", bridge_iface));
        output.push_str(&format!("{}\n", mgmt_iface));
        output.push_str(&format!("{}\n", vlan101_iface));

        // Expected output
        let expected_output = r#"
auto swp54
iface swp54
    bridge-access 199
    mstpctl-bpduguard yes
    mstpctl-portadminedge yes
    mtu 9216
    post-down /some/script.sh
    post-up /some/script.sh

auto bridge
iface bridge
    bridge-ports swp1 swp2 swp3 swp4 swp5 swp6 swp7 swp8 swp9 swp10 swp11 swp12 swp13 swp14 swp15 swp16 swp17 swp18 swp19 swp20 swp21 swp22 swp23 swp24 swp31 swp32 swp33 swp34 swp35 swp36 swp37 swp38 swp39 swp40 swp41 swp42 swp43 swp44 swp45 swp46 swp47 swp48 swp49 swp50 swp51 swp52 swp53 swp54
    bridge-pvid 1
    bridge-vids 100-154 199
    bridge-vlan-aware yes

auto mgmt
iface mgmt
    address 127.0.0.1/8
    address ::1/128
    vrf-table auto

auto vlan101
iface vlan101
    mtu 9216
    post-up /some/script.sh
    vlan-id 101
    vlan-raw-device bridge
"#;

        // Remove extra blank lines if any
        let expected_output = expected_output.trim();
        let output = output.trim();

        assert_eq!(output, expected_output);
    }

    #[test]
    fn test_parse_comments_and_sources() {
        let content = r#"# This is a comment
# Another comment at the top
source /etc/network/interfaces.d/*
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback
"#;
        let parser = Parser::new();
        let (interfaces, comments, sources) = parser.parse(content).unwrap();

        assert_eq!(comments.len(), 2);
        assert_eq!(comments[0], "# This is a comment");
        assert_eq!(comments[1], "# Another comment at the top");

        assert_eq!(sources.len(), 2);
        assert_eq!(sources[0], "source /etc/network/interfaces.d/*");
        assert_eq!(sources[1], "source-directory /etc/network/interfaces.d");

        assert_eq!(interfaces.len(), 1);
        assert!(interfaces.contains_key("lo"));
    }

    #[test]
    fn test_parse_allow_hotplug() {
        let content = r#"
auto eth0
allow-hotplug eth0
iface eth0 inet dhcp
"#;
        let parser = Parser::new();
        let (interfaces, _comments, _sources) = parser.parse(content).unwrap();

        let eth0 = &interfaces["eth0"];
        assert!(eth0.auto);
        assert_eq!(eth0.allow, vec!["hotplug"]);
        assert_eq!(eth0.method, Some(Method::Dhcp));
    }

    #[test]
    fn test_parse_empty_content() {
        let parser = Parser::new();
        let (interfaces, comments, sources) = parser.parse("").unwrap();

        assert!(interfaces.is_empty());
        assert!(comments.is_empty());
        assert!(sources.is_empty());
    }

    #[test]
    fn test_parse_only_comments() {
        let content = "# Just a comment\n# And another";
        let parser = Parser::new();
        let (interfaces, comments, sources) = parser.parse(content).unwrap();

        assert!(interfaces.is_empty());
        assert_eq!(comments.len(), 2);
        assert!(sources.is_empty());
    }
}