Routing.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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)
  89. {
  90. Locker locker(arp_table().lock());
  91. arp_table().resource().set(ip_addr, addr);
  92. s_arp_table_block_condition->unblock(ip_addr, addr);
  93. if constexpr (ROUTING_DEBUG) {
  94. dmesgln("ARP table ({} entries):", arp_table().resource().size());
  95. for (auto& it : arp_table().resource()) {
  96. dmesgln("{} :: {}", it.value.to_string(), it.key.to_string());
  97. }
  98. }
  99. }
  100. bool RoutingDecision::is_zero() const
  101. {
  102. return adapter.is_null() || next_hop.is_zero();
  103. }
  104. static MACAddress multicast_ethernet_address(IPv4Address const& address)
  105. {
  106. return MACAddress { 0x01, 0x00, 0x5e, (u8)(address[1] & 0x7f), address[2], address[3] };
  107. }
  108. RoutingDecision route_to(const IPv4Address& target, const IPv4Address& source, const RefPtr<NetworkAdapter> through)
  109. {
  110. auto matches = [&](auto& adapter) {
  111. if (!through)
  112. return true;
  113. return through == adapter;
  114. };
  115. auto if_matches = [&](auto& adapter, const auto& mac) -> RoutingDecision {
  116. if (!matches(adapter))
  117. return { nullptr, {} };
  118. return { adapter, mac };
  119. };
  120. if (target[0] == 0 && target[1] == 0 && target[2] == 0 && target[3] == 0)
  121. return if_matches(*NetworkingManagement::the().loopback_adapter(), NetworkingManagement::the().loopback_adapter()->mac_address());
  122. if (target[0] == 127)
  123. return if_matches(*NetworkingManagement::the().loopback_adapter(), NetworkingManagement::the().loopback_adapter()->mac_address());
  124. auto target_addr = target.to_u32();
  125. auto source_addr = source.to_u32();
  126. RefPtr<NetworkAdapter> local_adapter = nullptr;
  127. RefPtr<NetworkAdapter> gateway_adapter = nullptr;
  128. NetworkingManagement::the().for_each([source_addr, &target_addr, &local_adapter, &gateway_adapter, &matches, &through](NetworkAdapter& adapter) {
  129. auto adapter_addr = adapter.ipv4_address().to_u32();
  130. auto adapter_mask = adapter.ipv4_netmask().to_u32();
  131. if (target_addr == adapter_addr) {
  132. local_adapter = NetworkingManagement::the().loopback_adapter();
  133. return;
  134. }
  135. if (!adapter.link_up() || (adapter_addr == 0 && !through))
  136. return;
  137. if (source_addr != 0 && source_addr != adapter_addr)
  138. return;
  139. if ((target_addr & adapter_mask) == (adapter_addr & adapter_mask) && matches(adapter))
  140. local_adapter = adapter;
  141. if (adapter.ipv4_gateway().to_u32() != 0 && matches(adapter))
  142. gateway_adapter = adapter;
  143. });
  144. if (local_adapter && target == local_adapter->ipv4_address())
  145. return { local_adapter, local_adapter->mac_address() };
  146. if (!local_adapter && !gateway_adapter) {
  147. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find a suitable adapter for route to {}", target);
  148. return { nullptr, {} };
  149. }
  150. RefPtr<NetworkAdapter> adapter = nullptr;
  151. IPv4Address next_hop_ip;
  152. if (local_adapter) {
  153. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (direct): {} ({}/{}) for {}",
  154. local_adapter->name(),
  155. local_adapter->ipv4_address(),
  156. local_adapter->ipv4_netmask(),
  157. target);
  158. adapter = local_adapter;
  159. next_hop_ip = target;
  160. } else if (gateway_adapter) {
  161. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (using gateway {}): {} ({}/{}) for {}",
  162. gateway_adapter->ipv4_gateway(),
  163. gateway_adapter->name(),
  164. gateway_adapter->ipv4_address(),
  165. gateway_adapter->ipv4_netmask(),
  166. target);
  167. adapter = gateway_adapter;
  168. next_hop_ip = gateway_adapter->ipv4_gateway();
  169. } else {
  170. return { nullptr, {} };
  171. }
  172. // If it's a broadcast, we already know everything we need to know.
  173. // FIXME: We should also deal with the case where `target_addr` is
  174. // a broadcast to a subnet rather than a full broadcast.
  175. if (target_addr == 0xffffffff && matches(adapter))
  176. return { adapter, { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
  177. if (adapter == NetworkingManagement::the().loopback_adapter())
  178. return { adapter, adapter->mac_address() };
  179. if ((target_addr & IPv4Address { 240, 0, 0, 0 }.to_u32()) == IPv4Address { 224, 0, 0, 0 }.to_u32())
  180. return { adapter, multicast_ethernet_address(target) };
  181. {
  182. Locker locker(arp_table().lock());
  183. auto addr = arp_table().resource().get(next_hop_ip);
  184. if (addr.has_value()) {
  185. dbgln_if(ROUTING_DEBUG, "Routing: Using cached ARP entry for {} ({})", next_hop_ip, addr.value().to_string());
  186. return { adapter, addr.value() };
  187. }
  188. }
  189. dbgln_if(ROUTING_DEBUG, "Routing: Sending ARP request via adapter {} for IPv4 address {}", adapter->name(), next_hop_ip);
  190. ARPPacket request;
  191. request.set_operation(ARPOperation::Request);
  192. request.set_target_hardware_address({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
  193. request.set_target_protocol_address(next_hop_ip);
  194. request.set_sender_hardware_address(adapter->mac_address());
  195. request.set_sender_protocol_address(adapter->ipv4_address());
  196. adapter->send({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, request);
  197. if (NetworkTask::is_current()) {
  198. // FIXME: Waiting for the ARP response from inside the NetworkTask would
  199. // deadlock, so let's hope that whoever called route_to() tries again in a bit.
  200. dbgln_if(ROUTING_DEBUG, "Routing: Not waiting for ARP response from inside NetworkTask, sent ARP request using adapter {} for {}", adapter->name(), target);
  201. return { nullptr, {} };
  202. }
  203. Optional<MACAddress> addr;
  204. if (!Thread::current()->block<ARPTableBlocker>({}, next_hop_ip, addr).was_interrupted()) {
  205. if (addr.has_value()) {
  206. dbgln_if(ROUTING_DEBUG, "Routing: Got ARP response using adapter {} for {} ({})",
  207. adapter->name(),
  208. next_hop_ip,
  209. addr.value().to_string());
  210. return { adapter, addr.value() };
  211. }
  212. }
  213. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find route using adapter {} for {}", adapter->name(), target);
  214. return { nullptr, {} };
  215. }
  216. }