1 // Copyright (c) 2020 Intel Corporation. All rights reserved. 2 // 3 // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause 4 5 use super::{vnet_hdr_len, MacAddr, Tap, TapError}; 6 use std::net::Ipv4Addr; 7 use std::path::Path; 8 use std::{fs, io}; 9 use thiserror::Error; 10 11 #[derive(Error, Debug)] 12 pub enum Error { 13 #[error("Failed to convert an hexadecimal string into an integer: {0}")] 14 ConvertHexStringToInt(std::num::ParseIntError), 15 #[error("Error related to the multiqueue support (no support TAP side)")] 16 MultiQueueNoTapSupport, 17 #[error("Error related to the multiqueue support (no support device side)")] 18 MultiQueueNoDeviceSupport, 19 #[error("Failed to read the TAP flags from sysfs: {0}")] 20 ReadSysfsTunFlags(io::Error), 21 #[error("Open tap device failed: {0}")] 22 TapOpen(TapError), 23 #[error("Setting tap IP failed: {0}")] 24 TapSetIp(TapError), 25 #[error("Setting tap netmask failed: {0}")] 26 TapSetNetmask(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<Ipv4Addr>, 66 netmask: Option<Ipv4Addr>, 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.map_or(false, |n| { 77 Path::new(&format!("/sys/class/net/{n}")).exists() 78 }); 79 80 // In case the tap interface already exists, check if the number of 81 // queues is appropriate. The tap might not support multiqueue while 82 // the number of queues indicates the user expects multiple queues, or 83 // on the contrary, the tap might support multiqueue while the number 84 // of queues indicates the user doesn't expect multiple queues. 85 check_mq_support(&if_name, num_rx_q)?; 86 87 for i in 0..num_rx_q { 88 let tap: Tap; 89 if i == 0 { 90 tap = match if_name { 91 Some(name) => Tap::open_named(name, num_rx_q, flags).map_err(Error::TapOpen)?, 92 None => Tap::new(num_rx_q).map_err(Error::TapOpen)?, 93 }; 94 // Don't overwrite ip configuration of existing interfaces: 95 if !tap_existed { 96 if let Some(ip) = ip_addr { 97 tap.set_ip_addr(ip).map_err(Error::TapSetIp)?; 98 } 99 if let Some(mask) = netmask { 100 tap.set_netmask(mask).map_err(Error::TapSetNetmask)?; 101 } 102 } else { 103 warn!( 104 "Tap {} already exists. IP configuration will not be overwritten.", 105 if_name.unwrap_or_default() 106 ); 107 } 108 if let Some(mac) = host_mac { 109 tap.set_mac_addr(*mac).map_err(Error::TapSetMac)? 110 } else { 111 *host_mac = Some(tap.get_mac_addr().map_err(Error::TapGetMac)?) 112 } 113 if let Some(mtu) = mtu { 114 tap.set_mtu(mtu as i32).map_err(Error::TapSetMtu)?; 115 } 116 tap.enable().map_err(Error::TapEnable)?; 117 118 tap.set_vnet_hdr_size(vnet_hdr_size) 119 .map_err(Error::TapSetVnetHdrSize)?; 120 121 ifname = String::from_utf8(tap.get_if_name()).unwrap(); 122 } else { 123 tap = Tap::open_named(ifname.as_str(), num_rx_q, flags).map_err(Error::TapOpen)?; 124 125 tap.set_vnet_hdr_size(vnet_hdr_size) 126 .map_err(Error::TapSetVnetHdrSize)?; 127 } 128 taps.push(tap); 129 } 130 Ok(taps) 131 } 132