Skip to main content

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    DHCP_CLIENT_PORT, DHCP_MAX_DNS_SERVER_COUNT, DHCP_SERVER_PORT, DhcpMessageType, DhcpPacket,
9    DhcpRepr, IpAddress, IpProtocol, Ipv4Address, Ipv4AddressExt, Ipv4Cidr, Ipv4Repr,
10    UDP_HEADER_LEN, UdpRepr,
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            && let Some(buffer) = buffer.get_mut(..payload.len())
363        {
364            buffer.copy_from_slice(payload);
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        // When receiving T1 and T2, they must be in the order:
506        // T1 < T2 < lease_duration
507        let (renew_duration, rebind_duration) = match (
508            dhcp_repr
509                .renew_duration
510                .map(|d| Duration::from_secs(d as u64)),
511            dhcp_repr
512                .rebind_duration
513                .map(|d| Duration::from_secs(d as u64)),
514        ) {
515            (Some(renew_duration), Some(rebind_duration))
516                if renew_duration < rebind_duration && rebind_duration < lease_duration =>
517            {
518                (renew_duration, rebind_duration)
519            }
520            // RFC 2131 does not say what to do if only one value is
521            // provided, so:
522
523            // If only T1 is provided, set T2 to be 0.75 through the gap
524            // between T1 and the duration of the lease. If T1 is set to
525            // the default (0.5 * duration_of_lease), then T2 will also
526            // be set to the default (0.875 * duration_of_lease).
527            (Some(renew_duration), None) if renew_duration < lease_duration => (
528                renew_duration,
529                renew_duration + (lease_duration - renew_duration) * 3 / 4,
530            ),
531
532            // If only T2 is provided, then T1 will be set to be
533            // whichever is smaller of the default (0.5 *
534            // duration_of_lease) or T2.
535            (None, Some(rebind_duration)) if rebind_duration < lease_duration => {
536                ((lease_duration / 2).min(rebind_duration), rebind_duration)
537            }
538
539            // Use the defaults if the following order is not met:
540            // T1 < T2 < lease_duration
541            (_, _) => {
542                net_debug!("using default T1 and T2 values since the provided values are invalid");
543                (lease_duration / 2, lease_duration * 7 / 8)
544            }
545        };
546        let renew_at = now + renew_duration;
547        let rebind_at = now + rebind_duration;
548        let expires_at = now + lease_duration;
549
550        Some((config, renew_at, rebind_at, expires_at))
551    }
552
553    #[cfg(not(test))]
554    fn random_transaction_id(cx: &mut Context) -> u32 {
555        cx.rand().rand_u32()
556    }
557
558    #[cfg(test)]
559    fn random_transaction_id(_cx: &mut Context) -> u32 {
560        0x12345678
561    }
562
563    pub(crate) fn dispatch<F, E>(&mut self, cx: &mut Context, emit: F) -> Result<(), E>
564    where
565        F: FnOnce(&mut Context, (Ipv4Repr, UdpRepr, DhcpRepr)) -> Result<(), E>,
566    {
567        // note: Dhcpv4Socket is only usable in ethernet mediums, so the
568        // unwrap can never fail.
569        let HardwareAddress::Ethernet(ethernet_addr) = cx.hardware_addr() else {
570            panic!("using DHCPv4 socket with a non-ethernet hardware address.");
571        };
572
573        // Worst case biggest IPv4 header length.
574        // 0x0f * 4 = 60 bytes.
575        const MAX_IPV4_HEADER_LEN: usize = 60;
576
577        let mut dhcp_repr = DhcpRepr {
578            message_type: DhcpMessageType::Discover,
579            transaction_id: self.transaction_id,
580            secs: 0,
581            client_hardware_address: ethernet_addr,
582            client_ip: Ipv4Address::UNSPECIFIED,
583            your_ip: Ipv4Address::UNSPECIFIED,
584            server_ip: Ipv4Address::UNSPECIFIED,
585            router: None,
586            subnet_mask: None,
587            relay_agent_ip: Ipv4Address::UNSPECIFIED,
588            broadcast: false,
589            requested_ip: None,
590            client_identifier: Some(ethernet_addr),
591            server_identifier: None,
592            parameter_request_list: Some(
593                self.parameter_request_list
594                    .unwrap_or(DEFAULT_PARAMETER_REQUEST_LIST),
595            ),
596            max_size: Some((cx.ip_mtu() - MAX_IPV4_HEADER_LEN - UDP_HEADER_LEN) as u16),
597            lease_duration: None,
598            renew_duration: None,
599            rebind_duration: None,
600            dns_servers: None,
601            additional_options: self.outgoing_options,
602        };
603
604        let udp_repr = UdpRepr {
605            src_port: self.client_port,
606            dst_port: self.server_port,
607        };
608
609        let mut ipv4_repr = Ipv4Repr {
610            src_addr: Ipv4Address::UNSPECIFIED,
611            dst_addr: Ipv4Address::BROADCAST,
612            next_header: IpProtocol::Udp,
613            payload_len: 0, // filled right before emit
614            hop_limit: 64,
615        };
616
617        match &mut self.state {
618            ClientState::Discovering(state) => {
619                if cx.now() < state.retry_at {
620                    return Ok(());
621                }
622
623                let next_transaction_id = Self::random_transaction_id(cx);
624                dhcp_repr.transaction_id = next_transaction_id;
625
626                // send packet
627                net_debug!(
628                    "DHCP send DISCOVER to {}: {:?}",
629                    ipv4_repr.dst_addr,
630                    dhcp_repr
631                );
632                ipv4_repr.payload_len = udp_repr.header_len() + dhcp_repr.buffer_len();
633                emit(cx, (ipv4_repr, udp_repr, dhcp_repr))?;
634
635                // Update state AFTER the packet has been successfully sent.
636                state.retry_at = cx.now() + self.retry_config.discover_timeout;
637                self.transaction_id = next_transaction_id;
638                Ok(())
639            }
640            ClientState::Requesting(state) => {
641                if cx.now() < state.retry_at {
642                    return Ok(());
643                }
644
645                if state.retry >= self.retry_config.request_retries {
646                    net_debug!("DHCP request retries exceeded, restarting discovery");
647                    self.reset();
648                    return Ok(());
649                }
650
651                dhcp_repr.message_type = DhcpMessageType::Request;
652                dhcp_repr.requested_ip = Some(state.requested_ip);
653                dhcp_repr.server_identifier = Some(state.server.identifier);
654
655                net_debug!(
656                    "DHCP send request to {}: {:?}",
657                    ipv4_repr.dst_addr,
658                    dhcp_repr
659                );
660                ipv4_repr.payload_len = udp_repr.header_len() + dhcp_repr.buffer_len();
661                emit(cx, (ipv4_repr, udp_repr, dhcp_repr))?;
662
663                // Exponential backoff: Double every 2 retries.
664                state.retry_at = cx.now()
665                    + (self.retry_config.initial_request_timeout << (state.retry as u32 / 2));
666                state.retry += 1;
667
668                Ok(())
669            }
670            ClientState::Renewing(state) => {
671                let now = cx.now();
672                if state.expires_at <= now {
673                    net_debug!("DHCP lease expired");
674                    self.reset();
675                    // return Ok so we get polled again
676                    return Ok(());
677                }
678
679                if now < state.renew_at || state.rebinding && now < state.rebind_at {
680                    return Ok(());
681                }
682
683                state.rebinding |= now >= state.rebind_at;
684
685                ipv4_repr.src_addr = state.config.address.address();
686                // Renewing is unicast to the original server, rebinding is broadcast
687                if !state.rebinding {
688                    ipv4_repr.dst_addr = state.config.server.address;
689                }
690                dhcp_repr.message_type = DhcpMessageType::Request;
691                dhcp_repr.client_ip = state.config.address.address();
692
693                let next_transaction_id = Self::random_transaction_id(cx);
694                dhcp_repr.transaction_id = next_transaction_id;
695
696                net_debug!("DHCP send renew to {}: {:?}", ipv4_repr.dst_addr, dhcp_repr);
697                ipv4_repr.payload_len = udp_repr.header_len() + dhcp_repr.buffer_len();
698                emit(cx, (ipv4_repr, udp_repr, dhcp_repr))?;
699
700                // In both RENEWING and REBINDING states, if the client receives no
701                // response to its DHCPREQUEST message, the client SHOULD wait one-half
702                // of the remaining time until T2 (in RENEWING state) and one-half of
703                // the remaining lease time (in REBINDING state), down to a minimum of
704                // 60 seconds, before retransmitting the DHCPREQUEST message.
705                if state.rebinding {
706                    state.rebind_at = now
707                        + self
708                            .retry_config
709                            .min_renew_timeout
710                            .max((state.expires_at - now) / 2)
711                            .min(self.retry_config.max_renew_timeout);
712                } else {
713                    state.renew_at = now
714                        + self
715                            .retry_config
716                            .min_renew_timeout
717                            .max((state.rebind_at - now) / 2)
718                            .min(state.rebind_at - now)
719                            .min(self.retry_config.max_renew_timeout);
720                }
721
722                self.transaction_id = next_transaction_id;
723                Ok(())
724            }
725        }
726    }
727
728    /// Reset state and restart discovery phase.
729    ///
730    /// Use this to speed up acquisition of an address in a new
731    /// network if a link was down and it is now back up.
732    pub fn reset(&mut self) {
733        net_trace!("DHCP reset");
734        if let ClientState::Renewing(_) = &self.state {
735            self.config_changed();
736        }
737        self.state = ClientState::Discovering(DiscoverState {
738            retry_at: Instant::from_millis(0),
739        });
740    }
741
742    /// Query the socket for configuration changes.
743    ///
744    /// The socket has an internal "configuration changed" flag. If
745    /// set, this function returns the configuration and resets the flag.
746    pub fn poll(&mut self) -> Option<Event<'_>> {
747        if !self.config_changed {
748            None
749        } else if let ClientState::Renewing(state) = &self.state {
750            self.config_changed = false;
751            Some(Event::Configured(Config {
752                server: state.config.server,
753                address: state.config.address,
754                router: state.config.router,
755                dns_servers: state.config.dns_servers.clone(),
756                packet: self
757                    .receive_packet_buffer
758                    .as_deref()
759                    .map(DhcpPacket::new_unchecked),
760            }))
761        } else {
762            self.config_changed = false;
763            Some(Event::Deconfigured)
764        }
765    }
766
767    /// This function _must_ be called when the configuration provided to the
768    /// interface, by this DHCP socket, changes. It will update the `config_changed` field
769    /// so that a subsequent call to `poll` will yield an event, and wake a possible waker.
770    pub(crate) fn config_changed(&mut self) {
771        self.config_changed = true;
772        #[cfg(feature = "async")]
773        self.waker.wake();
774    }
775
776    /// Register a waker.
777    ///
778    /// The waker is woken on state changes that might affect the return value
779    /// of `poll` method calls, which indicates a new state in the DHCP configuration
780    /// provided by this DHCP socket.
781    ///
782    /// Notes:
783    ///
784    /// - Only one waker can be registered at a time. If another waker was previously registered,
785    ///   it is overwritten and will no longer be woken.
786    /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
787    #[cfg(feature = "async")]
788    pub fn register_waker(&mut self, waker: &Waker) {
789        self.waker.register(waker)
790    }
791}
792
793#[cfg(test)]
794mod test {
795
796    use std::ops::{Deref, DerefMut};
797
798    use super::*;
799    use crate::wire::EthernetAddress;
800
801    // =========================================================================================//
802    // Helper functions
803
804    struct TestSocket {
805        socket: Socket<'static>,
806        cx: Context,
807    }
808
809    impl Deref for TestSocket {
810        type Target = Socket<'static>;
811        fn deref(&self) -> &Self::Target {
812            &self.socket
813        }
814    }
815
816    impl DerefMut for TestSocket {
817        fn deref_mut(&mut self) -> &mut Self::Target {
818            &mut self.socket
819        }
820    }
821
822    fn send(
823        s: &mut TestSocket,
824        timestamp: Instant,
825        (ip_repr, udp_repr, dhcp_repr): (Ipv4Repr, UdpRepr, DhcpRepr),
826    ) {
827        s.cx.set_now(timestamp);
828
829        net_trace!("send: {:?}", ip_repr);
830        net_trace!("      {:?}", udp_repr);
831        net_trace!("      {:?}", dhcp_repr);
832
833        let mut payload = vec![0; dhcp_repr.buffer_len()];
834        dhcp_repr
835            .emit(&mut DhcpPacket::new_unchecked(&mut payload))
836            .unwrap();
837
838        s.socket.process(&mut s.cx, &ip_repr, &udp_repr, &payload)
839    }
840
841    fn recv(s: &mut TestSocket, timestamp: Instant, reprs: &[(Ipv4Repr, UdpRepr, DhcpRepr)]) {
842        s.cx.set_now(timestamp);
843
844        let mut i = 0;
845
846        while s.socket.poll_at(&mut s.cx) <= PollAt::Time(timestamp) {
847            let _ = s
848                .socket
849                .dispatch(&mut s.cx, |_, (mut ip_repr, udp_repr, dhcp_repr)| {
850                    assert_eq!(ip_repr.next_header, IpProtocol::Udp);
851                    assert_eq!(
852                        ip_repr.payload_len,
853                        udp_repr.header_len() + dhcp_repr.buffer_len()
854                    );
855
856                    // We validated the payload len, change it to 0 to make equality testing easier
857                    ip_repr.payload_len = 0;
858
859                    net_trace!("recv: {:?}", ip_repr);
860                    net_trace!("      {:?}", udp_repr);
861                    net_trace!("      {:?}", dhcp_repr);
862
863                    let got_repr = (ip_repr, udp_repr, dhcp_repr);
864                    match reprs.get(i) {
865                        Some(want_repr) => assert_eq!(want_repr, &got_repr),
866                        None => panic!("Too many reprs emitted"),
867                    }
868                    i += 1;
869                    Ok::<_, ()>(())
870                });
871        }
872
873        assert_eq!(i, reprs.len());
874    }
875
876    macro_rules! send {
877        ($socket:ident, $repr:expr) =>
878            (send!($socket, time 0, $repr));
879        ($socket:ident, time $time:expr, $repr:expr) =>
880            (send(&mut $socket, Instant::from_millis($time), $repr));
881    }
882
883    macro_rules! recv {
884        ($socket:ident, $reprs:expr) => ({
885            recv!($socket, time 0, $reprs);
886        });
887        ($socket:ident, time $time:expr, $reprs:expr) => ({
888            recv(&mut $socket, Instant::from_millis($time), &$reprs);
889        });
890    }
891
892    // =========================================================================================//
893    // Constants
894
895    const TXID: u32 = 0x12345678;
896
897    const MY_IP: Ipv4Address = Ipv4Address::new(192, 168, 1, 42);
898    const SERVER_IP: Ipv4Address = Ipv4Address::new(192, 168, 1, 1);
899    const DNS_IP_1: Ipv4Address = Ipv4Address::new(1, 1, 1, 1);
900    const DNS_IP_2: Ipv4Address = Ipv4Address::new(1, 1, 1, 2);
901    const DNS_IP_3: Ipv4Address = Ipv4Address::new(1, 1, 1, 3);
902    const DNS_IPS: &[Ipv4Address] = &[DNS_IP_1, DNS_IP_2, DNS_IP_3];
903
904    const MASK_24: Ipv4Address = Ipv4Address::new(255, 255, 255, 0);
905
906    const MY_MAC: EthernetAddress = EthernetAddress([0x02, 0x02, 0x02, 0x02, 0x02, 0x02]);
907
908    const IP_BROADCAST: Ipv4Repr = Ipv4Repr {
909        src_addr: Ipv4Address::UNSPECIFIED,
910        dst_addr: Ipv4Address::BROADCAST,
911        next_header: IpProtocol::Udp,
912        payload_len: 0,
913        hop_limit: 64,
914    };
915
916    const IP_BROADCAST_ADDRESSED: Ipv4Repr = Ipv4Repr {
917        src_addr: MY_IP,
918        dst_addr: Ipv4Address::BROADCAST,
919        next_header: IpProtocol::Udp,
920        payload_len: 0,
921        hop_limit: 64,
922    };
923
924    const IP_SERVER_BROADCAST: Ipv4Repr = Ipv4Repr {
925        src_addr: SERVER_IP,
926        dst_addr: Ipv4Address::BROADCAST,
927        next_header: IpProtocol::Udp,
928        payload_len: 0,
929        hop_limit: 64,
930    };
931
932    const IP_RECV: Ipv4Repr = Ipv4Repr {
933        src_addr: SERVER_IP,
934        dst_addr: MY_IP,
935        next_header: IpProtocol::Udp,
936        payload_len: 0,
937        hop_limit: 64,
938    };
939
940    const IP_SEND: Ipv4Repr = Ipv4Repr {
941        src_addr: MY_IP,
942        dst_addr: SERVER_IP,
943        next_header: IpProtocol::Udp,
944        payload_len: 0,
945        hop_limit: 64,
946    };
947
948    const UDP_SEND: UdpRepr = UdpRepr {
949        src_port: DHCP_CLIENT_PORT,
950        dst_port: DHCP_SERVER_PORT,
951    };
952    const UDP_RECV: UdpRepr = UdpRepr {
953        src_port: DHCP_SERVER_PORT,
954        dst_port: DHCP_CLIENT_PORT,
955    };
956
957    const DIFFERENT_CLIENT_PORT: u16 = 6800;
958    const DIFFERENT_SERVER_PORT: u16 = 6700;
959
960    const UDP_SEND_DIFFERENT_PORT: UdpRepr = UdpRepr {
961        src_port: DIFFERENT_CLIENT_PORT,
962        dst_port: DIFFERENT_SERVER_PORT,
963    };
964    const UDP_RECV_DIFFERENT_PORT: UdpRepr = UdpRepr {
965        src_port: DIFFERENT_SERVER_PORT,
966        dst_port: DIFFERENT_CLIENT_PORT,
967    };
968
969    const DHCP_DEFAULT: DhcpRepr = DhcpRepr {
970        message_type: DhcpMessageType::Unknown(99),
971        transaction_id: TXID,
972        secs: 0,
973        client_hardware_address: MY_MAC,
974        client_ip: Ipv4Address::UNSPECIFIED,
975        your_ip: Ipv4Address::UNSPECIFIED,
976        server_ip: Ipv4Address::UNSPECIFIED,
977        router: None,
978        subnet_mask: None,
979        relay_agent_ip: Ipv4Address::UNSPECIFIED,
980        broadcast: false,
981        requested_ip: None,
982        client_identifier: None,
983        server_identifier: None,
984        parameter_request_list: None,
985        dns_servers: None,
986        max_size: None,
987        renew_duration: None,
988        rebind_duration: None,
989        lease_duration: None,
990        additional_options: &[],
991    };
992
993    const DHCP_DISCOVER: DhcpRepr = DhcpRepr {
994        message_type: DhcpMessageType::Discover,
995        client_identifier: Some(MY_MAC),
996        parameter_request_list: Some(&[1, 3, 6]),
997        max_size: Some(1432),
998        ..DHCP_DEFAULT
999    };
1000
1001    fn dhcp_offer() -> DhcpRepr<'static> {
1002        DhcpRepr {
1003            message_type: DhcpMessageType::Offer,
1004            server_ip: SERVER_IP,
1005            server_identifier: Some(SERVER_IP),
1006
1007            your_ip: MY_IP,
1008            router: Some(SERVER_IP),
1009            subnet_mask: Some(MASK_24),
1010            dns_servers: Some(Vec::from_slice(DNS_IPS).unwrap()),
1011            lease_duration: Some(1000),
1012
1013            ..DHCP_DEFAULT
1014        }
1015    }
1016
1017    const DHCP_REQUEST: DhcpRepr = DhcpRepr {
1018        message_type: DhcpMessageType::Request,
1019        client_identifier: Some(MY_MAC),
1020        server_identifier: Some(SERVER_IP),
1021        max_size: Some(1432),
1022
1023        requested_ip: Some(MY_IP),
1024        parameter_request_list: Some(&[1, 3, 6]),
1025        ..DHCP_DEFAULT
1026    };
1027
1028    fn dhcp_ack() -> DhcpRepr<'static> {
1029        DhcpRepr {
1030            message_type: DhcpMessageType::Ack,
1031            server_ip: SERVER_IP,
1032            server_identifier: Some(SERVER_IP),
1033
1034            your_ip: MY_IP,
1035            router: Some(SERVER_IP),
1036            subnet_mask: Some(MASK_24),
1037            dns_servers: Some(Vec::from_slice(DNS_IPS).unwrap()),
1038            lease_duration: Some(1000),
1039
1040            ..DHCP_DEFAULT
1041        }
1042    }
1043
1044    const DHCP_NAK: DhcpRepr = DhcpRepr {
1045        message_type: DhcpMessageType::Nak,
1046        server_ip: SERVER_IP,
1047        server_identifier: Some(SERVER_IP),
1048        ..DHCP_DEFAULT
1049    };
1050
1051    const DHCP_RENEW: DhcpRepr = DhcpRepr {
1052        message_type: DhcpMessageType::Request,
1053        client_identifier: Some(MY_MAC),
1054        // NO server_identifier in renew requests, only in first one!
1055        client_ip: MY_IP,
1056        max_size: Some(1432),
1057
1058        requested_ip: None,
1059        parameter_request_list: Some(&[1, 3, 6]),
1060        ..DHCP_DEFAULT
1061    };
1062
1063    const DHCP_REBIND: DhcpRepr = DhcpRepr {
1064        message_type: DhcpMessageType::Request,
1065        client_identifier: Some(MY_MAC),
1066        // NO server_identifier in renew requests, only in first one!
1067        client_ip: MY_IP,
1068        max_size: Some(1432),
1069
1070        requested_ip: None,
1071        parameter_request_list: Some(&[1, 3, 6]),
1072        ..DHCP_DEFAULT
1073    };
1074
1075    // =========================================================================================//
1076    // Tests
1077
1078    use crate::phy::Medium;
1079    use crate::tests::setup;
1080    use rstest::*;
1081
1082    fn socket(medium: Medium) -> TestSocket {
1083        let (iface, _, _) = setup(medium);
1084        let mut s = Socket::new();
1085        assert_eq!(s.poll(), Some(Event::Deconfigured));
1086        TestSocket {
1087            socket: s,
1088            cx: iface.inner,
1089        }
1090    }
1091
1092    fn socket_different_port(medium: Medium) -> TestSocket {
1093        let (iface, _, _) = setup(medium);
1094        let mut s = Socket::new();
1095        s.set_ports(DIFFERENT_SERVER_PORT, DIFFERENT_CLIENT_PORT);
1096
1097        assert_eq!(s.poll(), Some(Event::Deconfigured));
1098        TestSocket {
1099            socket: s,
1100            cx: iface.inner,
1101        }
1102    }
1103
1104    fn socket_bound(medium: Medium) -> TestSocket {
1105        let mut s = socket(medium);
1106        s.state = ClientState::Renewing(RenewState {
1107            config: Config {
1108                server: ServerInfo {
1109                    address: SERVER_IP,
1110                    identifier: SERVER_IP,
1111                },
1112                address: Ipv4Cidr::new(MY_IP, 24),
1113                dns_servers: Vec::from_slice(DNS_IPS).unwrap(),
1114                router: Some(SERVER_IP),
1115                packet: None,
1116            },
1117            renew_at: Instant::from_secs(500),
1118            rebind_at: Instant::from_secs(875),
1119            rebinding: false,
1120            expires_at: Instant::from_secs(1000),
1121        });
1122
1123        s
1124    }
1125
1126    #[rstest]
1127    #[case::ip(Medium::Ethernet)]
1128    #[cfg(feature = "medium-ethernet")]
1129    fn test_bind(#[case] medium: Medium) {
1130        let mut s = socket(medium);
1131
1132        recv!(s, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1133        assert_eq!(s.poll(), None);
1134        send!(s, (IP_RECV, UDP_RECV, dhcp_offer()));
1135        assert_eq!(s.poll(), None);
1136        recv!(s, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1137        assert_eq!(s.poll(), None);
1138        send!(s, (IP_RECV, UDP_RECV, dhcp_ack()));
1139
1140        assert_eq!(
1141            s.poll(),
1142            Some(Event::Configured(Config {
1143                server: ServerInfo {
1144                    address: SERVER_IP,
1145                    identifier: SERVER_IP,
1146                },
1147                address: Ipv4Cidr::new(MY_IP, 24),
1148                dns_servers: Vec::from_slice(DNS_IPS).unwrap(),
1149                router: Some(SERVER_IP),
1150                packet: None,
1151            }))
1152        );
1153
1154        match &s.state {
1155            ClientState::Renewing(r) => {
1156                assert_eq!(r.renew_at, Instant::from_secs(500));
1157                assert_eq!(r.rebind_at, Instant::from_secs(875));
1158                assert_eq!(r.expires_at, Instant::from_secs(1000));
1159            }
1160            _ => panic!("Invalid state"),
1161        }
1162    }
1163
1164    #[rstest]
1165    #[case::ip(Medium::Ethernet)]
1166    #[cfg(feature = "medium-ethernet")]
1167    fn test_bind_different_ports(#[case] medium: Medium) {
1168        let mut s = socket_different_port(medium);
1169
1170        recv!(s, [(IP_BROADCAST, UDP_SEND_DIFFERENT_PORT, DHCP_DISCOVER)]);
1171        assert_eq!(s.poll(), None);
1172        send!(s, (IP_RECV, UDP_RECV_DIFFERENT_PORT, dhcp_offer()));
1173        assert_eq!(s.poll(), None);
1174        recv!(s, [(IP_BROADCAST, UDP_SEND_DIFFERENT_PORT, DHCP_REQUEST)]);
1175        assert_eq!(s.poll(), None);
1176        send!(s, (IP_RECV, UDP_RECV_DIFFERENT_PORT, dhcp_ack()));
1177
1178        assert_eq!(
1179            s.poll(),
1180            Some(Event::Configured(Config {
1181                server: ServerInfo {
1182                    address: SERVER_IP,
1183                    identifier: SERVER_IP,
1184                },
1185                address: Ipv4Cidr::new(MY_IP, 24),
1186                dns_servers: Vec::from_slice(DNS_IPS).unwrap(),
1187                router: Some(SERVER_IP),
1188                packet: None,
1189            }))
1190        );
1191
1192        match &s.state {
1193            ClientState::Renewing(r) => {
1194                assert_eq!(r.renew_at, Instant::from_secs(500));
1195                assert_eq!(r.rebind_at, Instant::from_secs(875));
1196                assert_eq!(r.expires_at, Instant::from_secs(1000));
1197            }
1198            _ => panic!("Invalid state"),
1199        }
1200    }
1201
1202    #[rstest]
1203    #[case::ip(Medium::Ethernet)]
1204    #[cfg(feature = "medium-ethernet")]
1205    fn test_discover_retransmit(#[case] medium: Medium) {
1206        let mut s = socket(medium);
1207
1208        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1209        recv!(s, time 1_000, []);
1210        recv!(s, time 10_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1211        recv!(s, time 11_000, []);
1212        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1213
1214        // check after retransmits it still works
1215        send!(s, time 20_000, (IP_RECV, UDP_RECV, dhcp_offer()));
1216        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1217    }
1218
1219    #[rstest]
1220    #[case::ip(Medium::Ethernet)]
1221    #[cfg(feature = "medium-ethernet")]
1222    fn test_request_retransmit(#[case] medium: Medium) {
1223        let mut s = socket(medium);
1224
1225        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1226        send!(s, time 0, (IP_RECV, UDP_RECV, dhcp_offer()));
1227        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1228        recv!(s, time 1_000, []);
1229        recv!(s, time 5_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1230        recv!(s, time 6_000, []);
1231        recv!(s, time 10_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1232        recv!(s, time 15_000, []);
1233        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1234
1235        // check after retransmits it still works
1236        send!(s, time 20_000, (IP_RECV, UDP_RECV, dhcp_ack()));
1237
1238        match &s.state {
1239            ClientState::Renewing(r) => {
1240                assert_eq!(r.renew_at, Instant::from_secs(20 + 500));
1241                assert_eq!(r.expires_at, Instant::from_secs(20 + 1000));
1242            }
1243            _ => panic!("Invalid state"),
1244        }
1245    }
1246
1247    #[rstest]
1248    #[case::ip(Medium::Ethernet)]
1249    #[cfg(feature = "medium-ethernet")]
1250    fn test_request_timeout(#[case] medium: Medium) {
1251        let mut s = socket(medium);
1252
1253        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1254        send!(s, time 0, (IP_RECV, UDP_RECV, dhcp_offer()));
1255        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1256        recv!(s, time 5_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1257        recv!(s, time 10_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1258        recv!(s, time 20_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1259        recv!(s, time 30_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1260
1261        // After 5 tries and 70 seconds, it gives up.
1262        // 5 + 5 + 10 + 10 + 20 = 70
1263        recv!(s, time 70_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1264
1265        // check it still works
1266        send!(s, time 60_000, (IP_RECV, UDP_RECV, dhcp_offer()));
1267        recv!(s, time 60_000, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1268    }
1269
1270    #[rstest]
1271    #[case::ip(Medium::Ethernet)]
1272    #[cfg(feature = "medium-ethernet")]
1273    fn test_request_nak(#[case] medium: Medium) {
1274        let mut s = socket(medium);
1275
1276        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1277        send!(s, time 0, (IP_RECV, UDP_RECV, dhcp_offer()));
1278        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_REQUEST)]);
1279        send!(s, time 0, (IP_SERVER_BROADCAST, UDP_RECV, DHCP_NAK));
1280        recv!(s, time 0, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1281    }
1282
1283    #[rstest]
1284    #[case::ip(Medium::Ethernet)]
1285    #[cfg(feature = "medium-ethernet")]
1286    fn test_renew(#[case] medium: Medium) {
1287        let mut s = socket_bound(medium);
1288
1289        recv!(s, []);
1290        assert_eq!(s.poll(), None);
1291        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1292        assert_eq!(s.poll(), None);
1293
1294        match &s.state {
1295            ClientState::Renewing(r) => {
1296                // the expiration still hasn't been bumped, because
1297                // we haven't received the ACK yet
1298                assert_eq!(r.expires_at, Instant::from_secs(1000));
1299            }
1300            _ => panic!("Invalid state"),
1301        }
1302
1303        send!(s, time 500_000, (IP_RECV, UDP_RECV, dhcp_ack()));
1304        assert_eq!(s.poll(), None);
1305
1306        match &s.state {
1307            ClientState::Renewing(r) => {
1308                // NOW the expiration gets bumped
1309                assert_eq!(r.renew_at, Instant::from_secs(500 + 500));
1310                assert_eq!(r.expires_at, Instant::from_secs(500 + 1000));
1311            }
1312            _ => panic!("Invalid state"),
1313        }
1314    }
1315
1316    #[rstest]
1317    #[case::ip(Medium::Ethernet)]
1318    #[cfg(feature = "medium-ethernet")]
1319    fn test_renew_rebind_retransmit(#[case] medium: Medium) {
1320        let mut s = socket_bound(medium);
1321
1322        recv!(s, []);
1323        // First renew attempt at T1
1324        recv!(s, time 499_000, []);
1325        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1326        // Next renew attempt at half way to T2
1327        recv!(s, time 687_000, []);
1328        recv!(s, time 687_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1329        // Next renew attempt at half way again to T2
1330        recv!(s, time 781_000, []);
1331        recv!(s, time 781_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1332        // Next renew attempt 60s later (minimum interval)
1333        recv!(s, time 841_000, []);
1334        recv!(s, time 841_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1335        // No more renews due to minimum interval
1336        recv!(s, time 874_000, []);
1337        // First rebind attempt
1338        recv!(s, time 875_000, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1339        // Next rebind attempt half way to expiry
1340        recv!(s, time 937_000, []);
1341        recv!(s, time 937_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1342        // Next rebind attempt 60s later (minimum interval)
1343        recv!(s, time 997_000, []);
1344        recv!(s, time 997_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1345
1346        // check it still works
1347        send!(s, time 999_000, (IP_RECV, UDP_RECV, dhcp_ack()));
1348        match &s.state {
1349            ClientState::Renewing(r) => {
1350                // NOW the expiration gets bumped
1351                assert_eq!(r.renew_at, Instant::from_secs(999 + 500));
1352                assert_eq!(r.expires_at, Instant::from_secs(999 + 1000));
1353            }
1354            _ => panic!("Invalid state"),
1355        }
1356    }
1357
1358    #[rstest]
1359    #[case::ip(Medium::Ethernet)]
1360    #[cfg(feature = "medium-ethernet")]
1361    fn test_renew_rebind_timeout(#[case] medium: Medium) {
1362        let mut s = socket_bound(medium);
1363
1364        recv!(s, []);
1365        // First renew attempt at T1
1366        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1367        // Next renew attempt at half way to T2
1368        recv!(s, time 687_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1369        // Next renew attempt at half way again to T2
1370        recv!(s, time 781_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1371        // Next renew attempt 60s later (minimum interval)
1372        recv!(s, time 841_250, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1373        // TODO uncomment below part of test
1374        // // First rebind attempt
1375        // recv!(s, time 875_000, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1376        // // Next rebind attempt half way to expiry
1377        // recv!(s, time 937_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1378        // // Next rebind attempt 60s later (minimum interval)
1379        // recv!(s, time 997_500, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1380        // No more rebinds due to minimum interval
1381        recv!(s, time 1_000_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1382        match &s.state {
1383            ClientState::Discovering(_) => {}
1384            _ => panic!("Invalid state"),
1385        }
1386    }
1387
1388    #[rstest]
1389    #[case::ip(Medium::Ethernet)]
1390    #[cfg(feature = "medium-ethernet")]
1391    fn test_min_max_renew_timeout(#[case] medium: Medium) {
1392        let mut s = socket_bound(medium);
1393        // Set a minimum of 45s and a maximum of 120s
1394        let config = RetryConfig {
1395            max_renew_timeout: Duration::from_secs(120),
1396            min_renew_timeout: Duration::from_secs(45),
1397            ..s.get_retry_config()
1398        };
1399        s.set_retry_config(config);
1400        recv!(s, []);
1401        // First renew attempt at T1
1402        recv!(s, time 499_999, []);
1403        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1404        // Next renew attempt 120s after T1 because we hit the max
1405        recv!(s, time 619_999, []);
1406        recv!(s, time 620_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1407        // Next renew attempt 120s after previous because we hit the max again
1408        recv!(s, time 739_999, []);
1409        recv!(s, time 740_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1410        // Next renew attempt half way to T2
1411        recv!(s, time 807_499, []);
1412        recv!(s, time 807_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1413        // Next renew attempt 45s after previous because we hit the min
1414        recv!(s, time 852_499, []);
1415        recv!(s, time 852_500, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1416        // Next is a rebind, because the min puts us after T2
1417        recv!(s, time 874_999, []);
1418        recv!(s, time 875_000, [(IP_BROADCAST_ADDRESSED, UDP_SEND, DHCP_REBIND)]);
1419    }
1420
1421    #[rstest]
1422    #[case::ip(Medium::Ethernet)]
1423    #[cfg(feature = "medium-ethernet")]
1424    fn test_renew_nak(#[case] medium: Medium) {
1425        let mut s = socket_bound(medium);
1426
1427        recv!(s, time 500_000, [(IP_SEND, UDP_SEND, DHCP_RENEW)]);
1428        send!(s, time 500_000, (IP_SERVER_BROADCAST, UDP_RECV, DHCP_NAK));
1429        recv!(s, time 500_000, [(IP_BROADCAST, UDP_SEND, DHCP_DISCOVER)]);
1430    }
1431}