smoltcp/socket/
dhcpv4.rs

1#[cfg(feature = "async")]
2use core::task::Waker;
3
4use crate::iface::Context;
5use crate::time::{Duration, Instant};
6use crate::wire::dhcpv4::field as dhcpv4_field;
7use crate::wire::{
8    DhcpMessageType, DhcpPacket, DhcpRepr, IpAddress, IpProtocol, Ipv4Address, Ipv4AddressExt,
9    Ipv4Cidr, Ipv4Repr, UdpRepr, DHCP_CLIENT_PORT, DHCP_MAX_DNS_SERVER_COUNT, DHCP_SERVER_PORT,
10    UDP_HEADER_LEN,
11};
12use crate::wire::{DhcpOption, HardwareAddress};
13use heapless::Vec;
14
15#[cfg(feature = "async")]
16use super::WakerRegistration;
17
18use super::PollAt;
19
20const DEFAULT_LEASE_DURATION: Duration = Duration::from_secs(120);
21
22const DEFAULT_PARAMETER_REQUEST_LIST: &[u8] = &[
23    dhcpv4_field::OPT_SUBNET_MASK,
24    dhcpv4_field::OPT_ROUTER,
25    dhcpv4_field::OPT_DOMAIN_NAME_SERVER,
26];
27
28/// IPv4 configuration data provided by the DHCP server.
29#[derive(Debug, Eq, PartialEq, Clone)]
30#[cfg_attr(feature = "defmt", derive(defmt::Format))]
31pub struct Config<'a> {
32    /// Information on how to reach the DHCP server that responded with DHCP
33    /// configuration.
34    pub server: ServerInfo,
35    /// IP address
36    pub address: Ipv4Cidr,
37    /// Router address, also known as default gateway. Does not necessarily
38    /// match the DHCP server's address.
39    pub router: Option<Ipv4Address>,
40    /// DNS servers
41    pub dns_servers: Vec<Ipv4Address, DHCP_MAX_DNS_SERVER_COUNT>,
42    /// Received DHCP packet
43    pub packet: Option<DhcpPacket<&'a [u8]>>,
44}
45
46/// Information on how to reach a DHCP server.
47#[derive(Debug, Clone, Copy, Eq, PartialEq)]
48#[cfg_attr(feature = "defmt", derive(defmt::Format))]
49pub struct ServerInfo {
50    /// IP address to use as destination in outgoing packets
51    pub address: Ipv4Address,
52    /// Server identifier to use in outgoing packets. Usually equal to server_address,
53    /// but may differ in some situations (eg DHCP relays)
54    pub identifier: Ipv4Address,
55}
56
57#[derive(Debug)]
58#[cfg_attr(feature = "defmt", derive(defmt::Format))]
59struct DiscoverState {
60    /// When to send next request
61    retry_at: Instant,
62}
63
64#[derive(Debug)]
65#[cfg_attr(feature = "defmt", derive(defmt::Format))]
66struct RequestState {
67    /// When to send next request
68    retry_at: Instant,
69    /// How many retries have been done
70    retry: u16,
71    /// Server we're trying to request from
72    server: ServerInfo,
73    /// IP address that we're trying to request.
74    requested_ip: Ipv4Address,
75}
76
77#[derive(Debug)]
78#[cfg_attr(feature = "defmt", derive(defmt::Format))]
79struct RenewState {
80    /// Active network config
81    config: Config<'static>,
82
83    /// Renew timer. When reached, we will start attempting
84    /// to renew this lease with the DHCP server.
85    ///
86    /// Must be less or equal than `rebind_at`.
87    renew_at: Instant,
88
89    /// Rebind timer. When reached, we will start broadcasting to renew
90    /// this lease with any DHCP server.
91    ///
92    /// Must be greater than or equal to `renew_at`, and less than or
93    /// equal to `expires_at`.
94    rebind_at: Instant,
95
96    /// Whether the T2 time has elapsed
97    rebinding: bool,
98
99    /// Expiration timer. When reached, this lease is no longer valid, so it must be
100    /// thrown away and the ethernet interface deconfigured.
101    expires_at: Instant,
102}
103
104#[derive(Debug)]
105#[cfg_attr(feature = "defmt", derive(defmt::Format))]
106enum ClientState {
107    /// Discovering the DHCP server
108    Discovering(DiscoverState),
109    /// Requesting an address
110    Requesting(RequestState),
111    /// Having an address, refresh it periodically.
112    Renewing(RenewState),
113}
114
115/// Timeout and retry configuration.
116#[derive(Debug, PartialEq, Eq, Copy, Clone)]
117#[cfg_attr(feature = "defmt", derive(defmt::Format))]
118#[non_exhaustive]
119pub struct RetryConfig {
120    pub discover_timeout: Duration,
121    /// The REQUEST timeout doubles every 2 tries.
122    pub initial_request_timeout: Duration,
123    pub request_retries: u16,
124    pub min_renew_timeout: Duration,
125    /// An upper bound on how long to wait between retrying a renew or rebind.
126    ///
127    /// Set this to [`Duration::MAX`] if you don't want to impose an upper bound.
128    pub max_renew_timeout: Duration,
129}
130
131impl Default for RetryConfig {
132    fn default() -> Self {
133        Self {
134            discover_timeout: Duration::from_secs(10),
135            initial_request_timeout: Duration::from_secs(5),
136            request_retries: 5,
137            min_renew_timeout: Duration::from_secs(60),
138            max_renew_timeout: Duration::MAX,
139        }
140    }
141}
142
143/// Return value for the `Dhcpv4Socket::poll` function
144#[derive(Debug, PartialEq, Eq, Clone)]
145#[cfg_attr(feature = "defmt", derive(defmt::Format))]
146pub enum Event<'a> {
147    /// Configuration has been lost (for example, the lease has expired)
148    Deconfigured,
149    /// Configuration has been newly acquired, or modified.
150    Configured(Config<'a>),
151}
152
153#[derive(Debug)]
154pub struct Socket<'a> {
155    /// State of the DHCP client.
156    state: ClientState,
157    /// Set to true on config/state change, cleared back to false by the `config` function.
158    config_changed: bool,
159    /// xid of the last sent message.
160    transaction_id: u32,
161
162    /// Max lease duration. If set, it sets a maximum cap to the server-provided lease duration.
163    /// Useful to react faster to IP configuration changes and to test whether renews work correctly.
164    max_lease_duration: Option<Duration>,
165
166    retry_config: RetryConfig,
167
168    /// Ignore NAKs.
169    ignore_naks: bool,
170
171    /// Server port config
172    pub(crate) server_port: u16,
173
174    /// Client port config
175    pub(crate) client_port: u16,
176
177    /// A buffer contains options additional to be added to outgoing DHCP
178    /// packets.
179    outgoing_options: &'a [DhcpOption<'a>],
180    /// A buffer containing all requested parameters.
181    parameter_request_list: Option<&'a [u8]>,
182
183    /// Incoming DHCP packets are copied into this buffer, overwriting the previous.
184    receive_packet_buffer: Option<&'a mut [u8]>,
185
186    /// Waker registration
187    #[cfg(feature = "async")]
188    waker: WakerRegistration,
189}
190
191/// DHCP client socket.
192///
193/// The socket acquires an IP address configuration through DHCP autonomously.
194/// You must query the configuration with `.poll()` after every call to `Interface::poll()`,
195/// and apply the configuration to the `Interface`.
196impl<'a> Socket<'a> {
197    /// Create a DHCPv4 socket
198    #[allow(clippy::new_without_default)]
199    pub fn new() -> Self {
200        Socket {
201            state: ClientState::Discovering(DiscoverState {
202                retry_at: Instant::from_millis(0),
203            }),
204            config_changed: true,
205            transaction_id: 1,
206            max_lease_duration: None,
207            retry_config: RetryConfig::default(),
208            ignore_naks: false,
209            outgoing_options: &[],
210            parameter_request_list: None,
211            receive_packet_buffer: None,
212            #[cfg(feature = "async")]
213            waker: WakerRegistration::new(),
214            server_port: DHCP_SERVER_PORT,
215            client_port: DHCP_CLIENT_PORT,
216        }
217    }
218
219    /// Set the retry/timeouts configuration.
220    pub fn set_retry_config(&mut self, config: RetryConfig) {
221        self.retry_config = config;
222    }
223
224    /// Gets the current retry/timeouts configuration
225    pub fn get_retry_config(&self) -> RetryConfig {
226        self.retry_config
227    }
228
229    /// Set the outgoing options.
230    pub fn set_outgoing_options(&mut self, options: &'a [DhcpOption<'a>]) {
231        self.outgoing_options = options;
232    }
233
234    /// Set the buffer into which incoming DHCP packets are copied into.
235    pub fn set_receive_packet_buffer(&mut self, buffer: &'a mut [u8]) {
236        self.receive_packet_buffer = Some(buffer);
237    }
238
239    /// Set the parameter request list.
240    ///
241    /// This should contain at least `OPT_SUBNET_MASK` (`1`), `OPT_ROUTER`
242    /// (`3`), and `OPT_DOMAIN_NAME_SERVER` (`6`).
243    pub fn set_parameter_request_list(&mut self, parameter_request_list: &'a [u8]) {
244        self.parameter_request_list = Some(parameter_request_list);
245    }
246
247    /// Get the configured max lease duration.
248    ///
249    /// See also [`Self::set_max_lease_duration()`]
250    pub fn max_lease_duration(&self) -> Option<Duration> {
251        self.max_lease_duration
252    }
253
254    /// Set the max lease duration.
255    ///
256    /// When set, the lease duration will be capped at the configured duration if the
257    /// DHCP server gives us a longer lease. This is generally not recommended, but
258    /// can be useful for debugging or reacting faster to network configuration changes.
259    ///
260    /// If None, no max is applied (the lease duration from the DHCP server is used.)
261    pub fn set_max_lease_duration(&mut self, max_lease_duration: Option<Duration>) {
262        self.max_lease_duration = max_lease_duration;
263    }
264
265    /// Get whether to ignore NAKs.
266    ///
267    /// See also [`Self::set_ignore_naks()`]
268    pub fn ignore_naks(&self) -> bool {
269        self.ignore_naks
270    }
271
272    /// Set whether to ignore NAKs.
273    ///
274    /// This is not compliant with the DHCP RFCs, since theoretically
275    /// we must stop using the assigned IP when receiving a NAK. This
276    /// can increase reliability on broken networks with buggy routers
277    /// or rogue DHCP servers, however.
278    pub fn set_ignore_naks(&mut self, ignore_naks: bool) {
279        self.ignore_naks = ignore_naks;
280    }
281
282    /// Set the server/client port
283    ///
284    /// Allows you to specify the ports used by DHCP.
285    /// This is meant to support esoteric usecases allowed by the dhclient program.
286    pub fn set_ports(&mut self, server_port: u16, client_port: u16) {
287        self.server_port = server_port;
288        self.client_port = client_port;
289    }
290
291    pub(crate) fn poll_at(&self, _cx: &mut Context) -> PollAt {
292        let t = match &self.state {
293            ClientState::Discovering(state) => state.retry_at,
294            ClientState::Requesting(state) => state.retry_at,
295            ClientState::Renewing(state) => if state.rebinding {
296                state.rebind_at
297            } else {
298                state.renew_at.min(state.rebind_at)
299            }
300            .min(state.expires_at),
301        };
302        PollAt::Time(t)
303    }
304
305    pub(crate) fn process(
306        &mut self,
307        cx: &mut Context,
308        ip_repr: &Ipv4Repr,
309        repr: &UdpRepr,
310        payload: &[u8],
311    ) {
312        let src_ip = ip_repr.src_addr;
313
314        // This is enforced in interface.rs.
315        assert!(repr.src_port == self.server_port && repr.dst_port == self.client_port);
316
317        let dhcp_packet = match DhcpPacket::new_checked(payload) {
318            Ok(dhcp_packet) => dhcp_packet,
319            Err(e) => {
320                net_debug!("DHCP invalid pkt from {}: {:?}", src_ip, e);
321                return;
322            }
323        };
324        let dhcp_repr = match DhcpRepr::parse(&dhcp_packet) {
325            Ok(dhcp_repr) => dhcp_repr,
326            Err(e) => {
327                net_debug!("DHCP error parsing pkt from {}: {:?}", src_ip, e);
328                return;
329            }
330        };
331
332        let HardwareAddress::Ethernet(ethernet_addr) = cx.hardware_addr() else {
333            panic!("using DHCPv4 socket with a non-ethernet hardware address.");
334        };
335
336        if dhcp_repr.client_hardware_address != ethernet_addr {
337            return;
338        }
339        if dhcp_repr.transaction_id != self.transaction_id {
340            return;
341        }
342        let server_identifier = match dhcp_repr.server_identifier {
343            Some(server_identifier) => server_identifier,
344            None => {
345                net_debug!(
346                    "DHCP ignoring {:?} because missing server_identifier",
347                    dhcp_repr.message_type
348                );
349                return;
350            }
351        };
352
353        net_debug!(
354            "DHCP recv {:?} from {}: {:?}",
355            dhcp_repr.message_type,
356            src_ip,
357            dhcp_repr
358        );
359
360        // Copy over the payload into the receive packet buffer.
361        if let Some(buffer) = self.receive_packet_buffer.as_mut() {
362            if let Some(buffer) = buffer.get_mut(..payload.len()) {
363                buffer.copy_from_slice(payload);
364            }
365        }
366
367        match (&mut self.state, dhcp_repr.message_type) {
368            (ClientState::Discovering(_state), DhcpMessageType::Offer) => {
369                if !dhcp_repr.your_ip.x_is_unicast() {
370                    net_debug!("DHCP ignoring OFFER because your_ip is not unicast");
371                    return;
372                }
373
374                self.state = ClientState::Requesting(RequestState {
375                    retry_at: cx.now(),
376                    retry: 0,
377                    server: ServerInfo {
378                        address: src_ip,
379                        identifier: server_identifier,
380                    },
381                    requested_ip: dhcp_repr.your_ip, // use the offered ip
382                });
383            }
384            (ClientState::Requesting(state), DhcpMessageType::Ack) => {
385                if let Some((config, renew_at, rebind_at, expires_at)) =
386                    Self::parse_ack(cx.now(), &dhcp_repr, self.max_lease_duration, state.server)
387                {
388                    self.state = ClientState::Renewing(RenewState {
389                        config,
390                        renew_at,
391                        rebind_at,
392                        expires_at,
393                        rebinding: false,
394                    });
395                    self.config_changed();
396                }
397            }
398            (ClientState::Requesting(_), DhcpMessageType::Nak) => {
399                if !self.ignore_naks {
400                    self.reset();
401                }
402            }
403            (ClientState::Renewing(state), DhcpMessageType::Ack) => {
404                if let Some((config, renew_at, rebind_at, expires_at)) = Self::parse_ack(
405                    cx.now(),
406                    &dhcp_repr,
407                    self.max_lease_duration,
408                    state.config.server,
409                ) {
410                    state.renew_at = renew_at;
411                    state.rebind_at = rebind_at;
412                    state.rebinding = false;
413                    state.expires_at = expires_at;
414                    // The `receive_packet_buffer` field isn't populated until
415                    // the client asks for the state, but receiving any packet
416                    // will change it, so we indicate that the config has
417                    // changed every time if the receive packet buffer is set,
418                    // but we only write changes to the rest of the config now.
419                    let config_changed =
420                        state.config != config || self.receive_packet_buffer.is_some();
421                    if state.config != config {
422                        state.config = config;
423                    }
424                    if config_changed {
425                        self.config_changed();
426                    }
427                }
428            }
429            (ClientState::Renewing(_), DhcpMessageType::Nak) => {
430                if !self.ignore_naks {
431                    self.reset();
432                }
433            }
434            _ => {
435                net_debug!(
436                    "DHCP ignoring {:?}: unexpected in current state",
437                    dhcp_repr.message_type
438                );
439            }
440        }
441    }
442
443    fn parse_ack(
444        now: Instant,
445        dhcp_repr: &DhcpRepr,
446        max_lease_duration: Option<Duration>,
447        server: ServerInfo,
448    ) -> Option<(Config<'static>, Instant, Instant, Instant)> {
449        let subnet_mask = match dhcp_repr.subnet_mask {
450            Some(subnet_mask) => subnet_mask,
451            None => {
452                net_debug!("DHCP ignoring ACK because missing subnet_mask");
453                return None;
454            }
455        };
456
457        let prefix_len = match IpAddress::Ipv4(subnet_mask).prefix_len() {
458            Some(prefix_len) => prefix_len,
459            None => {
460                net_debug!("DHCP ignoring ACK because subnet_mask is not a valid mask");
461                return None;
462            }
463        };
464
465        if !dhcp_repr.your_ip.x_is_unicast() {
466            net_debug!("DHCP ignoring ACK because your_ip is not unicast");
467            return None;
468        }
469
470        let mut lease_duration = dhcp_repr
471            .lease_duration
472            .map(|d| Duration::from_secs(d as _))
473            .unwrap_or(DEFAULT_LEASE_DURATION);
474        if let Some(max_lease_duration) = max_lease_duration {
475            lease_duration = lease_duration.min(max_lease_duration);
476        }
477
478        // Cleanup the DNS servers list, keeping only unicasts/
479        // TP-Link TD-W8970 sends 0.0.0.0 as second DNS server if there's only one configured :(
480        let mut dns_servers = Vec::new();
481
482        dhcp_repr
483            .dns_servers
484            .iter()
485            .flatten()
486            .filter(|s| s.x_is_unicast())
487            .for_each(|a| {
488                // This will never produce an error, as both the arrays and `dns_servers`
489                // have length DHCP_MAX_DNS_SERVER_COUNT
490                dns_servers.push(*a).ok();
491            });
492
493        let config = Config {
494            server,
495            address: Ipv4Cidr::new(dhcp_repr.your_ip, prefix_len),
496            router: dhcp_repr.router,
497            dns_servers,
498            packet: None,
499        };
500
501        // Set renew and rebind times as per RFC 2131:
502        // Times T1 and T2 are configurable by the server through
503        // options. T1 defaults to (0.5 * duration_of_lease). T2
504        // defaults to (0.875 * duration_of_lease).
505        let (renew_duration, rebind_duration) = match (
506            dhcp_repr
507                .renew_duration
508                .map(|d| Duration::from_secs(d as u64)),
509            dhcp_repr
510                .rebind_duration
511                .map(|d| Duration::from_secs(d as u64)),
512        ) {
513            (Some(renew_duration), Some(rebind_duration)) => (renew_duration, rebind_duration),
514            (None, None) => (lease_duration / 2, lease_duration * 7 / 8),
515            // RFC 2131 does not say what to do if only one value is
516            // provided, so:
517
518            // If only T1 is provided, set T2 to be 0.75 through the gap
519            // between T1 and the duration of the lease. If T1 is set to
520            // the default (0.5 * duration_of_lease), then T2 will also
521            // be set to the default (0.875 * duration_of_lease).
522            (Some(renew_duration), None) => (
523                renew_duration,
524                renew_duration + (lease_duration - renew_duration) * 3 / 4,
525            ),
526
527            // If only T2 is provided, then T1 will be set to be
528            // whichever is smaller of the default (0.5 *
529            // duration_of_lease) or T2.
530            (None, Some(rebind_duration)) => {
531                ((lease_duration / 2).min(rebind_duration), rebind_duration)
532            }
533        };
534        let renew_at = now + renew_duration;
535        let rebind_at = now + rebind_duration;
536        let expires_at = now + lease_duration;
537
538        Some((config, renew_at, rebind_at, expires_at))
539    }
540
541    #[cfg(not(test))]
542    fn random_transaction_id(cx: &mut Context) -> u32 {
543        cx.rand().rand_u32()
544    }
545
546    #[cfg(test)]
547    fn random_transaction_id(_cx: &mut Context) -> u32 {
548        0x12345678
549    }
550
551    pub(crate) fn dispatch<F, E>(&mut self, cx: &mut Context, emit: F) -> Result<(), E>
552    where
553        F: FnOnce(&mut Context, (Ipv4Repr, UdpRepr, DhcpRepr)) -> Result<(), E>,
554    {
555        // note: Dhcpv4Socket is only usable in ethernet mediums, so the
556        // unwrap can never fail.
557        let HardwareAddress::Ethernet(ethernet_addr) = cx.hardware_addr() else {
558            panic!("using DHCPv4 socket with a non-ethernet hardware address.");
559        };
560
561        // Worst case biggest IPv4 header length.
562        // 0x0f * 4 = 60 bytes.
563        const MAX_IPV4_HEADER_LEN: usize = 60;
564
565        // We don't directly modify self.transaction_id because sending the packet
566        // may fail. We only want to update state after successfully sending.
567        let next_transaction_id = Self::random_transaction_id(cx);
568
569        let mut dhcp_repr = DhcpRepr {
570            message_type: DhcpMessageType::Discover,
571            transaction_id: next_transaction_id,
572            secs: 0,
573            client_hardware_address: ethernet_addr,
574            client_ip: Ipv4Address::UNSPECIFIED,
575            your_ip: Ipv4Address::UNSPECIFIED,
576            server_ip: Ipv4Address::UNSPECIFIED,
577            router: None,
578            subnet_mask: None,
579            relay_agent_ip: Ipv4Address::UNSPECIFIED,
580            broadcast: false,
581            requested_ip: None,
582            client_identifier: Some(ethernet_addr),
583            server_identifier: None,
584            parameter_request_list: Some(
585                self.parameter_request_list
586                    .unwrap_or(DEFAULT_PARAMETER_REQUEST_LIST),
587            ),
588            max_size: Some((cx.ip_mtu() - MAX_IPV4_HEADER_LEN - UDP_HEADER_LEN) as u16),
589            lease_duration: None,
590            renew_duration: None,
591            rebind_duration: None,
592            dns_servers: None,
593            additional_options: self.outgoing_options,
594        };
595
596        let udp_repr = UdpRepr {
597            src_port: self.client_port,
598            dst_port: self.server_port,
599        };
600
601        let mut ipv4_repr = Ipv4Repr {
602            src_addr: Ipv4Address::UNSPECIFIED,
603            dst_addr: Ipv4Address::BROADCAST,
604            next_header: IpProtocol::Udp,
605            payload_len: 0, // filled right before emit
606            hop_limit: 64,
607        };
608
609        match &mut self.state {
610            ClientState::Discovering(state) => {
611                if cx.now() < state.retry_at {
612                    return Ok(());
613                }
614
615                // send packet
616                net_debug!(
617                    "DHCP send DISCOVER to {}: {:?}",
618                    ipv4_repr.dst_addr,
619                    dhcp_repr
620                );
621                ipv4_repr.payload_len = udp_repr.header_len() + dhcp_repr.buffer_len();
622                emit(cx, (ipv4_repr, udp_repr, dhcp_repr))?;
623
624                // Update state AFTER the packet has been successfully sent.
625                state.retry_at = cx.now() + self.retry_config.discover_timeout;
626                self.transaction_id = next_transaction_id;
627                Ok(())
628            }
629            ClientState::Requesting(state) => {
630                if cx.now() < state.retry_at {
631                    return Ok(());
632                }
633
634                if state.retry >= self.retry_config.request_retries {
635                    net_debug!("DHCP request retries exceeded, restarting discovery");
636                    self.reset();
637                    return Ok(());
638                }
639
640                dhcp_repr.message_type = DhcpMessageType::Request;
641                dhcp_repr.requested_ip = Some(state.requested_ip);
642                dhcp_repr.server_identifier = Some(state.server.identifier);
643
644                net_debug!(
645                    "DHCP send request to {}: {:?}",
646                    ipv4_repr.dst_addr,
647                    dhcp_repr
648                );
649                ipv4_repr.payload_len = udp_repr.header_len() + dhcp_repr.buffer_len();
650                emit(cx, (ipv4_repr, udp_repr, dhcp_repr))?;
651
652                // Exponential backoff: Double every 2 retries.
653                state.retry_at = cx.now()
654                    + (self.retry_config.initial_request_timeout << (state.retry as u32 / 2));
655                state.retry += 1;
656
657                self.transaction_id = next_transaction_id;
658                Ok(())
659            }
660            ClientState::Renewing(state) => {
661                let now = cx.now();
662                if state.expires_at <= now {
663                    net_debug!("DHCP lease expired");
664                    self.reset();
665                    // return Ok so we get polled again
666                    return Ok(());
667                }
668
669                if now < state.renew_at || state.rebinding && now < state.rebind_at {
670                    return Ok(());
671                }
672
673                state.rebinding |= now >= state.rebind_at;
674
675                ipv4_repr.src_addr = state.config.address.address();
676                // Renewing is unicast to the original server, rebinding is broadcast
677                if !state.rebinding {
678                    ipv4_repr.dst_addr = state.config.server.address;
679                }
680                dhcp_repr.message_type = DhcpMessageType::Request;
681                dhcp_repr.client_ip = state.config.address.address();
682
683                net_debug!("DHCP send renew to {}: {:?}", ipv4_repr.dst_addr, dhcp_repr);
684                ipv4_repr.payload_len = udp_repr.header_len() + dhcp_repr.buffer_len();
685                emit(cx, (ipv4_repr, udp_repr, dhcp_repr))?;
686
687                // In both RENEWING and REBINDING states, if the client receives no
688                // response to its DHCPREQUEST message, the client SHOULD wait one-half
689                // of the remaining time until T2 (in RENEWING state) and one-half of
690                // the remaining lease time (in REBINDING state), down to a minimum of
691                // 60 seconds, before retransmitting the DHCPREQUEST message.
692                if state.rebinding {
693                    state.rebind_at = now
694                        + self
695                            .retry_config
696                            .min_renew_timeout
697                            .max((state.expires_at - now) / 2)
698                            .min(self.retry_config.max_renew_timeout);
699                } else {
700                    state.renew_at = now
701                        + self
702                            .retry_config
703                            .min_renew_timeout
704                            .max((state.rebind_at - now) / 2)
705                            .min(state.rebind_at - now)
706                            .min(self.retry_config.max_renew_timeout);
707                }
708
709                self.transaction_id = next_transaction_id;
710                Ok(())
711            }
712        }
713    }
714
715    /// Reset state and restart discovery phase.
716    ///
717    /// Use this to speed up acquisition of an address in a new
718    /// network if a link was down and it is now back up.
719    pub fn reset(&mut self) {
720        net_trace!("DHCP reset");
721        if let ClientState::Renewing(_) = &self.state {
722            self.config_changed();
723        }
724        self.state = ClientState::Discovering(DiscoverState {
725            retry_at: Instant::from_millis(0),
726        });
727    }
728
729    /// Query the socket for configuration changes.
730    ///
731    /// The socket has an internal "configuration changed" flag. If
732    /// set, this function returns the configuration and resets the flag.
733    pub fn poll(&mut self) -> Option<Event> {
734        if !self.config_changed {
735            None
736        } else if let ClientState::Renewing(state) = &self.state {
737            self.config_changed = false;
738            Some(Event::Configured(Config {
739                server: state.config.server,
740                address: state.config.address,
741                router: state.config.router,
742                dns_servers: state.config.dns_servers.clone(),
743                packet: self
744                    .receive_packet_buffer
745                    .as_deref()
746                    .map(DhcpPacket::new_unchecked),
747            }))
748        } else {
749            self.config_changed = false;
750            Some(Event::Deconfigured)
751        }
752    }
753
754    /// This function _must_ be called when the configuration provided to the
755    /// interface, by this DHCP socket, changes. It will update the `config_changed` field
756    /// so that a subsequent call to `poll` will yield an event, and wake a possible waker.
757    pub(crate) fn config_changed(&mut self) {
758        self.config_changed = true;
759        #[cfg(feature = "async")]
760        self.waker.wake();
761    }
762
763    /// Register a waker.
764    ///
765    /// The waker is woken on state changes that might affect the return value
766    /// of `poll` method calls, which indicates a new state in the DHCP configuration
767    /// provided by this DHCP socket.
768    ///
769    /// Notes:
770    ///
771    /// - Only one waker can be registered at a time. If another waker was previously registered,
772    ///   it is overwritten and will no longer be woken.
773    /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
774    #[cfg(feature = "async")]
775    pub fn register_waker(&mut self, waker: &Waker) {
776        self.waker.register(waker)
777    }
778}
779
780#[cfg(test)]
781mod test {
782
783    use std::ops::{Deref, DerefMut};
784
785    use super::*;
786    use crate::wire::EthernetAddress;
787
788    // =========================================================================================//
789    // Helper functions
790
791    struct TestSocket {
792        socket: Socket<'static>,
793        cx: Context,
794    }
795
796    impl Deref for TestSocket {
797        type Target = Socket<'static>;
798        fn deref(&self) -> &Self::Target {
799            &self.socket
800        }
801    }
802
803    impl DerefMut for TestSocket {
804        fn deref_mut(&mut self) -> &mut Self::Target {
805            &mut self.socket
806        }
807    }
808
809    fn send(
810        s: &mut TestSocket,
811        timestamp: Instant,
812        (ip_repr, udp_repr, dhcp_repr): (Ipv4Repr, UdpRepr, DhcpRepr),
813    ) {
814        s.cx.set_now(timestamp);
815
816        net_trace!("send: {:?}", ip_repr);
817        net_trace!("      {:?}", udp_repr);
818        net_trace!("      {:?}", dhcp_repr);
819
820        let mut payload = vec![0; dhcp_repr.buffer_len()];
821        dhcp_repr
822            .emit(&mut DhcpPacket::new_unchecked(&mut payload))
823            .unwrap();
824
825        s.socket.process(&mut s.cx, &ip_repr, &udp_repr, &payload)
826    }
827
828    fn recv(s: &mut TestSocket, timestamp: Instant, reprs: &[(Ipv4Repr, UdpRepr, DhcpRepr)]) {
829        s.cx.set_now(timestamp);
830
831        let mut i = 0;
832
833        while s.socket.poll_at(&mut s.cx) <= PollAt::Time(timestamp) {
834            let _ = s
835                .socket
836                .dispatch(&mut s.cx, |_, (mut ip_repr, udp_repr, dhcp_repr)| {
837                    assert_eq!(ip_repr.next_header, IpProtocol::Udp);
838                    assert_eq!(
839                        ip_repr.payload_len,
840                        udp_repr.header_len() + dhcp_repr.buffer_len()
841                    );
842
843                    // We validated the payload len, change it to 0 to make equality testing easier
844                    ip_repr.payload_len = 0;
845
846                    net_trace!("recv: {:?}", ip_repr);
847                    net_trace!("      {:?}", udp_repr);
848                    net_trace!("      {:?}", dhcp_repr);
849
850                    let got_repr = (ip_repr, udp_repr, dhcp_repr);
851                    match reprs.get(i) {
852                        Some(want_repr) => assert_eq!(want_repr, &got_repr),
853                        None => panic!("Too many reprs emitted"),
854                    }
855                    i += 1;
856                    Ok::<_, ()>(())
857                });
858        }
859
860        assert_eq!(i, reprs.len());
861    }
862
863    macro_rules! send {
864        ($socket:ident, $repr:expr) =>
865            (send!($socket, time 0, $repr));
866        ($socket:ident, time $time:expr, $repr:expr) =>
867            (send(&mut $socket, Instant::from_millis($time), $repr));
868    }
869
870    macro_rules! recv {
871        ($socket:ident, $reprs:expr) => ({
872            recv!($socket, time 0, $reprs);
873        });
874        ($socket:ident, time $time:expr, $reprs:expr) => ({
875            recv(&mut $socket, Instant::from_millis($time), &$reprs);
876        });
877    }
878
879    // =========================================================================================//
880    // Constants
881
882    const TXID: u32 = 0x12345678;
883
884    const MY_IP: Ipv4Address = Ipv4Address::new(192, 168, 1, 42);
885    const SERVER_IP: Ipv4Address = Ipv4Address::new(192, 168, 1, 1);
886    const DNS_IP_1: Ipv4Address = Ipv4Address::new(1, 1, 1, 1);
887    const DNS_IP_2: Ipv4Address = Ipv4Address::new(1, 1, 1, 2);
888    const DNS_IP_3: Ipv4Address = Ipv4Address::new(1, 1, 1, 3);
889    const DNS_IPS: &[Ipv4Address] = &[DNS_IP_1, DNS_IP_2, DNS_IP_3];
890
891    const MASK_24: Ipv4Address = Ipv4Address::new(255, 255, 255, 0);
892
893    const MY_MAC: EthernetAddress = EthernetAddress([0x02, 0x02, 0x02, 0x02, 0x02, 0x02]);
894
895    const IP_BROADCAST: Ipv4Repr = Ipv4Repr {
896        src_addr: Ipv4Address::UNSPECIFIED,
897        dst_addr: Ipv4Address::BROADCAST,
898        next_header: IpProtocol::Udp,
899        payload_len: 0,
900        hop_limit: 64,
901    };
902
903    const IP_BROADCAST_ADDRESSED: Ipv4Repr = Ipv4Repr {
904        src_addr: MY_IP,
905        dst_addr: Ipv4Address::BROADCAST,
906        next_header: IpProtocol::Udp,
907        payload_len: 0,
908        hop_limit: 64,
909    };
910
911    const IP_SERVER_BROADCAST: Ipv4Repr = Ipv4Repr {
912        src_addr: SERVER_IP,
913        dst_addr: Ipv4Address::BROADCAST,
914        next_header: IpProtocol::Udp,
915        payload_len: 0,
916        hop_limit: 64,
917    };
918
919    const IP_RECV: Ipv4Repr = Ipv4Repr {
920        src_addr: SERVER_IP,
921        dst_addr: MY_IP,
922        next_header: IpProtocol::Udp,
923        payload_len: 0,
924        hop_limit: 64,
925    };
926
927    const IP_SEND: Ipv4Repr = Ipv4Repr {
928        src_addr: MY_IP,
929        dst_addr: SERVER_IP,
930        next_header: IpProtocol::Udp,
931        payload_len: 0,
932        hop_limit: 64,
933    };
934
935    const UDP_SEND: UdpRepr = UdpRepr {
936        src_port: DHCP_CLIENT_PORT,
937        dst_port: DHCP_SERVER_PORT,
938    };
939    const UDP_RECV: UdpRepr = UdpRepr {
940        src_port: DHCP_SERVER_PORT,
941        dst_port: DHCP_CLIENT_PORT,
942    };
943
944    const DIFFERENT_CLIENT_PORT: u16 = 6800;
945    const DIFFERENT_SERVER_PORT: u16 = 6700;
946
947    const UDP_SEND_DIFFERENT_PORT: UdpRepr = UdpRepr {
948        src_port: DIFFERENT_CLIENT_PORT,
949        dst_port: DIFFERENT_SERVER_PORT,
950    };
951    const UDP_RECV_DIFFERENT_PORT: UdpRepr = UdpRepr {
952        src_port: DIFFERENT_SERVER_PORT,
953        dst_port: DIFFERENT_CLIENT_PORT,
954    };
955
956    const DHCP_DEFAULT: DhcpRepr = DhcpRepr {
957        message_type: DhcpMessageType::Unknown(99),
958        transaction_id: TXID,
959        secs: 0,
960        client_hardware_address: MY_MAC,
961        client_ip: Ipv4Address::UNSPECIFIED,
962        your_ip: Ipv4Address::UNSPECIFIED,
963        server_ip: Ipv4Address::UNSPECIFIED,
964        router: None,
965        subnet_mask: None,
966        relay_agent_ip: Ipv4Address::UNSPECIFIED,
967        broadcast: false,
968        requested_ip: None,
969        client_identifier: None,
970        server_identifier: None,
971        parameter_request_list: None,
972        dns_servers: None,
973        max_size: None,
974        renew_duration: None,
975        rebind_duration: None,
976        lease_duration: None,
977        additional_options: &[],
978    };
979
980    const DHCP_DISCOVER: DhcpRepr = DhcpRepr {
981        message_type: DhcpMessageType::Discover,
982        client_identifier: Some(MY_MAC),
983        parameter_request_list: Some(&[1, 3, 6]),
984        max_size: Some(1432),
985        ..DHCP_DEFAULT
986    };
987
988    fn dhcp_offer() -> DhcpRepr<'static> {
989        DhcpRepr {
990            message_type: DhcpMessageType::Offer,
991            server_ip: SERVER_IP,
992            server_identifier: Some(SERVER_IP),
993
994            your_ip: MY_IP,
995            router: Some(SERVER_IP),
996            subnet_mask: Some(MASK_24),
997            dns_servers: Some(Vec::from_slice(DNS_IPS).unwrap()),
998            lease_duration: Some(1000),
999
1000            ..DHCP_DEFAULT
1001        }
1002    }
1003
1004    const DHCP_REQUEST: DhcpRepr = DhcpRepr {
1005        message_type: DhcpMessageType::Request,
1006        client_identifier: Some(MY_MAC),
1007        server_identifier: Some(SERVER_IP),
1008        max_size: Some(1432),
1009
1010        requested_ip: Some(MY_IP),
1011        parameter_request_list: Some(&[1, 3, 6]),
1012        ..DHCP_DEFAULT
1013    };
1014
1015    fn dhcp_ack() -> DhcpRepr<'static> {
1016        DhcpRepr {
1017            message_type: DhcpMessageType::Ack,
1018            server_ip: SERVER_IP,
1019            server_identifier: Some(SERVER_IP),
1020
1021            your_ip: MY_IP,
1022            router: Some(SERVER_IP),
1023            subnet_mask: Some(MASK_24),
1024            dns_servers: Some(Vec::from_slice(DNS_IPS).unwrap()),
1025            lease_duration: Some(1000),
1026
1027            ..DHCP_DEFAULT
1028        }
1029    }
1030
1031    const DHCP_NAK: DhcpRepr = DhcpRepr {
1032        message_type: DhcpMessageType::Nak,
1033        server_ip: SERVER_IP,
1034        server_identifier: Some(SERVER_IP),
1035        ..DHCP_DEFAULT
1036    };
1037
1038    const DHCP_RENEW: DhcpRepr = DhcpRepr {
1039        message_type: DhcpMessageType::Request,
1040        client_identifier: Some(MY_MAC),
1041        // NO server_identifier in renew requests, only in first one!
1042        client_ip: MY_IP,
1043        max_size: Some(1432),
1044
1045        requested_ip: None,
1046        parameter_request_list: Some(&[1, 3, 6]),
1047        ..DHCP_DEFAULT
1048    };
1049
1050    const DHCP_REBIND: DhcpRepr = DhcpRepr {
1051        message_type: DhcpMessageType::Request,
1052        client_identifier: Some(MY_MAC),
1053        // NO server_identifier in renew requests, only in first one!
1054        client_ip: MY_IP,
1055        max_size: Some(1432),
1056
1057        requested_ip: None,
1058        parameter_request_list: Some(&[1, 3, 6]),
1059        ..DHCP_DEFAULT
1060    };
1061
1062    // =========================================================================================//
1063    // Tests
1064
1065    use crate::phy::Medium;
1066    use crate::tests::setup;
1067    use rstest::*;
1068
1069    fn socket(medium: Medium) -> TestSocket {
1070        let (iface, _, _) = setup(medium);
1071        let mut s = Socket::new();
1072        assert_eq!(s.poll(), Some(Event::Deconfigured));
1073        TestSocket {
1074            socket: s,
1075            cx: iface.inner,
1076        }
1077    }
1078
1079    fn socket_different_port(medium: Medium) -> TestSocket {
1080        let (iface, _, _) = setup(medium);
1081        let mut s = Socket::new();
1082        s.set_ports(DIFFERENT_SERVER_PORT, DIFFERENT_CLIENT_PORT);
1083
1084        assert_eq!(s.poll(), Some(Event::Deconfigured));
1085        TestSocket {
1086            socket: s,
1087            cx: iface.inner,
1088        }
1089    }
1090
1091    fn socket_bound(medium: Medium) -> TestSocket {
1092        let mut s = socket(medium);
1093        s.state = ClientState::Renewing(RenewState {
1094            config: Config {
1095                server: ServerInfo {
1096                    address: SERVER_IP,
1097                    identifier: SERVER_IP,
1098                },
1099                address: Ipv4Cidr::new(MY_IP, 24),
1100                dns_servers: Vec::from_slice(DNS_IPS).unwrap(),
1101                router: Some(SERVER_IP),
1102                packet: None,
1103            },
1104            renew_at: Instant::from_secs(500),
1105            rebind_at: Instant::from_secs(875),
1106            rebinding: false,
1107            expires_at: Instant::from_secs(1000),
1108        });
1109
1110        s
1111    }
1112
1113    #[rstest]
1114    #[case::ip(Medium::Ethernet)]
1115    #[cfg(feature = "medium-ethernet")]
1116    fn test_bind(#[case] medium: Medium) {
1117        let mut s = socket(medium);
1118
1119        recv!(s, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1120        assert_eq!(s.poll(), None);
1121        send!(s, (IP_RECV, UDP_RECV, dhcp_offer()));
1122        assert_eq!(s.poll(), None);
1123        recv!(s, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1124        assert_eq!(s.poll(), None);
1125        send!(s, (IP_RECV, UDP_RECV, dhcp_ack()));
1126
1127        assert_eq!(
1128            s.poll(),
1129            Some(Event::Configured(Config {
1130                server: ServerInfo {
1131                    address: SERVER_IP,
1132                    identifier: SERVER_IP,
1133                },
1134                address: Ipv4Cidr::new(MY_IP, 24),
1135                dns_servers: Vec::from_slice(DNS_IPS).unwrap(),
1136                router: Some(SERVER_IP),
1137                packet: None,
1138            }))
1139        );
1140
1141        match &s.state {
1142            ClientState::Renewing(r) => {
1143                assert_eq!(r.renew_at, Instant::from_secs(500));
1144                assert_eq!(r.rebind_at, Instant::from_secs(875));
1145                assert_eq!(r.expires_at, Instant::from_secs(1000));
1146            }
1147            _ => panic!("Invalid state"),
1148        }
1149    }
1150
1151    #[rstest]
1152    #[case::ip(Medium::Ethernet)]
1153    #[cfg(feature = "medium-ethernet")]
1154    fn test_bind_different_ports(#[case] medium: Medium) {
1155        let mut s = socket_different_port(medium);
1156
1157        recv!(s, [(IP_BROADCAST, UDP_SEND_DIFFERENT_PORT, DHCP_DISCOVER)]);
1158        assert_eq!(s.poll(), None);
1159        send!(s, (IP_RECV, UDP_RECV_DIFFERENT_PORT, dhcp_offer()));
1160        assert_eq!(s.poll(), None);
1161        recv!(s, [(IP_BROADCAST, UDP_SEND_DIFFERENT_PORT, DHCP_REQUEST)]);
1162        assert_eq!(s.poll(), None);
1163        send!(s, (IP_RECV, UDP_RECV_DIFFERENT_PORT, dhcp_ack()));
1164
1165        assert_eq!(
1166            s.poll(),
1167            Some(Event::Configured(Config {
1168                server: ServerInfo {
1169                    address: SERVER_IP,
1170                    identifier: SERVER_IP,
1171                },
1172                address: Ipv4Cidr::new(MY_IP, 24),
1173                dns_servers: Vec::from_slice(DNS_IPS).unwrap(),
1174                router: Some(SERVER_IP),
1175                packet: None,
1176            }))
1177        );
1178
1179        match &s.state {
1180            ClientState::Renewing(r) => {
1181                assert_eq!(r.renew_at, Instant::from_secs(500));
1182                assert_eq!(r.rebind_at, Instant::from_secs(875));
1183                assert_eq!(r.expires_at, Instant::from_secs(1000));
1184            }
1185            _ => panic!("Invalid state"),
1186        }
1187    }
1188
1189    #[rstest]
1190    #[case::ip(Medium::Ethernet)]
1191    #[cfg(feature = "medium-ethernet")]
1192    fn test_discover_retransmit(#[case] medium: Medium) {
1193        let mut s = socket(medium);
1194
1195        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1196        recv!(s, time 1_000, []);
1197        recv!(s, time 10_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1198        recv!(s, time 11_000, []);
1199        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1200
1201        // check after retransmits it still works
1202        send!(s, time 20_000, (IP_RECV, UDP_RECV, dhcp_offer()));
1203        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1204    }
1205
1206    #[rstest]
1207    #[case::ip(Medium::Ethernet)]
1208    #[cfg(feature = "medium-ethernet")]
1209    fn test_request_retransmit(#[case] medium: Medium) {
1210        let mut s = socket(medium);
1211
1212        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1213        send!(s, time 0, (IP_RECV, UDP_RECV, dhcp_offer()));
1214        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1215        recv!(s, time 1_000, []);
1216        recv!(s, time 5_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1217        recv!(s, time 6_000, []);
1218        recv!(s, time 10_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1219        recv!(s, time 15_000, []);
1220        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1221
1222        // check after retransmits it still works
1223        send!(s, time 20_000, (IP_RECV, UDP_RECV, dhcp_ack()));
1224
1225        match &s.state {
1226            ClientState::Renewing(r) => {
1227                assert_eq!(r.renew_at, Instant::from_secs(20 + 500));
1228                assert_eq!(r.expires_at, Instant::from_secs(20 + 1000));
1229            }
1230            _ => panic!("Invalid state"),
1231        }
1232    }
1233
1234    #[rstest]
1235    #[case::ip(Medium::Ethernet)]
1236    #[cfg(feature = "medium-ethernet")]
1237    fn test_request_timeout(#[case] medium: Medium) {
1238        let mut s = socket(medium);
1239
1240        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1241        send!(s, time 0, (IP_RECV, UDP_RECV, dhcp_offer()));
1242        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1243        recv!(s, time 5_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1244        recv!(s, time 10_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1245        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1246        recv!(s, time 30_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1247
1248        // After 5 tries and 70 seconds, it gives up.
1249        // 5 + 5 + 10 + 10 + 20 = 70
1250        recv!(s, time 70_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1251
1252        // check it still works
1253        send!(s, time 60_000, (IP_RECV, UDP_RECV, dhcp_offer()));
1254        recv!(s, time 60_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1255    }
1256
1257    #[rstest]
1258    #[case::ip(Medium::Ethernet)]
1259    #[cfg(feature = "medium-ethernet")]
1260    fn test_request_nak(#[case] medium: Medium) {
1261        let mut s = socket(medium);
1262
1263        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1264        send!(s, time 0, (IP_RECV, UDP_RECV, dhcp_offer()));
1265        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1266        send!(s, time 0, (IP_SERVER_BROADCAST, UDP_RECV, DHCP_NAK));
1267        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1268    }
1269
1270    #[rstest]
1271    #[case::ip(Medium::Ethernet)]
1272    #[cfg(feature = "medium-ethernet")]
1273    fn test_renew(#[case] medium: Medium) {
1274        let mut s = socket_bound(medium);
1275
1276        recv!(s, []);
1277        assert_eq!(s.poll(), None);
1278        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1279        assert_eq!(s.poll(), None);
1280
1281        match &s.state {
1282            ClientState::Renewing(r) => {
1283                // the expiration still hasn't been bumped, because
1284                // we haven't received the ACK yet
1285                assert_eq!(r.expires_at, Instant::from_secs(1000));
1286            }
1287            _ => panic!("Invalid state"),
1288        }
1289
1290        send!(s, time 500_000, (IP_RECV, UDP_RECV, dhcp_ack()));
1291        assert_eq!(s.poll(), None);
1292
1293        match &s.state {
1294            ClientState::Renewing(r) => {
1295                // NOW the expiration gets bumped
1296                assert_eq!(r.renew_at, Instant::from_secs(500 + 500));
1297                assert_eq!(r.expires_at, Instant::from_secs(500 + 1000));
1298            }
1299            _ => panic!("Invalid state"),
1300        }
1301    }
1302
1303    #[rstest]
1304    #[case::ip(Medium::Ethernet)]
1305    #[cfg(feature = "medium-ethernet")]
1306    fn test_renew_rebind_retransmit(#[case] medium: Medium) {
1307        let mut s = socket_bound(medium);
1308
1309        recv!(s, []);
1310        // First renew attempt at T1
1311        recv!(s, time 499_000, []);
1312        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1313        // Next renew attempt at half way to T2
1314        recv!(s, time 687_000, []);
1315        recv!(s, time 687_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1316        // Next renew attempt at half way again to T2
1317        recv!(s, time 781_000, []);
1318        recv!(s, time 781_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1319        // Next renew attempt 60s later (minimum interval)
1320        recv!(s, time 841_000, []);
1321        recv!(s, time 841_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1322        // No more renews due to minimum interval
1323        recv!(s, time 874_000, []);
1324        // First rebind attempt
1325        recv!(s, time 875_000, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1326        // Next rebind attempt half way to expiry
1327        recv!(s, time 937_000, []);
1328        recv!(s, time 937_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1329        // Next rebind attempt 60s later (minimum interval)
1330        recv!(s, time 997_000, []);
1331        recv!(s, time 997_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1332
1333        // check it still works
1334        send!(s, time 999_000, (IP_RECV, UDP_RECV, dhcp_ack()));
1335        match &s.state {
1336            ClientState::Renewing(r) => {
1337                // NOW the expiration gets bumped
1338                assert_eq!(r.renew_at, Instant::from_secs(999 + 500));
1339                assert_eq!(r.expires_at, Instant::from_secs(999 + 1000));
1340            }
1341            _ => panic!("Invalid state"),
1342        }
1343    }
1344
1345    #[rstest]
1346    #[case::ip(Medium::Ethernet)]
1347    #[cfg(feature = "medium-ethernet")]
1348    fn test_renew_rebind_timeout(#[case] medium: Medium) {
1349        let mut s = socket_bound(medium);
1350
1351        recv!(s, []);
1352        // First renew attempt at T1
1353        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1354        // Next renew attempt at half way to T2
1355        recv!(s, time 687_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1356        // Next renew attempt at half way again to T2
1357        recv!(s, time 781_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1358        // Next renew attempt 60s later (minimum interval)
1359        recv!(s, time 841_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1360        // TODO uncomment below part of test
1361        // // First rebind attempt
1362        // recv!(s, time 875_000, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1363        // // Next rebind attempt half way to expiry
1364        // recv!(s, time 937_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1365        // // Next rebind attempt 60s later (minimum interval)
1366        // recv!(s, time 997_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1367        // No more rebinds due to minimum interval
1368        recv!(s, time 1_000_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1369        match &s.state {
1370            ClientState::Discovering(_) => {}
1371            _ => panic!("Invalid state"),
1372        }
1373    }
1374
1375    #[rstest]
1376    #[case::ip(Medium::Ethernet)]
1377    #[cfg(feature = "medium-ethernet")]
1378    fn test_min_max_renew_timeout(#[case] medium: Medium) {
1379        let mut s = socket_bound(medium);
1380        // Set a minimum of 45s and a maximum of 120s
1381        let config = RetryConfig {
1382            max_renew_timeout: Duration::from_secs(120),
1383            min_renew_timeout: Duration::from_secs(45),
1384            ..s.get_retry_config()
1385        };
1386        s.set_retry_config(config);
1387        recv!(s, []);
1388        // First renew attempt at T1
1389        recv!(s, time 499_999, []);
1390        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1391        // Next renew attempt 120s after T1 because we hit the max
1392        recv!(s, time 619_999, []);
1393        recv!(s, time 620_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1394        // Next renew attempt 120s after previous because we hit the max again
1395        recv!(s, time 739_999, []);
1396        recv!(s, time 740_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1397        // Next renew attempt half way to T2
1398        recv!(s, time 807_499, []);
1399        recv!(s, time 807_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1400        // Next renew attempt 45s after previous because we hit the min
1401        recv!(s, time 852_499, []);
1402        recv!(s, time 852_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1403        // Next is a rebind, because the min puts us after T2
1404        recv!(s, time 874_999, []);
1405        recv!(s, time 875_000, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1406    }
1407
1408    #[rstest]
1409    #[case::ip(Medium::Ethernet)]
1410    #[cfg(feature = "medium-ethernet")]
1411    fn test_renew_nak(#[case] medium: Medium) {
1412        let mut s = socket_bound(medium);
1413
1414        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1415        send!(s, time 500_000, (IP_SERVER_BROADCAST, UDP_RECV, DHCP_NAK));
1416        recv!(s, time 500_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1417    }
1418}