Routing.cpp 9.4 KB

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