Connection.cpp 7.7 KB

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