Connection.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Try.h>
  10. #include <LibCore/Event.h>
  11. #include <LibCore/EventLoop.h>
  12. #include <LibCore/Notifier.h>
  13. #include <LibCore/Socket.h>
  14. #include <LibCore/Timer.h>
  15. #include <LibIPC/Forward.h>
  16. #include <LibIPC/Message.h>
  17. #include <errno.h>
  18. #include <stdint.h>
  19. #include <stdio.h>
  20. #include <sys/socket.h>
  21. #include <sys/types.h>
  22. #include <unistd.h>
  23. namespace IPC {
  24. // NOTE: This is an abstraction to allow using IPC::Connection without a Core::EventLoop.
  25. // FIXME: It's not particularly nice, think of something nicer.
  26. struct DeferredInvoker {
  27. virtual ~DeferredInvoker() = default;
  28. virtual void schedule(Function<void()>) = 0;
  29. };
  30. class ConnectionBase : public Core::EventReceiver {
  31. C_OBJECT_ABSTRACT(ConnectionBase);
  32. public:
  33. virtual ~ConnectionBase() override = default;
  34. void set_fd_passing_socket(NonnullOwnPtr<Core::LocalSocket>);
  35. void set_deferred_invoker(NonnullOwnPtr<DeferredInvoker>);
  36. DeferredInvoker& deferred_invoker() { return *m_deferred_invoker; }
  37. bool is_open() const { return m_socket->is_open(); }
  38. ErrorOr<void> post_message(Message const&);
  39. void shutdown();
  40. virtual void die() { }
  41. Core::LocalSocket& socket() { return *m_socket; }
  42. Core::LocalSocket& fd_passing_socket();
  43. protected:
  44. explicit ConnectionBase(IPC::Stub&, NonnullOwnPtr<Core::LocalSocket>, u32 local_endpoint_magic);
  45. virtual void may_have_become_unresponsive() { }
  46. virtual void did_become_responsive() { }
  47. virtual void try_parse_messages(Vector<u8> const& bytes, size_t& index) = 0;
  48. virtual void shutdown_with_error(Error const&);
  49. OwnPtr<IPC::Message> wait_for_specific_endpoint_message_impl(u32 endpoint_magic, int message_id);
  50. void wait_for_socket_to_become_readable();
  51. ErrorOr<Vector<u8>> read_as_much_as_possible_from_socket_without_blocking();
  52. ErrorOr<void> drain_messages_from_peer();
  53. ErrorOr<void> post_message(MessageBuffer);
  54. void handle_messages();
  55. IPC::Stub& m_local_stub;
  56. NonnullOwnPtr<Core::LocalSocket> m_socket;
  57. OwnPtr<Core::LocalSocket> m_fd_passing_socket;
  58. RefPtr<Core::Timer> m_responsiveness_timer;
  59. Vector<NonnullOwnPtr<Message>> m_unprocessed_messages;
  60. ByteBuffer m_unprocessed_bytes;
  61. u32 m_local_endpoint_magic { 0 };
  62. NonnullOwnPtr<DeferredInvoker> m_deferred_invoker;
  63. };
  64. template<typename LocalEndpoint, typename PeerEndpoint>
  65. class Connection : public ConnectionBase {
  66. public:
  67. Connection(IPC::Stub& local_stub, NonnullOwnPtr<Core::LocalSocket> socket)
  68. : ConnectionBase(local_stub, move(socket), LocalEndpoint::static_magic())
  69. {
  70. m_socket->on_ready_to_read = [this] {
  71. NonnullRefPtr protect = *this;
  72. // FIXME: Do something about errors.
  73. (void)drain_messages_from_peer();
  74. handle_messages();
  75. };
  76. }
  77. template<typename MessageType>
  78. OwnPtr<MessageType> wait_for_specific_message()
  79. {
  80. return wait_for_specific_endpoint_message<MessageType, LocalEndpoint>();
  81. }
  82. template<typename RequestType, typename... Args>
  83. NonnullOwnPtr<typename RequestType::ResponseType> send_sync(Args&&... args)
  84. {
  85. MUST(post_message(RequestType(forward<Args>(args)...)));
  86. auto response = wait_for_specific_endpoint_message<typename RequestType::ResponseType, PeerEndpoint>();
  87. VERIFY(response);
  88. return response.release_nonnull();
  89. }
  90. template<typename RequestType, typename... Args>
  91. OwnPtr<typename RequestType::ResponseType> send_sync_but_allow_failure(Args&&... args)
  92. {
  93. if (post_message(RequestType(forward<Args>(args)...)).is_error())
  94. return nullptr;
  95. return wait_for_specific_endpoint_message<typename RequestType::ResponseType, PeerEndpoint>();
  96. }
  97. protected:
  98. template<typename MessageType, typename Endpoint>
  99. OwnPtr<MessageType> wait_for_specific_endpoint_message()
  100. {
  101. if (auto message = wait_for_specific_endpoint_message_impl(Endpoint::static_magic(), MessageType::static_message_id()))
  102. return message.template release_nonnull<MessageType>();
  103. return {};
  104. }
  105. virtual void try_parse_messages(Vector<u8> const& bytes, size_t& index) override
  106. {
  107. u32 message_size = 0;
  108. for (; index + sizeof(message_size) < bytes.size(); index += message_size) {
  109. memcpy(&message_size, bytes.data() + index, sizeof(message_size));
  110. if (message_size == 0 || bytes.size() - index - sizeof(uint32_t) < message_size)
  111. break;
  112. index += sizeof(message_size);
  113. auto remaining_bytes = ReadonlyBytes { bytes.data() + index, message_size };
  114. auto local_message = LocalEndpoint::decode_message(remaining_bytes, fd_passing_socket());
  115. if (!local_message.is_error()) {
  116. m_unprocessed_messages.append(local_message.release_value());
  117. continue;
  118. }
  119. auto peer_message = PeerEndpoint::decode_message(remaining_bytes, fd_passing_socket());
  120. if (!peer_message.is_error()) {
  121. m_unprocessed_messages.append(peer_message.release_value());
  122. continue;
  123. }
  124. dbgln("Failed to parse a message");
  125. dbgln("Local endpoint error: {}", local_message.error());
  126. dbgln("Peer endpoint error: {}", peer_message.error());
  127. break;
  128. }
  129. }
  130. };
  131. }
  132. template<typename LocalEndpoint, typename PeerEndpoint>
  133. struct AK::Formatter<IPC::Connection<LocalEndpoint, PeerEndpoint>> : Formatter<Core::EventReceiver> {
  134. };