Routing.cpp 9.6 KB

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