1 use smoltcp::{socket::dhcpv4, wire}; 2 3 use crate::{kdebug, kinfo, net::NET_DRIVERS, syscall::SystemError}; 4 5 pub fn net_init() -> Result<(), SystemError> { 6 dhcp_query()?; 7 return Ok(()); 8 } 9 fn dhcp_query() -> Result<(), SystemError> { 10 let binding = NET_DRIVERS.write(); 11 12 let net_face = binding.get(&0).unwrap().clone(); 13 14 drop(binding); 15 16 // Create sockets 17 let mut dhcp_socket = dhcpv4::Socket::new(); 18 19 // Set a ridiculously short max lease time to show DHCP renews work properly. 20 // This will cause the DHCP client to start renewing after 5 seconds, and give up the 21 // lease after 10 seconds if renew hasn't succeeded. 22 // IMPORTANT: This should be removed in production. 23 dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10))); 24 25 let mut sockets = smoltcp::iface::SocketSet::new(vec![]); 26 let dhcp_handle = sockets.add(dhcp_socket); 27 28 const DHCP_TRY_ROUND: u8 = 10; 29 for i in 0..DHCP_TRY_ROUND { 30 kdebug!("DHCP try round: {}", i); 31 let _flag = net_face.poll(&mut sockets); 32 let event = sockets.get_mut::<dhcpv4::Socket>(dhcp_handle).poll(); 33 // kdebug!("event = {event:?} !!!"); 34 35 match event { 36 None => {} 37 38 Some(dhcpv4::Event::Configured(config)) => { 39 // kdebug!("Find Config!! {config:?}"); 40 // kdebug!("Find ip address: {}", config.address); 41 // kdebug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs()); 42 43 net_face 44 .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)]) 45 .ok(); 46 47 if let Some(router) = config.router { 48 net_face 49 .inner_iface() 50 .lock() 51 .routes_mut() 52 .add_default_ipv4_route(router) 53 .unwrap(); 54 let cidr = net_face.inner_iface().lock().ip_addrs().first().cloned(); 55 if cidr.is_some() { 56 let cidr = cidr.unwrap(); 57 kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr); 58 return Ok(()); 59 } 60 } else { 61 net_face 62 .inner_iface() 63 .lock() 64 .routes_mut() 65 .remove_default_ipv4_route(); 66 } 67 } 68 69 Some(dhcpv4::Event::Deconfigured) => { 70 kdebug!("Dhcp v4 deconfigured"); 71 net_face 72 .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new( 73 wire::Ipv4Address::UNSPECIFIED, 74 0, 75 ))]) 76 .ok(); 77 net_face 78 .inner_iface() 79 .lock() 80 .routes_mut() 81 .remove_default_ipv4_route(); 82 } 83 } 84 } 85 86 return Err(SystemError::ETIMEDOUT); 87 } 88