Skip to main content

embassy_net/
lib.rs

1#![no_std]
2#![allow(async_fn_in_trait)]
3#![allow(unsafe_op_in_unsafe_fn)]
4#![warn(missing_docs)]
5#![doc = include_str!("../README.md")]
6
7//! ## Feature flags
8#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
9
10#[cfg(not(any(feature = "proto-ipv4", feature = "proto-ipv6")))]
11compile_error!("You must enable at least one of the following features: proto-ipv4, proto-ipv6");
12
13// This mod MUST go first, so that the others see its macros.
14pub(crate) mod fmt;
15
16#[cfg(feature = "dns")]
17pub mod dns;
18mod driver_util;
19#[cfg(feature = "icmp")]
20pub mod icmp;
21#[cfg(feature = "raw")]
22pub mod raw;
23#[cfg(feature = "tcp")]
24pub mod tcp;
25mod time;
26#[cfg(feature = "udp")]
27pub mod udp;
28
29use core::cell::RefCell;
30use core::future::{Future, poll_fn};
31use core::mem::MaybeUninit;
32use core::pin::pin;
33use core::task::{Context, Poll};
34
35pub use embassy_net_driver as driver;
36use embassy_net_driver::{Driver, LinkState};
37use embassy_sync::waitqueue::WakerRegistration;
38use embassy_time::{Instant, Timer};
39use heapless::Vec;
40#[cfg(feature = "dns")]
41pub use smoltcp::config::DNS_MAX_SERVER_COUNT;
42#[cfg(feature = "multicast")]
43pub use smoltcp::iface::MulticastError;
44#[cfg(any(feature = "dns", feature = "dhcpv4"))]
45use smoltcp::iface::SocketHandle;
46use smoltcp::iface::{Interface, SocketSet, SocketStorage};
47use smoltcp::phy::Medium;
48#[cfg(feature = "dhcpv4")]
49use smoltcp::socket::dhcpv4::{self, RetryConfig};
50#[cfg(feature = "medium-ethernet")]
51pub use smoltcp::wire::EthernetAddress;
52#[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154", feature = "medium-ip"))]
53pub use smoltcp::wire::HardwareAddress;
54#[cfg(any(feature = "udp", feature = "tcp"))]
55pub use smoltcp::wire::IpListenEndpoint;
56#[cfg(feature = "medium-ieee802154")]
57pub use smoltcp::wire::{Ieee802154Address, Ieee802154Frame};
58pub use smoltcp::wire::{IpAddress, IpCidr, IpEndpoint};
59#[cfg(feature = "proto-ipv4")]
60pub use smoltcp::wire::{Ipv4Address, Ipv4Cidr};
61#[cfg(feature = "proto-ipv6")]
62pub use smoltcp::wire::{Ipv6Address, Ipv6Cidr};
63
64use crate::driver_util::DriverAdapter;
65use crate::time::{instant_from_smoltcp, instant_to_smoltcp};
66
67const LOCAL_PORT_MIN: u16 = 1025;
68const LOCAL_PORT_MAX: u16 = 65535;
69#[cfg(feature = "dns")]
70const MAX_QUERIES: usize = 4;
71#[cfg(feature = "dhcpv4-hostname")]
72const MAX_HOSTNAME_LEN: usize = 32;
73
74/// Memory resources needed for a network stack.
75pub struct StackResources<const SOCK: usize> {
76    sockets: MaybeUninit<[SocketStorage<'static>; SOCK]>,
77    inner: MaybeUninit<RefCell<Inner>>,
78    #[cfg(feature = "dns")]
79    queries: MaybeUninit<[Option<dns::DnsQuery>; MAX_QUERIES]>,
80    #[cfg(feature = "dhcpv4-hostname")]
81    hostname: HostnameResources,
82}
83
84#[cfg(feature = "dhcpv4-hostname")]
85struct HostnameResources {
86    option: MaybeUninit<smoltcp::wire::DhcpOption<'static>>,
87    data: MaybeUninit<[u8; MAX_HOSTNAME_LEN]>,
88}
89
90impl<const SOCK: usize> StackResources<SOCK> {
91    /// Create a new set of stack resources.
92    pub const fn new() -> Self {
93        Self {
94            sockets: MaybeUninit::uninit(),
95            inner: MaybeUninit::uninit(),
96            #[cfg(feature = "dns")]
97            queries: MaybeUninit::uninit(),
98            #[cfg(feature = "dhcpv4-hostname")]
99            hostname: HostnameResources {
100                option: MaybeUninit::uninit(),
101                data: MaybeUninit::uninit(),
102            },
103        }
104    }
105}
106
107/// Static IP address configuration.
108#[cfg(feature = "proto-ipv4")]
109#[derive(Debug, Clone, PartialEq, Eq)]
110#[cfg_attr(feature = "defmt", derive(defmt::Format))]
111pub struct StaticConfigV4 {
112    /// IP address and subnet mask.
113    pub address: Ipv4Cidr,
114    /// Default gateway.
115    pub gateway: Option<Ipv4Address>,
116    /// DNS servers.
117    pub dns_servers: Vec<Ipv4Address, 3>,
118}
119
120/// Static IPv6 address configuration
121#[cfg(feature = "proto-ipv6")]
122#[derive(Debug, Clone, PartialEq, Eq)]
123#[cfg_attr(feature = "defmt", derive(defmt::Format))]
124pub struct StaticConfigV6 {
125    /// IP address and subnet mask.
126    pub address: Ipv6Cidr,
127    /// Default gateway.
128    pub gateway: Option<Ipv6Address>,
129    /// DNS servers.
130    pub dns_servers: Vec<Ipv6Address, 3>,
131}
132
133/// DHCP configuration.
134#[cfg(feature = "dhcpv4")]
135#[derive(Debug, Clone, PartialEq, Eq)]
136#[cfg_attr(feature = "defmt", derive(defmt::Format))]
137#[non_exhaustive]
138pub struct DhcpConfig {
139    /// Maximum lease duration.
140    ///
141    /// If not set, the lease duration specified by the server will be used.
142    /// If set, the lease duration will be capped at this value.
143    pub max_lease_duration: Option<embassy_time::Duration>,
144    /// Retry configuration.
145    pub retry_config: RetryConfig,
146    /// Ignore NAKs from DHCP servers.
147    ///
148    /// This is not compliant with the DHCP RFCs, since theoretically we must stop using the assigned IP when receiving a NAK. This can increase reliability on broken networks with buggy routers or rogue DHCP servers, however.
149    pub ignore_naks: bool,
150    /// Server port. This is almost always 67. Do not change unless you know what you're doing.
151    pub server_port: u16,
152    /// Client port. This is almost always 68. Do not change unless you know what you're doing.
153    pub client_port: u16,
154    /// Our hostname. This will be sent to the DHCP server as Option 12.
155    #[cfg(feature = "dhcpv4-hostname")]
156    pub hostname: Option<heapless::String<MAX_HOSTNAME_LEN>>,
157}
158
159#[cfg(feature = "dhcpv4")]
160impl Default for DhcpConfig {
161    fn default() -> Self {
162        Self {
163            max_lease_duration: Default::default(),
164            retry_config: Default::default(),
165            ignore_naks: Default::default(),
166            server_port: smoltcp::wire::DHCP_SERVER_PORT,
167            client_port: smoltcp::wire::DHCP_CLIENT_PORT,
168            #[cfg(feature = "dhcpv4-hostname")]
169            hostname: None,
170        }
171    }
172}
173
174/// Network stack configuration.
175#[derive(Debug, Clone, Default, PartialEq, Eq)]
176#[cfg_attr(feature = "defmt", derive(defmt::Format))]
177#[non_exhaustive]
178pub struct Config {
179    /// IPv4 configuration
180    #[cfg(feature = "proto-ipv4")]
181    pub ipv4: ConfigV4,
182    /// IPv6 configuration
183    #[cfg(feature = "proto-ipv6")]
184    pub ipv6: ConfigV6,
185}
186
187impl Config {
188    /// IPv4 configuration with static addressing.
189    #[cfg(feature = "proto-ipv4")]
190    pub const fn ipv4_static(config: StaticConfigV4) -> Self {
191        Self {
192            ipv4: ConfigV4::Static(config),
193            #[cfg(feature = "proto-ipv6")]
194            ipv6: ConfigV6::None,
195        }
196    }
197
198    /// IPv6 configuration with static addressing.
199    #[cfg(feature = "proto-ipv6")]
200    pub const fn ipv6_static(config: StaticConfigV6) -> Self {
201        Self {
202            #[cfg(feature = "proto-ipv4")]
203            ipv4: ConfigV4::None,
204            ipv6: ConfigV6::Static(config),
205        }
206    }
207
208    /// IPv4 configuration with dynamic addressing.
209    ///
210    /// # Example
211    /// ```rust
212    /// # use embassy_net::Config;
213    /// let _cfg = Config::dhcpv4(Default::default());
214    /// ```
215    #[cfg(feature = "dhcpv4")]
216    pub const fn dhcpv4(config: DhcpConfig) -> Self {
217        Self {
218            ipv4: ConfigV4::Dhcp(config),
219            #[cfg(feature = "proto-ipv6")]
220            ipv6: ConfigV6::None,
221        }
222    }
223
224    /// Slaac configuration with dynamic addressing.
225    #[cfg(feature = "slaac")]
226    pub const fn slaac() -> Self {
227        Self {
228            #[cfg(feature = "proto-ipv4")]
229            ipv4: ConfigV4::None,
230            ipv6: ConfigV6::Slaac,
231        }
232    }
233}
234
235/// Network stack IPv4 configuration.
236#[cfg(feature = "proto-ipv4")]
237#[derive(Debug, Clone, Default, PartialEq, Eq)]
238#[cfg_attr(feature = "defmt", derive(defmt::Format))]
239pub enum ConfigV4 {
240    /// Do not configure IPv4.
241    #[default]
242    None,
243    /// Use a static IPv4 address configuration.
244    Static(StaticConfigV4),
245    /// Use DHCP to obtain an IP address configuration.
246    #[cfg(feature = "dhcpv4")]
247    Dhcp(DhcpConfig),
248}
249
250/// Network stack IPv6 configuration.
251#[cfg(feature = "proto-ipv6")]
252#[derive(Debug, Clone, Default, PartialEq, Eq)]
253#[cfg_attr(feature = "defmt", derive(defmt::Format))]
254pub enum ConfigV6 {
255    /// Do not configure IPv6.
256    #[default]
257    None,
258    /// Use a static IPv6 address configuration.
259    Static(StaticConfigV6),
260    /// Use SLAAC for IPv6 address configuration.
261    #[cfg(feature = "slaac")]
262    Slaac,
263}
264
265/// Network stack runner.
266///
267/// You must call [`Runner::run()`] in a background task for the network stack to work.
268pub struct Runner<'d, D: Driver> {
269    driver: D,
270    stack: Stack<'d>,
271}
272
273/// Network stack handle
274///
275/// Use this to create sockets. It's `Copy`, so you can pass
276/// it by value instead of by reference.
277#[derive(Copy, Clone)]
278pub struct Stack<'d> {
279    inner: &'d RefCell<Inner>,
280}
281
282pub(crate) struct Inner {
283    pub(crate) sockets: SocketSet<'static>, // Lifetime type-erased.
284    pub(crate) iface: Interface,
285    /// Waker used for triggering polls.
286    pub(crate) waker: WakerRegistration,
287    /// Waker used for waiting for link up or config up.
288    state_waker: WakerRegistration,
289    hardware_address: HardwareAddress,
290    next_local_port: u16,
291    link_up: bool,
292    #[cfg(feature = "proto-ipv4")]
293    static_v4: Option<StaticConfigV4>,
294    #[cfg(feature = "proto-ipv6")]
295    static_v6: Option<StaticConfigV6>,
296    #[cfg(feature = "slaac")]
297    slaac: bool,
298    #[cfg(feature = "dhcpv4")]
299    dhcp_socket: Option<SocketHandle>,
300    #[cfg(feature = "dns")]
301    dns_socket: SocketHandle,
302    #[cfg(feature = "dns")]
303    dns_waker: WakerRegistration,
304    #[cfg(feature = "dhcpv4-hostname")]
305    hostname: *mut HostnameResources,
306}
307
308fn _assert_covariant<'a, 'b: 'a>(x: Stack<'b>) -> Stack<'a> {
309    x
310}
311
312/// Create a new network stack.
313pub fn new<'d, D: Driver, const SOCK: usize>(
314    mut driver: D,
315    config: Config,
316    resources: &'d mut StackResources<SOCK>,
317    random_seed: u64,
318) -> (Stack<'d>, Runner<'d, D>) {
319    let (hardware_address, medium) = to_smoltcp_hardware_address(driver.hardware_address());
320    let mut iface_cfg = smoltcp::iface::Config::new(hardware_address);
321    iface_cfg.random_seed = random_seed;
322    #[cfg(feature = "slaac")]
323    {
324        iface_cfg.slaac = matches!(config.ipv6, ConfigV6::Slaac);
325    }
326
327    #[allow(unused_mut)]
328    let mut iface = Interface::new(
329        iface_cfg,
330        &mut DriverAdapter {
331            inner: &mut driver,
332            cx: None,
333            medium,
334        },
335        instant_to_smoltcp(Instant::now()),
336    );
337
338    unsafe fn transmute_slice<T>(x: &mut [T]) -> &'static mut [T] {
339        core::mem::transmute(x)
340    }
341
342    let sockets = resources.sockets.write([SocketStorage::EMPTY; SOCK]);
343    #[allow(unused_mut)]
344    let mut sockets: SocketSet<'static> = SocketSet::new(unsafe { transmute_slice(sockets) });
345
346    let next_local_port = (random_seed % (LOCAL_PORT_MAX - LOCAL_PORT_MIN) as u64) as u16 + LOCAL_PORT_MIN;
347
348    #[cfg(feature = "dns")]
349    let dns_socket = sockets.add(dns::Socket::new(
350        &[],
351        managed::ManagedSlice::Borrowed(unsafe {
352            transmute_slice(resources.queries.write([const { None }; MAX_QUERIES]))
353        }),
354    ));
355
356    let mut inner = Inner {
357        sockets,
358        iface,
359        waker: WakerRegistration::new(),
360        state_waker: WakerRegistration::new(),
361        next_local_port,
362        hardware_address,
363        link_up: false,
364        #[cfg(feature = "proto-ipv4")]
365        static_v4: None,
366        #[cfg(feature = "proto-ipv6")]
367        static_v6: None,
368        #[cfg(feature = "slaac")]
369        slaac: false,
370        #[cfg(feature = "dhcpv4")]
371        dhcp_socket: None,
372        #[cfg(feature = "dns")]
373        dns_socket,
374        #[cfg(feature = "dns")]
375        dns_waker: WakerRegistration::new(),
376        #[cfg(feature = "dhcpv4-hostname")]
377        hostname: &mut resources.hostname,
378    };
379
380    #[cfg(feature = "proto-ipv4")]
381    inner.set_config_v4(config.ipv4);
382    #[cfg(feature = "proto-ipv6")]
383    inner.set_config_v6(config.ipv6);
384    inner.apply_static_config();
385
386    let inner = &*resources.inner.write(RefCell::new(inner));
387    let stack = Stack { inner };
388    (stack, Runner { driver, stack })
389}
390
391fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> (HardwareAddress, Medium) {
392    match addr {
393        #[cfg(feature = "medium-ethernet")]
394        driver::HardwareAddress::Ethernet(eth) => (HardwareAddress::Ethernet(EthernetAddress(eth)), Medium::Ethernet),
395        #[cfg(feature = "medium-ieee802154")]
396        driver::HardwareAddress::Ieee802154(ieee) => (
397            HardwareAddress::Ieee802154(Ieee802154Address::Extended(ieee)),
398            Medium::Ieee802154,
399        ),
400        #[cfg(feature = "medium-ip")]
401        driver::HardwareAddress::Ip => (HardwareAddress::Ip, Medium::Ip),
402
403        #[allow(unreachable_patterns)]
404        _ => panic!(
405            "Unsupported medium {:?}. Make sure to enable the right medium feature in embassy-net's Cargo features.",
406            addr
407        ),
408    }
409}
410
411impl<'d> Stack<'d> {
412    fn with<R>(&self, f: impl FnOnce(&Inner) -> R) -> R {
413        f(&self.inner.borrow())
414    }
415
416    fn with_mut<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
417        f(&mut self.inner.borrow_mut())
418    }
419
420    /// Get the hardware address of the network interface.
421    pub fn hardware_address(&self) -> HardwareAddress {
422        self.with(|i| i.hardware_address)
423    }
424
425    /// Check whether the link is up.
426    pub fn is_link_up(&self) -> bool {
427        self.with(|i| i.link_up)
428    }
429
430    /// Check whether the network stack has a valid IP configuration.
431    /// This is true if the network stack has a static IP configuration or if DHCP has completed
432    pub fn is_config_up(&self) -> bool {
433        let v4_up;
434        let v6_up;
435
436        #[cfg(feature = "proto-ipv4")]
437        {
438            v4_up = self.config_v4().is_some();
439        }
440        #[cfg(not(feature = "proto-ipv4"))]
441        {
442            v4_up = false;
443        }
444
445        #[cfg(feature = "proto-ipv6")]
446        {
447            v6_up = self.config_v6().is_some();
448        }
449        #[cfg(not(feature = "proto-ipv6"))]
450        {
451            v6_up = false;
452        }
453
454        v4_up || v6_up
455    }
456
457    /// Wait for the network device to obtain a link signal.
458    pub async fn wait_link_up(&self) {
459        self.wait(|| self.is_link_up()).await
460    }
461
462    /// Wait for the network device to lose link signal.
463    pub async fn wait_link_down(&self) {
464        self.wait(|| !self.is_link_up()).await
465    }
466
467    /// Wait for the network stack to obtain a valid IP configuration.
468    ///
469    /// ## Notes:
470    /// - Ensure [`Runner::run`] has been started before using this function.
471    ///
472    /// - This function may never return (e.g. if no configuration is obtained through DHCP).
473    /// The caller is supposed to handle a timeout for this case.
474    ///
475    /// ## Example
476    /// ```ignore
477    /// let config = embassy_net::Config::dhcpv4(Default::default());
478    /// // Init network stack
479    /// // NOTE: DHCP and DNS need one socket slot if enabled. This is why we're
480    /// // provisioning space for 3 sockets here: one for DHCP, one for DNS, and one for your code (e.g. TCP).
481    /// // If you use more sockets you must increase this. If you don't enable DHCP or DNS you can decrease it.
482    /// static RESOURCES: StaticCell<embassy_net::StackResources<3>> = StaticCell::new();
483    /// let (stack, runner) = embassy_net::new(
484    ///    driver,
485    ///    config,
486    ///    RESOURCES.init(embassy_net::StackResources::new()),
487    ///    seed
488    /// );
489    /// // Launch network task that runs `runner.run().await`
490    /// spawner.spawn(net_task(runner).unwrap());
491    /// // Wait for DHCP config
492    /// stack.wait_config_up().await;
493    /// // use the network stack
494    /// // ...
495    /// ```
496    pub async fn wait_config_up(&self) {
497        self.wait(|| self.is_config_up()).await
498    }
499
500    /// Wait for the network stack to lose a valid IP configuration.
501    pub async fn wait_config_down(&self) {
502        self.wait(|| !self.is_config_up()).await
503    }
504
505    fn wait<'a>(&'a self, mut predicate: impl FnMut() -> bool + 'a) -> impl Future<Output = ()> + 'a {
506        poll_fn(move |cx| {
507            if predicate() {
508                Poll::Ready(())
509            } else {
510                // If the config is not up, we register a waker that is woken up
511                // when a config is applied (static, slaac or DHCP).
512                trace!("Waiting for config up");
513
514                self.with_mut(|i| {
515                    i.state_waker.register(cx.waker());
516                });
517
518                Poll::Pending
519            }
520        })
521    }
522
523    /// Get the current IPv4 configuration.
524    ///
525    /// If using DHCP, this will be None if DHCP hasn't been able to
526    /// acquire an IP address, or Some if it has.
527    #[cfg(feature = "proto-ipv4")]
528    pub fn config_v4(&self) -> Option<StaticConfigV4> {
529        self.with(|i| i.static_v4.clone())
530    }
531
532    /// Get the current IPv6 configuration.
533    #[cfg(feature = "proto-ipv6")]
534    pub fn config_v6(&self) -> Option<StaticConfigV6> {
535        self.with(|i| i.static_v6.clone())
536    }
537
538    /// Set the IPv4 configuration.
539    #[cfg(feature = "proto-ipv4")]
540    pub fn set_config_v4(&self, config: ConfigV4) {
541        self.with_mut(|i| {
542            i.set_config_v4(config);
543            i.apply_static_config();
544        })
545    }
546
547    /// Set the IPv6 configuration.
548    #[cfg(feature = "proto-ipv6")]
549    pub fn set_config_v6(&self, config: ConfigV6) {
550        self.with_mut(|i| {
551            i.set_config_v6(config);
552            i.apply_static_config();
553        })
554    }
555
556    /// Make a query for a given name and return the corresponding IP addresses.
557    #[cfg(feature = "dns")]
558    pub async fn dns_query(
559        &self,
560        name: &str,
561        qtype: dns::DnsQueryType,
562    ) -> Result<Vec<IpAddress, { smoltcp::config::DNS_MAX_RESULT_COUNT }>, dns::Error> {
563        // For A and AAAA queries we try detect whether `name` is just an IP address
564        match qtype {
565            #[cfg(feature = "proto-ipv4")]
566            dns::DnsQueryType::A => {
567                if let Ok(ip) = name.parse().map(IpAddress::Ipv4) {
568                    return Ok([ip].into_iter().collect());
569                }
570            }
571            #[cfg(feature = "proto-ipv6")]
572            dns::DnsQueryType::Aaaa => {
573                if let Ok(ip) = name.parse().map(IpAddress::Ipv6) {
574                    return Ok([ip].into_iter().collect());
575                }
576            }
577            _ => {}
578        }
579
580        let query = poll_fn(|cx| {
581            self.with_mut(|i| {
582                let socket = i.sockets.get_mut::<dns::Socket>(i.dns_socket);
583                match socket.start_query(i.iface.context(), name, qtype) {
584                    Ok(handle) => {
585                        i.waker.wake();
586                        Poll::Ready(Ok(handle))
587                    }
588                    Err(dns::StartQueryError::NoFreeSlot) => {
589                        i.dns_waker.register(cx.waker());
590                        Poll::Pending
591                    }
592                    Err(e) => Poll::Ready(Err(e)),
593                }
594            })
595        })
596        .await?;
597
598        #[must_use = "to delay the drop handler invocation to the end of the scope"]
599        struct OnDrop<F: FnOnce()> {
600            f: core::mem::MaybeUninit<F>,
601        }
602
603        impl<F: FnOnce()> OnDrop<F> {
604            fn new(f: F) -> Self {
605                Self {
606                    f: core::mem::MaybeUninit::new(f),
607                }
608            }
609
610            fn defuse(self) {
611                core::mem::forget(self)
612            }
613        }
614
615        impl<F: FnOnce()> Drop for OnDrop<F> {
616            fn drop(&mut self) {
617                unsafe { self.f.as_ptr().read()() }
618            }
619        }
620
621        let drop = OnDrop::new(|| {
622            self.with_mut(|i| {
623                let socket = i.sockets.get_mut::<dns::Socket>(i.dns_socket);
624                socket.cancel_query(query);
625                i.waker.wake();
626                i.dns_waker.wake();
627            })
628        });
629
630        let res = poll_fn(|cx| {
631            self.with_mut(|i| {
632                let socket = i.sockets.get_mut::<dns::Socket>(i.dns_socket);
633                match socket.get_query_result(query) {
634                    Ok(addrs) => {
635                        i.dns_waker.wake();
636                        Poll::Ready(Ok(addrs))
637                    }
638                    Err(dns::GetQueryResultError::Pending) => {
639                        socket.register_query_waker(query, cx.waker());
640                        Poll::Pending
641                    }
642                    Err(e) => {
643                        i.dns_waker.wake();
644                        Poll::Ready(Err(e.into()))
645                    }
646                }
647            })
648        })
649        .await;
650
651        drop.defuse();
652
653        res
654    }
655}
656
657#[cfg(feature = "multicast")]
658impl<'d> Stack<'d> {
659    /// Join a multicast group.
660    pub fn join_multicast_group(&self, addr: impl Into<IpAddress>) -> Result<(), MulticastError> {
661        self.with_mut(|i| i.iface.join_multicast_group(addr))
662    }
663
664    /// Leave a multicast group.
665    pub fn leave_multicast_group(&self, addr: impl Into<IpAddress>) -> Result<(), MulticastError> {
666        self.with_mut(|i| i.iface.leave_multicast_group(addr))
667    }
668
669    /// Get whether the network stack has joined the given multicast group.
670    pub fn has_multicast_group(&self, addr: impl Into<IpAddress>) -> bool {
671        self.with(|i| i.iface.has_multicast_group(addr))
672    }
673}
674
675impl Inner {
676    #[cfg(feature = "slaac")]
677    fn get_link_local_address(&self) -> IpCidr {
678        let ll_prefix = Ipv6Cidr::new(Ipv6Cidr::LINK_LOCAL_PREFIX.address(), 64);
679        Ipv6Cidr::from_link_prefix(&ll_prefix, self.hardware_address)
680            .unwrap()
681            .into()
682    }
683
684    #[allow(clippy::absurd_extreme_comparisons)]
685    pub fn get_local_port(&mut self) -> u16 {
686        let res = self.next_local_port;
687        self.next_local_port = if res >= LOCAL_PORT_MAX { LOCAL_PORT_MIN } else { res + 1 };
688        res
689    }
690
691    #[cfg(feature = "proto-ipv4")]
692    pub fn set_config_v4(&mut self, config: ConfigV4) {
693        // Handle static config.
694        self.static_v4 = match config.clone() {
695            ConfigV4::None => None,
696            #[cfg(feature = "dhcpv4")]
697            ConfigV4::Dhcp(_) => None,
698            ConfigV4::Static(c) => Some(c),
699        };
700
701        // Handle DHCP config.
702        #[cfg(feature = "dhcpv4")]
703        match config {
704            ConfigV4::Dhcp(c) => {
705                // Create the socket if it doesn't exist.
706                if self.dhcp_socket.is_none() {
707                    let socket = smoltcp::socket::dhcpv4::Socket::new();
708                    let handle = self.sockets.add(socket);
709                    self.dhcp_socket = Some(handle);
710                }
711
712                // Configure it
713                let socket = self.sockets.get_mut::<dhcpv4::Socket>(unwrap!(self.dhcp_socket));
714                socket.set_ignore_naks(c.ignore_naks);
715                socket.set_max_lease_duration(c.max_lease_duration.map(crate::time::duration_to_smoltcp));
716                socket.set_ports(c.server_port, c.client_port);
717                socket.set_retry_config(c.retry_config);
718
719                socket.set_outgoing_options(&[]);
720                #[cfg(feature = "dhcpv4-hostname")]
721                if let Some(h) = c.hostname {
722                    // safety:
723                    // - we just did set_outgoing_options([]) so we know the socket is no longer holding a reference.
724                    // - we know this pointer lives for as long as the stack exists, because `new()` borrows
725                    //   the resources for `'d`. Therefore it's OK to pass a reference to this to smoltcp.
726                    let hostname = unsafe { &mut *self.hostname };
727
728                    // create data
729                    let data = hostname.data.write([0; MAX_HOSTNAME_LEN]);
730                    data[..h.len()].copy_from_slice(h.as_bytes());
731                    let data: &[u8] = &data[..h.len()];
732
733                    // set the option.
734                    let option = hostname.option.write(smoltcp::wire::DhcpOption { data, kind: 12 });
735                    socket.set_outgoing_options(core::slice::from_ref(option));
736                }
737
738                socket.reset();
739            }
740            _ => {
741                // Remove DHCP socket if any.
742                if let Some(socket) = self.dhcp_socket {
743                    self.sockets.remove(socket);
744                    self.dhcp_socket = None;
745                }
746            }
747        }
748    }
749
750    #[cfg(feature = "proto-ipv6")]
751    pub fn set_config_v6(&mut self, config: ConfigV6) {
752        #[cfg(feature = "slaac")]
753        {
754            self.slaac = matches!(config, ConfigV6::Slaac);
755        }
756        self.static_v6 = match config {
757            ConfigV6::None => None,
758            ConfigV6::Static(c) => Some(c),
759            #[cfg(feature = "slaac")]
760            ConfigV6::Slaac => None,
761        };
762    }
763
764    fn apply_static_config(&mut self) {
765        let mut addrs = Vec::new();
766        #[cfg(feature = "dns")]
767        let mut dns_servers: Vec<_, 6> = Vec::new();
768        #[cfg(feature = "proto-ipv4")]
769        let mut gateway_v4 = None;
770        #[cfg(feature = "proto-ipv6")]
771        let mut gateway_v6 = None;
772
773        #[cfg(feature = "proto-ipv4")]
774        if let Some(config) = &self.static_v4 {
775            debug!("IPv4: UP");
776            debug!("   IP address:      {:?}", config.address);
777            debug!("   Default gateway: {:?}", config.gateway);
778
779            unwrap!(addrs.push(IpCidr::Ipv4(config.address)).ok());
780            gateway_v4 = config.gateway;
781            #[cfg(feature = "dns")]
782            for s in &config.dns_servers {
783                debug!("   DNS server:      {:?}", s);
784                unwrap!(dns_servers.push(s.clone().into()).ok());
785            }
786        } else {
787            info!("IPv4: DOWN");
788        }
789
790        #[cfg(feature = "proto-ipv6")]
791        if let Some(config) = &self.static_v6 {
792            debug!("IPv6: UP");
793            debug!("   IP address:      {:?}", config.address);
794            debug!("   Default gateway: {:?}", config.gateway);
795
796            unwrap!(addrs.push(IpCidr::Ipv6(config.address)).ok());
797            gateway_v6 = config.gateway;
798            #[cfg(feature = "dns")]
799            for s in &config.dns_servers {
800                debug!("   DNS server:      {:?}", s);
801                unwrap!(dns_servers.push(s.clone().into()).ok());
802            }
803        } else {
804            info!("IPv6: DOWN");
805        }
806
807        // Apply addresses
808        self.iface.update_ip_addrs(|a| {
809            *a = addrs;
810        });
811
812        // Add the link local-address
813        #[cfg(feature = "slaac")]
814        {
815            let ll_address = self.get_link_local_address();
816            self.iface.update_ip_addrs(|a| {
817                let _ = a.push(ll_address);
818            })
819        }
820
821        // Apply gateways
822        #[cfg(feature = "proto-ipv4")]
823        if let Some(gateway) = gateway_v4 {
824            unwrap!(self.iface.routes_mut().add_default_ipv4_route(gateway));
825        } else {
826            self.iface.routes_mut().remove_default_ipv4_route();
827        }
828        #[cfg(feature = "proto-ipv6")]
829        if let Some(gateway) = gateway_v6 {
830            unwrap!(self.iface.routes_mut().add_default_ipv6_route(gateway));
831        } else {
832            self.iface.routes_mut().remove_default_ipv6_route();
833        }
834
835        // Apply DNS servers
836        #[cfg(feature = "dns")]
837        if !dns_servers.is_empty() {
838            let count = if dns_servers.len() > DNS_MAX_SERVER_COUNT {
839                warn!("Number of DNS servers exceeds DNS_MAX_SERVER_COUNT, truncating list.");
840                DNS_MAX_SERVER_COUNT
841            } else {
842                dns_servers.len()
843            };
844            self.sockets
845                .get_mut::<smoltcp::socket::dns::Socket>(self.dns_socket)
846                .update_servers(&dns_servers[..count]);
847        }
848
849        self.state_waker.wake();
850    }
851
852    fn poll<D: Driver>(&mut self, cx: &mut Context<'_>, driver: &mut D) {
853        self.waker.register(cx.waker());
854
855        let (_hardware_addr, medium) = to_smoltcp_hardware_address(driver.hardware_address());
856
857        #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
858        {
859            let do_set = match medium {
860                #[cfg(feature = "medium-ethernet")]
861                Medium::Ethernet => true,
862                #[cfg(feature = "medium-ieee802154")]
863                Medium::Ieee802154 => true,
864                #[allow(unreachable_patterns)]
865                _ => false,
866            };
867            if do_set {
868                self.iface.set_hardware_addr(_hardware_addr);
869            }
870        }
871
872        let timestamp = instant_to_smoltcp(Instant::now());
873        let mut smoldev = DriverAdapter {
874            cx: Some(cx),
875            inner: driver,
876            medium,
877        };
878        self.iface.poll(timestamp, &mut smoldev, &mut self.sockets);
879
880        // Update link up
881        let old_link_up = self.link_up;
882        self.link_up = driver.link_state(cx) == LinkState::Up;
883
884        // Print when changed
885        if old_link_up != self.link_up {
886            info!("link_up = {:?}", self.link_up);
887            self.state_waker.wake();
888        }
889
890        #[allow(unused_mut)]
891        let mut configure = false;
892
893        #[cfg(feature = "dhcpv4")]
894        {
895            configure |= if let Some(dhcp_handle) = self.dhcp_socket {
896                let socket = self.sockets.get_mut::<dhcpv4::Socket>(dhcp_handle);
897
898                if self.link_up {
899                    if old_link_up != self.link_up {
900                        socket.reset();
901                    }
902                    match socket.poll() {
903                        None => false,
904                        Some(dhcpv4::Event::Deconfigured) => {
905                            self.static_v4 = None;
906                            true
907                        }
908                        Some(dhcpv4::Event::Configured(config)) => {
909                            self.static_v4 = Some(StaticConfigV4 {
910                                address: config.address,
911                                gateway: config.router,
912                                dns_servers: config.dns_servers,
913                            });
914                            true
915                        }
916                    }
917                } else if old_link_up {
918                    socket.reset();
919                    self.static_v4 = None;
920                    true
921                } else {
922                    false
923                }
924            } else {
925                false
926            }
927        }
928
929        #[cfg(feature = "slaac")]
930        if self.slaac && self.iface.slaac_updated_at() == timestamp {
931            let ipv6_address = self.iface.ip_addrs().iter().find_map(|addr| match addr {
932                IpCidr::Ipv6(ip6_address) if !Ipv6Cidr::LINK_LOCAL_PREFIX.contains_addr(&ip6_address.address()) => {
933                    Some(ip6_address)
934                }
935                _ => None,
936            });
937            self.static_v6 = if let Some(address) = ipv6_address {
938                let gateway = self
939                    .iface
940                    .routes()
941                    .get_default_ipv6_route()
942                    .map(|r| match r.via_router {
943                        IpAddress::Ipv6(gateway) => Some(gateway),
944                        #[cfg(feature = "proto-ipv4")]
945                        _ => None,
946                    })
947                    .flatten();
948                let config = StaticConfigV6 {
949                    address: *address,
950                    gateway,
951                    dns_servers: Vec::new(), // RDNSS not (yet) supported by smoltcp.
952                };
953                Some(config)
954            } else {
955                None
956            };
957            configure = true;
958        }
959
960        if configure {
961            self.apply_static_config()
962        }
963
964        if let Some(poll_at) = self.iface.poll_at(timestamp, &mut self.sockets) {
965            let t = pin!(Timer::at(instant_from_smoltcp(poll_at)));
966            if t.poll(cx).is_ready() {
967                cx.waker().wake_by_ref();
968            }
969        }
970    }
971}
972
973impl<'d, D: Driver> Runner<'d, D> {
974    /// Run the network stack.
975    ///
976    /// You must call this in a background task, to process network events.
977    pub async fn run(&mut self) -> ! {
978        poll_fn(|cx| {
979            self.stack.with_mut(|i| i.poll(cx, &mut self.driver));
980            Poll::<()>::Pending
981        })
982        .await;
983        unreachable!()
984    }
985}