Socket.cpp 6.8 KB

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