Socket.cpp 6.4 KB

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