Connection.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/NonnullOwnPtrVector.h>
  9. #include <LibCore/Event.h>
  10. #include <LibCore/EventLoop.h>
  11. #include <LibCore/LocalSocket.h>
  12. #include <LibCore/Notifier.h>
  13. #include <LibCore/Timer.h>
  14. #include <LibIPC/Message.h>
  15. #include <errno.h>
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <sys/select.h>
  20. #include <sys/socket.h>
  21. #include <sys/types.h>
  22. #include <unistd.h>
  23. namespace IPC {
  24. template<typename LocalEndpoint, typename PeerEndpoint>
  25. class Connection : public Core::Object {
  26. public:
  27. using LocalStub = typename LocalEndpoint::Stub;
  28. Connection(LocalStub& local_stub, NonnullRefPtr<Core::LocalSocket> socket)
  29. : m_local_stub(local_stub)
  30. , m_socket(move(socket))
  31. , m_notifier(Core::Notifier::construct(m_socket->fd(), Core::Notifier::Read, this))
  32. {
  33. m_responsiveness_timer = Core::Timer::create_single_shot(3000, [this] { may_have_become_unresponsive(); });
  34. m_notifier->on_ready_to_read = [this] {
  35. NonnullRefPtr protect = *this;
  36. drain_messages_from_peer();
  37. handle_messages();
  38. };
  39. }
  40. template<typename MessageType>
  41. OwnPtr<MessageType> wait_for_specific_message()
  42. {
  43. return wait_for_specific_endpoint_message<MessageType, LocalEndpoint>();
  44. }
  45. void post_message(const Message& message)
  46. {
  47. post_message(message.encode());
  48. }
  49. // FIXME: unnecessary copy
  50. void post_message(MessageBuffer buffer)
  51. {
  52. // NOTE: If this connection is being shut down, but has not yet been destroyed,
  53. // the socket will be closed. Don't try to send more messages.
  54. if (!m_socket->is_open())
  55. return;
  56. // Prepend the message size.
  57. uint32_t message_size = buffer.data.size();
  58. buffer.data.prepend(reinterpret_cast<const u8*>(&message_size), sizeof(message_size));
  59. #ifdef __serenity__
  60. for (auto& fd : buffer.fds) {
  61. auto rc = sendfd(m_socket->fd(), fd->value());
  62. if (rc < 0) {
  63. perror("sendfd");
  64. shutdown();
  65. }
  66. }
  67. #else
  68. if (!buffer.fds.is_empty())
  69. warnln("fd passing is not supported on this platform, sorry :(");
  70. #endif
  71. size_t total_nwritten = 0;
  72. while (total_nwritten < buffer.data.size()) {
  73. auto nwritten = write(m_socket->fd(), buffer.data.data() + total_nwritten, buffer.data.size() - total_nwritten);
  74. if (nwritten < 0) {
  75. switch (errno) {
  76. case EPIPE:
  77. dbgln("{}::post_message: Disconnected from peer", *this);
  78. shutdown();
  79. return;
  80. case EAGAIN:
  81. dbgln("{}::post_message: Peer buffer overflowed", *this);
  82. shutdown();
  83. return;
  84. default:
  85. perror("Connection::post_message write");
  86. shutdown();
  87. return;
  88. }
  89. }
  90. total_nwritten += nwritten;
  91. }
  92. m_responsiveness_timer->start();
  93. }
  94. template<typename RequestType, typename... Args>
  95. NonnullOwnPtr<typename RequestType::ResponseType> send_sync(Args&&... args)
  96. {
  97. post_message(RequestType(forward<Args>(args)...));
  98. auto response = wait_for_specific_endpoint_message<typename RequestType::ResponseType, PeerEndpoint>();
  99. VERIFY(response);
  100. return response.release_nonnull();
  101. }
  102. template<typename RequestType, typename... Args>
  103. OwnPtr<typename RequestType::ResponseType> send_sync_but_allow_failure(Args&&... args)
  104. {
  105. post_message(RequestType(forward<Args>(args)...));
  106. return wait_for_specific_endpoint_message<typename RequestType::ResponseType, PeerEndpoint>();
  107. }
  108. virtual void may_have_become_unresponsive() { }
  109. virtual void did_become_responsive() { }
  110. void shutdown()
  111. {
  112. m_notifier->close();
  113. m_socket->close();
  114. die();
  115. }
  116. virtual void die() { }
  117. protected:
  118. Core::LocalSocket& socket() { return *m_socket; }
  119. template<typename MessageType, typename Endpoint>
  120. OwnPtr<MessageType> wait_for_specific_endpoint_message()
  121. {
  122. for (;;) {
  123. // Double check we don't already have the event waiting for us.
  124. // Otherwise we might end up blocked for a while for no reason.
  125. for (size_t i = 0; i < m_unprocessed_messages.size(); ++i) {
  126. auto& message = m_unprocessed_messages[i];
  127. if (message.endpoint_magic() != Endpoint::static_magic())
  128. continue;
  129. if (message.message_id() == MessageType::static_message_id())
  130. return m_unprocessed_messages.take(i).template release_nonnull<MessageType>();
  131. }
  132. if (!m_socket->is_open())
  133. break;
  134. fd_set rfds;
  135. FD_ZERO(&rfds);
  136. FD_SET(m_socket->fd(), &rfds);
  137. for (;;) {
  138. if (auto rc = select(m_socket->fd() + 1, &rfds, nullptr, nullptr, nullptr); rc < 0) {
  139. if (errno == EINTR)
  140. continue;
  141. perror("wait_for_specific_endpoint_message: select");
  142. VERIFY_NOT_REACHED();
  143. } else {
  144. VERIFY(rc > 0);
  145. VERIFY(FD_ISSET(m_socket->fd(), &rfds));
  146. break;
  147. }
  148. }
  149. if (!drain_messages_from_peer())
  150. break;
  151. }
  152. return {};
  153. }
  154. bool drain_messages_from_peer()
  155. {
  156. Vector<u8> bytes;
  157. if (!m_unprocessed_bytes.is_empty()) {
  158. bytes.append(m_unprocessed_bytes.data(), m_unprocessed_bytes.size());
  159. m_unprocessed_bytes.clear();
  160. }
  161. while (m_socket->is_open()) {
  162. u8 buffer[4096];
  163. ssize_t nread = recv(m_socket->fd(), buffer, sizeof(buffer), MSG_DONTWAIT);
  164. if (nread < 0) {
  165. if (errno == EAGAIN)
  166. break;
  167. perror("recv");
  168. exit(1);
  169. return false;
  170. }
  171. if (nread == 0) {
  172. if (bytes.is_empty()) {
  173. deferred_invoke([this](auto&) { die(); });
  174. }
  175. return false;
  176. }
  177. bytes.append(buffer, nread);
  178. }
  179. if (!bytes.is_empty()) {
  180. m_responsiveness_timer->stop();
  181. did_become_responsive();
  182. }
  183. size_t index = 0;
  184. u32 message_size = 0;
  185. for (; index + sizeof(message_size) < bytes.size(); index += message_size) {
  186. memcpy(&message_size, bytes.data() + index, sizeof(message_size));
  187. if (message_size == 0 || bytes.size() - index - sizeof(uint32_t) < message_size)
  188. break;
  189. index += sizeof(message_size);
  190. auto remaining_bytes = ReadonlyBytes { bytes.data() + index, bytes.size() - index };
  191. if (auto message = LocalEndpoint::decode_message(remaining_bytes, m_socket->fd())) {
  192. m_unprocessed_messages.append(message.release_nonnull());
  193. } else if (auto message = PeerEndpoint::decode_message(remaining_bytes, m_socket->fd())) {
  194. m_unprocessed_messages.append(message.release_nonnull());
  195. } else {
  196. dbgln("Failed to parse a message");
  197. break;
  198. }
  199. }
  200. if (index < bytes.size()) {
  201. // Sometimes we might receive a partial message. That's okay, just stash away
  202. // the unprocessed bytes and we'll prepend them to the next incoming message
  203. // in the next run of this function.
  204. auto remaining_bytes = ByteBuffer::copy(bytes.data() + index, bytes.size() - index);
  205. if (!m_unprocessed_bytes.is_empty()) {
  206. dbgln("{}::drain_messages_from_peer: Already have unprocessed bytes", *this);
  207. shutdown();
  208. return false;
  209. }
  210. m_unprocessed_bytes = remaining_bytes;
  211. }
  212. if (!m_unprocessed_messages.is_empty()) {
  213. deferred_invoke([this](auto&) {
  214. handle_messages();
  215. });
  216. }
  217. return true;
  218. }
  219. void handle_messages()
  220. {
  221. auto messages = move(m_unprocessed_messages);
  222. for (auto& message : messages) {
  223. if (message.endpoint_magic() == LocalEndpoint::static_magic())
  224. if (auto response = m_local_stub.handle(message))
  225. post_message(*response);
  226. }
  227. }
  228. protected:
  229. LocalStub& m_local_stub;
  230. NonnullRefPtr<Core::LocalSocket> m_socket;
  231. RefPtr<Core::Timer> m_responsiveness_timer;
  232. RefPtr<Core::Notifier> m_notifier;
  233. NonnullOwnPtrVector<Message> m_unprocessed_messages;
  234. ByteBuffer m_unprocessed_bytes;
  235. };
  236. }
  237. template<typename LocalEndpoint, typename PeerEndpoint>
  238. struct AK::Formatter<IPC::Connection<LocalEndpoint, PeerEndpoint>> : Formatter<Core::Object> {
  239. };