Connection.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCore/System.h>
  8. #include <LibIPC/Connection.h>
  9. #include <LibIPC/Stub.h>
  10. #include <sys/select.h>
  11. namespace IPC {
  12. struct CoreEventLoopDeferredInvoker final : public DeferredInvoker {
  13. virtual ~CoreEventLoopDeferredInvoker() = default;
  14. virtual void schedule(Function<void()> callback) override
  15. {
  16. Core::deferred_invoke(move(callback));
  17. }
  18. };
  19. ConnectionBase::ConnectionBase(IPC::Stub& local_stub, NonnullOwnPtr<Core::LocalSocket> socket, u32 local_endpoint_magic)
  20. : m_local_stub(local_stub)
  21. , m_socket(move(socket))
  22. , m_local_endpoint_magic(local_endpoint_magic)
  23. , m_deferred_invoker(make<CoreEventLoopDeferredInvoker>())
  24. {
  25. m_responsiveness_timer = Core::Timer::create_single_shot(3000, [this] { may_have_become_unresponsive(); }).release_value_but_fixme_should_propagate_errors();
  26. }
  27. void ConnectionBase::set_deferred_invoker(NonnullOwnPtr<DeferredInvoker> deferred_invoker)
  28. {
  29. m_deferred_invoker = move(deferred_invoker);
  30. }
  31. void ConnectionBase::set_fd_passing_socket(NonnullOwnPtr<Core::LocalSocket> socket)
  32. {
  33. m_fd_passing_socket = move(socket);
  34. }
  35. Core::LocalSocket& ConnectionBase::fd_passing_socket()
  36. {
  37. if (m_fd_passing_socket)
  38. return *m_fd_passing_socket;
  39. return *m_socket;
  40. }
  41. ErrorOr<void> ConnectionBase::post_message(Message const& message)
  42. {
  43. return post_message(TRY(message.encode()));
  44. }
  45. ErrorOr<void> ConnectionBase::post_message(MessageBuffer buffer)
  46. {
  47. // NOTE: If this connection is being shut down, but has not yet been destroyed,
  48. // the socket will be closed. Don't try to send more messages.
  49. if (!m_socket->is_open())
  50. return Error::from_string_literal("Trying to post_message during IPC shutdown");
  51. // Prepend the message size.
  52. uint32_t message_size = buffer.data.size();
  53. TRY(buffer.data.try_prepend(reinterpret_cast<u8 const*>(&message_size), sizeof(message_size)));
  54. for (auto& fd : buffer.fds) {
  55. if (auto result = fd_passing_socket().send_fd(fd->value()); result.is_error()) {
  56. shutdown_with_error(result.error());
  57. return result;
  58. }
  59. }
  60. ReadonlyBytes bytes_to_write { buffer.data.span() };
  61. int writes_done = 0;
  62. size_t initial_size = bytes_to_write.size();
  63. while (!bytes_to_write.is_empty()) {
  64. auto maybe_nwritten = m_socket->write(bytes_to_write);
  65. writes_done++;
  66. if (maybe_nwritten.is_error()) {
  67. auto error = maybe_nwritten.release_error();
  68. if (error.is_errno()) {
  69. // FIXME: This is a hacky way to at least not crash on large messages
  70. // The limit of 100 writes is arbitrary, and there to prevent indefinite spinning on the EventLoop
  71. if (error.code() == EAGAIN && writes_done < 100) {
  72. sched_yield();
  73. continue;
  74. }
  75. shutdown_with_error(error);
  76. switch (error.code()) {
  77. case EPIPE:
  78. return Error::from_string_literal("IPC::Connection::post_message: Disconnected from peer");
  79. case EAGAIN:
  80. return Error::from_string_literal("IPC::Connection::post_message: Peer buffer overflowed");
  81. default:
  82. return Error::from_syscall("IPC::Connection::post_message write"sv, -error.code());
  83. }
  84. } else {
  85. return error;
  86. }
  87. }
  88. bytes_to_write = bytes_to_write.slice(maybe_nwritten.value());
  89. }
  90. if (writes_done > 1) {
  91. dbgln("LibIPC::Connection FIXME Warning, needed {} writes needed to send message of size {}B, this is pretty bad, as it spins on the EventLoop", writes_done, initial_size);
  92. }
  93. // Note: This disables responsiveness detection when an event loop is absent.
  94. // There are no users which both need this feature but don't have an event loop.
  95. if (Core::EventLoop::has_been_instantiated())
  96. m_responsiveness_timer->start();
  97. return {};
  98. }
  99. void ConnectionBase::shutdown()
  100. {
  101. m_socket->close();
  102. die();
  103. }
  104. void ConnectionBase::shutdown_with_error(Error const& error)
  105. {
  106. dbgln("IPC::ConnectionBase ({:p}) had an error ({}), disconnecting.", this, error);
  107. shutdown();
  108. }
  109. void ConnectionBase::handle_messages()
  110. {
  111. auto messages = move(m_unprocessed_messages);
  112. for (auto& message : messages) {
  113. if (message->endpoint_magic() == m_local_endpoint_magic) {
  114. auto handler_result = m_local_stub.handle(*message);
  115. if (handler_result.is_error()) {
  116. dbgln("IPC::ConnectionBase::handle_messages: {}", handler_result.error());
  117. continue;
  118. }
  119. if (auto response = handler_result.release_value()) {
  120. if (auto post_result = post_message(*response); post_result.is_error()) {
  121. dbgln("IPC::ConnectionBase::handle_messages: {}", post_result.error());
  122. }
  123. }
  124. }
  125. }
  126. }
  127. void ConnectionBase::wait_for_socket_to_become_readable()
  128. {
  129. auto maybe_did_become_readable = m_socket->can_read_without_blocking(-1);
  130. if (maybe_did_become_readable.is_error()) {
  131. dbgln("ConnectionBase::wait_for_socket_to_become_readable: {}", maybe_did_become_readable.error());
  132. warnln("ConnectionBase::wait_for_socket_to_become_readable: {}", maybe_did_become_readable.error());
  133. VERIFY_NOT_REACHED();
  134. }
  135. VERIFY(maybe_did_become_readable.value());
  136. }
  137. ErrorOr<Vector<u8>> ConnectionBase::read_as_much_as_possible_from_socket_without_blocking()
  138. {
  139. Vector<u8> bytes;
  140. if (!m_unprocessed_bytes.is_empty()) {
  141. bytes.append(m_unprocessed_bytes.data(), m_unprocessed_bytes.size());
  142. m_unprocessed_bytes.clear();
  143. }
  144. u8 buffer[4096];
  145. bool should_shut_down = false;
  146. auto schedule_shutdown = [this, &should_shut_down]() {
  147. should_shut_down = true;
  148. m_deferred_invoker->schedule([strong_this = NonnullRefPtr(*this)] {
  149. strong_this->shutdown();
  150. });
  151. };
  152. while (m_socket->is_open()) {
  153. auto maybe_bytes_read = m_socket->read_without_waiting({ buffer, 4096 });
  154. if (maybe_bytes_read.is_error()) {
  155. auto error = maybe_bytes_read.release_error();
  156. if (error.is_syscall() && error.code() == EAGAIN) {
  157. break;
  158. }
  159. if (error.is_syscall() && error.code() == ECONNRESET) {
  160. schedule_shutdown();
  161. break;
  162. }
  163. dbgln("ConnectionBase::read_as_much_as_possible_from_socket_without_blocking: {}", error);
  164. warnln("ConnectionBase::read_as_much_as_possible_from_socket_without_blocking: {}", error);
  165. VERIFY_NOT_REACHED();
  166. }
  167. auto bytes_read = maybe_bytes_read.release_value();
  168. if (bytes_read.is_empty()) {
  169. schedule_shutdown();
  170. break;
  171. }
  172. bytes.append(bytes_read.data(), bytes_read.size());
  173. }
  174. if (!bytes.is_empty()) {
  175. m_responsiveness_timer->stop();
  176. did_become_responsive();
  177. } else if (should_shut_down) {
  178. return Error::from_string_literal("IPC connection EOF");
  179. }
  180. return bytes;
  181. }
  182. ErrorOr<void> ConnectionBase::drain_messages_from_peer()
  183. {
  184. auto bytes = TRY(read_as_much_as_possible_from_socket_without_blocking());
  185. size_t index = 0;
  186. try_parse_messages(bytes, index);
  187. if (index < bytes.size()) {
  188. // Sometimes we might receive a partial message. That's okay, just stash away
  189. // the unprocessed bytes and we'll prepend them to the next incoming message
  190. // in the next run of this function.
  191. auto remaining_bytes = TRY(ByteBuffer::copy(bytes.span().slice(index)));
  192. if (!m_unprocessed_bytes.is_empty()) {
  193. shutdown();
  194. return Error::from_string_literal("drain_messages_from_peer: Already have unprocessed bytes");
  195. }
  196. m_unprocessed_bytes = move(remaining_bytes);
  197. }
  198. if (!m_unprocessed_messages.is_empty()) {
  199. m_deferred_invoker->schedule([strong_this = NonnullRefPtr(*this)] {
  200. strong_this->handle_messages();
  201. });
  202. }
  203. return {};
  204. }
  205. OwnPtr<IPC::Message> ConnectionBase::wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id)
  206. {
  207. for (;;) {
  208. // Double check we don't already have the event waiting for us.
  209. // Otherwise we might end up blocked for a while for no reason.
  210. for (size_t i = 0; i < m_unprocessed_messages.size(); ++i) {
  211. auto& message = m_unprocessed_messages[i];
  212. if (message->endpoint_magic() != endpoint_magic)
  213. continue;
  214. if (message->message_id() == message_id)
  215. return m_unprocessed_messages.take(i);
  216. }
  217. if (!m_socket->is_open())
  218. break;
  219. wait_for_socket_to_become_readable();
  220. if (drain_messages_from_peer().is_error())
  221. break;
  222. }
  223. return {};
  224. }
  225. }