Routing.cpp 9.7 KB

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