dhcp_client.rs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #![allow(clippy::option_map_unit_fn)]
  2. mod utils;
  3. use log::*;
  4. use std::collections::BTreeMap;
  5. use std::os::unix::io::AsRawFd;
  6. use smoltcp::iface::{Interface, InterfaceBuilder, NeighborCache, Routes};
  7. use smoltcp::socket::{Dhcpv4Event, Dhcpv4Socket, SocketSet};
  8. use smoltcp::time::Instant;
  9. use smoltcp::wire::{EthernetAddress, IpCidr, Ipv4Address, Ipv4Cidr};
  10. use smoltcp::{
  11. phy::{wait as phy_wait, Device, Medium},
  12. time::Duration,
  13. };
  14. fn main() {
  15. #[cfg(feature = "log")]
  16. utils::setup_logging("");
  17. let (mut opts, mut free) = utils::create_options();
  18. utils::add_tuntap_options(&mut opts, &mut free);
  19. utils::add_middleware_options(&mut opts, &mut free);
  20. let mut matches = utils::parse_options(&opts, free);
  21. let device = utils::parse_tuntap_options(&mut matches);
  22. let fd = device.as_raw_fd();
  23. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  24. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  25. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
  26. let ip_addrs = [IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0)];
  27. let mut routes_storage = [None; 1];
  28. let routes = Routes::new(&mut routes_storage[..]);
  29. let medium = device.capabilities().medium;
  30. let mut builder = InterfaceBuilder::new(device)
  31. .ip_addrs(ip_addrs)
  32. .routes(routes);
  33. if medium == Medium::Ethernet {
  34. builder = builder
  35. .ethernet_addr(ethernet_addr)
  36. .neighbor_cache(neighbor_cache);
  37. }
  38. let mut iface = builder.finalize();
  39. let mut sockets = SocketSet::new(vec![]);
  40. let mut dhcp_socket = Dhcpv4Socket::new();
  41. // Set a ridiculously short max lease time to show DHCP renews work properly.
  42. // This will cause the DHCP client to start renewing after 5 seconds, and give up the
  43. // lease after 10 seconds if renew hasn't succeeded.
  44. // IMPORTANT: This should be removed in production.
  45. dhcp_socket.set_max_lease_duration(Some(Duration::from_secs(10)));
  46. let dhcp_handle = sockets.add(dhcp_socket);
  47. loop {
  48. let timestamp = Instant::now();
  49. if let Err(e) = iface.poll(&mut sockets, timestamp) {
  50. debug!("poll error: {}", e);
  51. }
  52. match sockets.get::<Dhcpv4Socket>(dhcp_handle).poll() {
  53. None => {}
  54. Some(Dhcpv4Event::Configured(config)) => {
  55. debug!("DHCP config acquired!");
  56. debug!("IP address: {}", config.address);
  57. set_ipv4_addr(&mut iface, config.address);
  58. if let Some(router) = config.router {
  59. debug!("Default gateway: {}", router);
  60. iface.routes_mut().add_default_ipv4_route(router).unwrap();
  61. } else {
  62. debug!("Default gateway: None");
  63. iface.routes_mut().remove_default_ipv4_route();
  64. }
  65. for (i, s) in config.dns_servers.iter().enumerate() {
  66. if let Some(s) = s {
  67. debug!("DNS server {}: {}", i, s);
  68. }
  69. }
  70. }
  71. Some(Dhcpv4Event::Deconfigured) => {
  72. debug!("DHCP lost config!");
  73. set_ipv4_addr(&mut iface, Ipv4Cidr::new(Ipv4Address::UNSPECIFIED, 0));
  74. iface.routes_mut().remove_default_ipv4_route();
  75. }
  76. }
  77. phy_wait(fd, iface.poll_delay(&sockets, timestamp)).expect("wait error");
  78. }
  79. }
  80. fn set_ipv4_addr<DeviceT>(iface: &mut Interface<'_, DeviceT>, cidr: Ipv4Cidr)
  81. where
  82. DeviceT: for<'d> Device<'d>,
  83. {
  84. iface.update_ip_addrs(|addrs| {
  85. let dest = addrs.iter_mut().next().unwrap();
  86. *dest = IpCidr::Ipv4(cidr);
  87. });
  88. }