Connection.cpp 6.2 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. m_processing_timer = Core::Timer::create_single_shot(0, [this] { handle_messages(); });
  18. }
  19. ConnectionBase::~ConnectionBase()
  20. {
  21. }
  22. void ConnectionBase::post_message(Message const& message)
  23. {
  24. post_message(message.encode());
  25. }
  26. void ConnectionBase::post_message(MessageBuffer buffer)
  27. {
  28. // NOTE: If this connection is being shut down, but has not yet been destroyed,
  29. // the socket will be closed. Don't try to send more messages.
  30. if (!m_socket->is_open())
  31. return;
  32. // Prepend the message size.
  33. uint32_t message_size = buffer.data.size();
  34. buffer.data.prepend(reinterpret_cast<const u8*>(&message_size), sizeof(message_size));
  35. #ifdef __serenity__
  36. for (auto& fd : buffer.fds) {
  37. auto rc = sendfd(m_socket->fd(), fd->value());
  38. if (rc < 0) {
  39. perror("sendfd");
  40. shutdown();
  41. }
  42. }
  43. #else
  44. if (!buffer.fds.is_empty())
  45. warnln("fd passing is not supported on this platform, sorry :(");
  46. #endif
  47. size_t total_nwritten = 0;
  48. while (total_nwritten < buffer.data.size()) {
  49. auto nwritten = write(m_socket->fd(), buffer.data.data() + total_nwritten, buffer.data.size() - total_nwritten);
  50. if (nwritten < 0) {
  51. switch (errno) {
  52. case EPIPE:
  53. dbgln("{}::post_message: Disconnected from peer", static_cast<Core::Object const&>(*this));
  54. shutdown();
  55. return;
  56. case EAGAIN:
  57. dbgln("{}::post_message: Peer buffer overflowed", static_cast<Core::Object const&>(*this));
  58. shutdown();
  59. return;
  60. default:
  61. perror("Connection::post_message write");
  62. shutdown();
  63. return;
  64. }
  65. }
  66. total_nwritten += nwritten;
  67. }
  68. m_responsiveness_timer->start();
  69. }
  70. void ConnectionBase::shutdown()
  71. {
  72. m_notifier->close();
  73. m_socket->close();
  74. die();
  75. }
  76. void ConnectionBase::handle_messages()
  77. {
  78. auto messages = move(m_unprocessed_messages);
  79. for (auto& message : messages) {
  80. if (message.endpoint_magic() == m_local_endpoint_magic)
  81. if (auto response = m_local_stub.handle(message))
  82. post_message(*response);
  83. }
  84. }
  85. void ConnectionBase::wait_for_socket_to_become_readable()
  86. {
  87. fd_set read_fds;
  88. FD_ZERO(&read_fds);
  89. FD_SET(m_socket->fd(), &read_fds);
  90. for (;;) {
  91. if (auto rc = select(m_socket->fd() + 1, &read_fds, nullptr, nullptr, nullptr); rc < 0) {
  92. if (errno == EINTR)
  93. continue;
  94. perror("wait_for_specific_endpoint_message: select");
  95. VERIFY_NOT_REACHED();
  96. } else {
  97. VERIFY(rc > 0);
  98. VERIFY(FD_ISSET(m_socket->fd(), &read_fds));
  99. break;
  100. }
  101. }
  102. }
  103. Result<Vector<u8>, bool> ConnectionBase::read_as_much_as_possible_from_socket_without_blocking()
  104. {
  105. Vector<u8> bytes;
  106. if (!m_unprocessed_bytes.is_empty()) {
  107. bytes.append(m_unprocessed_bytes.data(), m_unprocessed_bytes.size());
  108. m_unprocessed_bytes.clear();
  109. }
  110. while (m_socket->is_open()) {
  111. u8 buffer[4096];
  112. ssize_t nread = recv(m_socket->fd(), buffer, sizeof(buffer), MSG_DONTWAIT);
  113. if (nread < 0) {
  114. if (errno == EAGAIN)
  115. break;
  116. perror("recv");
  117. exit(1);
  118. return false;
  119. }
  120. if (nread == 0) {
  121. if (bytes.is_empty()) {
  122. deferred_invoke([this] { shutdown(); });
  123. return false;
  124. }
  125. break;
  126. }
  127. bytes.append(buffer, nread);
  128. }
  129. if (!bytes.is_empty()) {
  130. m_responsiveness_timer->stop();
  131. did_become_responsive();
  132. }
  133. return bytes;
  134. }
  135. bool ConnectionBase::drain_messages_from_peer()
  136. {
  137. auto bytes = TRY(read_as_much_as_possible_from_socket_without_blocking());
  138. size_t index = 0;
  139. try_parse_messages(bytes, index);
  140. if (index < bytes.size()) {
  141. // Sometimes we might receive a partial message. That's okay, just stash away
  142. // the unprocessed bytes and we'll prepend them to the next incoming message
  143. // in the next run of this function.
  144. auto remaining_bytes_result = ByteBuffer::copy(bytes.span().slice(index));
  145. if (!remaining_bytes_result.has_value()) {
  146. dbgln("{}::drain_messages_from_peer: Failed to allocate buffer", static_cast<Core::Object const&>(*this));
  147. return false;
  148. }
  149. if (!m_unprocessed_bytes.is_empty()) {
  150. dbgln("{}::drain_messages_from_peer: Already have unprocessed bytes", static_cast<Core::Object const&>(*this));
  151. shutdown();
  152. return false;
  153. }
  154. m_unprocessed_bytes = remaining_bytes_result.release_value();
  155. }
  156. if (!m_unprocessed_messages.is_empty()) {
  157. if (!m_processing_timer->is_active())
  158. m_processing_timer->start();
  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. }