dhcpv4.rs 50 KB

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