DHCPv4Client.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  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 "DHCPv4Client.h"
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/Debug.h>
  29. #include <AK/Endian.h>
  30. #include <AK/Function.h>
  31. #include <LibCore/SocketAddress.h>
  32. #include <LibCore/Timer.h>
  33. #include <stdio.h>
  34. static void send(const InterfaceDescriptor& iface, const DHCPv4Packet& packet, Core::Object*)
  35. {
  36. int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  37. if (fd < 0) {
  38. dbgln("ERROR: socket :: {}", strerror(errno));
  39. return;
  40. }
  41. if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface.m_ifname.characters(), IFNAMSIZ) < 0) {
  42. dbgln("ERROR: setsockopt(SO_BINDTODEVICE) :: {}", strerror(errno));
  43. return;
  44. }
  45. sockaddr_in dst;
  46. memset(&dst, 0, sizeof(dst));
  47. dst.sin_family = AF_INET;
  48. dst.sin_port = htons(67);
  49. dst.sin_addr.s_addr = IPv4Address { 255, 255, 255, 255 }.to_u32();
  50. memset(&dst.sin_zero, 0, sizeof(dst.sin_zero));
  51. auto rc = sendto(fd, &packet, sizeof(packet), 0, (sockaddr*)&dst, sizeof(dst));
  52. if (rc < 0) {
  53. dbgln("sendto failed with {}", strerror(errno));
  54. // FIXME: what do we do here?
  55. }
  56. }
  57. static void set_params(const InterfaceDescriptor& iface, const IPv4Address& ipv4_addr, const IPv4Address& netmask, const IPv4Address& gateway)
  58. {
  59. int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
  60. if (fd < 0) {
  61. dbgln("ERROR: socket :: {}", strerror(errno));
  62. return;
  63. }
  64. struct ifreq ifr;
  65. memset(&ifr, 0, sizeof(ifr));
  66. bool fits = iface.m_ifname.copy_characters_to_buffer(ifr.ifr_name, IFNAMSIZ);
  67. if (!fits) {
  68. dbgln("Interface name doesn't fit into IFNAMSIZ!");
  69. return;
  70. }
  71. // set the IP address
  72. ifr.ifr_addr.sa_family = AF_INET;
  73. ((sockaddr_in&)ifr.ifr_addr).sin_addr.s_addr = ipv4_addr.to_in_addr_t();
  74. if (ioctl(fd, SIOCSIFADDR, &ifr) < 0) {
  75. dbgln("ERROR: ioctl(SIOCSIFADDR) :: {}", strerror(errno));
  76. }
  77. // set the network mask
  78. ((sockaddr_in&)ifr.ifr_netmask).sin_addr.s_addr = netmask.to_in_addr_t();
  79. if (ioctl(fd, SIOCSIFNETMASK, &ifr) < 0) {
  80. dbgln("ERROR: ioctl(SIOCSIFNETMASK) :: {}", strerror(errno));
  81. }
  82. // set the default gateway
  83. struct rtentry rt;
  84. memset(&rt, 0, sizeof(rt));
  85. rt.rt_dev = const_cast<char*>(iface.m_ifname.characters());
  86. rt.rt_gateway.sa_family = AF_INET;
  87. ((sockaddr_in&)rt.rt_gateway).sin_addr.s_addr = gateway.to_in_addr_t();
  88. rt.rt_flags = RTF_UP | RTF_GATEWAY;
  89. if (ioctl(fd, SIOCADDRT, &rt) < 0) {
  90. dbgln("Error: ioctl(SIOCADDRT) :: {}", strerror(errno));
  91. }
  92. }
  93. DHCPv4Client::DHCPv4Client(Vector<InterfaceDescriptor> ifnames)
  94. : m_ifnames(ifnames)
  95. {
  96. m_server = Core::UDPServer::construct(this);
  97. m_server->on_ready_to_receive = [this] {
  98. auto buffer = m_server->receive(sizeof(DHCPv4Packet));
  99. dbgln("Received {} bytes", buffer.size());
  100. if (buffer.size() != sizeof(DHCPv4Packet)) {
  101. dbgln("we expected {} bytes, this is a bad packet", sizeof(DHCPv4Packet));
  102. return;
  103. }
  104. auto& packet = *(DHCPv4Packet*)buffer.data();
  105. process_incoming(packet);
  106. };
  107. if (!m_server->bind({}, 68)) {
  108. dbgln("The server we just created somehow came already bound, refusing to continue");
  109. ASSERT_NOT_REACHED();
  110. }
  111. for (auto& iface : m_ifnames)
  112. dhcp_discover(iface);
  113. }
  114. DHCPv4Client::~DHCPv4Client()
  115. {
  116. }
  117. void DHCPv4Client::handle_offer(const DHCPv4Packet& packet, const ParsedDHCPv4Options& options)
  118. {
  119. dbgln("We were offered {} for {}", packet.yiaddr().to_string(), options.get<u32>(DHCPOption::IPAddressLeaseTime).value_or(0));
  120. auto* transaction = const_cast<DHCPv4Transaction*>(m_ongoing_transactions.get(packet.xid()).value_or(nullptr));
  121. if (!transaction) {
  122. dbgln("we're not looking for {}", packet.xid());
  123. return;
  124. }
  125. if (transaction->has_ip)
  126. return;
  127. if (transaction->accepted_offer) {
  128. // we've accepted someone's offer, but they haven't given us an ack
  129. // TODO: maybe record this offer?
  130. return;
  131. }
  132. // TAKE IT...
  133. transaction->offered_lease_time = options.get<u32>(DHCPOption::IPAddressLeaseTime).value();
  134. dhcp_request(*transaction, packet);
  135. }
  136. void DHCPv4Client::handle_ack(const DHCPv4Packet& packet, const ParsedDHCPv4Options& options)
  137. {
  138. if constexpr (debug_dhcpv4_client) {
  139. dbgln("The DHCP server handed us {}", packet.yiaddr().to_string());
  140. dbgln("Here are the options: {}", options.to_string());
  141. }
  142. auto* transaction = const_cast<DHCPv4Transaction*>(m_ongoing_transactions.get(packet.xid()).value_or(nullptr));
  143. if (!transaction) {
  144. dbgln("we're not looking for {}", packet.xid());
  145. return;
  146. }
  147. transaction->has_ip = true;
  148. auto& interface = transaction->interface;
  149. auto new_ip = packet.yiaddr();
  150. auto lease_time = AK::convert_between_host_and_network_endian(options.get<u32>(DHCPOption::IPAddressLeaseTime).value_or(transaction->offered_lease_time));
  151. // set a timer for the duration of the lease, we shall renew if needed
  152. Core::Timer::create_single_shot(
  153. lease_time * 1000,
  154. [this, transaction, interface = InterfaceDescriptor { interface }, new_ip] {
  155. transaction->accepted_offer = false;
  156. transaction->has_ip = false;
  157. dhcp_discover(interface, new_ip);
  158. },
  159. this);
  160. set_params(transaction->interface, new_ip, options.get<IPv4Address>(DHCPOption::SubnetMask).value(), options.get_many<IPv4Address>(DHCPOption::Router, 1).first());
  161. }
  162. void DHCPv4Client::handle_nak(const DHCPv4Packet& packet, const ParsedDHCPv4Options& options)
  163. {
  164. dbgln("The DHCP server told us to go chase our own tail about {}", packet.yiaddr().to_string());
  165. dbgln("Here are the options: {}", options.to_string());
  166. // make another request a bit later :shrug:
  167. auto* transaction = const_cast<DHCPv4Transaction*>(m_ongoing_transactions.get(packet.xid()).value_or(nullptr));
  168. if (!transaction) {
  169. dbgln("we're not looking for {}", packet.xid());
  170. return;
  171. }
  172. transaction->accepted_offer = false;
  173. transaction->has_ip = false;
  174. auto& iface = transaction->interface;
  175. Core::Timer::create_single_shot(
  176. 10000,
  177. [this, iface = InterfaceDescriptor { iface }] {
  178. dhcp_discover(iface);
  179. },
  180. this);
  181. }
  182. void DHCPv4Client::process_incoming(const DHCPv4Packet& packet)
  183. {
  184. auto options = packet.parse_options();
  185. dbgln<debug_dhcpv4_client>("Here are the options: {}", options.to_string());
  186. auto value = options.get<DHCPMessageType>(DHCPOption::DHCPMessageType).value();
  187. switch (value) {
  188. case DHCPMessageType::DHCPOffer:
  189. handle_offer(packet, options);
  190. break;
  191. case DHCPMessageType::DHCPAck:
  192. handle_ack(packet, options);
  193. break;
  194. case DHCPMessageType::DHCPNak:
  195. handle_nak(packet, options);
  196. break;
  197. case DHCPMessageType::DHCPDiscover:
  198. case DHCPMessageType::DHCPRequest:
  199. case DHCPMessageType::DHCPRelease:
  200. // These are not for us
  201. // we're just getting them because there are other people on our subnet
  202. // broadcasting stuff
  203. break;
  204. case DHCPMessageType::DHCPDecline:
  205. default:
  206. dbgln("I dunno what to do with this {}", (u8)value);
  207. ASSERT_NOT_REACHED();
  208. break;
  209. }
  210. }
  211. void DHCPv4Client::dhcp_discover(const InterfaceDescriptor& iface, IPv4Address previous)
  212. {
  213. auto transaction_id = rand();
  214. if constexpr (debug_dhcpv4_client) {
  215. dbgln("Trying to lease an IP for {} with ID {}", iface.m_ifname, transaction_id);
  216. if (!previous.is_zero())
  217. dbgln("going to request the server to hand us {}", previous.to_string());
  218. }
  219. DHCPv4PacketBuilder builder;
  220. DHCPv4Packet& packet = builder.peek();
  221. packet.set_op(DHCPv4Op::BootRequest);
  222. packet.set_htype(1); // 10mb ethernet
  223. packet.set_hlen(sizeof(MACAddress));
  224. packet.set_xid(transaction_id);
  225. packet.set_flags(DHCPv4Flags::Broadcast);
  226. packet.ciaddr() = previous;
  227. packet.set_chaddr(iface.m_mac_address);
  228. packet.set_secs(65535); // we lie
  229. // set packet options
  230. builder.set_message_type(DHCPMessageType::DHCPDiscover);
  231. auto& dhcp_packet = builder.build();
  232. // broadcast the discover request
  233. send(iface, dhcp_packet, this);
  234. m_ongoing_transactions.set(transaction_id, make<DHCPv4Transaction>(iface));
  235. }
  236. void DHCPv4Client::dhcp_request(DHCPv4Transaction& transaction, const DHCPv4Packet& offer)
  237. {
  238. auto& iface = transaction.interface;
  239. dbgln("Leasing the IP {} for adapter {}", offer.yiaddr().to_string(), iface.m_ifname);
  240. DHCPv4PacketBuilder builder;
  241. DHCPv4Packet& packet = builder.peek();
  242. packet.set_op(DHCPv4Op::BootRequest);
  243. packet.set_htype(1); // 10mb ethernet
  244. packet.set_hlen(sizeof(MACAddress));
  245. packet.set_xid(offer.xid());
  246. packet.set_flags(DHCPv4Flags::Broadcast);
  247. packet.set_chaddr(iface.m_mac_address);
  248. packet.set_secs(65535); // we lie
  249. // set packet options
  250. builder.set_message_type(DHCPMessageType::DHCPRequest);
  251. auto& dhcp_packet = builder.build();
  252. // broadcast the "request" request
  253. send(iface, dhcp_packet, this);
  254. transaction.accepted_offer = true;
  255. }