DHCPv4Client.cpp 10 KB

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