Connection.cpp 8.8 KB

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