Routing.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/HashMap.h>
  7. #include <AK/Singleton.h>
  8. #include <Kernel/Debug.h>
  9. #include <Kernel/Net/LoopbackAdapter.h>
  10. #include <Kernel/Net/NetworkTask.h>
  11. #include <Kernel/Net/NetworkingManagement.h>
  12. #include <Kernel/Net/Routing.h>
  13. #include <Kernel/Thread.h>
  14. namespace Kernel {
  15. static AK::Singleton<Lockable<HashMap<IPv4Address, MACAddress>>> s_arp_table;
  16. class ARPTableBlocker : public Thread::Blocker {
  17. public:
  18. ARPTableBlocker(IPv4Address ip_addr, Optional<MACAddress>& addr);
  19. virtual const char* state_string() const override { return "Routing (ARP)"; }
  20. virtual Type blocker_type() const override { return Type::Routing; }
  21. virtual bool should_block() override { return m_should_block; }
  22. virtual void not_blocking(bool) override;
  23. bool unblock(bool from_add_blocker, const IPv4Address& ip_addr, const MACAddress& addr)
  24. {
  25. if (m_ip_addr != ip_addr)
  26. return false;
  27. {
  28. ScopedSpinLock lock(m_lock);
  29. if (m_did_unblock)
  30. return false;
  31. m_did_unblock = true;
  32. m_addr = addr;
  33. }
  34. if (!from_add_blocker)
  35. unblock_from_blocker();
  36. return true;
  37. }
  38. const IPv4Address& ip_addr() const { return m_ip_addr; }
  39. private:
  40. const IPv4Address m_ip_addr;
  41. Optional<MACAddress>& m_addr;
  42. bool m_did_unblock { false };
  43. bool m_should_block { true };
  44. };
  45. class ARPTableBlockCondition : public Thread::BlockCondition {
  46. public:
  47. void unblock(const IPv4Address& ip_addr, const MACAddress& addr)
  48. {
  49. BlockCondition::unblock([&](auto& b, void*, bool&) {
  50. VERIFY(b.blocker_type() == Thread::Blocker::Type::Routing);
  51. auto& blocker = static_cast<ARPTableBlocker&>(b);
  52. return blocker.unblock(false, ip_addr, addr);
  53. });
  54. }
  55. protected:
  56. virtual bool should_add_blocker(Thread::Blocker& b, void*) override
  57. {
  58. VERIFY(b.blocker_type() == Thread::Blocker::Type::Routing);
  59. auto& blocker = static_cast<ARPTableBlocker&>(b);
  60. auto val = s_arp_table->resource().get(blocker.ip_addr());
  61. if (!val.has_value())
  62. return true;
  63. return blocker.unblock(true, blocker.ip_addr(), val.value());
  64. }
  65. };
  66. static AK::Singleton<ARPTableBlockCondition> s_arp_table_block_condition;
  67. ARPTableBlocker::ARPTableBlocker(IPv4Address ip_addr, Optional<MACAddress>& addr)
  68. : m_ip_addr(ip_addr)
  69. , m_addr(addr)
  70. {
  71. if (!set_block_condition(*s_arp_table_block_condition))
  72. m_should_block = false;
  73. }
  74. void ARPTableBlocker::not_blocking(bool timeout_in_past)
  75. {
  76. VERIFY(timeout_in_past || !m_should_block);
  77. auto addr = s_arp_table->resource().get(ip_addr());
  78. ScopedSpinLock lock(m_lock);
  79. if (!m_did_unblock) {
  80. m_did_unblock = true;
  81. m_addr = move(addr);
  82. }
  83. }
  84. Lockable<HashMap<IPv4Address, MACAddress>>& arp_table()
  85. {
  86. return *s_arp_table;
  87. }
  88. void update_arp_table(const IPv4Address& ip_addr, const MACAddress& addr, UpdateArp update)
  89. {
  90. MutexLocker locker(arp_table().lock());
  91. if (update == UpdateArp::Set)
  92. arp_table().resource().set(ip_addr, addr);
  93. if (update == UpdateArp::Delete)
  94. arp_table().resource().remove(ip_addr);
  95. s_arp_table_block_condition->unblock(ip_addr, addr);
  96. if constexpr (ROUTING_DEBUG) {
  97. dmesgln("ARP table ({} entries):", arp_table().resource().size());
  98. for (auto& it : arp_table().resource()) {
  99. dmesgln("{} :: {}", it.value.to_string(), it.key.to_string());
  100. }
  101. }
  102. }
  103. bool RoutingDecision::is_zero() const
  104. {
  105. return adapter.is_null() || next_hop.is_zero();
  106. }
  107. static MACAddress multicast_ethernet_address(IPv4Address const& address)
  108. {
  109. return MACAddress { 0x01, 0x00, 0x5e, (u8)(address[1] & 0x7f), address[2], address[3] };
  110. }
  111. RoutingDecision route_to(const IPv4Address& target, const IPv4Address& source, const RefPtr<NetworkAdapter> through)
  112. {
  113. auto matches = [&](auto& adapter) {
  114. if (!through)
  115. return true;
  116. return through == adapter;
  117. };
  118. auto if_matches = [&](auto& adapter, const auto& mac) -> RoutingDecision {
  119. if (!matches(adapter))
  120. return { nullptr, {} };
  121. return { adapter, mac };
  122. };
  123. if (target[0] == 0 && target[1] == 0 && target[2] == 0 && target[3] == 0)
  124. return if_matches(*NetworkingManagement::the().loopback_adapter(), NetworkingManagement::the().loopback_adapter()->mac_address());
  125. if (target[0] == 127)
  126. return if_matches(*NetworkingManagement::the().loopback_adapter(), NetworkingManagement::the().loopback_adapter()->mac_address());
  127. auto target_addr = target.to_u32();
  128. auto source_addr = source.to_u32();
  129. RefPtr<NetworkAdapter> local_adapter = nullptr;
  130. RefPtr<NetworkAdapter> gateway_adapter = nullptr;
  131. NetworkingManagement::the().for_each([source_addr, &target_addr, &local_adapter, &gateway_adapter, &matches, &through](NetworkAdapter& adapter) {
  132. auto adapter_addr = adapter.ipv4_address().to_u32();
  133. auto adapter_mask = adapter.ipv4_netmask().to_u32();
  134. if (target_addr == adapter_addr) {
  135. local_adapter = NetworkingManagement::the().loopback_adapter();
  136. return;
  137. }
  138. if (!adapter.link_up() || (adapter_addr == 0 && !through))
  139. return;
  140. if (source_addr != 0 && source_addr != adapter_addr)
  141. return;
  142. if ((target_addr & adapter_mask) == (adapter_addr & adapter_mask) && matches(adapter))
  143. local_adapter = adapter;
  144. if (adapter.ipv4_gateway().to_u32() != 0 && matches(adapter))
  145. gateway_adapter = adapter;
  146. });
  147. if (local_adapter && target == local_adapter->ipv4_address())
  148. return { local_adapter, local_adapter->mac_address() };
  149. if (!local_adapter && !gateway_adapter) {
  150. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find a suitable adapter for route to {}", target);
  151. return { nullptr, {} };
  152. }
  153. RefPtr<NetworkAdapter> adapter = nullptr;
  154. IPv4Address next_hop_ip;
  155. if (local_adapter) {
  156. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (direct): {} ({}/{}) for {}",
  157. local_adapter->name(),
  158. local_adapter->ipv4_address(),
  159. local_adapter->ipv4_netmask(),
  160. target);
  161. adapter = local_adapter;
  162. next_hop_ip = target;
  163. } else if (gateway_adapter) {
  164. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (using gateway {}): {} ({}/{}) for {}",
  165. gateway_adapter->ipv4_gateway(),
  166. gateway_adapter->name(),
  167. gateway_adapter->ipv4_address(),
  168. gateway_adapter->ipv4_netmask(),
  169. target);
  170. adapter = gateway_adapter;
  171. next_hop_ip = gateway_adapter->ipv4_gateway();
  172. } else {
  173. return { nullptr, {} };
  174. }
  175. // If it's a broadcast, we already know everything we need to know.
  176. // FIXME: We should also deal with the case where `target_addr` is
  177. // a broadcast to a subnet rather than a full broadcast.
  178. if (target_addr == 0xffffffff && matches(adapter))
  179. return { adapter, { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
  180. if (adapter == NetworkingManagement::the().loopback_adapter())
  181. return { adapter, adapter->mac_address() };
  182. if ((target_addr & IPv4Address { 240, 0, 0, 0 }.to_u32()) == IPv4Address { 224, 0, 0, 0 }.to_u32())
  183. return { adapter, multicast_ethernet_address(target) };
  184. {
  185. MutexLocker locker(arp_table().lock());
  186. auto addr = arp_table().resource().get(next_hop_ip);
  187. if (addr.has_value()) {
  188. dbgln_if(ROUTING_DEBUG, "Routing: Using cached ARP entry for {} ({})", next_hop_ip, addr.value().to_string());
  189. return { adapter, addr.value() };
  190. }
  191. }
  192. dbgln_if(ROUTING_DEBUG, "Routing: Sending ARP request via adapter {} for IPv4 address {}", adapter->name(), next_hop_ip);
  193. ARPPacket request;
  194. request.set_operation(ARPOperation::Request);
  195. request.set_target_hardware_address({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
  196. request.set_target_protocol_address(next_hop_ip);
  197. request.set_sender_hardware_address(adapter->mac_address());
  198. request.set_sender_protocol_address(adapter->ipv4_address());
  199. adapter->send({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, request);
  200. if (NetworkTask::is_current()) {
  201. // FIXME: Waiting for the ARP response from inside the NetworkTask would
  202. // deadlock, so let's hope that whoever called route_to() tries again in a bit.
  203. dbgln_if(ROUTING_DEBUG, "Routing: Not waiting for ARP response from inside NetworkTask, sent ARP request using adapter {} for {}", adapter->name(), target);
  204. return { nullptr, {} };
  205. }
  206. Optional<MACAddress> addr;
  207. if (!Thread::current()->block<ARPTableBlocker>({}, next_hop_ip, addr).was_interrupted()) {
  208. if (addr.has_value()) {
  209. dbgln_if(ROUTING_DEBUG, "Routing: Got ARP response using adapter {} for {} ({})",
  210. adapter->name(),
  211. next_hop_ip,
  212. addr.value().to_string());
  213. return { adapter, addr.value() };
  214. }
  215. }
  216. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find route using adapter {} for {}", adapter->name(), target);
  217. return { nullptr, {} };
  218. }
  219. }