• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #![cfg(unix)]
6 
7 use std::env::current_exe;
8 use std::net;
9 use std::process::Command;
10 
11 use net_util::sys::unix::Tap;
12 use net_util::MacAddress;
13 use net_util::TapTCommon;
14 
15 /// The tests below require root privileges.
16 /// Re-invoke the test binary to execute the specified test with sudo. The test will fail if
17 /// passwordless sudo is not available.
call_test_with_sudo(name: &str)18 fn call_test_with_sudo(name: &str) {
19     // Try a passwordless sudo first to provide a proper error message.
20     // Note: The combination of SUDO_ASKPASS and --askpass will fail if sudo has to ask for a
21     // password.
22     let can_sudo = Command::new("sudo")
23         .args(["--askpass", "true"])
24         .env("SUDO_ASKPASS", "false")
25         .output()
26         .unwrap();
27     if !can_sudo.status.success() {
28         panic!("This test need to be run as root or with passwordless sudo.");
29     }
30 
31     let result = Command::new("sudo")
32         .args([
33             "--preserve-env",
34             current_exe().unwrap().to_str().unwrap(),
35             "--nocapture",
36             "--ignored",
37             "--exact",
38             name,
39         ])
40         .status()
41         .unwrap();
42 
43     if !result.success() {
44         panic!("Test {name} failed in child process.");
45     }
46 }
47 
48 #[test]
tap_create()49 fn tap_create() {
50     call_test_with_sudo("tap_create_impl")
51 }
52 
53 #[test]
54 #[ignore = "Only to be called by tap_create"]
tap_create_impl()55 fn tap_create_impl() {
56     Tap::new(true, false).unwrap();
57 }
58 
59 #[test]
tap_configure()60 fn tap_configure() {
61     call_test_with_sudo("tap_configure_impl")
62 }
63 
64 #[test]
65 #[ignore = "Only to be called by tap_configure"]
tap_configure_impl()66 fn tap_configure_impl() {
67     let tap = Tap::new(true, false).unwrap();
68     let ip_addr: net::Ipv4Addr = "100.115.92.5".parse().unwrap();
69     let netmask: net::Ipv4Addr = "255.255.255.252".parse().unwrap();
70     let mac_addr: MacAddress = "a2:06:b9:3d:68:4d".parse().unwrap();
71 
72     tap.set_ip_addr(ip_addr).unwrap();
73     tap.set_netmask(netmask).unwrap();
74     tap.set_mac_address(mac_addr).unwrap();
75     tap.set_vnet_hdr_size(16).unwrap();
76     tap.set_offload(0).unwrap();
77 }
78 
79 #[test]
tap_enable()80 fn tap_enable() {
81     call_test_with_sudo("tap_enable_impl")
82 }
83 
84 #[test]
85 #[ignore = "Only to be called by tap_enable"]
tap_enable_impl()86 fn tap_enable_impl() {
87     let tap = Tap::new(true, false).unwrap();
88 
89     tap.enable().unwrap();
90 }
91