Connection.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibIPC/Connection.h>
  7. #include <LibIPC/Stub.h>
  8. #include <sys/select.h>
  9. namespace IPC {
  10. ConnectionBase::ConnectionBase(IPC::Stub& local_stub, NonnullRefPtr<Core::LocalSocket> socket, u32 local_endpoint_magic)
  11. : m_local_stub(local_stub)
  12. , m_socket(move(socket))
  13. , m_notifier(Core::Notifier::construct(m_socket->fd(), Core::Notifier::Read, this))
  14. , m_local_endpoint_magic(local_endpoint_magic)
  15. {
  16. m_responsiveness_timer = Core::Timer::create_single_shot(3000, [this] { may_have_become_unresponsive(); });
  17. }
  18. ConnectionBase::~ConnectionBase()
  19. {
  20. }
  21. void ConnectionBase::post_message(Message const& message)
  22. {
  23. post_message(message.encode());
  24. }
  25. void ConnectionBase::post_message(MessageBuffer buffer)
  26. {
  27. // NOTE: If this connection is being shut down, but has not yet been destroyed,
  28. // the socket will be closed. Don't try to send more messages.
  29. if (!m_socket->is_open())
  30. return;
  31. // Prepend the message size.
  32. uint32_t message_size = buffer.data.size();
  33. buffer.data.prepend(reinterpret_cast<const u8*>(&message_size), sizeof(message_size));
  34. #ifdef __serenity__
  35. for (auto& fd : buffer.fds) {
  36. auto rc = sendfd(m_socket->fd(), fd->value());
  37. if (rc < 0) {
  38. perror("sendfd");
  39. shutdown();
  40. }
  41. }
  42. #else
  43. if (!buffer.fds.is_empty())
  44. warnln("fd passing is not supported on this platform, sorry :(");
  45. #endif
  46. size_t total_nwritten = 0;
  47. while (total_nwritten < buffer.data.size()) {
  48. auto nwritten = write(m_socket->fd(), buffer.data.data() + total_nwritten, buffer.data.size() - total_nwritten);
  49. if (nwritten < 0) {
  50. switch (errno) {
  51. case EPIPE:
  52. dbgln("{}::post_message: Disconnected from peer", static_cast<Core::Object const&>(*this));
  53. shutdown();
  54. return;
  55. case EAGAIN:
  56. dbgln("{}::post_message: Peer buffer overflowed", static_cast<Core::Object const&>(*this));
  57. shutdown();
  58. return;
  59. default:
  60. perror("Connection::post_message write");
  61. shutdown();
  62. return;
  63. }
  64. }
  65. total_nwritten += nwritten;
  66. }
  67. m_responsiveness_timer->start();
  68. }
  69. void ConnectionBase::shutdown()
  70. {
  71. m_notifier->close();
  72. m_socket->close();
  73. die();
  74. }
  75. void ConnectionBase::handle_messages()
  76. {
  77. auto messages = move(m_unprocessed_messages);
  78. for (auto& message : messages) {
  79. if (message.endpoint_magic() == m_local_endpoint_magic)
  80. if (auto response = m_local_stub.handle(message))
  81. post_message(*response);
  82. }
  83. }
  84. void ConnectionBase::wait_for_socket_to_become_readable()
  85. {
  86. fd_set read_fds;
  87. FD_ZERO(&read_fds);
  88. FD_SET(m_socket->fd(), &read_fds);
  89. for (;;) {
  90. if (auto rc = select(m_socket->fd() + 1, &read_fds, nullptr, nullptr, nullptr); rc < 0) {
  91. if (errno == EINTR)
  92. continue;
  93. perror("wait_for_specific_endpoint_message: select");
  94. VERIFY_NOT_REACHED();
  95. } else {
  96. VERIFY(rc > 0);
  97. VERIFY(FD_ISSET(m_socket->fd(), &read_fds));
  98. break;
  99. }
  100. }
  101. }
  102. Result<Vector<u8>, bool> ConnectionBase::read_as_much_as_possible_from_socket_without_blocking()
  103. {
  104. Vector<u8> bytes;
  105. if (!m_unprocessed_bytes.is_empty()) {
  106. bytes.append(m_unprocessed_bytes.data(), m_unprocessed_bytes.size());
  107. m_unprocessed_bytes.clear();
  108. }
  109. while (m_socket->is_open()) {
  110. u8 buffer[4096];
  111. ssize_t nread = recv(m_socket->fd(), buffer, sizeof(buffer), MSG_DONTWAIT);
  112. if (nread < 0) {
  113. if (errno == EAGAIN)
  114. break;
  115. perror("recv");
  116. exit(1);
  117. return false;
  118. }
  119. if (nread == 0) {
  120. if (bytes.is_empty()) {
  121. deferred_invoke([this] { shutdown(); });
  122. return false;
  123. }
  124. break;
  125. }
  126. bytes.append(buffer, nread);
  127. }
  128. if (!bytes.is_empty()) {
  129. m_responsiveness_timer->stop();
  130. did_become_responsive();
  131. }
  132. return bytes;
  133. }
  134. bool ConnectionBase::drain_messages_from_peer()
  135. {
  136. auto bytes = TRY(read_as_much_as_possible_from_socket_without_blocking());
  137. size_t index = 0;
  138. try_parse_messages(bytes, index);
  139. if (index < bytes.size()) {
  140. // Sometimes we might receive a partial message. That's okay, just stash away
  141. // the unprocessed bytes and we'll prepend them to the next incoming message
  142. // in the next run of this function.
  143. auto remaining_bytes_result = ByteBuffer::copy(bytes.span().slice(index));
  144. if (!remaining_bytes_result.has_value()) {
  145. dbgln("{}::drain_messages_from_peer: Failed to allocate buffer", static_cast<Core::Object const&>(*this));
  146. return false;
  147. }
  148. if (!m_unprocessed_bytes.is_empty()) {
  149. dbgln("{}::drain_messages_from_peer: Already have unprocessed bytes", static_cast<Core::Object const&>(*this));
  150. shutdown();
  151. return false;
  152. }
  153. m_unprocessed_bytes = remaining_bytes_result.release_value();
  154. }
  155. if (!m_unprocessed_messages.is_empty()) {
  156. deferred_invoke([this] {
  157. handle_messages();
  158. });
  159. }
  160. return true;
  161. }
  162. OwnPtr<IPC::Message> ConnectionBase::wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id)
  163. {
  164. for (;;) {
  165. // Double check we don't already have the event waiting for us.
  166. // Otherwise we might end up blocked for a while for no reason.
  167. for (size_t i = 0; i < m_unprocessed_messages.size(); ++i) {
  168. auto& message = m_unprocessed_messages[i];
  169. if (message.endpoint_magic() != endpoint_magic)
  170. continue;
  171. if (message.message_id() == message_id)
  172. return m_unprocessed_messages.take(i);
  173. }
  174. if (!m_socket->is_open())
  175. break;
  176. wait_for_socket_to_become_readable();
  177. if (!drain_messages_from_peer())
  178. break;
  179. }
  180. return {};
  181. }
  182. }