Socket.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. strcpy(saddr.sun_path, address.to_string().characters());
  100. m_destination_address = address;
  101. return common_connect((const sockaddr*)&saddr, sizeof(saddr));
  102. }
  103. bool Socket::common_connect(const struct sockaddr* addr, socklen_t addrlen)
  104. {
  105. int rc = ::connect(fd(), addr, addrlen);
  106. if (rc < 0) {
  107. if (errno == EINPROGRESS) {
  108. #ifdef CSOCKET_DEBUG
  109. dbg() << *this << " connection in progress (EINPROGRESS)";
  110. #endif
  111. m_notifier = Notifier::construct(fd(), Notifier::Event::Write, this);
  112. m_notifier->on_ready_to_write = [this] {
  113. #ifdef CSOCKET_DEBUG
  114. dbg() << *this << " connected!";
  115. #endif
  116. m_connected = true;
  117. ensure_read_notifier();
  118. m_notifier->set_event_mask(Notifier::Event::None);
  119. if (on_connected)
  120. on_connected();
  121. };
  122. return true;
  123. }
  124. int saved_errno = errno;
  125. fprintf(stderr, "Core::Socket: Failed to connect() to %s: %s\n", destination_address().to_string().characters(), strerror(saved_errno));
  126. errno = saved_errno;
  127. return false;
  128. }
  129. #ifdef CSOCKET_DEBUG
  130. dbg() << *this << " connected ok!";
  131. #endif
  132. m_connected = true;
  133. ensure_read_notifier();
  134. if (on_connected)
  135. on_connected();
  136. return true;
  137. }
  138. ByteBuffer Socket::receive(int max_size)
  139. {
  140. auto buffer = read(max_size);
  141. if (eof()) {
  142. dbg() << *this << " connection appears to have closed in receive().";
  143. m_connected = false;
  144. }
  145. return buffer;
  146. }
  147. bool Socket::send(const ByteBuffer& data)
  148. {
  149. ssize_t nsent = ::send(fd(), data.data(), data.size(), 0);
  150. if (nsent < 0) {
  151. set_error(errno);
  152. return false;
  153. }
  154. ASSERT(static_cast<size_t>(nsent) == data.size());
  155. return true;
  156. }
  157. void Socket::did_update_fd(int fd)
  158. {
  159. if (fd < 0) {
  160. m_read_notifier = nullptr;
  161. return;
  162. }
  163. if (m_connected) {
  164. ensure_read_notifier();
  165. } else {
  166. // I don't think it would be right if we updated the fd while not connected *but* while having a notifier..
  167. ASSERT(!m_read_notifier);
  168. }
  169. }
  170. void Socket::ensure_read_notifier()
  171. {
  172. ASSERT(m_connected);
  173. m_read_notifier = Notifier::construct(fd(), Notifier::Event::Read, this);
  174. m_read_notifier->on_ready_to_read = [this] {
  175. if (on_ready_to_read)
  176. on_ready_to_read();
  177. };
  178. }
  179. }