Connection.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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, NonnullOwnPtr<Core::Stream::LocalSocket> socket, u32 local_endpoint_magic)
  12. : m_local_stub(local_stub)
  13. , m_socket(move(socket))
  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. ErrorOr<void> ConnectionBase::post_message(Message const& message)
  22. {
  23. return post_message(message.encode());
  24. }
  25. ErrorOr<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 Error::from_string_literal("Trying to post_message during IPC shutdown"sv);
  31. // Prepend the message size.
  32. uint32_t message_size = buffer.data.size();
  33. TRY(buffer.data.try_prepend(reinterpret_cast<const u8*>(&message_size), sizeof(message_size)));
  34. #ifdef __serenity__
  35. for (auto& fd : buffer.fds) {
  36. if (auto result = m_socket->send_fd(fd.value()); result.is_error()) {
  37. dbgln("{}", result.error());
  38. shutdown();
  39. return result;
  40. }
  41. }
  42. #else
  43. if (!buffer.fds.is_empty())
  44. warnln("fd passing is not supported on this platform, sorry :(");
  45. #endif
  46. ReadonlyBytes bytes_to_write { buffer.data.span() };
  47. while (!bytes_to_write.is_empty()) {
  48. auto maybe_nwritten = m_socket->write(bytes_to_write);
  49. if (maybe_nwritten.is_error()) {
  50. auto error = maybe_nwritten.release_error();
  51. if (error.is_errno()) {
  52. switch (error.code()) {
  53. case EPIPE:
  54. shutdown();
  55. return Error::from_string_literal("IPC::Connection::post_message: Disconnected from peer"sv);
  56. case EAGAIN:
  57. shutdown();
  58. return Error::from_string_literal("IPC::Connection::post_message: Peer buffer overflowed"sv);
  59. default:
  60. shutdown();
  61. return Error::from_syscall("IPC::Connection::post_message write"sv, -error.code());
  62. }
  63. } else {
  64. return error;
  65. }
  66. }
  67. bytes_to_write = bytes_to_write.slice(maybe_nwritten.value());
  68. }
  69. m_responsiveness_timer->start();
  70. return {};
  71. }
  72. void ConnectionBase::shutdown()
  73. {
  74. m_socket->close();
  75. die();
  76. }
  77. void ConnectionBase::handle_messages()
  78. {
  79. auto messages = move(m_unprocessed_messages);
  80. for (auto& message : messages) {
  81. if (message.endpoint_magic() == m_local_endpoint_magic) {
  82. if (auto response = m_local_stub.handle(message)) {
  83. if (auto result = post_message(*response); result.is_error()) {
  84. dbgln("IPC::ConnectionBase::handle_messages: {}", result.error());
  85. }
  86. }
  87. }
  88. }
  89. }
  90. void ConnectionBase::wait_for_socket_to_become_readable()
  91. {
  92. auto maybe_did_become_readable = m_socket->can_read_without_blocking(-1);
  93. if (maybe_did_become_readable.is_error()) {
  94. dbgln("ConnectionBase::wait_for_socket_to_become_readable: {}", maybe_did_become_readable.error());
  95. warnln("ConnectionBase::wait_for_socket_to_become_readable: {}", maybe_did_become_readable.error());
  96. VERIFY_NOT_REACHED();
  97. }
  98. VERIFY(maybe_did_become_readable.value());
  99. }
  100. ErrorOr<Vector<u8>> ConnectionBase::read_as_much_as_possible_from_socket_without_blocking()
  101. {
  102. Vector<u8> bytes;
  103. if (!m_unprocessed_bytes.is_empty()) {
  104. bytes.append(m_unprocessed_bytes.data(), m_unprocessed_bytes.size());
  105. m_unprocessed_bytes.clear();
  106. }
  107. u8 buffer[4096];
  108. while (m_socket->is_open()) {
  109. auto maybe_nread = m_socket->read_without_waiting({ buffer, 4096 });
  110. if (maybe_nread.is_error()) {
  111. auto error = maybe_nread.release_error();
  112. if (error.is_syscall() && error.code() == EAGAIN) {
  113. break;
  114. }
  115. dbgln("ConnectionBase::read_as_much_as_possible_from_socket_without_blocking: {}", error);
  116. warnln("ConnectionBase::read_as_much_as_possible_from_socket_without_blocking: {}", error);
  117. VERIFY_NOT_REACHED();
  118. }
  119. auto nread = maybe_nread.release_value();
  120. if (nread == 0) {
  121. if (bytes.is_empty()) {
  122. deferred_invoke([this] { shutdown(); });
  123. return Error::from_string_literal("IPC connection EOF"sv);
  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. ErrorOr<void> 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 maybe_remaining_bytes = ByteBuffer::copy(bytes.span().slice(index));
  145. if (!maybe_remaining_bytes.has_value())
  146. return Error::from_string_literal("drain_messages_from_peer: Failed to allocate buffer"sv);
  147. if (!m_unprocessed_bytes.is_empty()) {
  148. shutdown();
  149. return Error::from_string_literal("drain_messages_from_peer: Already have unprocessed bytes"sv);
  150. }
  151. m_unprocessed_bytes = maybe_remaining_bytes.release_value();
  152. }
  153. if (!m_unprocessed_messages.is_empty()) {
  154. deferred_invoke([this] {
  155. handle_messages();
  156. });
  157. }
  158. return {};
  159. }
  160. OwnPtr<IPC::Message> ConnectionBase::wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id)
  161. {
  162. for (;;) {
  163. // Double check we don't already have the event waiting for us.
  164. // Otherwise we might end up blocked for a while for no reason.
  165. for (size_t i = 0; i < m_unprocessed_messages.size(); ++i) {
  166. auto& message = m_unprocessed_messages[i];
  167. if (message.endpoint_magic() != endpoint_magic)
  168. continue;
  169. if (message.message_id() == message_id)
  170. return m_unprocessed_messages.take(i);
  171. }
  172. if (!m_socket->is_open())
  173. break;
  174. wait_for_socket_to_become_readable();
  175. if (drain_messages_from_peer().is_error())
  176. break;
  177. }
  178. return {};
  179. }
  180. }