net_core.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. use alloc::{collections::BTreeMap, sync::Arc};
  2. use log::{debug, info, warn};
  3. use smoltcp::{socket::dhcpv4, wire};
  4. use system_error::SystemError;
  5. use crate::{
  6. driver::net::{Iface, Operstate},
  7. libs::rwlock::RwLockReadGuard,
  8. net::NET_DEVICES,
  9. time::{sleep::nanosleep, PosixTimeSpec},
  10. };
  11. pub fn net_init() -> Result<(), SystemError> {
  12. dhcp_query()
  13. }
  14. fn dhcp_query() -> Result<(), SystemError> {
  15. let binding = NET_DEVICES.write_irqsave();
  16. // Default iface, misspelled to net_face
  17. let net_face = binding
  18. .iter()
  19. .find(|(_, iface)| iface.common().is_default_iface())
  20. .unwrap()
  21. .1
  22. .clone();
  23. drop(binding);
  24. // Create sockets
  25. let mut dhcp_socket = dhcpv4::Socket::new();
  26. // Set a ridiculously short max lease time to show DHCP renews work properly.
  27. // This will cause the DHCP client to start renewing after 5 seconds, and give up the
  28. // lease after 10 seconds if renew hasn't succeeded.
  29. // IMPORTANT: This should be removed in production.
  30. dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10)));
  31. let sockets = || net_face.sockets().lock_irqsave();
  32. let dhcp_handle = sockets().add(dhcp_socket);
  33. defer::defer!({
  34. sockets().remove(dhcp_handle);
  35. });
  36. const DHCP_TRY_ROUND: u8 = 100;
  37. for i in 0..DHCP_TRY_ROUND {
  38. log::debug!("DHCP try round: {}", i);
  39. net_face.poll();
  40. let mut binding = sockets();
  41. let event = binding.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
  42. match event {
  43. None => {}
  44. Some(dhcpv4::Event::Configured(config)) => {
  45. // debug!("Find Config!! {config:?}");
  46. // debug!("Find ip address: {}", config.address);
  47. // debug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs());
  48. net_face
  49. .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)])
  50. .ok();
  51. if let Some(router) = config.router {
  52. let mut smol_iface = net_face.smol_iface().lock();
  53. smol_iface.routes_mut().update(|table| {
  54. let _ = table.push(smoltcp::iface::Route {
  55. cidr: smoltcp::wire::IpCidr::Ipv4(smoltcp::wire::Ipv4Cidr::new(
  56. smoltcp::wire::Ipv4Address::new(127, 0, 0, 0),
  57. 8,
  58. )),
  59. via_router: smoltcp::wire::IpAddress::v4(127, 0, 0, 1),
  60. preferred_until: None,
  61. expires_at: None,
  62. });
  63. });
  64. if smol_iface
  65. .routes_mut()
  66. .add_default_ipv4_route(router)
  67. .is_err()
  68. {
  69. log::warn!("Route table full");
  70. }
  71. let cidr = smol_iface.ip_addrs().first().cloned();
  72. if let Some(cidr) = cidr {
  73. // 这里先在这里将网卡设置为up,后面等netlink实现了再修改
  74. net_face.set_operstate(Operstate::IF_OPER_UP);
  75. info!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr);
  76. return Ok(());
  77. }
  78. } else {
  79. net_face
  80. .smol_iface()
  81. .lock()
  82. .routes_mut()
  83. .remove_default_ipv4_route();
  84. }
  85. }
  86. Some(dhcpv4::Event::Deconfigured) => {
  87. debug!("Dhcp v4 deconfigured");
  88. net_face
  89. .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new(
  90. wire::Ipv4Address::UNSPECIFIED,
  91. 0,
  92. ))])
  93. .ok();
  94. net_face
  95. .smol_iface()
  96. .lock()
  97. .routes_mut()
  98. .remove_default_ipv4_route();
  99. }
  100. }
  101. // 在睡眠前释放锁
  102. drop(binding);
  103. let sleep_time = PosixTimeSpec {
  104. tv_sec: 0,
  105. tv_nsec: 50,
  106. };
  107. let _ = nanosleep(sleep_time)?;
  108. }
  109. return Err(SystemError::ETIMEDOUT);
  110. }
  111. pub fn poll_ifaces() {
  112. // log::debug!("poll_ifaces");
  113. let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn Iface>>> = NET_DEVICES.read_irqsave();
  114. if guard.len() == 0 {
  115. warn!("poll_ifaces: No net driver found!");
  116. return;
  117. }
  118. for (_, iface) in guard.iter() {
  119. iface.poll();
  120. }
  121. }