Connection.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. bool is_open() const { return m_socket->is_open(); }
  118. protected:
  119. Core::LocalSocket& socket() { return *m_socket; }
  120. template<typename MessageType, typename Endpoint>
  121. OwnPtr<MessageType> wait_for_specific_endpoint_message()
  122. {
  123. for (;;) {
  124. // Double check we don't already have the event waiting for us.
  125. // Otherwise we might end up blocked for a while for no reason.
  126. for (size_t i = 0; i < m_unprocessed_messages.size(); ++i) {
  127. auto& message = m_unprocessed_messages[i];
  128. if (message.endpoint_magic() != Endpoint::static_magic())
  129. continue;
  130. if (message.message_id() == MessageType::static_message_id())
  131. return m_unprocessed_messages.take(i).template release_nonnull<MessageType>();
  132. }
  133. if (!m_socket->is_open())
  134. break;
  135. fd_set rfds;
  136. FD_ZERO(&rfds);
  137. FD_SET(m_socket->fd(), &rfds);
  138. for (;;) {
  139. if (auto rc = select(m_socket->fd() + 1, &rfds, nullptr, nullptr, nullptr); rc < 0) {
  140. if (errno == EINTR)
  141. continue;
  142. perror("wait_for_specific_endpoint_message: select");
  143. VERIFY_NOT_REACHED();
  144. } else {
  145. VERIFY(rc > 0);
  146. VERIFY(FD_ISSET(m_socket->fd(), &rfds));
  147. break;
  148. }
  149. }
  150. if (!drain_messages_from_peer())
  151. break;
  152. }
  153. return {};
  154. }
  155. bool drain_messages_from_peer()
  156. {
  157. Vector<u8> bytes;
  158. if (!m_unprocessed_bytes.is_empty()) {
  159. bytes.append(m_unprocessed_bytes.data(), m_unprocessed_bytes.size());
  160. m_unprocessed_bytes.clear();
  161. }
  162. while (m_socket->is_open()) {
  163. u8 buffer[4096];
  164. ssize_t nread = recv(m_socket->fd(), buffer, sizeof(buffer), MSG_DONTWAIT);
  165. if (nread < 0) {
  166. if (errno == EAGAIN)
  167. break;
  168. perror("recv");
  169. exit(1);
  170. return false;
  171. }
  172. if (nread == 0) {
  173. if (bytes.is_empty()) {
  174. deferred_invoke([this] { shutdown(); });
  175. return false;
  176. }
  177. break;
  178. }
  179. bytes.append(buffer, nread);
  180. }
  181. if (!bytes.is_empty()) {
  182. m_responsiveness_timer->stop();
  183. did_become_responsive();
  184. }
  185. size_t index = 0;
  186. u32 message_size = 0;
  187. for (; index + sizeof(message_size) < bytes.size(); index += message_size) {
  188. memcpy(&message_size, bytes.data() + index, sizeof(message_size));
  189. if (message_size == 0 || bytes.size() - index - sizeof(uint32_t) < message_size)
  190. break;
  191. index += sizeof(message_size);
  192. auto remaining_bytes = ReadonlyBytes { bytes.data() + index, message_size };
  193. if (auto message = LocalEndpoint::decode_message(remaining_bytes, m_socket->fd())) {
  194. m_unprocessed_messages.append(message.release_nonnull());
  195. } else if (auto message = PeerEndpoint::decode_message(remaining_bytes, m_socket->fd())) {
  196. m_unprocessed_messages.append(message.release_nonnull());
  197. } else {
  198. dbgln("Failed to parse a message");
  199. break;
  200. }
  201. }
  202. if (index < bytes.size()) {
  203. // Sometimes we might receive a partial message. That's okay, just stash away
  204. // the unprocessed bytes and we'll prepend them to the next incoming message
  205. // in the next run of this function.
  206. auto remaining_bytes_result = ByteBuffer::copy(bytes.span().slice(index));
  207. if (!remaining_bytes_result.has_value()) {
  208. dbgln("{}::drain_messages_from_peer: Failed to allocate buffer", *this);
  209. return false;
  210. }
  211. if (!m_unprocessed_bytes.is_empty()) {
  212. dbgln("{}::drain_messages_from_peer: Already have unprocessed bytes", *this);
  213. shutdown();
  214. return false;
  215. }
  216. m_unprocessed_bytes = remaining_bytes_result.release_value();
  217. }
  218. if (!m_unprocessed_messages.is_empty()) {
  219. deferred_invoke([this] {
  220. handle_messages();
  221. });
  222. }
  223. return true;
  224. }
  225. void handle_messages()
  226. {
  227. auto messages = move(m_unprocessed_messages);
  228. for (auto& message : messages) {
  229. if (message.endpoint_magic() == LocalEndpoint::static_magic())
  230. if (auto response = m_local_stub.handle(message))
  231. post_message(*response);
  232. }
  233. }
  234. protected:
  235. LocalStub& m_local_stub;
  236. NonnullRefPtr<Core::LocalSocket> m_socket;
  237. RefPtr<Core::Timer> m_responsiveness_timer;
  238. RefPtr<Core::Notifier> m_notifier;
  239. NonnullOwnPtrVector<Message> m_unprocessed_messages;
  240. ByteBuffer m_unprocessed_bytes;
  241. };
  242. }
  243. template<typename LocalEndpoint, typename PeerEndpoint>
  244. struct AK::Formatter<IPC::Connection<LocalEndpoint, PeerEndpoint>> : Formatter<Core::Object> {
  245. };