IPv4Socket.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2018-2020, 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/StringBuilder.h>
  27. #include <Kernel/FileSystem/FileDescription.h>
  28. #include <Kernel/Net/ARP.h>
  29. #include <Kernel/Net/ICMP.h>
  30. #include <Kernel/Net/IPv4.h>
  31. #include <Kernel/Net/IPv4Socket.h>
  32. #include <Kernel/Net/NetworkAdapter.h>
  33. #include <Kernel/Net/Routing.h>
  34. #include <Kernel/Net/TCP.h>
  35. #include <Kernel/Net/TCPSocket.h>
  36. #include <Kernel/Net/UDP.h>
  37. #include <Kernel/Net/UDPSocket.h>
  38. #include <Kernel/Process.h>
  39. #include <Kernel/UnixTypes.h>
  40. #include <LibC/errno_numbers.h>
  41. #include <LibC/sys/ioctl_numbers.h>
  42. //#define IPV4_SOCKET_DEBUG
  43. Lockable<HashTable<IPv4Socket*>>& IPv4Socket::all_sockets()
  44. {
  45. static Lockable<HashTable<IPv4Socket*>>* s_table;
  46. if (!s_table)
  47. s_table = new Lockable<HashTable<IPv4Socket*>>;
  48. return *s_table;
  49. }
  50. NonnullRefPtr<IPv4Socket> IPv4Socket::create(int type, int protocol)
  51. {
  52. if (type == SOCK_STREAM)
  53. return TCPSocket::create(protocol);
  54. if (type == SOCK_DGRAM)
  55. return UDPSocket::create(protocol);
  56. return adopt(*new IPv4Socket(type, protocol));
  57. }
  58. IPv4Socket::IPv4Socket(int type, int protocol)
  59. : Socket(AF_INET, type, protocol)
  60. {
  61. #ifdef IPV4_SOCKET_DEBUG
  62. kprintf("%s(%u) IPv4Socket{%p} created with type=%u, protocol=%d\n", current->process().name().characters(), current->pid(), this, type, protocol);
  63. #endif
  64. m_buffer_mode = type == SOCK_STREAM ? BufferMode::Bytes : BufferMode::Packets;
  65. if (m_buffer_mode == BufferMode::Bytes) {
  66. m_scratch_buffer = KBuffer::create_with_size(65536);
  67. }
  68. LOCKER(all_sockets().lock());
  69. all_sockets().resource().set(this);
  70. }
  71. IPv4Socket::~IPv4Socket()
  72. {
  73. LOCKER(all_sockets().lock());
  74. all_sockets().resource().remove(this);
  75. }
  76. bool IPv4Socket::get_local_address(sockaddr* address, socklen_t* address_size)
  77. {
  78. // FIXME: Look into what fallback behavior we should have here.
  79. if (*address_size < sizeof(sockaddr_in))
  80. return false;
  81. auto& ia = (sockaddr_in&)*address;
  82. ia.sin_family = AF_INET;
  83. ia.sin_port = htons(m_local_port);
  84. memcpy(&ia.sin_addr, &m_local_address, sizeof(IPv4Address));
  85. *address_size = sizeof(sockaddr_in);
  86. return true;
  87. }
  88. bool IPv4Socket::get_peer_address(sockaddr* address, socklen_t* address_size)
  89. {
  90. // FIXME: Look into what fallback behavior we should have here.
  91. if (*address_size < sizeof(sockaddr_in))
  92. return false;
  93. auto& ia = (sockaddr_in&)*address;
  94. ia.sin_family = AF_INET;
  95. ia.sin_port = htons(m_peer_port);
  96. memcpy(&ia.sin_addr, &m_peer_address, sizeof(IPv4Address));
  97. *address_size = sizeof(sockaddr_in);
  98. return true;
  99. }
  100. KResult IPv4Socket::bind(const sockaddr* user_address, socklen_t address_size)
  101. {
  102. ASSERT(setup_state() == SetupState::Unstarted);
  103. if (address_size != sizeof(sockaddr_in))
  104. return KResult(-EINVAL);
  105. sockaddr_in address;
  106. copy_from_user(&address, user_address, sizeof(sockaddr_in));
  107. if (address.sin_family != AF_INET)
  108. return KResult(-EINVAL);
  109. auto requested_local_port = ntohs(address.sin_port);
  110. if (!current->process().is_superuser()) {
  111. if (requested_local_port < 1024) {
  112. dbg() << current->process() << " (uid " << current->process().uid() << ") attempted to bind " << class_name() << " to port " << requested_local_port;
  113. return KResult(-EACCES);
  114. }
  115. }
  116. m_local_address = IPv4Address((const u8*)&address.sin_addr.s_addr);
  117. m_local_port = requested_local_port;
  118. #ifdef IPV4_SOCKET_DEBUG
  119. dbgprintf("IPv4Socket::bind %s{%p} to %s:%u\n", class_name(), this, m_local_address.to_string().characters(), m_local_port);
  120. #endif
  121. return protocol_bind();
  122. }
  123. KResult IPv4Socket::listen(int backlog)
  124. {
  125. int rc = allocate_local_port_if_needed();
  126. if (rc < 0)
  127. return KResult(-EADDRINUSE);
  128. set_backlog(backlog);
  129. m_role = Role::Listener;
  130. #ifdef IPV4_SOCKET_DEBUG
  131. kprintf("IPv4Socket{%p} listening with backlog=%d\n", this, backlog);
  132. #endif
  133. return protocol_listen();
  134. }
  135. KResult IPv4Socket::connect(FileDescription& description, const sockaddr* address, socklen_t address_size, ShouldBlock should_block)
  136. {
  137. if (address_size != sizeof(sockaddr_in))
  138. return KResult(-EINVAL);
  139. if (address->sa_family != AF_INET)
  140. return KResult(-EINVAL);
  141. if (m_role == Role::Connected)
  142. return KResult(-EISCONN);
  143. auto& ia = *(const sockaddr_in*)address;
  144. m_peer_address = IPv4Address((const u8*)&ia.sin_addr.s_addr);
  145. m_peer_port = ntohs(ia.sin_port);
  146. return protocol_connect(description, should_block);
  147. }
  148. void IPv4Socket::attach(FileDescription&)
  149. {
  150. }
  151. void IPv4Socket::detach(FileDescription&)
  152. {
  153. }
  154. bool IPv4Socket::can_read(const FileDescription&) const
  155. {
  156. if (m_role == Role::Listener)
  157. return can_accept();
  158. if (protocol_is_disconnected())
  159. return true;
  160. return m_can_read;
  161. }
  162. bool IPv4Socket::can_write(const FileDescription&) const
  163. {
  164. return is_connected();
  165. }
  166. int IPv4Socket::allocate_local_port_if_needed()
  167. {
  168. if (m_local_port)
  169. return m_local_port;
  170. int port = protocol_allocate_local_port();
  171. if (port < 0)
  172. return port;
  173. m_local_port = (u16)port;
  174. return port;
  175. }
  176. ssize_t IPv4Socket::sendto(FileDescription&, const void* data, size_t data_length, int flags, const sockaddr* addr, socklen_t addr_length)
  177. {
  178. (void)flags;
  179. if (addr && addr_length != sizeof(sockaddr_in))
  180. return -EINVAL;
  181. if (addr) {
  182. if (addr->sa_family != AF_INET) {
  183. kprintf("sendto: Bad address family: %u is not AF_INET!\n", addr->sa_family);
  184. return -EAFNOSUPPORT;
  185. }
  186. auto& ia = *(const sockaddr_in*)addr;
  187. m_peer_address = IPv4Address((const u8*)&ia.sin_addr.s_addr);
  188. m_peer_port = ntohs(ia.sin_port);
  189. }
  190. auto routing_decision = route_to(m_peer_address, m_local_address);
  191. if (routing_decision.is_zero())
  192. return -EHOSTUNREACH;
  193. if (m_local_address.to_u32() == 0)
  194. m_local_address = routing_decision.adapter->ipv4_address();
  195. int rc = allocate_local_port_if_needed();
  196. if (rc < 0)
  197. return rc;
  198. #ifdef IPV4_SOCKET_DEBUG
  199. kprintf("sendto: destination=%s:%u\n", m_peer_address.to_string().characters(), m_peer_port);
  200. #endif
  201. if (type() == SOCK_RAW) {
  202. routing_decision.adapter->send_ipv4(routing_decision.next_hop, m_peer_address, (IPv4Protocol)protocol(), (const u8*)data, data_length, m_ttl);
  203. return data_length;
  204. }
  205. int nsent = protocol_send(data, data_length);
  206. if (nsent > 0)
  207. current->did_ipv4_socket_write(nsent);
  208. return nsent;
  209. }
  210. ssize_t IPv4Socket::recvfrom(FileDescription& description, void* buffer, size_t buffer_length, int flags, sockaddr* addr, socklen_t* addr_length)
  211. {
  212. if (addr_length && *addr_length < sizeof(sockaddr_in))
  213. return -EINVAL;
  214. #ifdef IPV4_SOCKET_DEBUG
  215. kprintf("recvfrom: type=%d, local_port=%u\n", type(), local_port());
  216. #endif
  217. if (buffer_mode() == BufferMode::Bytes) {
  218. LOCKER(lock());
  219. if (m_receive_buffer.is_empty()) {
  220. if (protocol_is_disconnected()) {
  221. return 0;
  222. }
  223. if (!description.is_blocking()) {
  224. return -EAGAIN;
  225. }
  226. load_receive_deadline();
  227. auto res = current->block<Thread::ReceiveBlocker>(description);
  228. LOCKER(lock());
  229. if (!m_can_read) {
  230. if (res != Thread::BlockResult::WokeNormally)
  231. return -EINTR;
  232. // Unblocked due to timeout.
  233. return -EAGAIN;
  234. }
  235. }
  236. ASSERT(!m_receive_buffer.is_empty());
  237. int nreceived = m_receive_buffer.read((u8*)buffer, buffer_length);
  238. if (nreceived > 0)
  239. current->did_ipv4_socket_read((size_t)nreceived);
  240. m_can_read = !m_receive_buffer.is_empty();
  241. return nreceived;
  242. }
  243. ReceivedPacket packet;
  244. {
  245. LOCKER(lock());
  246. if (m_receive_queue.is_empty()) {
  247. // FIXME: Shouldn't this return -ENOTCONN instead of EOF?
  248. // But if so, we still need to deliver at least one EOF read to userspace.. right?
  249. if (protocol_is_disconnected())
  250. return 0;
  251. if (!description.is_blocking())
  252. return -EAGAIN;
  253. }
  254. if (!m_receive_queue.is_empty()) {
  255. packet = m_receive_queue.take_first();
  256. m_can_read = !m_receive_queue.is_empty();
  257. #ifdef IPV4_SOCKET_DEBUG
  258. kprintf("IPv4Socket(%p): recvfrom without blocking %d bytes, packets in queue: %zu\n", this, packet.data.value().size(), m_receive_queue.size_slow());
  259. #endif
  260. }
  261. }
  262. if (!packet.data.has_value()) {
  263. if (protocol_is_disconnected()) {
  264. kprintf("IPv4Socket{%p} is protocol-disconnected, returning 0 in recvfrom!\n", this);
  265. return 0;
  266. }
  267. load_receive_deadline();
  268. auto res = current->block<Thread::ReceiveBlocker>(description);
  269. LOCKER(lock());
  270. if (!m_can_read) {
  271. if (res != Thread::BlockResult::WokeNormally)
  272. return -EINTR;
  273. // Unblocked due to timeout.
  274. return -EAGAIN;
  275. }
  276. ASSERT(m_can_read);
  277. ASSERT(!m_receive_queue.is_empty());
  278. packet = m_receive_queue.take_first();
  279. m_can_read = !m_receive_queue.is_empty();
  280. #ifdef IPV4_SOCKET_DEBUG
  281. kprintf("IPv4Socket(%p): recvfrom with blocking %d bytes, packets in queue: %zu\n", this, packet.data.value().size(), m_receive_queue.size_slow());
  282. #endif
  283. }
  284. ASSERT(packet.data.has_value());
  285. auto& ipv4_packet = *(const IPv4Packet*)(packet.data.value().data());
  286. if (addr) {
  287. #ifdef IPV4_SOCKET_DEBUG
  288. dbgprintf("Incoming packet is from: %s:%u\n", packet.peer_address.to_string().characters(), packet.peer_port);
  289. #endif
  290. auto& ia = *(sockaddr_in*)addr;
  291. memcpy(&ia.sin_addr, &packet.peer_address, sizeof(IPv4Address));
  292. ia.sin_port = htons(packet.peer_port);
  293. ia.sin_family = AF_INET;
  294. ASSERT(addr_length);
  295. *addr_length = sizeof(sockaddr_in);
  296. }
  297. if (type() == SOCK_RAW) {
  298. ASSERT(buffer_length >= ipv4_packet.payload_size());
  299. memcpy(buffer, ipv4_packet.payload(), ipv4_packet.payload_size());
  300. return ipv4_packet.payload_size();
  301. }
  302. int nreceived = protocol_receive(packet.data.value(), buffer, buffer_length, flags);
  303. if (nreceived > 0)
  304. current->did_ipv4_socket_read(nreceived);
  305. return nreceived;
  306. }
  307. bool IPv4Socket::did_receive(const IPv4Address& source_address, u16 source_port, KBuffer&& packet)
  308. {
  309. LOCKER(lock());
  310. auto packet_size = packet.size();
  311. if (buffer_mode() == BufferMode::Bytes) {
  312. size_t space_in_receive_buffer = m_receive_buffer.space_for_writing();
  313. if (packet_size > space_in_receive_buffer) {
  314. kprintf("IPv4Socket(%p): did_receive refusing packet since buffer is full.\n", this);
  315. ASSERT(m_can_read);
  316. return false;
  317. }
  318. int nreceived = protocol_receive(packet, m_scratch_buffer.value().data(), m_scratch_buffer.value().size(), 0);
  319. m_receive_buffer.write(m_scratch_buffer.value().data(), nreceived);
  320. m_can_read = !m_receive_buffer.is_empty();
  321. } else {
  322. // FIXME: Maybe track the number of packets so we don't have to walk the entire packet queue to count them..
  323. if (m_receive_queue.size_slow() > 2000) {
  324. kprintf("IPv4Socket(%p): did_receive refusing packet since queue is full.\n", this);
  325. return false;
  326. }
  327. m_receive_queue.append({ source_address, source_port, move(packet) });
  328. m_can_read = true;
  329. }
  330. m_bytes_received += packet_size;
  331. #ifdef IPV4_SOCKET_DEBUG
  332. if (buffer_mode() == BufferMode::Bytes)
  333. kprintf("IPv4Socket(%p): did_receive %d bytes, total_received=%u, bytes in buffer: %zu\n", this, packet_size, m_bytes_received, m_receive_buffer.bytes_in_write_buffer());
  334. else
  335. kprintf("IPv4Socket(%p): did_receive %d bytes, total_received=%u, packets in queue: %zu\n", this, packet_size, m_bytes_received, m_receive_queue.size_slow());
  336. #endif
  337. return true;
  338. }
  339. String IPv4Socket::absolute_path(const FileDescription&) const
  340. {
  341. if (m_role == Role::None)
  342. return "socket";
  343. StringBuilder builder;
  344. builder.append("socket:");
  345. builder.appendf("%s:%d", m_local_address.to_string().characters(), m_local_port);
  346. if (m_role == Role::Accepted || m_role == Role::Connected)
  347. builder.appendf(" / %s:%d", m_peer_address.to_string().characters(), m_peer_port);
  348. switch (m_role) {
  349. case Role::Listener:
  350. builder.append(" (listening)");
  351. break;
  352. case Role::Accepted:
  353. builder.append(" (accepted)");
  354. break;
  355. case Role::Connected:
  356. builder.append(" (connected)");
  357. break;
  358. case Role::Connecting:
  359. builder.append(" (connecting)");
  360. break;
  361. default:
  362. ASSERT_NOT_REACHED();
  363. }
  364. return builder.to_string();
  365. }
  366. KResult IPv4Socket::setsockopt(int level, int option, const void* value, socklen_t value_size)
  367. {
  368. if (level != IPPROTO_IP)
  369. return Socket::setsockopt(level, option, value, value_size);
  370. switch (option) {
  371. case IP_TTL:
  372. if (value_size < sizeof(int))
  373. return KResult(-EINVAL);
  374. if (*(const int*)value < 0 || *(const int*)value > 255)
  375. return KResult(-EINVAL);
  376. m_ttl = (u8) * (const int*)value;
  377. return KSuccess;
  378. default:
  379. return KResult(-ENOPROTOOPT);
  380. }
  381. }
  382. KResult IPv4Socket::getsockopt(FileDescription& description, int level, int option, void* value, socklen_t* value_size)
  383. {
  384. if (level != IPPROTO_IP)
  385. return Socket::getsockopt(description, level, option, value, value_size);
  386. switch (option) {
  387. case IP_TTL:
  388. if (*value_size < sizeof(int))
  389. return KResult(-EINVAL);
  390. *(int*)value = m_ttl;
  391. return KSuccess;
  392. default:
  393. return KResult(-ENOPROTOOPT);
  394. }
  395. }
  396. int IPv4Socket::ioctl(FileDescription&, unsigned request, unsigned arg)
  397. {
  398. REQUIRE_PROMISE(inet);
  399. auto* ifr = (ifreq*)arg;
  400. if (!current->process().validate_read_typed(ifr))
  401. return -EFAULT;
  402. char namebuf[IFNAMSIZ + 1];
  403. memcpy(namebuf, ifr->ifr_name, IFNAMSIZ);
  404. namebuf[sizeof(namebuf) - 1] = '\0';
  405. auto adapter = NetworkAdapter::lookup_by_name(namebuf);
  406. if (!adapter)
  407. return -ENODEV;
  408. switch (request) {
  409. case SIOCSIFADDR:
  410. if (!current->process().is_superuser())
  411. return -EPERM;
  412. if (ifr->ifr_addr.sa_family != AF_INET)
  413. return -EAFNOSUPPORT;
  414. adapter->set_ipv4_address(IPv4Address(((sockaddr_in&)ifr->ifr_addr).sin_addr.s_addr));
  415. return 0;
  416. case SIOCGIFADDR:
  417. if (!current->process().validate_write_typed(ifr))
  418. return -EFAULT;
  419. ifr->ifr_addr.sa_family = AF_INET;
  420. ((sockaddr_in&)ifr->ifr_addr).sin_addr.s_addr = adapter->ipv4_address().to_u32();
  421. return 0;
  422. case SIOCGIFHWADDR:
  423. if (!current->process().validate_write_typed(ifr))
  424. return -EFAULT;
  425. ifr->ifr_hwaddr.sa_family = AF_INET;
  426. {
  427. auto mac_address = adapter->mac_address();
  428. memcpy(ifr->ifr_hwaddr.sa_data, &mac_address, sizeof(MACAddress));
  429. }
  430. return 0;
  431. }
  432. return -EINVAL;
  433. }