• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
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/callback.h"
17 #include "base/macros.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/strings/string_piece.h"
20 #include "base/time/time.h"
21 #include "dbus/dbus_export.h"
22 #include "dbus/object_path.h"
23 
24 namespace dbus {
25 
26 class Bus;
27 class ErrorResponse;
28 class MethodCall;
29 class Response;
30 class ScopedDBusError;
31 class Signal;
32 
33 // ObjectProxy is used to communicate with remote objects, mainly for
34 // calling methods of these objects.
35 //
36 // ObjectProxy is a ref counted object, to ensure that |this| of the
37 // object is alive when callbacks referencing |this| are called; the
38 // bus always holds at least one of those references so object proxies
39 // always last as long as the bus that created them.
40 class CHROME_DBUS_EXPORT ObjectProxy
41     : public base::RefCountedThreadSafe<ObjectProxy> {
42  public:
43   // Client code should use Bus::GetObjectProxy() or
44   // Bus::GetObjectProxyWithOptions() instead of this constructor.
45   ObjectProxy(Bus* bus,
46               const std::string& service_name,
47               const ObjectPath& object_path,
48               int options);
49 
50   // Options to be OR-ed together when calling Bus::GetObjectProxyWithOptions().
51   // Set the IGNORE_SERVICE_UNKNOWN_ERRORS option to silence logging of
52   // org.freedesktop.DBus.Error.ServiceUnknown errors and
53   // org.freedesktop.DBus.Error.ObjectUnknown errors.
54   enum Options {
55     DEFAULT_OPTIONS = 0,
56     IGNORE_SERVICE_UNKNOWN_ERRORS = 1 << 0
57   };
58 
59   // Special timeout constants.
60   //
61   // The constants correspond to DBUS_TIMEOUT_USE_DEFAULT and
62   // DBUS_TIMEOUT_INFINITE. Here we use literal numbers instead of these
63   // macros as these aren't defined with D-Bus earlier than 1.4.12.
64   enum {
65     TIMEOUT_USE_DEFAULT = -1,
66     TIMEOUT_INFINITE = 0x7fffffff,
67   };
68 
69   // Called when an error response is returned or no response is returned.
70   // Used for CallMethodWithErrorCallback().
71   typedef base::Callback<void(ErrorResponse*)> ErrorCallback;
72 
73   // Called when the response is returned. Used for CallMethod().
74   typedef base::Callback<void(Response*)> ResponseCallback;
75 
76   // Called when a signal is received. Signal* is the incoming signal.
77   typedef base::Callback<void (Signal*)> SignalCallback;
78 
79   // Called when NameOwnerChanged signal is received.
80   typedef base::Callback<void(
81       const std::string& old_owner,
82       const std::string& new_owner)> NameOwnerChangedCallback;
83 
84   // Called when the service becomes available.
85   typedef base::Callback<void(
86       bool service_is_available)> WaitForServiceToBeAvailableCallback;
87 
88   // Called when the object proxy is connected to the signal.
89   // Parameters:
90   // - the interface name.
91   // - the signal name.
92   // - whether it was successful or not.
93   typedef base::Callback<void (const std::string&, const std::string&, bool)>
94       OnConnectedCallback;
95 
96   // Calls the method of the remote object and blocks until the response
97   // is returned. Returns NULL on error with the error details specified
98   // in the |error| object.
99   //
100   // BLOCKING CALL.
101   virtual std::unique_ptr<Response> CallMethodAndBlockWithErrorDetails(
102       MethodCall* method_call,
103       int timeout_ms,
104       ScopedDBusError* error);
105 
106   // Calls the method of the remote object and blocks until the response
107   // is returned. Returns NULL on error.
108   //
109   // BLOCKING CALL.
110   virtual std::unique_ptr<Response> CallMethodAndBlock(MethodCall* method_call,
111                                                        int timeout_ms);
112 
113   // Requests to call the method of the remote object.
114   //
115   // |callback| will be called in the origin thread, once the method call
116   // is complete. As it's called in the origin thread, |callback| can
117   // safely reference objects in the origin thread (i.e. UI thread in most
118   // cases). If the caller is not interested in the response from the
119   // method (i.e. calling a method that does not return a value),
120   // EmptyResponseCallback() can be passed to the |callback| parameter.
121   //
122   // If the method call is successful, a pointer to Response object will
123   // be passed to the callback. If unsuccessful, NULL will be passed to
124   // the callback.
125   //
126   // Must be called in the origin thread.
127   virtual void CallMethod(MethodCall* method_call,
128                           int timeout_ms,
129                           ResponseCallback callback);
130 
131   // Requests to call the method of the remote object.
132   //
133   // |callback| and |error_callback| will be called in the origin thread, once
134   // the method call is complete. As it's called in the origin thread,
135   // |callback| can safely reference objects in the origin thread (i.e.
136   // UI thread in most cases). If the caller is not interested in the response
137   // from the method (i.e. calling a method that does not return a value),
138   // EmptyResponseCallback() can be passed to the |callback| parameter.
139   //
140   // If the method call is successful, a pointer to Response object will
141   // be passed to the callback. If unsuccessful, the error callback will be
142   // called and a pointer to ErrorResponse object will be passed to the error
143   // callback if available, otherwise NULL will be passed.
144   //
145   // Must be called in the origin thread.
146   virtual void CallMethodWithErrorCallback(MethodCall* method_call,
147                                            int timeout_ms,
148                                            ResponseCallback callback,
149                                            ErrorCallback error_callback);
150 
151   // Requests to connect to the signal from the remote object.
152   //
153   // |signal_callback| will be called in the origin thread, when the
154   // signal is received from the remote object. As it's called in the
155   // origin thread, |signal_callback| can safely reference objects in the
156   // origin thread (i.e. UI thread in most cases).
157   //
158   // |on_connected_callback| is called when the object proxy is connected
159   // to the signal, or failed to be connected, in the origin thread.
160   //
161   // If a SignalCallback has already been registered for the given
162   // |interface_name| and |signal_name|, |signal_callback| will be
163   // added to the list of callbacks for |interface_name| and
164   // |signal_name|.
165   //
166   // Must be called in the origin thread.
167   virtual void ConnectToSignal(const std::string& interface_name,
168                                const std::string& signal_name,
169                                SignalCallback signal_callback,
170                                OnConnectedCallback on_connected_callback);
171 
172   // Sets a callback for "NameOwnerChanged" signal. The callback is called on
173   // the origin thread when D-Bus system sends "NameOwnerChanged" for the name
174   // represented by |service_name_|.
175   virtual void SetNameOwnerChangedCallback(NameOwnerChangedCallback callback);
176 
177   // Runs the callback as soon as the service becomes available.
178   virtual void WaitForServiceToBeAvailable(
179       WaitForServiceToBeAvailableCallback callback);
180 
181   // Detaches from the remote object. The Bus object will take care of
182   // detaching so you don't have to do this manually.
183   //
184   // BLOCKING CALL.
185   virtual void Detach();
186 
object_path()187   const ObjectPath& object_path() const { return object_path_; }
188 
189   // Returns an empty callback that does nothing. Can be used for
190   // CallMethod().
191   static ResponseCallback EmptyResponseCallback();
192 
193  protected:
194   // This is protected, so we can define sub classes.
195   virtual ~ObjectProxy();
196 
197  private:
198   friend class base::RefCountedThreadSafe<ObjectProxy>;
199 
200   // Struct of data we'll be passing from StartAsyncMethodCall() to
201   // OnPendingCallIsCompleteThunk().
202   struct OnPendingCallIsCompleteData {
203     OnPendingCallIsCompleteData(ObjectProxy* in_object_proxy,
204                                 ResponseCallback in_response_callback,
205                                 ErrorCallback error_callback,
206                                 base::TimeTicks start_time);
207     ~OnPendingCallIsCompleteData();
208 
209     ObjectProxy* object_proxy;
210     ResponseCallback response_callback;
211     ErrorCallback error_callback;
212     base::TimeTicks start_time;
213   };
214 
215   // Starts the async method call. This is a helper function to implement
216   // CallMethod().
217   void StartAsyncMethodCall(int timeout_ms,
218                             DBusMessage* request_message,
219                             ResponseCallback response_callback,
220                             ErrorCallback error_callback,
221                             base::TimeTicks start_time);
222 
223   // Called when the pending call is complete.
224   void OnPendingCallIsComplete(DBusPendingCall* pending_call,
225                                ResponseCallback response_callback,
226                                ErrorCallback error_callback,
227                                base::TimeTicks start_time);
228 
229   // Runs the response callback with the given response object.
230   void RunResponseCallback(ResponseCallback response_callback,
231                            ErrorCallback error_callback,
232                            base::TimeTicks start_time,
233                            DBusMessage* response_message);
234 
235   // Redirects the function call to OnPendingCallIsComplete().
236   static void OnPendingCallIsCompleteThunk(DBusPendingCall* pending_call,
237                                            void* user_data);
238 
239   // Connects to NameOwnerChanged signal.
240   bool ConnectToNameOwnerChangedSignal();
241 
242   // Helper function for ConnectToSignal().
243   bool ConnectToSignalInternal(const std::string& interface_name,
244                                const std::string& signal_name,
245                                SignalCallback signal_callback);
246 
247   // Helper function for WaitForServiceToBeAvailable().
248   void WaitForServiceToBeAvailableInternal();
249 
250   // Handles the incoming request messages and dispatches to the signal
251   // callbacks.
252   DBusHandlerResult HandleMessage(DBusConnection* connection,
253                                   DBusMessage* raw_message);
254 
255   // Runs the method. Helper function for HandleMessage().
256   void RunMethod(base::TimeTicks start_time,
257                  std::vector<SignalCallback> signal_callbacks,
258                  Signal* signal);
259 
260   // Redirects the function call to HandleMessage().
261   static DBusHandlerResult HandleMessageThunk(DBusConnection* connection,
262                                               DBusMessage* raw_message,
263                                               void* user_data);
264 
265   // Helper method for logging response errors appropriately.
266   void LogMethodCallFailure(const base::StringPiece& interface_name,
267                             const base::StringPiece& method_name,
268                             const base::StringPiece& error_name,
269                             const base::StringPiece& error_message) const;
270 
271   // Used as ErrorCallback by CallMethod().
272   void OnCallMethodError(const std::string& interface_name,
273                          const std::string& method_name,
274                          ResponseCallback response_callback,
275                          ErrorResponse* error_response);
276 
277   // Adds the match rule to the bus and associate the callback with the signal.
278   bool AddMatchRuleWithCallback(const std::string& match_rule,
279                                 const std::string& absolute_signal_name,
280                                 SignalCallback signal_callback);
281 
282   // Adds the match rule to the bus so that HandleMessage can see the signal.
283   bool AddMatchRuleWithoutCallback(const std::string& match_rule,
284                                    const std::string& absolute_signal_name);
285 
286   // Calls D-Bus's GetNameOwner method synchronously to update
287   // |service_name_owner_| with the current owner of |service_name_|.
288   //
289   // BLOCKING CALL.
290   void UpdateNameOwnerAndBlock();
291 
292   // Handles NameOwnerChanged signal from D-Bus's special message bus.
293   DBusHandlerResult HandleNameOwnerChanged(
294       std::unique_ptr<dbus::Signal> signal);
295 
296   // Runs |name_owner_changed_callback_|.
297   void RunNameOwnerChangedCallback(const std::string& old_owner,
298                                    const std::string& new_owner);
299 
300   // Runs |wait_for_service_to_be_available_callbacks_|.
301   void RunWaitForServiceToBeAvailableCallbacks(bool service_is_available);
302 
303   scoped_refptr<Bus> bus_;
304   std::string service_name_;
305   ObjectPath object_path_;
306 
307   // The method table where keys are absolute signal names (i.e. interface
308   // name + signal name), and values are lists of the corresponding callbacks.
309   typedef std::map<std::string, std::vector<SignalCallback> > MethodTable;
310   MethodTable method_table_;
311 
312   // The callback called when NameOwnerChanged signal is received.
313   NameOwnerChangedCallback name_owner_changed_callback_;
314 
315   // Called when the service becomes available.
316   std::vector<WaitForServiceToBeAvailableCallback>
317       wait_for_service_to_be_available_callbacks_;
318 
319   std::set<std::string> match_rules_;
320 
321   const bool ignore_service_unknown_errors_;
322 
323   // Known name owner of the well-known bus name represented by |service_name_|.
324   std::string service_name_owner_;
325 
326   std::set<DBusPendingCall*> pending_calls_;
327 
328   DISALLOW_COPY_AND_ASSIGN(ObjectProxy);
329 };
330 
331 }  // namespace dbus
332 
333 #endif  // DBUS_OBJECT_PROXY_H_
334