tuntap_interface.rs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. use std::cell::RefCell;
  2. use std::io;
  3. use std::os::unix::io::{AsRawFd, RawFd};
  4. use std::rc::Rc;
  5. use std::vec::Vec;
  6. use crate::phy::{self, sys, Device, DeviceCapabilities, Medium};
  7. use crate::time::Instant;
  8. /// A virtual TUN (IP) or TAP (Ethernet) interface.
  9. #[derive(Debug)]
  10. pub struct TunTapInterface {
  11. lower: Rc<RefCell<sys::TunTapInterfaceDesc>>,
  12. mtu: usize,
  13. medium: Medium,
  14. }
  15. impl AsRawFd for TunTapInterface {
  16. fn as_raw_fd(&self) -> RawFd {
  17. self.lower.borrow().as_raw_fd()
  18. }
  19. }
  20. impl TunTapInterface {
  21. /// Attaches to a TUN/TAP interface called `name`, or creates it if it does not exist.
  22. ///
  23. /// If `name` is a persistent interface configured with UID of the current user,
  24. /// no special privileges are needed. Otherwise, this requires superuser privileges
  25. /// or a corresponding capability set on the executable.
  26. pub fn new(name: &str, medium: Medium) -> io::Result<TunTapInterface> {
  27. let lower = sys::TunTapInterfaceDesc::new(name, medium)?;
  28. let mtu = lower.interface_mtu()?;
  29. Ok(TunTapInterface {
  30. lower: Rc::new(RefCell::new(lower)),
  31. mtu,
  32. medium,
  33. })
  34. }
  35. /// Attaches to a TUN/TAP interface specified by file descriptor `fd`.
  36. ///
  37. /// On platforms like Android, a file descriptor to a tun interface is exposed.
  38. /// On these platforms, a TunTapInterface cannot be instantiated with a name.
  39. pub fn from_fd(fd: RawFd, medium: Medium, mtu: usize) -> io::Result<TunTapInterface> {
  40. let lower = sys::TunTapInterfaceDesc::from_fd(fd, mtu)?;
  41. Ok(TunTapInterface {
  42. lower: Rc::new(RefCell::new(lower)),
  43. mtu,
  44. medium,
  45. })
  46. }
  47. }
  48. impl Device for TunTapInterface {
  49. type RxToken<'a> = RxToken;
  50. type TxToken<'a> = TxToken;
  51. fn capabilities(&self) -> DeviceCapabilities {
  52. DeviceCapabilities {
  53. max_transmission_unit: self.mtu,
  54. medium: self.medium,
  55. ..DeviceCapabilities::default()
  56. }
  57. }
  58. fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
  59. let mut lower = self.lower.borrow_mut();
  60. let mut buffer = vec![0; self.mtu];
  61. match lower.recv(&mut buffer[..]) {
  62. Ok(size) => {
  63. buffer.resize(size, 0);
  64. let rx = RxToken { buffer };
  65. let tx = TxToken {
  66. lower: self.lower.clone(),
  67. };
  68. Some((rx, tx))
  69. }
  70. Err(err) if err.kind() == io::ErrorKind::WouldBlock => None,
  71. Err(err) => panic!("{}", err),
  72. }
  73. }
  74. fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
  75. Some(TxToken {
  76. lower: self.lower.clone(),
  77. })
  78. }
  79. }
  80. #[doc(hidden)]
  81. pub struct RxToken {
  82. buffer: Vec<u8>,
  83. }
  84. impl phy::RxToken for RxToken {
  85. fn consume<R, F>(mut self, f: F) -> R
  86. where
  87. F: FnOnce(&mut [u8]) -> R,
  88. {
  89. f(&mut self.buffer[..])
  90. }
  91. }
  92. #[doc(hidden)]
  93. pub struct TxToken {
  94. lower: Rc<RefCell<sys::TunTapInterfaceDesc>>,
  95. }
  96. impl phy::TxToken for TxToken {
  97. fn consume<R, F>(self, len: usize, f: F) -> R
  98. where
  99. F: FnOnce(&mut [u8]) -> R,
  100. {
  101. let mut lower = self.lower.borrow_mut();
  102. let mut buffer = vec![0; len];
  103. let result = f(&mut buffer);
  104. match lower.send(&buffer[..]) {
  105. Ok(_) => {}
  106. Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
  107. net_debug!("phy: tx failed due to WouldBlock")
  108. }
  109. Err(err) => panic!("{}", err),
  110. }
  111. result
  112. }
  113. }