Socket.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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/ByteBuffer.h>
  27. #include <LibCore/Notifier.h>
  28. #include <LibCore/Socket.h>
  29. #include <arpa/inet.h>
  30. #include <errno.h>
  31. #include <fcntl.h>
  32. #include <netdb.h>
  33. #include <netinet/in.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <sys/socket.h>
  37. #include <unistd.h>
  38. //#define CSOCKET_DEBUG
  39. namespace Core {
  40. Socket::Socket(Type type, Object* parent)
  41. : IODevice(parent)
  42. , m_type(type)
  43. {
  44. register_property(
  45. "source_address", [this] { return m_source_address.to_string(); },
  46. [](auto&) { return false; });
  47. register_property(
  48. "destination_address", [this] { return m_destination_address.to_string(); },
  49. [](auto&) { return false; });
  50. register_property(
  51. "source_port", [this] { return m_source_port; },
  52. [](auto&) { return false; });
  53. register_property(
  54. "destination_port", [this] { return m_destination_port; },
  55. [](auto&) { return false; });
  56. register_property(
  57. "connected", [this] { return m_connected; },
  58. [](auto&) { return false; });
  59. }
  60. Socket::~Socket()
  61. {
  62. close();
  63. }
  64. bool Socket::connect(const String& hostname, int port)
  65. {
  66. auto* hostent = gethostbyname(hostname.characters());
  67. if (!hostent) {
  68. dbgln("Socket::connect: Unable to resolve '{}'", hostname);
  69. return false;
  70. }
  71. IPv4Address host_address((const u8*)hostent->h_addr_list[0]);
  72. #ifdef CSOCKET_DEBUG
  73. dbg() << "Socket::connect: Resolved '" << hostname << "' to " << host_address;
  74. #endif
  75. return connect(host_address, port);
  76. }
  77. void Socket::set_blocking(bool blocking)
  78. {
  79. int flags = fcntl(fd(), F_GETFL, 0);
  80. ASSERT(flags >= 0);
  81. if (blocking)
  82. flags = fcntl(fd(), F_SETFL, flags & ~O_NONBLOCK);
  83. else
  84. flags = fcntl(fd(), F_SETFL, flags | O_NONBLOCK);
  85. ASSERT(flags == 0);
  86. }
  87. bool Socket::connect(const SocketAddress& address, int port)
  88. {
  89. ASSERT(!is_connected());
  90. ASSERT(address.type() == SocketAddress::Type::IPv4);
  91. #ifdef CSOCKET_DEBUG
  92. dbg() << *this << " connecting to " << address << "...";
  93. #endif
  94. ASSERT(port > 0 && port <= 65535);
  95. struct sockaddr_in addr;
  96. memset(&addr, 0, sizeof(addr));
  97. auto ipv4_address = address.ipv4_address();
  98. memcpy(&addr.sin_addr.s_addr, &ipv4_address, sizeof(IPv4Address));
  99. addr.sin_family = AF_INET;
  100. addr.sin_port = htons(port);
  101. m_destination_address = address;
  102. m_destination_port = port;
  103. return common_connect((struct sockaddr*)&addr, sizeof(addr));
  104. }
  105. bool Socket::connect(const SocketAddress& address)
  106. {
  107. ASSERT(!is_connected());
  108. ASSERT(address.type() == SocketAddress::Type::Local);
  109. #ifdef CSOCKET_DEBUG
  110. dbg() << *this << " connecting to " << address << "...";
  111. #endif
  112. sockaddr_un saddr;
  113. saddr.sun_family = AF_LOCAL;
  114. auto dest_address = address.to_string();
  115. bool fits = dest_address.copy_characters_to_buffer(saddr.sun_path, sizeof(saddr.sun_path));
  116. if (!fits) {
  117. fprintf(stderr, "Core::Socket: Failed to connect() to %s: Path is too long!\n", dest_address.characters());
  118. errno = EINVAL;
  119. return false;
  120. }
  121. m_destination_address = address;
  122. return common_connect((const sockaddr*)&saddr, sizeof(saddr));
  123. }
  124. bool Socket::common_connect(const struct sockaddr* addr, socklen_t addrlen)
  125. {
  126. auto connected = [this] {
  127. #ifdef CSOCKET_DEBUG
  128. dbg() << *this << " connected!";
  129. #endif
  130. if (!m_connected) {
  131. m_connected = true;
  132. ensure_read_notifier();
  133. if (m_notifier) {
  134. m_notifier->remove_from_parent();
  135. m_notifier = nullptr;
  136. }
  137. if (on_connected)
  138. on_connected();
  139. }
  140. };
  141. int rc = ::connect(fd(), addr, addrlen);
  142. if (rc < 0) {
  143. if (errno == EINPROGRESS) {
  144. #ifdef CSOCKET_DEBUG
  145. dbg() << *this << " connection in progress (EINPROGRESS)";
  146. #endif
  147. m_notifier = Notifier::construct(fd(), Notifier::Event::Write, this);
  148. m_notifier->on_ready_to_write = move(connected);
  149. return true;
  150. }
  151. int saved_errno = errno;
  152. fprintf(stderr, "Core::Socket: Failed to connect() to %s: %s\n", destination_address().to_string().characters(), strerror(saved_errno));
  153. errno = saved_errno;
  154. return false;
  155. }
  156. #ifdef CSOCKET_DEBUG
  157. dbg() << *this << " connected ok!";
  158. #endif
  159. connected();
  160. return true;
  161. }
  162. ByteBuffer Socket::receive(int max_size)
  163. {
  164. auto buffer = read(max_size);
  165. if (eof())
  166. m_connected = false;
  167. return buffer;
  168. }
  169. bool Socket::send(ReadonlyBytes data)
  170. {
  171. ssize_t nsent = ::send(fd(), data.data(), data.size(), 0);
  172. if (nsent < 0) {
  173. set_error(errno);
  174. return false;
  175. }
  176. ASSERT(static_cast<size_t>(nsent) == data.size());
  177. return true;
  178. }
  179. void Socket::did_update_fd(int fd)
  180. {
  181. if (fd < 0) {
  182. if (m_read_notifier) {
  183. m_read_notifier->remove_from_parent();
  184. m_read_notifier = nullptr;
  185. }
  186. if (m_notifier) {
  187. m_notifier->remove_from_parent();
  188. m_notifier = nullptr;
  189. }
  190. return;
  191. }
  192. if (m_connected) {
  193. ensure_read_notifier();
  194. } else {
  195. // I don't think it would be right if we updated the fd while not connected *but* while having a notifier..
  196. ASSERT(!m_read_notifier);
  197. }
  198. }
  199. void Socket::ensure_read_notifier()
  200. {
  201. ASSERT(m_connected);
  202. m_read_notifier = Notifier::construct(fd(), Notifier::Event::Read, this);
  203. m_read_notifier->on_ready_to_read = [this] {
  204. if (!can_read())
  205. return;
  206. if (on_ready_to_read)
  207. on_ready_to_read();
  208. };
  209. }
  210. }