Routing.cpp 8.8 KB

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