mod.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*! Access to networking hardware.
  2. The `phy` module deals with the *network devices*. It provides a trait
  3. for transmitting and receiving frames, [Device](trait.Device.html)
  4. and implementations of it:
  5. * the [_loopback_](struct.Loopback.html), for zero dependency testing;
  6. * _middleware_ [Tracer](struct.Tracer.html) and
  7. [FaultInjector](struct.FaultInjector.html), to facilitate debugging;
  8. * _adapters_ [RawSocket](struct.RawSocket.html) and
  9. [TunTapInterface](struct.TunTapInterface.html), to transmit and receive frames
  10. on the host OS.
  11. */
  12. #![cfg_attr(
  13. feature = "medium-ethernet",
  14. doc = r##"
  15. # Examples
  16. An implementation of the [Device](trait.Device.html) trait for a simple hardware
  17. Ethernet controller could look as follows:
  18. ```rust
  19. use smoltcp::phy::{self, DeviceCapabilities, Device, Medium};
  20. use smoltcp::time::Instant;
  21. struct StmPhy {
  22. rx_buffer: [u8; 1536],
  23. tx_buffer: [u8; 1536],
  24. }
  25. impl<'a> StmPhy {
  26. fn new() -> StmPhy {
  27. StmPhy {
  28. rx_buffer: [0; 1536],
  29. tx_buffer: [0; 1536],
  30. }
  31. }
  32. }
  33. impl phy::Device for StmPhy {
  34. type RxToken<'a> = StmPhyRxToken<'a> where Self: 'a;
  35. type TxToken<'a> = StmPhyTxToken<'a> where Self: 'a;
  36. fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
  37. Some((StmPhyRxToken(&mut self.rx_buffer[..]),
  38. StmPhyTxToken(&mut self.tx_buffer[..])))
  39. }
  40. fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
  41. Some(StmPhyTxToken(&mut self.tx_buffer[..]))
  42. }
  43. fn capabilities(&self) -> DeviceCapabilities {
  44. let mut caps = DeviceCapabilities::default();
  45. caps.max_transmission_unit = 1536;
  46. caps.max_burst_size = Some(1);
  47. caps.medium = Medium::Ethernet;
  48. caps
  49. }
  50. }
  51. struct StmPhyRxToken<'a>(&'a mut [u8]);
  52. impl<'a> phy::RxToken for StmPhyRxToken<'a> {
  53. fn consume<R, F>(mut self, f: F) -> R
  54. where F: FnOnce(&mut [u8]) -> R
  55. {
  56. // TODO: receive packet into buffer
  57. let result = f(&mut self.0);
  58. println!("rx called");
  59. result
  60. }
  61. }
  62. struct StmPhyTxToken<'a>(&'a mut [u8]);
  63. impl<'a> phy::TxToken for StmPhyTxToken<'a> {
  64. fn consume<R, F>(self, len: usize, f: F) -> R
  65. where F: FnOnce(&mut [u8]) -> R
  66. {
  67. let result = f(&mut self.0[..len]);
  68. println!("tx called {}", len);
  69. // TODO: send packet out
  70. result
  71. }
  72. }
  73. ```
  74. "##
  75. )]
  76. use crate::time::Instant;
  77. #[cfg(all(
  78. any(feature = "phy-raw_socket", feature = "phy-tuntap_interface"),
  79. unix
  80. ))]
  81. mod sys;
  82. mod fault_injector;
  83. mod fuzz_injector;
  84. #[cfg(feature = "alloc")]
  85. mod loopback;
  86. mod pcap_writer;
  87. #[cfg(all(feature = "phy-raw_socket", unix))]
  88. mod raw_socket;
  89. mod tracer;
  90. #[cfg(all(
  91. feature = "phy-tuntap_interface",
  92. any(target_os = "linux", target_os = "android")
  93. ))]
  94. mod tuntap_interface;
  95. #[cfg(all(
  96. any(feature = "phy-raw_socket", feature = "phy-tuntap_interface"),
  97. unix
  98. ))]
  99. pub use self::sys::wait;
  100. pub use self::fault_injector::FaultInjector;
  101. pub use self::fuzz_injector::{FuzzInjector, Fuzzer};
  102. #[cfg(feature = "alloc")]
  103. pub use self::loopback::Loopback;
  104. pub use self::pcap_writer::{PcapLinkType, PcapMode, PcapSink, PcapWriter};
  105. #[cfg(all(feature = "phy-raw_socket", unix))]
  106. pub use self::raw_socket::RawSocket;
  107. pub use self::tracer::Tracer;
  108. #[cfg(all(
  109. feature = "phy-tuntap_interface",
  110. any(target_os = "linux", target_os = "android")
  111. ))]
  112. pub use self::tuntap_interface::TunTapInterface;
  113. /// An ID that can be used to uniquely identify a packet to a [`Device`],
  114. /// sent or received by that same [`Device`]
  115. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  116. #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Default)]
  117. #[non_exhaustive]
  118. pub struct PacketMeta {
  119. #[cfg(feature = "packet-id")]
  120. pub id: Option<u32>,
  121. }
  122. /// A description of checksum behavior for a particular protocol.
  123. #[derive(Debug, Clone, Copy, Default)]
  124. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  125. pub enum Checksum {
  126. /// Verify checksum when receiving and compute checksum when sending.
  127. #[default]
  128. Both,
  129. /// Verify checksum when receiving.
  130. Rx,
  131. /// Compute checksum before sending.
  132. Tx,
  133. /// Ignore checksum completely.
  134. None,
  135. }
  136. impl Checksum {
  137. /// Returns whether checksum should be verified when receiving.
  138. pub fn rx(&self) -> bool {
  139. match *self {
  140. Checksum::Both | Checksum::Rx => true,
  141. _ => false,
  142. }
  143. }
  144. /// Returns whether checksum should be verified when sending.
  145. pub fn tx(&self) -> bool {
  146. match *self {
  147. Checksum::Both | Checksum::Tx => true,
  148. _ => false,
  149. }
  150. }
  151. }
  152. /// A description of checksum behavior for every supported protocol.
  153. #[derive(Debug, Clone, Default)]
  154. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  155. #[non_exhaustive]
  156. pub struct ChecksumCapabilities {
  157. pub ipv4: Checksum,
  158. pub udp: Checksum,
  159. pub tcp: Checksum,
  160. #[cfg(feature = "proto-ipv4")]
  161. pub icmpv4: Checksum,
  162. #[cfg(feature = "proto-ipv6")]
  163. pub icmpv6: Checksum,
  164. }
  165. impl ChecksumCapabilities {
  166. /// Checksum behavior that results in not computing or verifying checksums
  167. /// for any of the supported protocols.
  168. pub fn ignored() -> Self {
  169. ChecksumCapabilities {
  170. ipv4: Checksum::None,
  171. udp: Checksum::None,
  172. tcp: Checksum::None,
  173. #[cfg(feature = "proto-ipv4")]
  174. icmpv4: Checksum::None,
  175. #[cfg(feature = "proto-ipv6")]
  176. icmpv6: Checksum::None,
  177. }
  178. }
  179. }
  180. /// A description of device capabilities.
  181. ///
  182. /// Higher-level protocols may achieve higher throughput or lower latency if they consider
  183. /// the bandwidth or packet size limitations.
  184. #[derive(Debug, Clone, Default)]
  185. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  186. #[non_exhaustive]
  187. pub struct DeviceCapabilities {
  188. /// Medium of the device.
  189. ///
  190. /// This indicates what kind of packet the sent/received bytes are, and determines
  191. /// some behaviors of Interface. For example, ARP/NDISC address resolution is only done
  192. /// for Ethernet mediums.
  193. pub medium: Medium,
  194. /// Maximum transmission unit.
  195. ///
  196. /// The network device is unable to send or receive frames larger than the value returned
  197. /// by this function.
  198. ///
  199. /// For Ethernet devices, this is the maximum Ethernet frame size, including the Ethernet header (14 octets), but
  200. /// *not* including the Ethernet FCS (4 octets). Therefore, Ethernet MTU = IP MTU + 14.
  201. ///
  202. /// Note that in Linux and other OSes, "MTU" is the IP MTU, not the Ethernet MTU, even for Ethernet
  203. /// devices. This is a common source of confusion.
  204. ///
  205. /// Most common IP MTU is 1500. Minimum is 576 (for IPv4) or 1280 (for IPv6). Maximum is 9216 octets.
  206. pub max_transmission_unit: usize,
  207. /// Maximum burst size, in terms of MTU.
  208. ///
  209. /// The network device is unable to send or receive bursts large than the value returned
  210. /// by this function.
  211. ///
  212. /// If `None`, there is no fixed limit on burst size, e.g. if network buffers are
  213. /// dynamically allocated.
  214. pub max_burst_size: Option<usize>,
  215. /// Checksum behavior.
  216. ///
  217. /// If the network device is capable of verifying or computing checksums for some protocols,
  218. /// it can request that the stack not do so in software to improve performance.
  219. pub checksum: ChecksumCapabilities,
  220. }
  221. impl DeviceCapabilities {
  222. pub fn ip_mtu(&self) -> usize {
  223. match self.medium {
  224. #[cfg(feature = "medium-ethernet")]
  225. Medium::Ethernet => {
  226. self.max_transmission_unit - crate::wire::EthernetFrame::<&[u8]>::header_len()
  227. }
  228. #[cfg(feature = "medium-ip")]
  229. Medium::Ip => self.max_transmission_unit,
  230. #[cfg(feature = "medium-ieee802154")]
  231. Medium::Ieee802154 => self.max_transmission_unit, // TODO(thvdveld): what is the MTU for Medium::IEEE802
  232. }
  233. }
  234. }
  235. /// Type of medium of a device.
  236. #[derive(Debug, Eq, PartialEq, Copy, Clone)]
  237. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  238. pub enum Medium {
  239. /// Ethernet medium. Devices of this type send and receive Ethernet frames,
  240. /// and interfaces using it must do neighbor discovery via ARP or NDISC.
  241. ///
  242. /// Examples of devices of this type are Ethernet, WiFi (802.11), Linux `tap`, and VPNs in tap (layer 2) mode.
  243. #[cfg(feature = "medium-ethernet")]
  244. Ethernet,
  245. /// IP medium. Devices of this type send and receive IP frames, without an
  246. /// Ethernet header. MAC addresses are not used, and no neighbor discovery (ARP, NDISC) is done.
  247. ///
  248. /// Examples of devices of this type are the Linux `tun`, PPP interfaces, VPNs in tun (layer 3) mode.
  249. #[cfg(feature = "medium-ip")]
  250. Ip,
  251. #[cfg(feature = "medium-ieee802154")]
  252. Ieee802154,
  253. }
  254. impl Default for Medium {
  255. fn default() -> Medium {
  256. #[cfg(feature = "medium-ethernet")]
  257. return Medium::Ethernet;
  258. #[cfg(all(feature = "medium-ip", not(feature = "medium-ethernet")))]
  259. return Medium::Ip;
  260. #[cfg(all(
  261. feature = "medium-ieee802154",
  262. not(feature = "medium-ip"),
  263. not(feature = "medium-ethernet")
  264. ))]
  265. return Medium::Ieee802154;
  266. #[cfg(all(
  267. not(feature = "medium-ip"),
  268. not(feature = "medium-ethernet"),
  269. not(feature = "medium-ieee802154")
  270. ))]
  271. return panic!("No medium enabled");
  272. }
  273. }
  274. /// An interface for sending and receiving raw network frames.
  275. ///
  276. /// The interface is based on _tokens_, which are types that allow to receive/transmit a
  277. /// single packet. The `receive` and `transmit` functions only construct such tokens, the
  278. /// real sending/receiving operation are performed when the tokens are consumed.
  279. pub trait Device {
  280. type RxToken<'a>: RxToken
  281. where
  282. Self: 'a;
  283. type TxToken<'a>: TxToken
  284. where
  285. Self: 'a;
  286. /// Construct a token pair consisting of one receive token and one transmit token.
  287. ///
  288. /// The additional transmit token makes it possible to generate a reply packet based
  289. /// on the contents of the received packet. For example, this makes it possible to
  290. /// handle arbitrarily large ICMP echo ("ping") requests, where the all received bytes
  291. /// need to be sent back, without heap allocation.
  292. ///
  293. /// The timestamp must be a number of milliseconds, monotonically increasing since an
  294. /// arbitrary moment in time, such as system startup.
  295. fn receive(&mut self, timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)>;
  296. /// Construct a transmit token.
  297. ///
  298. /// The timestamp must be a number of milliseconds, monotonically increasing since an
  299. /// arbitrary moment in time, such as system startup.
  300. fn transmit(&mut self, timestamp: Instant) -> Option<Self::TxToken<'_>>;
  301. /// Get a description of device capabilities.
  302. fn capabilities(&self) -> DeviceCapabilities;
  303. }
  304. /// A token to receive a single network packet.
  305. pub trait RxToken {
  306. /// Consumes the token to receive a single network packet.
  307. ///
  308. /// This method receives a packet and then calls the given closure `f` with the raw
  309. /// packet bytes as argument.
  310. fn consume<R, F>(self, f: F) -> R
  311. where
  312. F: FnOnce(&mut [u8]) -> R;
  313. /// The Packet ID associated with the frame received by this [`RxToken`]
  314. fn meta(&self) -> PacketMeta {
  315. PacketMeta::default()
  316. }
  317. }
  318. /// A token to transmit a single network packet.
  319. pub trait TxToken {
  320. /// Consumes the token to send a single network packet.
  321. ///
  322. /// This method constructs a transmit buffer of size `len` and calls the passed
  323. /// closure `f` with a mutable reference to that buffer. The closure should construct
  324. /// a valid network packet (e.g. an ethernet packet) in the buffer. When the closure
  325. /// returns, the transmit buffer is sent out.
  326. fn consume<R, F>(self, len: usize, f: F) -> R
  327. where
  328. F: FnOnce(&mut [u8]) -> R;
  329. /// The Packet ID to be associated with the frame to be transmitted by this [`TxToken`].
  330. #[allow(unused_variables)]
  331. fn set_meta(&mut self, meta: PacketMeta) {}
  332. }