1 // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 // 4 // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. 5 // Use of this source code is governed by a BSD-style license that can be 6 // found in the THIRD-PARTY file. 7 8 use super::{ 9 create_inet_socket, create_sockaddr, create_unix_socket, vnet_hdr_len, Error as NetUtilError, 10 MacAddr, 11 }; 12 use crate::mac::MAC_ADDR_LEN; 13 use std::fs::File; 14 use std::io::{Error as IoError, Read, Result as IoResult, Write}; 15 use std::net; 16 use std::os::raw::*; 17 use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; 18 use thiserror::Error; 19 use vmm_sys_util::ioctl::{ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val}; 20 21 #[derive(Error, Debug)] 22 pub enum Error { 23 #[error("Couldn't open /dev/net/tun: {0}")] 24 OpenTun(IoError), 25 #[error("Unable to configure tap interface: {0}")] 26 ConfigureTap(IoError), 27 #[error("Unable to retrieve features: {0}")] 28 GetFeatures(IoError), 29 #[error("Missing multiqueue support in the kernel.")] 30 MultiQueueKernelSupport, 31 #[error("ioctl failed: {0}")] 32 IoctlError(IoError), 33 #[error("Failed to create a socket: {0}")] 34 NetUtil(NetUtilError), 35 #[error("Invalid interface name.")] 36 InvalidIfname, 37 #[error("Error parsing MAC data: {0}")] 38 MacParsing(IoError), 39 } 40 41 pub type Result<T> = ::std::result::Result<T, Error>; 42 43 /// Handle for a network tap interface. 44 /// 45 /// For now, this simply wraps the file descriptor for the tap device so methods 46 /// can run ioctls on the interface. The tap interface fd will be closed when 47 /// Tap goes out of scope, and the kernel will clean up the interface 48 /// automatically. 49 #[derive(Debug)] 50 pub struct Tap { 51 tap_file: File, 52 if_name: Vec<u8>, 53 } 54 55 impl PartialEq for Tap { 56 fn eq(&self, other: &Tap) -> bool { 57 self.if_name == other.if_name 58 } 59 } 60 61 impl std::clone::Clone for Tap { 62 fn clone(&self) -> Self { 63 Tap { 64 tap_file: self.tap_file.try_clone().unwrap(), 65 if_name: self.if_name.clone(), 66 } 67 } 68 } 69 70 // Returns a byte vector representing the contents of a null terminated C string which 71 // contains if_name. 72 fn build_terminated_if_name(if_name: &str) -> Result<Vec<u8>> { 73 // Convert the string slice to bytes, and shadow the variable, 74 // since we no longer need the &str version. 75 let if_name = if_name.as_bytes(); 76 77 // TODO: the 16usize limit of the if_name member from struct Tap is pretty arbitrary. 78 // We leave it as is for now, but this should be refactored at some point. 79 if if_name.len() > 15 { 80 return Err(Error::InvalidIfname); 81 } 82 83 let mut terminated_if_name = vec![b'\0'; if_name.len() + 1]; 84 terminated_if_name[..if_name.len()].copy_from_slice(if_name); 85 86 Ok(terminated_if_name) 87 } 88 89 impl Tap { 90 pub fn open_named(if_name: &str, num_queue_pairs: usize, flags: Option<i32>) -> Result<Tap> { 91 let terminated_if_name = build_terminated_if_name(if_name)?; 92 93 let fd = unsafe { 94 // Open calls are safe because we give a constant null-terminated 95 // string and verify the result. 96 libc::open( 97 b"/dev/net/tun\0".as_ptr() as *const c_char, 98 flags.unwrap_or(libc::O_RDWR | libc::O_NONBLOCK | libc::O_CLOEXEC), 99 ) 100 }; 101 if fd < 0 { 102 return Err(Error::OpenTun(IoError::last_os_error())); 103 } 104 105 // We just checked that the fd is valid. 106 let tuntap = unsafe { File::from_raw_fd(fd) }; 107 108 // Let's validate some features before going any further. 109 // ioctl is safe since we call it with a valid tap fd and check the return 110 // value. 111 let mut features = 0; 112 let ret = unsafe { ioctl_with_mut_ref(&tuntap, net_gen::TUNGETFEATURES(), &mut features) }; 113 if ret < 0 { 114 return Err(Error::GetFeatures(IoError::last_os_error())); 115 } 116 117 // Check if the user parameters match the kernel support for MQ 118 if (features & net_gen::IFF_MULTI_QUEUE == 0) && num_queue_pairs > 1 { 119 return Err(Error::MultiQueueKernelSupport); 120 } 121 122 // This is pretty messy because of the unions used by ifreq. Since we 123 // don't call as_mut on the same union field more than once, this block 124 // is safe. 125 let mut ifreq: net_gen::ifreq = Default::default(); 126 unsafe { 127 let ifrn_name = ifreq.ifr_ifrn.ifrn_name.as_mut(); 128 let name_slice = &mut ifrn_name[..terminated_if_name.len()]; 129 name_slice.copy_from_slice(terminated_if_name.as_slice()); 130 ifreq.ifr_ifru.ifru_flags = 131 (net_gen::IFF_TAP | net_gen::IFF_NO_PI | net_gen::IFF_VNET_HDR) as c_short; 132 if num_queue_pairs > 1 { 133 ifreq.ifr_ifru.ifru_flags |= net_gen::IFF_MULTI_QUEUE as c_short; 134 } 135 } 136 137 // ioctl is safe since we call it with a valid tap fd and check the return 138 // value. 139 let ret = unsafe { ioctl_with_mut_ref(&tuntap, net_gen::TUNSETIFF(), &mut ifreq) }; 140 if ret < 0 { 141 return Err(Error::ConfigureTap(IoError::last_os_error())); 142 } 143 144 let mut if_name = unsafe { ifreq.ifr_ifrn.ifrn_name }.to_vec(); 145 if_name.truncate(terminated_if_name.len() - 1); 146 // Safe since only the name is accessed, and it's cloned out. 147 Ok(Tap { 148 tap_file: tuntap, 149 if_name, 150 }) 151 } 152 153 /// Create a new tap interface. 154 pub fn new(num_queue_pairs: usize) -> Result<Tap> { 155 Self::open_named("vmtap%d", num_queue_pairs, None) 156 } 157 158 pub fn from_tap_fd(fd: RawFd, num_queue_pairs: usize) -> Result<Tap> { 159 // Ensure that the file is opened non-blocking, this is particularly 160 // needed when opened via the shell for macvtap. 161 let ret = unsafe { 162 let mut flags = libc::fcntl(fd, libc::F_GETFL); 163 flags |= libc::O_NONBLOCK; 164 libc::fcntl(fd, libc::F_SETFL, flags) 165 }; 166 if ret < 0 { 167 return Err(Error::ConfigureTap(IoError::last_os_error())); 168 } 169 170 let tap_file = unsafe { File::from_raw_fd(fd) }; 171 let mut ifreq: net_gen::ifreq = Default::default(); 172 173 // Get current config including name 174 let ret = unsafe { ioctl_with_mut_ref(&tap_file, net_gen::TUNGETIFF(), &mut ifreq) }; 175 if ret < 0 { 176 return Err(Error::IoctlError(IoError::last_os_error())); 177 } 178 // We only access one field of the ifru union, hence this is safe. 179 let if_name = unsafe { ifreq.ifr_ifrn.ifrn_name }.to_vec(); 180 181 // Try and update flags. Depending on how the tap was created (macvtap 182 // or via open_named()) this might return -EEXIST so we just ignore that. 183 unsafe { 184 ifreq.ifr_ifru.ifru_flags = 185 (net_gen::IFF_TAP | net_gen::IFF_NO_PI | net_gen::IFF_VNET_HDR) as c_short; 186 if num_queue_pairs > 1 { 187 ifreq.ifr_ifru.ifru_flags |= net_gen::IFF_MULTI_QUEUE as c_short; 188 } 189 } 190 let ret = unsafe { ioctl_with_mut_ref(&tap_file, net_gen::TUNSETIFF(), &mut ifreq) }; 191 if ret < 0 && IoError::last_os_error().raw_os_error().unwrap() != libc::EEXIST { 192 return Err(Error::ConfigureTap(IoError::last_os_error())); 193 } 194 195 let tap = Tap { tap_file, if_name }; 196 let vnet_hdr_size = vnet_hdr_len() as i32; 197 tap.set_vnet_hdr_size(vnet_hdr_size)?; 198 199 Ok(tap) 200 } 201 202 /// Set the host-side IP address for the tap interface. 203 pub fn set_ip_addr(&self, ip_addr: net::Ipv4Addr) -> Result<()> { 204 let sock = create_inet_socket().map_err(Error::NetUtil)?; 205 let addr = create_sockaddr(ip_addr); 206 207 let mut ifreq = self.get_ifreq(); 208 209 ifreq.ifr_ifru.ifru_addr = addr; 210 211 // ioctl is safe. Called with a valid sock fd, and we check the return. 212 let ret = 213 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCSIFADDR as c_ulong, &ifreq) }; 214 if ret < 0 { 215 return Err(Error::IoctlError(IoError::last_os_error())); 216 } 217 218 Ok(()) 219 } 220 221 /// Set mac addr for tap interface. 222 pub fn set_mac_addr(&self, addr: MacAddr) -> Result<()> { 223 // Checking if the mac address already matches the desired one 224 // is useful to avoid making the "set ioctl" in the case where 225 // the VMM is running without the privilege to do that. 226 // In practice this comes from a reboot after the configuration 227 // has been update with the kernel generated address. 228 if self.get_mac_addr()? == addr { 229 return Ok(()); 230 } 231 232 let sock = create_unix_socket().map_err(Error::NetUtil)?; 233 234 let mut ifreq = self.get_ifreq(); 235 236 // ioctl is safe. Called with a valid sock fd, and we check the return. 237 let ret = 238 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCGIFHWADDR as c_ulong, &ifreq) }; 239 if ret < 0 { 240 return Err(Error::IoctlError(IoError::last_os_error())); 241 } 242 // We only access one field of the ifru union, hence this is safe. 243 unsafe { 244 let ifru_hwaddr = &mut ifreq.ifr_ifru.ifru_hwaddr; 245 for (i, v) in addr.get_bytes().iter().enumerate() { 246 ifru_hwaddr.sa_data[i] = *v as c_uchar; 247 } 248 } 249 250 // ioctl is safe. Called with a valid sock fd, and we check the return. 251 let ret = 252 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCSIFHWADDR as c_ulong, &ifreq) }; 253 if ret < 0 { 254 return Err(Error::IoctlError(IoError::last_os_error())); 255 } 256 257 Ok(()) 258 } 259 260 /// Get mac addr for tap interface. 261 pub fn get_mac_addr(&self) -> Result<MacAddr> { 262 let sock = create_unix_socket().map_err(Error::NetUtil)?; 263 264 let ifreq = self.get_ifreq(); 265 266 // ioctl is safe. Called with a valid sock fd, and we check the return. 267 let ret = 268 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCGIFHWADDR as c_ulong, &ifreq) }; 269 if ret < 0 { 270 return Err(Error::IoctlError(IoError::last_os_error())); 271 } 272 273 // We only access one field of the ifru union, hence this is safe. 274 let addr = unsafe { 275 MacAddr::from_bytes(&ifreq.ifr_ifru.ifru_hwaddr.sa_data[0..MAC_ADDR_LEN]) 276 .map_err(Error::MacParsing)? 277 }; 278 Ok(addr) 279 } 280 281 /// Set the netmask for the subnet that the tap interface will exist on. 282 pub fn set_netmask(&self, netmask: net::Ipv4Addr) -> Result<()> { 283 let sock = create_inet_socket().map_err(Error::NetUtil)?; 284 let addr = create_sockaddr(netmask); 285 286 let mut ifreq = self.get_ifreq(); 287 288 ifreq.ifr_ifru.ifru_addr = addr; 289 290 // ioctl is safe. Called with a valid sock fd, and we check the return. 291 let ret = 292 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCSIFNETMASK as c_ulong, &ifreq) }; 293 if ret < 0 { 294 return Err(Error::IoctlError(IoError::last_os_error())); 295 } 296 297 Ok(()) 298 } 299 300 pub fn mtu(&self) -> Result<i32> { 301 let sock = create_unix_socket().map_err(Error::NetUtil)?; 302 303 let ifreq = self.get_ifreq(); 304 305 // ioctl is safe. Called with a valid sock fd, and we check the return. 306 let ret = unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCGIFMTU as c_ulong, &ifreq) }; 307 if ret < 0 { 308 return Err(Error::IoctlError(IoError::last_os_error())); 309 } 310 311 let mtu = unsafe { ifreq.ifr_ifru.ifru_mtu }; 312 313 Ok(mtu) 314 } 315 316 pub fn set_mtu(&self, mtu: i32) -> Result<()> { 317 let sock = create_unix_socket().map_err(Error::NetUtil)?; 318 319 let mut ifreq = self.get_ifreq(); 320 ifreq.ifr_ifru.ifru_mtu = mtu; 321 322 // ioctl is safe. Called with a valid sock fd, and we check the return. 323 let ret = unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCSIFMTU as c_ulong, &ifreq) }; 324 if ret < 0 { 325 return Err(Error::IoctlError(IoError::last_os_error())); 326 } 327 328 Ok(()) 329 } 330 331 /// Set the offload flags for the tap interface. 332 pub fn set_offload(&self, flags: c_uint) -> Result<()> { 333 // ioctl is safe. Called with a valid tap fd, and we check the return. 334 let ret = 335 unsafe { ioctl_with_val(&self.tap_file, net_gen::TUNSETOFFLOAD(), flags as c_ulong) }; 336 if ret < 0 { 337 return Err(Error::IoctlError(IoError::last_os_error())); 338 } 339 340 Ok(()) 341 } 342 343 /// Enable the tap interface. 344 pub fn enable(&self) -> Result<()> { 345 let sock = create_unix_socket().map_err(Error::NetUtil)?; 346 347 let mut ifreq = self.get_ifreq(); 348 349 let ret = 350 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCGIFFLAGS as c_ulong, &ifreq) }; 351 if ret < 0 { 352 return Err(Error::IoctlError(IoError::last_os_error())); 353 } 354 355 // If TAP device is already up don't try and enable it 356 let ifru_flags = unsafe { ifreq.ifr_ifru.ifru_flags }; 357 if ifru_flags & net_gen::net_device_flags_IFF_UP as i16 358 == net_gen::net_device_flags_IFF_UP as i16 359 { 360 return Ok(()); 361 } 362 363 ifreq.ifr_ifru.ifru_flags = net_gen::net_device_flags_IFF_UP as i16; 364 365 // ioctl is safe. Called with a valid sock fd, and we check the return. 366 let ret = 367 unsafe { ioctl_with_ref(&sock, net_gen::sockios::SIOCSIFFLAGS as c_ulong, &ifreq) }; 368 if ret < 0 { 369 return Err(Error::IoctlError(IoError::last_os_error())); 370 } 371 372 Ok(()) 373 } 374 375 /// Set the size of the vnet hdr. 376 pub fn set_vnet_hdr_size(&self, size: c_int) -> Result<()> { 377 // ioctl is safe. Called with a valid tap fd, and we check the return. 378 let ret = unsafe { ioctl_with_ref(&self.tap_file, net_gen::TUNSETVNETHDRSZ(), &size) }; 379 if ret < 0 { 380 return Err(Error::IoctlError(IoError::last_os_error())); 381 } 382 383 Ok(()) 384 } 385 386 fn get_ifreq(&self) -> net_gen::ifreq { 387 let mut ifreq: net_gen::ifreq = Default::default(); 388 389 // This sets the name of the interface, which is the only entry 390 // in a single-field union. 391 unsafe { 392 let ifrn_name = ifreq.ifr_ifrn.ifrn_name.as_mut(); 393 let name_slice = &mut ifrn_name[..self.if_name.len()]; 394 name_slice.copy_from_slice(&self.if_name); 395 } 396 397 ifreq 398 } 399 400 pub fn get_if_name(&self) -> Vec<u8> { 401 self.if_name.clone() 402 } 403 } 404 405 impl Read for Tap { 406 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { 407 self.tap_file.read(buf) 408 } 409 } 410 411 impl Write for Tap { 412 fn write(&mut self, buf: &[u8]) -> IoResult<usize> { 413 self.tap_file.write(buf) 414 } 415 416 fn flush(&mut self) -> IoResult<()> { 417 Ok(()) 418 } 419 } 420 421 impl AsRawFd for Tap { 422 fn as_raw_fd(&self) -> RawFd { 423 self.tap_file.as_raw_fd() 424 } 425 } 426 427 #[cfg(test)] 428 mod tests { 429 use std::net::Ipv4Addr; 430 use std::str; 431 use std::sync::{mpsc, Mutex}; 432 use std::thread; 433 use std::time::Duration; 434 435 use once_cell::sync::Lazy; 436 437 use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket}; 438 use pnet::packet::ip::IpNextHeaderProtocols; 439 use pnet::packet::ipv4::{Ipv4Packet, MutableIpv4Packet}; 440 use pnet::packet::udp::{MutableUdpPacket, UdpPacket}; 441 use pnet::packet::{MutablePacket, Packet}; 442 use pnet::util::MacAddr; 443 use pnet_datalink::Channel::Ethernet; 444 use pnet_datalink::{DataLinkReceiver, DataLinkSender, NetworkInterface}; 445 446 use super::*; 447 448 static DATA_STRING: &str = "test for tap"; 449 static SUBNET_MASK: &str = "255.255.255.0"; 450 451 // We needed to have a mutex as a global variable, so we used once_cell for testing. The main 452 // potential problem, caused by tests being run in parallel by cargo, is creating different 453 // TAPs and trying to associate the same address, so we hide the IP address &str behind this 454 // mutex, more as a convention to remember to lock it at the very beginning of each function 455 // susceptible to this issue. Another variant is to use a different IP address per function, 456 // but we must remember to pick an unique one each time. 457 static TAP_IP_LOCK: Lazy<Mutex<&'static str>> = Lazy::new(|| Mutex::new("192.168.241.1")); 458 459 // Describes the outcomes we are currently interested in when parsing a packet (we use 460 // an UDP packet for testing). 461 struct ParsedPkt<'a> { 462 eth: EthernetPacket<'a>, 463 ipv4: Option<Ipv4Packet<'a>>, 464 udp: Option<UdpPacket<'a>>, 465 } 466 467 impl<'a> ParsedPkt<'a> { 468 fn new(buf: &'a [u8]) -> Self { 469 let eth = EthernetPacket::new(buf).unwrap(); 470 let mut ipv4 = None; 471 let mut udp = None; 472 473 if eth.get_ethertype() == EtherTypes::Ipv4 { 474 let ipv4_start = 14; 475 ipv4 = Some(Ipv4Packet::new(&buf[ipv4_start..]).unwrap()); 476 477 // Hiding the old ipv4 variable for the rest of this block. 478 let ipv4 = Ipv4Packet::new(eth.payload()).unwrap(); 479 480 if ipv4.get_next_level_protocol() == IpNextHeaderProtocols::Udp { 481 // The value in header_length indicates the number of 32 bit words 482 // that make up the header, not the actual length in bytes. 483 let udp_start = ipv4_start + ipv4.get_header_length() as usize * 4; 484 udp = Some(UdpPacket::new(&buf[udp_start..]).unwrap()); 485 } 486 } 487 488 ParsedPkt { eth, ipv4, udp } 489 } 490 491 fn print(&self) { 492 print!( 493 "{} {} {} ", 494 self.eth.get_source(), 495 self.eth.get_destination(), 496 self.eth.get_ethertype() 497 ); 498 if let Some(ref ipv4) = self.ipv4 { 499 print!( 500 "{} {} {} ", 501 ipv4.get_source(), 502 ipv4.get_destination(), 503 ipv4.get_next_level_protocol() 504 ); 505 } 506 if let Some(ref udp) = self.udp { 507 print!( 508 "{} {} {}", 509 udp.get_source(), 510 udp.get_destination(), 511 str::from_utf8(udp.payload()).unwrap() 512 ); 513 } 514 println!(); 515 } 516 } 517 518 fn tap_name_to_string(tap: &Tap) -> String { 519 let null_pos = tap.if_name.iter().position(|x| *x == 0).unwrap(); 520 str::from_utf8(&tap.if_name[..null_pos]) 521 .unwrap() 522 .to_string() 523 } 524 525 // Given a buffer of appropriate size, this fills in the relevant fields based on the 526 // provided information. Payload refers to the UDP payload. 527 fn pnet_build_packet(buf: &mut [u8], dst_mac: MacAddr, payload: &[u8]) { 528 let mut eth = MutableEthernetPacket::new(buf).unwrap(); 529 eth.set_source(MacAddr::new(0x06, 0, 0, 0, 0, 0)); 530 eth.set_destination(dst_mac); 531 eth.set_ethertype(EtherTypes::Ipv4); 532 533 let mut ipv4 = MutableIpv4Packet::new(eth.payload_mut()).unwrap(); 534 ipv4.set_version(4); 535 ipv4.set_header_length(5); 536 ipv4.set_total_length(20 + 8 + payload.len() as u16); 537 ipv4.set_ttl(200); 538 ipv4.set_next_level_protocol(IpNextHeaderProtocols::Udp); 539 ipv4.set_source(Ipv4Addr::new(192, 168, 241, 1)); 540 ipv4.set_destination(Ipv4Addr::new(192, 168, 241, 2)); 541 542 let mut udp = MutableUdpPacket::new(ipv4.payload_mut()).unwrap(); 543 udp.set_source(1000); 544 udp.set_destination(1001); 545 udp.set_length(8 + payload.len() as u16); 546 udp.set_payload(payload); 547 } 548 549 // Sends a test packet on the interface named "ifname". 550 fn pnet_send_packet(ifname: String) { 551 let payload = DATA_STRING.as_bytes(); 552 553 // eth hdr + ip hdr + udp hdr + payload len 554 let buf_size = 14 + 20 + 8 + payload.len(); 555 556 let (mac, mut tx, _) = pnet_get_mac_tx_rx(ifname); 557 558 let res = tx.build_and_send(1, buf_size, &mut |buf| { 559 pnet_build_packet(buf, mac, payload); 560 }); 561 // Make sure build_and_send() -> Option<io::Result<()>> succeeds. 562 res.unwrap().unwrap(); 563 } 564 565 // For a given interface name, this returns a tuple that contains the MAC address of the 566 // interface, an object that can be used to send Ethernet frames, and a receiver of 567 // Ethernet frames arriving at the specified interface. 568 fn pnet_get_mac_tx_rx( 569 ifname: String, 570 ) -> (MacAddr, Box<dyn DataLinkSender>, Box<dyn DataLinkReceiver>) { 571 let interface_name_matches = |iface: &NetworkInterface| iface.name == ifname; 572 573 // Find the network interface with the provided name. 574 let interfaces = pnet_datalink::interfaces(); 575 let interface = interfaces.into_iter().find(interface_name_matches).unwrap(); 576 577 if let Ok(Ethernet(tx, rx)) = pnet_datalink::channel(&interface, Default::default()) { 578 (interface.mac.unwrap(), tx, rx) 579 } else { 580 panic!("datalink channel error or unhandled channel type"); 581 } 582 } 583 584 #[test] 585 fn test_tap_create() { 586 let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 587 588 let t = Tap::new(1).unwrap(); 589 println!("created tap: {:?}", t); 590 } 591 592 #[test] 593 fn test_tap_from_fd() { 594 let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 595 596 let orig_tap = Tap::new(1).unwrap(); 597 let fd = orig_tap.as_raw_fd(); 598 let _new_tap = Tap::from_tap_fd(fd, 1).unwrap(); 599 } 600 601 #[test] 602 fn test_tap_configure() { 603 // This should be the first thing to be called inside the function, so everything else 604 // is torn down by the time the mutex is automatically released. Also, we should 605 // explicitly bind the MutexGuard to a variable via let, the make sure it lives until 606 // the end of the function. 607 let tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 608 609 let tap = Tap::new(1).unwrap(); 610 let ip_addr: net::Ipv4Addr = (*tap_ip_guard).parse().unwrap(); 611 let netmask: net::Ipv4Addr = SUBNET_MASK.parse().unwrap(); 612 613 let ret = tap.set_ip_addr(ip_addr); 614 assert!(ret.is_ok()); 615 let ret = tap.set_netmask(netmask); 616 assert!(ret.is_ok()); 617 } 618 619 #[test] 620 fn test_set_options() { 621 let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 622 623 // This line will fail to provide an initialized FD if the test is not run as root. 624 let tap = Tap::new(1).unwrap(); 625 tap.set_vnet_hdr_size(16).unwrap(); 626 tap.set_offload(0).unwrap(); 627 } 628 629 #[test] 630 fn test_tap_enable() { 631 let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 632 633 let tap = Tap::new(1).unwrap(); 634 let ret = tap.enable(); 635 assert!(ret.is_ok()); 636 } 637 638 #[test] 639 fn test_raw_fd() { 640 let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 641 642 let tap = Tap::new(1).unwrap(); 643 assert_eq!(tap.as_raw_fd(), tap.tap_file.as_raw_fd()); 644 } 645 646 #[test] 647 fn test_read() { 648 let tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 649 650 let mut tap = Tap::new(1).unwrap(); 651 tap.set_ip_addr((*tap_ip_guard).parse().unwrap()).unwrap(); 652 tap.set_netmask(SUBNET_MASK.parse().unwrap()).unwrap(); 653 tap.enable().unwrap(); 654 655 // Send a packet to the interface. We expect to be able to receive it on the associated fd. 656 pnet_send_packet(tap_name_to_string(&tap)); 657 658 let mut buf = [0u8; 4096]; 659 660 let mut found_packet_sz = None; 661 662 // In theory, this could actually loop forever if something keeps sending data through the 663 // tap interface, but it's highly unlikely. 664 while found_packet_sz.is_none() { 665 let result = tap.read(&mut buf); 666 assert!(result.is_ok()); 667 668 let size = result.unwrap(); 669 670 // We skip the first 10 bytes because the IFF_VNET_HDR flag is set when the interface 671 // is created, and the legacy header is 10 bytes long without a certain flag which 672 // is not set in Tap::new(). 673 let eth_bytes = &buf[10..size]; 674 675 let packet = EthernetPacket::new(eth_bytes).unwrap(); 676 if packet.get_ethertype() != EtherTypes::Ipv4 { 677 // not an IPv4 packet 678 continue; 679 } 680 681 let ipv4_bytes = ð_bytes[14..]; 682 let packet = Ipv4Packet::new(ipv4_bytes).unwrap(); 683 684 // Our packet should carry an UDP payload, and not contain IP options. 685 if packet.get_next_level_protocol() != IpNextHeaderProtocols::Udp 686 && packet.get_header_length() != 5 687 { 688 continue; 689 } 690 691 let udp_bytes = &ipv4_bytes[20..]; 692 693 let udp_len = UdpPacket::new(udp_bytes).unwrap().get_length() as usize; 694 695 // Skip the header bytes. 696 let inner_string = str::from_utf8(&udp_bytes[8..udp_len]).unwrap(); 697 698 if inner_string.eq(DATA_STRING) { 699 found_packet_sz = Some(size); 700 break; 701 } 702 } 703 704 assert!(found_packet_sz.is_some()); 705 } 706 707 #[test] 708 fn test_write() { 709 let tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); 710 711 let mut tap = Tap::new(1).unwrap(); 712 tap.set_ip_addr((*tap_ip_guard).parse().unwrap()).unwrap(); 713 tap.set_netmask(SUBNET_MASK.parse().unwrap()).unwrap(); 714 tap.enable().unwrap(); 715 716 let (mac, _, mut rx) = pnet_get_mac_tx_rx(tap_name_to_string(&tap)); 717 718 let payload = DATA_STRING.as_bytes(); 719 720 // vnet hdr + eth hdr + ip hdr + udp hdr + payload len 721 let buf_size = 10 + 14 + 20 + 8 + payload.len(); 722 723 let mut buf = vec![0u8; buf_size]; 724 // leave the vnet hdr as is 725 pnet_build_packet(&mut buf[10..], mac, payload); 726 727 assert!(tap.write(&buf[..]).is_ok()); 728 assert!(tap.flush().is_ok()); 729 730 let (channel_tx, channel_rx) = mpsc::channel(); 731 732 // We use a separate thread to wait for the test packet because the API exposed by pnet is 733 // blocking. This thread will be killed when the main thread exits. 734 let _handle = thread::spawn(move || loop { 735 let buf = rx.next().unwrap(); 736 let p = ParsedPkt::new(buf); 737 p.print(); 738 739 if let Some(ref udp) = p.udp { 740 if payload == udp.payload() { 741 channel_tx.send(true).unwrap(); 742 break; 743 } 744 } 745 }); 746 747 // We wait for at most SLEEP_MILLIS * SLEEP_ITERS milliseconds for the reception of the 748 // test packet to be detected. 749 static SLEEP_MILLIS: u64 = 500; 750 static SLEEP_ITERS: u32 = 6; 751 752 let mut found_test_packet = false; 753 754 for _ in 0..SLEEP_ITERS { 755 thread::sleep(Duration::from_millis(SLEEP_MILLIS)); 756 if let Ok(true) = channel_rx.try_recv() { 757 found_test_packet = true; 758 break; 759 } 760 } 761 762 assert!(found_test_packet); 763 } 764 } 765