Fix emulator build error
[platform/framework/web/chromium-efl.git] / dbus / object_proxy.h
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 DBUS_OBJECT_PROXY_H_
6 #define DBUS_OBJECT_PROXY_H_
7
8 #include <dbus/dbus.h>
9
10 #include <map>
11 #include <memory>
12 #include <set>
13 #include <string>
14 #include <vector>
15
16 #include "base/functional/callback.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/strings/string_piece.h"
19 #include "base/task/sequenced_task_runner.h"
20 #include "base/time/time.h"
21 #include "base/types/expected.h"
22 #include "dbus/dbus_export.h"
23 #include "dbus/error.h"
24 #include "dbus/object_path.h"
25
26 namespace dbus {
27
28 class Bus;
29 class ErrorResponse;
30 class MethodCall;
31 class Response;
32 class Signal;
33
34 // ObjectProxy is used to communicate with remote objects, mainly for
35 // calling methods of these objects.
36 //
37 // ObjectProxy is a ref counted object, to ensure that |this| of the
38 // object is alive when callbacks referencing |this| are called; the
39 // bus always holds at least one of those references so object proxies
40 // always last as long as the bus that created them.
41 class CHROME_DBUS_EXPORT ObjectProxy
42     : public base::RefCountedThreadSafe<ObjectProxy> {
43  public:
44   // Client code should use Bus::GetObjectProxy() or
45   // Bus::GetObjectProxyWithOptions() instead of this constructor.
46   ObjectProxy(Bus* bus,
47               const std::string& service_name,
48               const ObjectPath& object_path,
49               int options);
50
51   ObjectProxy(const ObjectProxy&) = delete;
52   ObjectProxy& operator=(const ObjectProxy&) = delete;
53
54   // Options to be OR-ed together when calling Bus::GetObjectProxyWithOptions().
55   // Set the IGNORE_SERVICE_UNKNOWN_ERRORS option to silence logging of
56   // org.freedesktop.DBus.Error.ServiceUnknown errors and
57   // org.freedesktop.DBus.Error.ObjectUnknown errors.
58   enum Options {
59     DEFAULT_OPTIONS = 0,
60     IGNORE_SERVICE_UNKNOWN_ERRORS = 1 << 0
61   };
62
63   // Special timeout constants.
64   //
65   // The constants correspond to DBUS_TIMEOUT_USE_DEFAULT and
66   // DBUS_TIMEOUT_INFINITE. Here we use literal numbers instead of these
67   // macros as these aren't defined with D-Bus earlier than 1.4.12.
68   enum {
69     TIMEOUT_USE_DEFAULT = -1,
70     TIMEOUT_INFINITE = 0x7fffffff,
71   };
72
73   // Called when an error response is returned or no response is returned.
74   // Used for CallMethodWithErrorCallback().
75   using ErrorCallback = base::OnceCallback<void(ErrorResponse*)>;
76
77   // Called when the response is returned. Used for CallMethod().
78   using ResponseCallback = base::OnceCallback<void(Response*)>;
79
80   // Called when the response is returned or an error occurs. Used for
81   // CallMethodWithErrorResponse().
82   // Note that even in error case, ErrorResponse* may be nullptr.
83   // E.g. out-of-memory error is found in libdbus, or the connection of
84   // |bus_| is not yet established.
85   using ResponseOrErrorCallback =
86       base::OnceCallback<void(Response*, ErrorResponse*)>;
87
88   // Called when a signal is received. Signal* is the incoming signal.
89   using SignalCallback = base::RepeatingCallback<void(Signal*)>;
90
91   // Called when NameOwnerChanged signal is received.
92   using NameOwnerChangedCallback =
93       base::RepeatingCallback<void(const std::string& old_owner,
94                                    const std::string& new_owner)>;
95
96   // Called when the service becomes available.
97   using WaitForServiceToBeAvailableCallback =
98       base::OnceCallback<void(bool service_is_available)>;
99
100   // Called when the object proxy is connected to the signal.
101   // Parameters:
102   // - the interface name.
103   // - the signal name.
104   // - whether it was successful or not.
105   using OnConnectedCallback =
106       base::OnceCallback<void(const std::string&, const std::string&, bool)>;
107
108   // Calls the method of the remote object and blocks until the response
109   // is returned.
110   //
111   // If this is failing due to the reason outside of libdbus, this may return
112   // an invalid error to indicate the situation.
113   // This must be called on D-Bus thread.
114   //
115   // BLOCKING CALL.
116   virtual base::expected<std::unique_ptr<Response>, Error> CallMethodAndBlock(
117       MethodCall* method_call,
118       int timeout_ms);
119
120   // Requests to call the method of the remote object.
121   //
122   // |callback| will be called in the origin thread, once the method call
123   // is complete. As it's called in the origin thread, |callback| can
124   // safely reference objects in the origin thread (i.e. UI thread in most
125   // cases).
126   //
127   // If the method call is successful, a pointer to Response object will
128   // be passed to the callback. If unsuccessful, nullptr will be passed to
129   // the callback.
130   //
131   // Must be called in the origin thread.
132   virtual void CallMethod(MethodCall* method_call,
133                           int timeout_ms,
134                           ResponseCallback callback);
135
136   // Requests to call the method of the remote object.
137   //
138   // This is almost as same as CallMethod() defined above.
139   // The difference is that, the |callback| can take ErrorResponse.
140   // In case of error, ErrorResponse object is passed to the |callback|
141   // if the remote object returned an error, or nullptr if a response was not
142   // received at all (e.g., D-Bus connection is not established). In either
143   // error case, Response* should be nullptr.
144   virtual void CallMethodWithErrorResponse(MethodCall* method_call,
145                                            int timeout_ms,
146                                            ResponseOrErrorCallback callback);
147
148   // DEPRECATED. Please use CallMethodWithErrorResponse() instead.
149   // TODO(hidehiko): Remove this when migration is done.
150   // Requests to call the method of the remote object.
151   //
152   // |callback| and |error_callback| will be called in the origin thread, once
153   // the method call is complete. As it's called in the origin thread,
154   // |callback| can safely reference objects in the origin thread (i.e.
155   // UI thread in most cases).
156   //
157   // If the method call is successful, |callback| will be invoked with a
158   // Response object. If unsuccessful, |error_callback| will be invoked with an
159   // ErrorResponse object (if the remote object returned an error) or nullptr
160   // (if a response was not received at all).
161   //
162   // Must be called in the origin thread.
163   virtual void CallMethodWithErrorCallback(MethodCall* method_call,
164                                            int timeout_ms,
165                                            ResponseCallback callback,
166                                            ErrorCallback error_callback);
167
168   // Requests to connect to the signal from the remote object.
169   //
170   // |signal_callback| will be called in the origin thread, when the
171   // signal is received from the remote object. As it's called in the
172   // origin thread, |signal_callback| can safely reference objects in the
173   // origin thread (i.e. UI thread in most cases).
174   //
175   // |on_connected_callback| is called when the object proxy is connected
176   // to the signal, or failed to be connected, in the origin thread.
177   //
178   // If a SignalCallback has already been registered for the given
179   // |interface_name| and |signal_name|, |signal_callback| will be
180   // added to the list of callbacks for |interface_name| and
181   // |signal_name|.
182   //
183   // Must be called in the origin thread.
184   virtual void ConnectToSignal(const std::string& interface_name,
185                                const std::string& signal_name,
186                                SignalCallback signal_callback,
187                                OnConnectedCallback on_connected_callback);
188
189   // Blocking version of ConnectToSignal.  Returns true on success.  Must be
190   // called from the DBus thread.
191   //
192   // BLOCKING CALL.
193   virtual bool ConnectToSignalAndBlock(const std::string& interface_name,
194                                        const std::string& signal_name,
195                                        SignalCallback signal_callback);
196
197   // Sets a callback for "NameOwnerChanged" signal. The callback is called on
198   // the origin thread when D-Bus system sends "NameOwnerChanged" for the name
199   // represented by |service_name_|.
200   virtual void SetNameOwnerChangedCallback(NameOwnerChangedCallback callback);
201
202   // Registers |callback| to run when the service becomes available. If the
203   // service is already available, or if connecting to the name-owner-changed
204   // signal fails, |callback| will be run once asynchronously. Otherwise,
205   // |callback| will be run once in the future after the service becomes
206   // available.
207   virtual void WaitForServiceToBeAvailable(
208       WaitForServiceToBeAvailableCallback callback);
209
210   // Detaches from the remote object. The Bus object will take care of
211   // detaching so you don't have to do this manually.
212   //
213   // BLOCKING CALL.
214   virtual void Detach();
215
216   const ObjectPath& object_path() const { return object_path_; }
217
218  protected:
219   // This is protected, so we can define sub classes.
220   virtual ~ObjectProxy();
221
222  private:
223   friend class base::RefCountedThreadSafe<ObjectProxy>;
224
225   // Callback passed to CallMethod and its family should be deleted on the
226   // origin thread in any cases. This class manages the work.
227   class ReplyCallbackHolder {
228    public:
229     // Designed to be created on the origin thread.
230     // Both |origin_task_runner| and |callback| must not be null.
231     ReplyCallbackHolder(
232         scoped_refptr<base::SequencedTaskRunner> origin_task_runner,
233         ResponseOrErrorCallback callback);
234
235     // This is movable to be bound to an OnceCallback.
236     ReplyCallbackHolder(ReplyCallbackHolder&& other);
237
238     ReplyCallbackHolder(const ReplyCallbackHolder&) = delete;
239     ReplyCallbackHolder& operator=(const ReplyCallbackHolder&) = delete;
240
241     // |callback_| needs to be destroyed on the origin thread.
242     // If this is not destroyed on non-origin thread, it PostTask()s the
243     // callback to the origin thread for destroying.
244     ~ReplyCallbackHolder();
245
246     // Returns |callback_| with releasing its ownership.
247     // This must be called on the origin thread.
248     ResponseOrErrorCallback ReleaseCallback();
249
250    private:
251     scoped_refptr<base::SequencedTaskRunner> origin_task_runner_;
252     ResponseOrErrorCallback callback_;
253   };
254
255   // Starts the async method call. This is a helper function to implement
256   // CallMethod().
257   void StartAsyncMethodCall(int timeout_ms,
258                             DBusMessage* request_message,
259                             ReplyCallbackHolder callback_holder);
260
261   // Called when the pending call is complete.
262   void OnPendingCallIsComplete(ReplyCallbackHolder callback_holder,
263                                DBusPendingCall* pending_call);
264
265   // Runs the ResponseOrErrorCallback with the given response object.
266   void RunResponseOrErrorCallback(ReplyCallbackHolder callback_holder,
267                                   Response* response,
268                                   ErrorResponse* error_response);
269
270   // Connects to NameOwnerChanged signal.
271   bool ConnectToNameOwnerChangedSignal();
272
273   // Tries to connect to NameOwnerChanged signal, ignores any error.
274   void TryConnectToNameOwnerChangedSignal();
275
276   // Helper function for WaitForServiceToBeAvailable().
277   void WaitForServiceToBeAvailableInternal();
278
279   // Handles the incoming request messages and dispatches to the signal
280   // callbacks.
281   DBusHandlerResult HandleMessage(DBusConnection* connection,
282                                   DBusMessage* raw_message);
283
284   // Runs the method. Helper function for HandleMessage().
285   void RunMethod(std::vector<SignalCallback> signal_callbacks, Signal* signal);
286
287   // Redirects the function call to HandleMessage().
288   static DBusHandlerResult HandleMessageThunk(DBusConnection* connection,
289                                               DBusMessage* raw_message,
290                                               void* user_data);
291
292   // Helper method for logging response errors appropriately.
293   void LogMethodCallFailure(const base::StringPiece& interface_name,
294                             const base::StringPiece& method_name,
295                             const base::StringPiece& error_name,
296                             const base::StringPiece& error_message) const;
297
298   // Used as ResponseOrErrorCallback by CallMethod().
299   // Logs error message, and drops |error_response| from the arguments to pass
300   // |response_callback|.
301   void OnCallMethod(const std::string& interface_name,
302                     const std::string& method_name,
303                     ResponseCallback response_callback,
304                     Response* response,
305                     ErrorResponse* error_response);
306
307   // Adds the match rule to the bus and associate the callback with the signal.
308   bool AddMatchRuleWithCallback(const std::string& match_rule,
309                                 const std::string& absolute_signal_name,
310                                 SignalCallback signal_callback);
311
312   // Adds the match rule to the bus so that HandleMessage can see the signal.
313   bool AddMatchRuleWithoutCallback(const std::string& match_rule,
314                                    const std::string& absolute_signal_name);
315
316   // Calls D-Bus's GetNameOwner method synchronously to update
317   // |service_name_owner_| with the current owner of |service_name_|.
318   //
319   // BLOCKING CALL.
320   void UpdateNameOwnerAndBlock();
321
322   // Handles NameOwnerChanged signal from D-Bus's special message bus.
323   DBusHandlerResult HandleNameOwnerChanged(
324       std::unique_ptr<dbus::Signal> signal);
325
326   // Runs |name_owner_changed_callback_|.
327   void RunNameOwnerChangedCallback(const std::string& old_owner,
328                                    const std::string& new_owner);
329
330   // Runs |wait_for_service_to_be_available_callbacks_|.
331   void RunWaitForServiceToBeAvailableCallbacks(bool service_is_available);
332
333   scoped_refptr<Bus> bus_;
334   std::string service_name_;
335   ObjectPath object_path_;
336
337   // The method table where keys are absolute signal names (i.e. interface
338   // name + signal name), and values are lists of the corresponding callbacks.
339   using MethodTable = std::map<std::string, std::vector<SignalCallback>>;
340   MethodTable method_table_;
341
342   // The callback called when NameOwnerChanged signal is received.
343   NameOwnerChangedCallback name_owner_changed_callback_;
344
345   // Called when the service becomes available.
346   std::vector<WaitForServiceToBeAvailableCallback>
347       wait_for_service_to_be_available_callbacks_;
348
349   std::set<std::string> match_rules_;
350
351   const bool ignore_service_unknown_errors_;
352
353   // Known name owner of the well-known bus name represented by |service_name_|.
354   std::string service_name_owner_;
355
356   std::set<DBusPendingCall*> pending_calls_;
357 };
358
359 }  // namespace dbus
360
361 #endif  // DBUS_OBJECT_PROXY_H_