1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef DBUS_OBJECT_PROXY_H_
6 #define DBUS_OBJECT_PROXY_H_
16 #include "base/callback.h"
17 #include "base/macros.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/sequenced_task_runner.h"
20 #include "base/strings/string_piece.h"
21 #include "base/time/time.h"
22 #include "dbus/dbus_export.h"
23 #include "dbus/object_path.h"
31 class ScopedDBusError;
34 // ObjectProxy is used to communicate with remote objects, mainly for
35 // calling methods of these objects.
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> {
44 // Client code should use Bus::GetObjectProxy() or
45 // Bus::GetObjectProxyWithOptions() instead of this constructor.
47 const std::string& service_name,
48 const ObjectPath& object_path,
51 // Options to be OR-ed together when calling Bus::GetObjectProxyWithOptions().
52 // Set the IGNORE_SERVICE_UNKNOWN_ERRORS option to silence logging of
53 // org.freedesktop.DBus.Error.ServiceUnknown errors and
54 // org.freedesktop.DBus.Error.ObjectUnknown errors.
57 IGNORE_SERVICE_UNKNOWN_ERRORS = 1 << 0
60 // Special timeout constants.
62 // The constants correspond to DBUS_TIMEOUT_USE_DEFAULT and
63 // DBUS_TIMEOUT_INFINITE. Here we use literal numbers instead of these
64 // macros as these aren't defined with D-Bus earlier than 1.4.12.
66 TIMEOUT_USE_DEFAULT = -1,
67 TIMEOUT_INFINITE = 0x7fffffff,
70 // Called when an error response is returned or no response is returned.
71 // Used for CallMethodWithErrorCallback().
72 using ErrorCallback = base::OnceCallback<void(ErrorResponse*)>;
74 // Called when the response is returned. Used for CallMethod().
75 using ResponseCallback = base::OnceCallback<void(Response*)>;
77 // Called when the response is returned or an error occurs. Used for
78 // CallMethodWithErrorResponse().
79 // Note that even in error case, ErrorResponse* may be nullptr.
80 // E.g. out-of-memory error is found in libdbus, or the connection of
81 // |bus_| is not yet established.
82 using ResponseOrErrorCallback =
83 base::OnceCallback<void(Response*, ErrorResponse*)>;
85 // Called when a signal is received. Signal* is the incoming signal.
86 using SignalCallback = base::RepeatingCallback<void(Signal*)>;
88 // Called when NameOwnerChanged signal is received.
89 using NameOwnerChangedCallback =
90 base::RepeatingCallback<void(const std::string& old_owner,
91 const std::string& new_owner)>;
93 // Called when the service becomes available.
94 using WaitForServiceToBeAvailableCallback =
95 base::OnceCallback<void(bool service_is_available)>;
97 // Called when the object proxy is connected to the signal.
99 // - the interface name.
100 // - the signal name.
101 // - whether it was successful or not.
102 using OnConnectedCallback =
103 base::OnceCallback<void(const std::string&, const std::string&, bool)>;
105 // Calls the method of the remote object and blocks until the response
106 // is returned. Returns NULL on error with the error details specified
107 // in the |error| object.
110 virtual std::unique_ptr<Response> CallMethodAndBlockWithErrorDetails(
111 MethodCall* method_call,
113 ScopedDBusError* error);
115 // Calls the method of the remote object and blocks until the response
116 // is returned. Returns NULL on error.
119 virtual std::unique_ptr<Response> CallMethodAndBlock(MethodCall* method_call,
122 // Requests to call the method of the remote object.
124 // |callback| will be called in the origin thread, once the method call
125 // is complete. As it's called in the origin thread, |callback| can
126 // safely reference objects in the origin thread (i.e. UI thread in most
129 // If the method call is successful, a pointer to Response object will
130 // be passed to the callback. If unsuccessful, nullptr will be passed to
133 // Must be called in the origin thread.
134 virtual void CallMethod(MethodCall* method_call,
136 ResponseCallback callback);
138 // Requests to call the method of the remote object.
140 // This is almost as same as CallMethod() defined above.
141 // The difference is that, the |callback| can take ErrorResponse.
142 // In case of error, ErrorResponse object is passed to the |callback|
143 // if the remote object returned an error, or nullptr if a response was not
144 // received at all (e.g., D-Bus connection is not established). In either
145 // error case, Response* should be nullptr.
146 virtual void CallMethodWithErrorResponse(MethodCall* method_call,
148 ResponseOrErrorCallback callback);
150 // DEPRECATED. Please use CallMethodWithErrorResponse() instead.
151 // TODO(hidehiko): Remove this when migration is done.
152 // Requests to call the method of the remote object.
154 // |callback| and |error_callback| will be called in the origin thread, once
155 // the method call is complete. As it's called in the origin thread,
156 // |callback| can safely reference objects in the origin thread (i.e.
157 // UI thread in most cases).
159 // If the method call is successful, |callback| will be invoked with a
160 // Response object. If unsuccessful, |error_callback| will be invoked with an
161 // ErrorResponse object (if the remote object returned an error) or nullptr
162 // (if a response was not received at all).
164 // Must be called in the origin thread.
165 virtual void CallMethodWithErrorCallback(MethodCall* method_call,
167 ResponseCallback callback,
168 ErrorCallback error_callback);
170 // Requests to connect to the signal from the remote object.
172 // |signal_callback| will be called in the origin thread, when the
173 // signal is received from the remote object. As it's called in the
174 // origin thread, |signal_callback| can safely reference objects in the
175 // origin thread (i.e. UI thread in most cases).
177 // |on_connected_callback| is called when the object proxy is connected
178 // to the signal, or failed to be connected, in the origin thread.
180 // If a SignalCallback has already been registered for the given
181 // |interface_name| and |signal_name|, |signal_callback| will be
182 // added to the list of callbacks for |interface_name| and
185 // Must be called in the origin thread.
186 virtual void ConnectToSignal(const std::string& interface_name,
187 const std::string& signal_name,
188 SignalCallback signal_callback,
189 OnConnectedCallback on_connected_callback);
191 // Blocking version of ConnectToSignal. Returns true on success. Must be
192 // called from the DBus thread.
195 virtual bool ConnectToSignalAndBlock(const std::string& interface_name,
196 const std::string& signal_name,
197 SignalCallback signal_callback);
199 // Sets a callback for "NameOwnerChanged" signal. The callback is called on
200 // the origin thread when D-Bus system sends "NameOwnerChanged" for the name
201 // represented by |service_name_|.
202 virtual void SetNameOwnerChangedCallback(NameOwnerChangedCallback callback);
204 // Registers |callback| to run when the service becomes available. If the
205 // service is already available, or if connecting to the name-owner-changed
206 // signal fails, |callback| will be run once asynchronously. Otherwise,
207 // |callback| will be run once in the future after the service becomes
209 virtual void WaitForServiceToBeAvailable(
210 WaitForServiceToBeAvailableCallback callback);
212 // Detaches from the remote object. The Bus object will take care of
213 // detaching so you don't have to do this manually.
216 virtual void Detach();
218 const ObjectPath& object_path() const { return object_path_; }
221 // This is protected, so we can define sub classes.
222 virtual ~ObjectProxy();
225 friend class base::RefCountedThreadSafe<ObjectProxy>;
227 // Callback passed to CallMethod and its family should be deleted on the
228 // origin thread in any cases. This class manages the work.
229 class ReplyCallbackHolder {
231 // Designed to be created on the origin thread.
232 // Both |origin_task_runner| and |callback| must not be null.
234 scoped_refptr<base::SequencedTaskRunner> origin_task_runner,
235 ResponseOrErrorCallback callback);
237 // This is movable to be bound to an OnceCallback.
238 ReplyCallbackHolder(ReplyCallbackHolder&& other);
240 // |callback_| needs to be destroyed on the origin thread.
241 // If this is not destroyed on non-origin thread, it PostTask()s the
242 // callback to the origin thread for destroying.
243 ~ReplyCallbackHolder();
245 // Returns |callback_| with releasing its ownership.
246 // This must be called on the origin thread.
247 ResponseOrErrorCallback ReleaseCallback();
249 // Whether |callback_| is null.
250 // TODO(http://crbug/1211451): Remove after fix.
251 bool IsNullCallback() const;
254 scoped_refptr<base::SequencedTaskRunner> origin_task_runner_;
255 ResponseOrErrorCallback callback_;
256 DISALLOW_COPY_AND_ASSIGN(ReplyCallbackHolder);
259 // Starts the async method call. This is a helper function to implement
261 void StartAsyncMethodCall(int timeout_ms,
262 DBusMessage* request_message,
263 ReplyCallbackHolder callback_holder,
264 base::TimeTicks start_time);
266 // Called when the pending call is complete.
267 void OnPendingCallIsComplete(ReplyCallbackHolder callback_holder,
268 base::TimeTicks start_time,
269 DBusPendingCall* pending_call);
271 // Runs the ResponseOrErrorCallback with the given response object.
272 void RunResponseOrErrorCallback(ReplyCallbackHolder callback_holderk,
273 base::TimeTicks start_time,
275 ErrorResponse* error_response);
277 // Connects to NameOwnerChanged signal.
278 bool ConnectToNameOwnerChangedSignal();
280 // Tries to connect to NameOwnerChanged signal, ignores any error.
281 void TryConnectToNameOwnerChangedSignal();
283 // Helper function for WaitForServiceToBeAvailable().
284 void WaitForServiceToBeAvailableInternal();
286 // Handles the incoming request messages and dispatches to the signal
288 DBusHandlerResult HandleMessage(DBusConnection* connection,
289 DBusMessage* raw_message);
291 // Runs the method. Helper function for HandleMessage().
292 void RunMethod(base::TimeTicks start_time,
293 std::vector<SignalCallback> signal_callbacks,
296 // Redirects the function call to HandleMessage().
297 static DBusHandlerResult HandleMessageThunk(DBusConnection* connection,
298 DBusMessage* raw_message,
301 // Helper method for logging response errors appropriately.
302 void LogMethodCallFailure(const base::StringPiece& interface_name,
303 const base::StringPiece& method_name,
304 const base::StringPiece& error_name,
305 const base::StringPiece& error_message) const;
307 // Used as ResponseOrErrorCallback by CallMethod().
308 // Logs error message, and drops |error_response| from the arguments to pass
309 // |response_callback|.
310 void OnCallMethod(const std::string& interface_name,
311 const std::string& method_name,
312 ResponseCallback response_callback,
314 ErrorResponse* error_response);
316 // Adds the match rule to the bus and associate the callback with the signal.
317 bool AddMatchRuleWithCallback(const std::string& match_rule,
318 const std::string& absolute_signal_name,
319 SignalCallback signal_callback);
321 // Adds the match rule to the bus so that HandleMessage can see the signal.
322 bool AddMatchRuleWithoutCallback(const std::string& match_rule,
323 const std::string& absolute_signal_name);
325 // Calls D-Bus's GetNameOwner method synchronously to update
326 // |service_name_owner_| with the current owner of |service_name_|.
329 void UpdateNameOwnerAndBlock();
331 // Handles NameOwnerChanged signal from D-Bus's special message bus.
332 DBusHandlerResult HandleNameOwnerChanged(
333 std::unique_ptr<dbus::Signal> signal);
335 // Runs |name_owner_changed_callback_|.
336 void RunNameOwnerChangedCallback(const std::string& old_owner,
337 const std::string& new_owner);
339 // Runs |wait_for_service_to_be_available_callbacks_|.
340 void RunWaitForServiceToBeAvailableCallbacks(bool service_is_available);
342 scoped_refptr<Bus> bus_;
343 std::string service_name_;
344 ObjectPath object_path_;
346 // The method table where keys are absolute signal names (i.e. interface
347 // name + signal name), and values are lists of the corresponding callbacks.
348 using MethodTable = std::map<std::string, std::vector<SignalCallback>>;
349 MethodTable method_table_;
351 // The callback called when NameOwnerChanged signal is received.
352 NameOwnerChangedCallback name_owner_changed_callback_;
354 // Called when the service becomes available.
355 std::vector<WaitForServiceToBeAvailableCallback>
356 wait_for_service_to_be_available_callbacks_;
358 std::set<std::string> match_rules_;
360 const bool ignore_service_unknown_errors_;
362 // Known name owner of the well-known bus name represented by |service_name_|.
363 std::string service_name_owner_;
365 std::set<DBusPendingCall*> pending_calls_;
367 DISALLOW_COPY_AND_ASSIGN(ObjectProxy);
372 #endif // DBUS_OBJECT_PROXY_H_