xref: /aosp_15_r20/external/cronet/ipc/ipc_channel_reader.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef IPC_IPC_CHANNEL_READER_H_
6 #define IPC_IPC_CHANNEL_READER_H_
7 
8 #include <stddef.h>
9 
10 #include <set>
11 
12 #include "base/component_export.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/raw_ptr.h"
15 #include "ipc/ipc_channel.h"
16 
17 namespace IPC {
18 namespace internal {
19 
20 // This class provides common pipe reading functionality for the
21 // platform-specific IPC channel implementations.
22 //
23 // It does the common input buffer management and message dispatch, while the
24 // platform-specific parts provide the pipe management through a virtual
25 // interface implemented on a per-platform basis.
26 //
27 // Note that there is no "writer" corresponding to this because the code for
28 // writing to the channel is much simpler and has very little common
29 // functionality that would benefit from being factored out. If we add
30 // something like that in the future, it would be more appropriate to add it
31 // here (and rename appropriately) rather than writing a different class.
COMPONENT_EXPORT(IPC)32 class COMPONENT_EXPORT(IPC) ChannelReader {
33  public:
34   explicit ChannelReader(Listener* listener);
35 
36   ChannelReader(const ChannelReader&) = delete;
37   ChannelReader& operator=(const ChannelReader&) = delete;
38 
39   virtual ~ChannelReader();
40 
41   void set_listener(Listener* listener) { listener_ = listener; }
42 
43   // This type is returned by ProcessIncomingMessages to indicate the effect of
44   // the method.
45   enum DispatchState {
46     // All messages were successfully dispatched, or there were no messages to
47     // dispatch.
48     DISPATCH_FINISHED,
49     // There was a channel error.
50     DISPATCH_ERROR,
51     // Dispatching messages is blocked on receiving more information from the
52     // broker.
53     DISPATCH_WAITING_ON_BROKER,
54   };
55 
56   // Call to process messages received from the IPC connection and dispatch
57   // them.
58   DispatchState ProcessIncomingMessages();
59 
60   // Handles asynchronously read data.
61   //
62   // Optionally call this after returning READ_PENDING from ReadData to
63   // indicate that buffer was filled with the given number of bytes of
64   // data. See ReadData for more.
65   DispatchState AsyncReadComplete(int bytes_read);
66 
67   // Returns true if the given message is internal to the IPC implementation,
68   // like the "hello" message sent on channel set-up.
69   bool IsInternalMessage(const Message& m);
70 
71   // Returns true if the given message is an Hello message
72   // sent on channel set-up.
73   bool IsHelloMessage(const Message& m);
74 
75  protected:
76   enum ReadState { READ_SUCCEEDED, READ_FAILED, READ_PENDING };
77 
78   Listener* listener() const { return listener_; }
79 
80   // Subclasses should call this method in their destructor to give this class a
81   // chance to clean up state that might be dependent on subclass members.
82   void CleanUp();
83 
84   // Populates the given buffer with data from the pipe.
85   //
86   // Returns the state of the read. On READ_SUCCESS, the number of bytes
87   // read will be placed into |*bytes_read| (which can be less than the
88   // buffer size). On READ_FAILED, the channel will be closed.
89   //
90   // If the return value is READ_PENDING, it means that there was no data
91   // ready for reading. The implementation is then responsible for either
92   // calling AsyncReadComplete with the number of bytes read into the
93   // buffer, or ProcessIncomingMessages to try the read again (depending
94   // on whether the platform's async I/O is "try again" or "write
95   // asynchronously into your buffer").
96   virtual ReadState ReadData(char* buffer, int buffer_len, int* bytes_read) = 0;
97 
98   // Loads the required file desciptors into the given message. Returns true
99   // on success. False means a fatal channel error.
100   //
101   // This will read from the input_fds_ and read more handles from the FD
102   // pipe if necessary.
103   virtual bool ShouldDispatchInputMessage(Message* msg) = 0;
104 
105   // Overridden by subclasses to get attachments that are sent alongside the IPC
106   // channel.
107   // Returns true on success. False means a fatal channel error.
108   virtual bool GetAttachments(Message* msg) = 0;
109 
110   // Performs post-dispatch checks. Called when all input buffers are empty,
111   // though there could be more data ready to be read from the OS.
112   virtual bool DidEmptyInputBuffers() = 0;
113 
114   // Handles internal messages, like the hello message sent on channel startup.
115   virtual void HandleInternalMessage(const Message& msg) = 0;
116 
117   // Exposed for testing purposes only.
118   virtual void DispatchMessage(Message* m);
119 
120  private:
121   FRIEND_TEST_ALL_PREFIXES(ChannelReaderTest, AttachmentAlreadyBrokered);
122   FRIEND_TEST_ALL_PREFIXES(ChannelReaderTest, AttachmentNotYetBrokered);
123   FRIEND_TEST_ALL_PREFIXES(ChannelReaderTest, ResizeOverflowBuffer);
124   FRIEND_TEST_ALL_PREFIXES(ChannelReaderTest, InvalidMessageSize);
125   FRIEND_TEST_ALL_PREFIXES(ChannelReaderTest, TrimBuffer);
126 
127   // Takes the data received from the IPC channel and translates it into
128   // Messages. Complete messages are passed to HandleTranslatedMessage().
129   // Returns |false| on unrecoverable error.
130   bool TranslateInputData(const char* input_data, int input_data_len);
131 
132   // Internal messages and messages bound for the attachment broker are
133   // immediately dispatched. Other messages are passed to
134   // HandleExternalMessage().
135   // Returns |false| on unrecoverable error.
136   bool HandleTranslatedMessage(Message* translated_message);
137 
138   // Populates the message with brokered and non-brokered attachments. If
139   // possible, the message is immediately dispatched. Otherwise, a deep copy of
140   // the message is added to |queued_messages_|. |blocked_ids_| are updated if
141   // necessary.
142   bool HandleExternalMessage(Message* external_message);
143 
144   // If there was a dispatch error, informs |listener_|.
145   void HandleDispatchError(const Message& message);
146 
147   // Checks that |size| is a valid message size. Has side effects if it's not.
148   bool CheckMessageSize(size_t size);
149 
150   raw_ptr<Listener> listener_;
151 
152   // We read from the pipe into this buffer. Managed by DispatchInputData, do
153   // not access directly outside that function.
154   char input_buf_[Channel::kReadBufferSize];
155 
156   // Large messages that span multiple pipe buffers, get built-up using
157   // this buffer.
158   std::string input_overflow_buf_;
159 
160   // Maximum overflow buffer size, see Channel::kMaximumReadBufferSize.
161   // This is not a constant because we update it to reflect the reality
162   // of std::string::reserve() implementation.
163   size_t max_input_buffer_size_;
164 };
165 
166 }  // namespace internal
167 }  // namespace IPC
168 
169 #endif  // IPC_IPC_CHANNEL_READER_H_
170