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