Routing.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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<SpinlockProtected<HashMap<IPv4Address, MACAddress>, LockRank::None>> s_arp_table;
  17. static Singleton<SpinlockProtected<Route::RouteList, LockRank::None>> s_routing_table;
  18. class ARPTableBlocker final : public Thread::Blocker {
  19. public:
  20. ARPTableBlocker(IPv4Address ip_addr, Optional<MACAddress>& addr);
  21. virtual StringView state_string() const override { return "Routing (ARP)"sv; }
  22. virtual Type blocker_type() const override { return Type::Routing; }
  23. virtual bool setup_blocker() override;
  24. virtual void will_unblock_immediately_without_blocking(UnblockImmediatelyReason) override;
  25. bool unblock_if_matching_ip_address(bool from_add_blocker, IPv4Address const& ip_address, MACAddress const& mac_address)
  26. {
  27. if (m_ip_address != ip_address)
  28. return false;
  29. {
  30. SpinlockLocker lock(m_lock);
  31. if (m_did_unblock)
  32. return false;
  33. m_did_unblock = true;
  34. m_mac_address = mac_address;
  35. }
  36. if (!from_add_blocker)
  37. unblock_from_blocker();
  38. return true;
  39. }
  40. IPv4Address const& ip_address() const { return m_ip_address; }
  41. private:
  42. IPv4Address const m_ip_address;
  43. Optional<MACAddress>& m_mac_address;
  44. bool m_did_unblock { false };
  45. };
  46. class ARPTableBlockerSet final : public Thread::BlockerSet {
  47. public:
  48. void unblock_blockers_waiting_for_ipv4_address(IPv4Address const& ipv4_address, MACAddress const& mac_address)
  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_if_matching_ip_address(false, ipv4_address, mac_address);
  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 maybe_mac_address = arp_table().with([&](auto const& table) -> auto{
  62. return table.get(blocker.ip_address());
  63. });
  64. if (!maybe_mac_address.has_value())
  65. return true;
  66. return !blocker.unblock_if_matching_ip_address(true, blocker.ip_address(), maybe_mac_address.value());
  67. }
  68. };
  69. static Singleton<ARPTableBlockerSet> s_arp_table_blocker_set;
  70. ARPTableBlocker::ARPTableBlocker(IPv4Address ip_addr, Optional<MACAddress>& addr)
  71. : m_ip_address(ip_addr)
  72. , m_mac_address(addr)
  73. {
  74. }
  75. bool ARPTableBlocker::setup_blocker()
  76. {
  77. return add_to_blocker_set(*s_arp_table_blocker_set);
  78. }
  79. void ARPTableBlocker::will_unblock_immediately_without_blocking(UnblockImmediatelyReason)
  80. {
  81. auto addr = arp_table().with([&](auto const& table) -> auto{
  82. return table.get(ip_address());
  83. });
  84. SpinlockLocker lock(m_lock);
  85. if (!m_did_unblock) {
  86. m_did_unblock = true;
  87. m_mac_address = move(addr);
  88. }
  89. }
  90. SpinlockProtected<HashMap<IPv4Address, MACAddress>, LockRank::None>& arp_table()
  91. {
  92. return *s_arp_table;
  93. }
  94. void update_arp_table(IPv4Address const& ip_addr, MACAddress const& addr, UpdateTable update)
  95. {
  96. arp_table().with([&](auto& table) {
  97. if (update == UpdateTable::Set)
  98. table.set(ip_addr, addr);
  99. if (update == UpdateTable::Delete)
  100. table.remove(ip_addr);
  101. });
  102. s_arp_table_blocker_set->unblock_blockers_waiting_for_ipv4_address(ip_addr, addr);
  103. if constexpr (ARP_DEBUG) {
  104. arp_table().with([&](auto const& table) {
  105. dmesgln("ARP table ({} entries):", table.size());
  106. for (auto& it : table)
  107. dmesgln("{} :: {}", it.value.to_string(), it.key.to_string());
  108. });
  109. }
  110. }
  111. SpinlockProtected<Route::RouteList, LockRank::None>& routing_table()
  112. {
  113. return *s_routing_table;
  114. }
  115. ErrorOr<void> update_routing_table(IPv4Address const& destination, IPv4Address const& gateway, IPv4Address const& netmask, u16 flags, RefPtr<NetworkAdapter> adapter, UpdateTable update)
  116. {
  117. dbgln_if(ROUTING_DEBUG, "update_routing_table {} {} {} {} {} {}", destination, gateway, netmask, flags, adapter, update == UpdateTable::Set ? "Set" : "Delete");
  118. auto route_entry = adopt_ref_if_nonnull(new (nothrow) Route { destination, gateway, netmask, flags, adapter.release_nonnull() });
  119. if (!route_entry)
  120. return ENOMEM;
  121. TRY(routing_table().with([&](auto& table) -> ErrorOr<void> {
  122. if (update == UpdateTable::Set) {
  123. for (auto const& route : table) {
  124. if (route == *route_entry)
  125. return EEXIST;
  126. }
  127. table.append(*route_entry);
  128. }
  129. if (update == UpdateTable::Delete) {
  130. for (auto& route : table) {
  131. dbgln_if(ROUTING_DEBUG, "candidate: {} {} {} {} {}", route.destination, route.gateway, route.netmask, route.flags, route.adapter);
  132. if (route.matches(*route_entry)) {
  133. // FIXME: Remove all entries, not only the first one.
  134. table.remove(route);
  135. return {};
  136. }
  137. }
  138. return ESRCH;
  139. }
  140. return {};
  141. }));
  142. return {};
  143. }
  144. bool RoutingDecision::is_zero() const
  145. {
  146. return adapter.is_null() || next_hop.is_zero();
  147. }
  148. static MACAddress multicast_ethernet_address(IPv4Address const& address)
  149. {
  150. return MACAddress { 0x01, 0x00, 0x5e, (u8)(address[1] & 0x7f), address[2], address[3] };
  151. }
  152. RoutingDecision route_to(IPv4Address const& target, IPv4Address const& source, RefPtr<NetworkAdapter> const through, AllowUsingGateway allow_using_gateway)
  153. {
  154. auto matches = [&](auto& adapter) {
  155. if (!through)
  156. return true;
  157. return through == adapter;
  158. };
  159. auto if_matches = [&](auto& adapter, auto const& mac) -> RoutingDecision {
  160. if (!matches(adapter))
  161. return { nullptr, {} };
  162. return { adapter, mac };
  163. };
  164. if (target[0] == 0 && target[1] == 0 && target[2] == 0 && target[3] == 0)
  165. return if_matches(*NetworkingManagement::the().loopback_adapter(), NetworkingManagement::the().loopback_adapter()->mac_address());
  166. if (target[0] == 127)
  167. return if_matches(*NetworkingManagement::the().loopback_adapter(), NetworkingManagement::the().loopback_adapter()->mac_address());
  168. auto target_addr = target.to_u32();
  169. auto source_addr = source.to_u32();
  170. RefPtr<NetworkAdapter> local_adapter = nullptr;
  171. RefPtr<Route> chosen_route = nullptr;
  172. NetworkingManagement::the().for_each([source_addr, &target_addr, &local_adapter, &matches, &through](NetworkAdapter& adapter) {
  173. auto adapter_addr = adapter.ipv4_address().to_u32();
  174. auto adapter_mask = adapter.ipv4_netmask().to_u32();
  175. if (target_addr == adapter_addr) {
  176. local_adapter = NetworkingManagement::the().loopback_adapter();
  177. return;
  178. }
  179. if (!adapter.link_up() || (adapter_addr == 0 && !through))
  180. return;
  181. if (source_addr != 0 && source_addr != adapter_addr)
  182. return;
  183. if ((target_addr & adapter_mask) == (adapter_addr & adapter_mask) && matches(adapter))
  184. local_adapter = adapter;
  185. });
  186. u32 longest_prefix_match = 0;
  187. routing_table().for_each([&target_addr, &matches, &longest_prefix_match, &chosen_route](auto& route) {
  188. auto route_addr = route.destination.to_u32();
  189. auto route_mask = route.netmask.to_u32();
  190. if (route_addr == 0 && matches(*route.adapter)) {
  191. dbgln_if(ROUTING_DEBUG, "Resorting to default route found for adapter: {}", route.adapter->name());
  192. chosen_route = route;
  193. }
  194. // We have a direct match and we can exit the routing table earlier.
  195. if (target_addr == route_addr) {
  196. dbgln_if(ROUTING_DEBUG, "Target address has a direct match in the routing table");
  197. chosen_route = route;
  198. return;
  199. }
  200. if ((target_addr & route_mask) == (route_addr & route_mask) && (route_addr != 0)) {
  201. auto prefix = (target_addr & (route_addr & route_mask));
  202. if (chosen_route && prefix == longest_prefix_match) {
  203. chosen_route = (route.netmask.to_u32() > chosen_route->netmask.to_u32()) ? route : chosen_route;
  204. dbgln_if(ROUTING_DEBUG, "Found a matching prefix match. Using longer netmask: {}", chosen_route->netmask);
  205. }
  206. if (prefix > longest_prefix_match) {
  207. dbgln_if(ROUTING_DEBUG, "Found a longer prefix match - route: {}, netmask: {}", route.destination.to_string(), route.netmask);
  208. longest_prefix_match = prefix;
  209. chosen_route = route;
  210. }
  211. }
  212. });
  213. if (local_adapter && target == local_adapter->ipv4_address())
  214. return { local_adapter, local_adapter->mac_address() };
  215. if (!local_adapter && !chosen_route) {
  216. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find a suitable adapter for route to {}", target);
  217. return { nullptr, {} };
  218. }
  219. RefPtr<NetworkAdapter> adapter = nullptr;
  220. IPv4Address next_hop_ip;
  221. if (local_adapter) {
  222. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (direct): {} ({}/{}) for {}",
  223. local_adapter->name(),
  224. local_adapter->ipv4_address(),
  225. local_adapter->ipv4_netmask(),
  226. target);
  227. adapter = local_adapter;
  228. next_hop_ip = target;
  229. } else if (chosen_route && allow_using_gateway == AllowUsingGateway::Yes) {
  230. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (using gateway {}): {} ({}/{}) for {}",
  231. chosen_route->gateway,
  232. chosen_route->adapter->name(),
  233. chosen_route->adapter->ipv4_address(),
  234. chosen_route->adapter->ipv4_netmask(),
  235. target);
  236. adapter = chosen_route->adapter;
  237. next_hop_ip = chosen_route->gateway;
  238. } else {
  239. return { nullptr, {} };
  240. }
  241. // If it's a broadcast, we already know everything we need to know.
  242. // FIXME: We should also deal with the case where `target_addr` is
  243. // a broadcast to a subnet rather than a full broadcast.
  244. if (target_addr == 0xffffffff && matches(adapter))
  245. return { adapter, { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
  246. if (adapter == NetworkingManagement::the().loopback_adapter())
  247. return { adapter, adapter->mac_address() };
  248. if ((target_addr & IPv4Address { 240, 0, 0, 0 }.to_u32()) == IPv4Address { 224, 0, 0, 0 }.to_u32())
  249. return { adapter, multicast_ethernet_address(target) };
  250. {
  251. auto addr = arp_table().with([&](auto const& table) -> auto{
  252. return table.get(next_hop_ip);
  253. });
  254. if (addr.has_value()) {
  255. dbgln_if(ARP_DEBUG, "Routing: Using cached ARP entry for {} ({})", next_hop_ip, addr.value().to_string());
  256. return { adapter, addr.value() };
  257. }
  258. }
  259. dbgln_if(ARP_DEBUG, "Routing: Sending ARP request via adapter {} for IPv4 address {}", adapter->name(), next_hop_ip);
  260. ARPPacket request;
  261. request.set_operation(ARPOperation::Request);
  262. request.set_target_hardware_address({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
  263. request.set_target_protocol_address(next_hop_ip);
  264. request.set_sender_hardware_address(adapter->mac_address());
  265. request.set_sender_protocol_address(adapter->ipv4_address());
  266. adapter->send({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, request);
  267. if (NetworkTask::is_current()) {
  268. // FIXME: Waiting for the ARP response from inside the NetworkTask would
  269. // deadlock, so let's hope that whoever called route_to() tries again in a bit.
  270. dbgln_if(ARP_DEBUG, "Routing: Not waiting for ARP response from inside NetworkTask, sent ARP request using adapter {} for {}", adapter->name(), target);
  271. return { nullptr, {} };
  272. }
  273. Optional<MACAddress> addr;
  274. if (!Thread::current()->block<ARPTableBlocker>({}, next_hop_ip, addr).was_interrupted()) {
  275. if (addr.has_value()) {
  276. dbgln_if(ARP_DEBUG, "Routing: Got ARP response using adapter {} for {} ({})",
  277. adapter->name(),
  278. next_hop_ip,
  279. addr.value().to_string());
  280. return { adapter, addr.value() };
  281. }
  282. }
  283. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find route using adapter {} for {}", adapter->name(), target);
  284. return { nullptr, {} };
  285. }
  286. }