Connection.cpp 6.4 KB

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