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