Routing.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/HashMap.h>
  27. #include <AK/Singleton.h>
  28. #include <Kernel/Debug.h>
  29. #include <Kernel/Net/LoopbackAdapter.h>
  30. #include <Kernel/Net/Routing.h>
  31. #include <Kernel/Thread.h>
  32. namespace Kernel {
  33. static AK::Singleton<Lockable<HashMap<IPv4Address, MACAddress>>> s_arp_table;
  34. class ARPTableBlocker : public Thread::Blocker {
  35. public:
  36. ARPTableBlocker(IPv4Address ip_addr, Optional<MACAddress>& addr);
  37. virtual const char* state_string() const override { return "Routing (ARP)"; }
  38. virtual Type blocker_type() const override { return Type::Routing; }
  39. virtual bool should_block() override { return m_should_block; }
  40. virtual void not_blocking(bool) override;
  41. bool unblock(bool from_add_blocker, const IPv4Address& ip_addr, const MACAddress& addr)
  42. {
  43. if (m_ip_addr != ip_addr)
  44. return false;
  45. {
  46. ScopedSpinLock lock(m_lock);
  47. if (m_did_unblock)
  48. return false;
  49. m_did_unblock = true;
  50. m_addr = addr;
  51. }
  52. if (!from_add_blocker)
  53. unblock_from_blocker();
  54. return true;
  55. }
  56. const IPv4Address& ip_addr() const { return m_ip_addr; }
  57. private:
  58. const IPv4Address m_ip_addr;
  59. Optional<MACAddress>& m_addr;
  60. bool m_did_unblock { false };
  61. bool m_should_block { true };
  62. };
  63. class ARPTableBlockCondition : public Thread::BlockCondition {
  64. public:
  65. void unblock(const IPv4Address& ip_addr, const MACAddress& addr)
  66. {
  67. BlockCondition::unblock([&](auto& b, void*, bool&) {
  68. VERIFY(b.blocker_type() == Thread::Blocker::Type::Routing);
  69. auto& blocker = static_cast<ARPTableBlocker&>(b);
  70. return blocker.unblock(false, ip_addr, addr);
  71. });
  72. }
  73. protected:
  74. virtual bool should_add_blocker(Thread::Blocker& b, void*) override
  75. {
  76. VERIFY(b.blocker_type() == Thread::Blocker::Type::Routing);
  77. auto& blocker = static_cast<ARPTableBlocker&>(b);
  78. auto val = s_arp_table->resource().get(blocker.ip_addr());
  79. if (!val.has_value())
  80. return true;
  81. return blocker.unblock(true, blocker.ip_addr(), val.value());
  82. }
  83. };
  84. static AK::Singleton<ARPTableBlockCondition> s_arp_table_block_condition;
  85. ARPTableBlocker::ARPTableBlocker(IPv4Address ip_addr, Optional<MACAddress>& addr)
  86. : m_ip_addr(ip_addr)
  87. , m_addr(addr)
  88. {
  89. if (!set_block_condition(*s_arp_table_block_condition))
  90. m_should_block = false;
  91. }
  92. void ARPTableBlocker::not_blocking(bool timeout_in_past)
  93. {
  94. VERIFY(timeout_in_past || !m_should_block);
  95. auto addr = s_arp_table->resource().get(ip_addr());
  96. ScopedSpinLock lock(m_lock);
  97. if (!m_did_unblock) {
  98. m_did_unblock = true;
  99. m_addr = move(addr);
  100. }
  101. }
  102. Lockable<HashMap<IPv4Address, MACAddress>>& arp_table()
  103. {
  104. return *s_arp_table;
  105. }
  106. void update_arp_table(const IPv4Address& ip_addr, const MACAddress& addr)
  107. {
  108. LOCKER(arp_table().lock());
  109. arp_table().resource().set(ip_addr, addr);
  110. s_arp_table_block_condition->unblock(ip_addr, addr);
  111. dmesgln("ARP table ({} entries):", arp_table().resource().size());
  112. for (auto& it : arp_table().resource()) {
  113. dmesgln("{} :: {}", it.value.to_string(), it.key.to_string());
  114. }
  115. }
  116. bool RoutingDecision::is_zero() const
  117. {
  118. return adapter.is_null() || next_hop.is_zero();
  119. }
  120. RoutingDecision route_to(const IPv4Address& target, const IPv4Address& source, const RefPtr<NetworkAdapter> through)
  121. {
  122. auto matches = [&](auto& adapter) {
  123. if (!through)
  124. return true;
  125. return through == adapter;
  126. };
  127. auto if_matches = [&](auto& adapter, const auto& mac) -> RoutingDecision {
  128. if (!matches(adapter))
  129. return { nullptr, {} };
  130. return { adapter, mac };
  131. };
  132. if (target[0] == 127)
  133. return if_matches(LoopbackAdapter::the(), LoopbackAdapter::the().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. NetworkAdapter::for_each([source_addr, &target_addr, &local_adapter, &gateway_adapter, &matches](auto& adapter) {
  139. auto adapter_addr = adapter.ipv4_address().to_u32();
  140. auto adapter_mask = adapter.ipv4_netmask().to_u32();
  141. if (source_addr != 0 && source_addr != adapter_addr)
  142. return;
  143. if ((target_addr & adapter_mask) == (adapter_addr & adapter_mask) && matches(adapter))
  144. local_adapter = adapter;
  145. if (adapter.ipv4_gateway().to_u32() != 0 && matches(adapter))
  146. gateway_adapter = adapter;
  147. });
  148. if (local_adapter && target == local_adapter->ipv4_address())
  149. return { local_adapter, local_adapter->mac_address() };
  150. if (!local_adapter && !gateway_adapter) {
  151. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find a suitable adapter for route to {}", target);
  152. return { nullptr, {} };
  153. }
  154. RefPtr<NetworkAdapter> adapter = nullptr;
  155. IPv4Address next_hop_ip;
  156. if (local_adapter) {
  157. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (direct): {} ({}/{}) for {}",
  158. local_adapter->name(),
  159. local_adapter->ipv4_address(),
  160. local_adapter->ipv4_netmask(),
  161. target);
  162. adapter = local_adapter;
  163. next_hop_ip = target;
  164. } else if (gateway_adapter) {
  165. dbgln_if(ROUTING_DEBUG, "Routing: Got adapter for route (using gateway {}): {} ({}/{}) for {}",
  166. gateway_adapter->ipv4_gateway(),
  167. gateway_adapter->name(),
  168. gateway_adapter->ipv4_address(),
  169. gateway_adapter->ipv4_netmask(),
  170. target);
  171. adapter = gateway_adapter;
  172. next_hop_ip = gateway_adapter->ipv4_gateway();
  173. } else {
  174. return { nullptr, {} };
  175. }
  176. // If it's a broadcast, we already know everything we need to know.
  177. // FIXME: We should also deal with the case where `target_addr` is
  178. // a broadcast to a subnet rather than a full broadcast.
  179. if (target_addr == 0xffffffff && matches(adapter))
  180. return { adapter, { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
  181. {
  182. LOCKER(arp_table().lock());
  183. auto addr = arp_table().resource().get(next_hop_ip);
  184. if (addr.has_value()) {
  185. dbgln_if(ROUTING_DEBUG, "Routing: Using cached ARP entry for {} ({})", next_hop_ip, addr.value().to_string());
  186. return { adapter, addr.value() };
  187. }
  188. }
  189. dbgln_if(ROUTING_DEBUG, "Routing: Sending ARP request via adapter {} for IPv4 address {}", adapter->name(), next_hop_ip);
  190. ARPPacket request;
  191. request.set_operation(ARPOperation::Request);
  192. request.set_target_hardware_address({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
  193. request.set_target_protocol_address(next_hop_ip);
  194. request.set_sender_hardware_address(adapter->mac_address());
  195. request.set_sender_protocol_address(adapter->ipv4_address());
  196. adapter->send({ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, request);
  197. Optional<MACAddress> addr;
  198. if (!Thread::current()->block<ARPTableBlocker>({}, next_hop_ip, addr).was_interrupted()) {
  199. if (addr.has_value()) {
  200. dbgln_if(ROUTING_DEBUG, "Routing: Got ARP response using adapter {} for {} ({})",
  201. adapter->name(),
  202. next_hop_ip,
  203. addr.value().to_string());
  204. return { adapter, addr.value() };
  205. }
  206. }
  207. dbgln_if(ROUTING_DEBUG, "Routing: Couldn't find route using adapter {} for {}", adapter->name(), target);
  208. return { nullptr, {} };
  209. }
  210. }