1 // Copyright (c) 2020 Intel Corporation. All rights reserved. 2 // 3 // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause 4 5 use std::net::IpAddr; 6 use std::path::Path; 7 use std::{fs, io}; 8 9 use thiserror::Error; 10 11 use super::{vnet_hdr_len, MacAddr, Tap, TapError}; 12 13 #[derive(Error, Debug)] 14 pub enum Error { 15 #[error("Failed to convert an hexadecimal string into an integer: {0}")] 16 ConvertHexStringToInt(std::num::ParseIntError), 17 #[error("Error related to the multiqueue support (no support TAP side)")] 18 MultiQueueNoTapSupport, 19 #[error("Error related to the multiqueue support (no support device side)")] 20 MultiQueueNoDeviceSupport, 21 #[error("Failed to read the TAP flags from sysfs: {0}")] 22 ReadSysfsTunFlags(io::Error), 23 #[error("Open tap device failed: {0}")] 24 TapOpen(TapError), 25 #[error("Setting tap IP and/or netmask failed: {0}")] 26 TapSetIpNetmask(TapError), 27 #[error("Setting MAC address failed: {0}")] 28 TapSetMac(TapError), 29 #[error("Getting MAC address failed: {0}")] 30 TapGetMac(TapError), 31 #[error("Setting vnet header size failed: {0}")] 32 TapSetVnetHdrSize(TapError), 33 #[error("Setting MTU failed: {0}")] 34 TapSetMtu(TapError), 35 #[error("Enabling tap interface failed: {0}")] 36 TapEnable(TapError), 37 } 38 39 type Result<T> = std::result::Result<T, Error>; 40 41 fn check_mq_support(if_name: &Option<&str>, queue_pairs: usize) -> Result<()> { 42 if let Some(tap_name) = if_name { 43 let mq = queue_pairs > 1; 44 let path = format!("/sys/class/net/{tap_name}/tun_flags"); 45 // interface does not exist, check is not required 46 if !Path::new(&path).exists() { 47 return Ok(()); 48 } 49 let tun_flags_str = fs::read_to_string(path).map_err(Error::ReadSysfsTunFlags)?; 50 let tun_flags = u32::from_str_radix(tun_flags_str.trim().trim_start_matches("0x"), 16) 51 .map_err(Error::ConvertHexStringToInt)?; 52 if (tun_flags & net_gen::IFF_MULTI_QUEUE != 0) && !mq { 53 return Err(Error::MultiQueueNoDeviceSupport); 54 } else if (tun_flags & net_gen::IFF_MULTI_QUEUE == 0) && mq { 55 return Err(Error::MultiQueueNoTapSupport); 56 } 57 } 58 Ok(()) 59 } 60 61 /// Create a new virtio network device with the given IP address and 62 /// netmask. 63 pub fn open_tap( 64 if_name: Option<&str>, 65 ip_addr: Option<IpAddr>, 66 netmask: Option<IpAddr>, 67 host_mac: &mut Option<MacAddr>, 68 mtu: Option<u16>, 69 num_rx_q: usize, 70 flags: Option<i32>, 71 ) -> Result<Vec<Tap>> { 72 let mut taps: Vec<Tap> = Vec::new(); 73 let mut ifname: String = String::new(); 74 let vnet_hdr_size = vnet_hdr_len() as i32; 75 // Check if the given interface exists before we create it. 76 let tap_existed = if_name.is_some_and(|n| Path::new(&format!("/sys/class/net/{n}")).exists()); 77 78 // In case the tap interface already exists, check if the number of 79 // queues is appropriate. The tap might not support multiqueue while 80 // the number of queues indicates the user expects multiple queues, or 81 // on the contrary, the tap might support multiqueue while the number 82 // of queues indicates the user doesn't expect multiple queues. 83 check_mq_support(&if_name, num_rx_q)?; 84 85 for i in 0..num_rx_q { 86 let tap: Tap; 87 if i == 0 { 88 tap = match if_name { 89 Some(name) => Tap::open_named(name, num_rx_q, flags).map_err(Error::TapOpen)?, 90 None => Tap::new(num_rx_q).map_err(Error::TapOpen)?, 91 }; 92 // Don't overwrite ip configuration of existing interfaces: 93 if !tap_existed { 94 if let Some(ip) = ip_addr { 95 tap.set_ip_addr(ip, netmask) 96 .map_err(Error::TapSetIpNetmask)?; 97 } 98 } else { 99 warn!( 100 "Tap {} already exists. IP configuration will not be overwritten.", 101 if_name.unwrap_or_default() 102 ); 103 } 104 if let Some(mac) = host_mac { 105 tap.set_mac_addr(*mac).map_err(Error::TapSetMac)? 106 } else { 107 *host_mac = Some(tap.get_mac_addr().map_err(Error::TapGetMac)?) 108 } 109 if let Some(mtu) = mtu { 110 tap.set_mtu(mtu as i32).map_err(Error::TapSetMtu)?; 111 } 112 tap.enable().map_err(Error::TapEnable)?; 113 114 tap.set_vnet_hdr_size(vnet_hdr_size) 115 .map_err(Error::TapSetVnetHdrSize)?; 116 117 ifname = String::from_utf8(tap.get_if_name()).unwrap(); 118 } else { 119 tap = Tap::open_named(ifname.as_str(), num_rx_q, flags).map_err(Error::TapOpen)?; 120 121 tap.set_vnet_hdr_size(vnet_hdr_size) 122 .map_err(Error::TapSetVnetHdrSize)?; 123 } 124 taps.push(tap); 125 } 126 Ok(taps) 127 } 128