bus.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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. #ifndef DBUS_BUS_H_
  5. #define DBUS_BUS_H_
  6. #include <dbus/dbus.h>
  7. #include <stdint.h>
  8. #include <map>
  9. #include <set>
  10. #include <string>
  11. #include <utility>
  12. #include <vector>
  13. #include "base/callback.h"
  14. #include "base/memory/raw_ptr.h"
  15. #include "base/memory/ref_counted.h"
  16. #include "base/synchronization/waitable_event.h"
  17. #include "base/threading/platform_thread.h"
  18. #include "dbus/dbus_export.h"
  19. #include "dbus/object_path.h"
  20. namespace base {
  21. class SequencedTaskRunner;
  22. }
  23. namespace dbus {
  24. class ExportedObject;
  25. class ObjectManager;
  26. class ObjectProxy;
  27. // Bus is used to establish a connection with D-Bus, create object
  28. // proxies, and export objects.
  29. //
  30. // For asynchronous operations such as an asynchronous method call, the
  31. // bus object will use a task runner to monitor the underlying file
  32. // descriptor used for D-Bus communication. By default, the bus will use
  33. // the current thread's task runner. If |dbus_task_runner| option is
  34. // specified, the bus will use that task runner instead.
  35. //
  36. // THREADING
  37. //
  38. // In the D-Bus library, we use the two threads:
  39. //
  40. // - The origin thread: the thread that created the Bus object.
  41. // - The D-Bus thread: the thread servicing |dbus_task_runner|.
  42. //
  43. // The origin thread is usually Chrome's UI thread. The D-Bus thread is
  44. // usually a dedicated thread for the D-Bus library.
  45. //
  46. // BLOCKING CALLS
  47. //
  48. // Functions that issue blocking calls are marked "BLOCKING CALL" and
  49. // these functions should be called in the D-Bus thread (if
  50. // supplied). AssertOnDBusThread() is placed in these functions.
  51. //
  52. // Note that it's hard to tell if a libdbus function is actually blocking
  53. // or not (ex. dbus_bus_request_name() internally calls
  54. // dbus_connection_send_with_reply_and_block(), which is a blocking
  55. // call). To err on the safe side, we consider all libdbus functions that
  56. // deal with the connection to dbus-daemon to be blocking.
  57. //
  58. // SHUTDOWN
  59. //
  60. // The Bus object must be shut down manually by ShutdownAndBlock() and
  61. // friends. We require the manual shutdown to make the operation explicit
  62. // rather than doing it silently in the destructor.
  63. //
  64. // EXAMPLE USAGE:
  65. //
  66. // Synchronous method call:
  67. //
  68. // dbus::Bus::Options options;
  69. // // Set up the bus options here.
  70. // ...
  71. // dbus::Bus bus(options);
  72. //
  73. // dbus::ObjectProxy* object_proxy =
  74. // bus.GetObjectProxy(service_name, object_path);
  75. //
  76. // dbus::MethodCall method_call(interface_name, method_name);
  77. // std::unique_ptr<dbus::Response> response(
  78. // object_proxy.CallMethodAndBlock(&method_call, timeout_ms));
  79. // if (response.get() != nullptr) { // Success.
  80. // ...
  81. // }
  82. //
  83. // Asynchronous method call:
  84. //
  85. // void OnResponse(dbus::Response* response) {
  86. // // response is NULL if the method call failed.
  87. // if (!response)
  88. // return;
  89. // }
  90. //
  91. // ...
  92. // object_proxy.CallMethod(&method_call, timeout_ms,
  93. // base::BindOnce(&OnResponse));
  94. //
  95. // Exporting a method:
  96. //
  97. // void Echo(dbus::MethodCall* method_call,
  98. // dbus::ExportedObject::ResponseSender response_sender) {
  99. // // Do something with method_call.
  100. // Response* response = Response::FromMethodCall(method_call);
  101. // // Build response here.
  102. // // Can send an immediate response here to implement a synchronous service
  103. // // or store the response_sender and send a response later to implement an
  104. // // asynchronous service.
  105. // std::move(response_sender).Run(response);
  106. // }
  107. //
  108. // void OnExported(const std::string& interface_name,
  109. // const ObjectPath& object_path,
  110. // bool success) {
  111. // // success is true if the method was exported successfully.
  112. // }
  113. //
  114. // ...
  115. // dbus::ExportedObject* exported_object =
  116. // bus.GetExportedObject(service_name, object_path);
  117. // exported_object.ExportMethod(interface_name, method_name,
  118. // base::BindRepeating(&Echo),
  119. // base::BindOnce(&OnExported));
  120. //
  121. // WHY IS THIS A REF COUNTED OBJECT?
  122. //
  123. // Bus is a ref counted object, to ensure that |this| of the object is
  124. // alive when callbacks referencing |this| are called. However, after the
  125. // bus is shut down, |connection_| can be NULL. Hence, callbacks should
  126. // not rely on that |connection_| is alive.
  127. class CHROME_DBUS_EXPORT Bus : public base::RefCountedThreadSafe<Bus> {
  128. public:
  129. // Specifies the bus type. SESSION is used to communicate with per-user
  130. // services like GNOME applications. SYSTEM is used to communicate with
  131. // system-wide services like NetworkManager. CUSTOM_ADDRESS is used to
  132. // communicate with an user specified address.
  133. enum BusType {
  134. SESSION = DBUS_BUS_SESSION,
  135. SYSTEM = DBUS_BUS_SYSTEM,
  136. CUSTOM_ADDRESS,
  137. };
  138. // Specifies the connection type. PRIVATE should usually be used unless
  139. // you are sure that SHARED is safe for you, which is unlikely the case
  140. // in Chrome.
  141. //
  142. // PRIVATE gives you a private connection, that won't be shared with
  143. // other Bus objects.
  144. //
  145. // SHARED gives you a connection shared among other Bus objects, which
  146. // is unsafe if the connection is shared with multiple threads.
  147. enum ConnectionType {
  148. PRIVATE,
  149. SHARED,
  150. };
  151. // Specifies whether the GetServiceOwnerAndBlock call should report or
  152. // suppress errors.
  153. enum GetServiceOwnerOption {
  154. REPORT_ERRORS,
  155. SUPPRESS_ERRORS,
  156. };
  157. // Specifies service ownership options.
  158. //
  159. // REQUIRE_PRIMARY indicates that you require primary ownership of the
  160. // service name.
  161. //
  162. // ALLOW_REPLACEMENT indicates that you'll allow another connection to
  163. // steal ownership of this service name from you.
  164. //
  165. // REQUIRE_PRIMARY_ALLOW_REPLACEMENT does the obvious.
  166. enum ServiceOwnershipOptions {
  167. REQUIRE_PRIMARY = (DBUS_NAME_FLAG_DO_NOT_QUEUE |
  168. DBUS_NAME_FLAG_REPLACE_EXISTING),
  169. REQUIRE_PRIMARY_ALLOW_REPLACEMENT = (REQUIRE_PRIMARY |
  170. DBUS_NAME_FLAG_ALLOW_REPLACEMENT),
  171. };
  172. // Options used to create a Bus object.
  173. struct CHROME_DBUS_EXPORT Options {
  174. Options();
  175. ~Options();
  176. Options(Options&&);
  177. Options& operator=(Options&&);
  178. BusType bus_type; // SESSION by default.
  179. ConnectionType connection_type; // PRIVATE by default.
  180. // If dbus_task_runner is set, the bus object will use that
  181. // task runner to process asynchronous operations.
  182. //
  183. // The thread servicing the task runner should meet the following
  184. // requirements:
  185. // 1) Already running.
  186. // 2) Has a MessageLoopForIO.
  187. scoped_refptr<base::SequencedTaskRunner> dbus_task_runner;
  188. // Specifies the server addresses to be connected. If you want to
  189. // communicate with non dbus-daemon such as ibus-daemon, set |bus_type| to
  190. // CUSTOM_ADDRESS, and |address| to the D-Bus server address you want to
  191. // connect to. The format of this address value is the dbus address style
  192. // which is described in
  193. // http://dbus.freedesktop.org/doc/dbus-specification.html#addresses
  194. //
  195. // EXAMPLE USAGE:
  196. // dbus::Bus::Options options;
  197. // options.bus_type = CUSTOM_ADDRESS;
  198. // options.address.assign("unix:path=/tmp/dbus-XXXXXXX");
  199. // // Set up other options
  200. // dbus::Bus bus(options);
  201. //
  202. // // Do something.
  203. //
  204. std::string address;
  205. };
  206. // Creates a Bus object. The actual connection will be established when
  207. // Connect() is called.
  208. explicit Bus(const Options& options);
  209. Bus(const Bus&) = delete;
  210. Bus& operator=(const Bus&) = delete;
  211. // Called when an ownership request is complete.
  212. // Parameters:
  213. // - the requested service name.
  214. // - whether ownership has been obtained or not.
  215. using OnOwnershipCallback =
  216. base::OnceCallback<void(const std::string&, bool)>;
  217. // Called when GetServiceOwner() completes.
  218. // |service_owner| is the return value from GetServiceOwnerAndBlock().
  219. using GetServiceOwnerCallback =
  220. base::OnceCallback<void(const std::string& service_owner)>;
  221. // Called when a service owner changes.
  222. using ServiceOwnerChangeCallback =
  223. base::RepeatingCallback<void(const std::string& service_owner)>;
  224. // TODO(satorux): Remove the service name parameter as the caller of
  225. // RequestOwnership() knows the service name.
  226. // Gets the object proxy for the given service name and the object path.
  227. // The caller must not delete the returned object.
  228. //
  229. // Returns an existing object proxy if the bus object already owns the
  230. // object proxy for the given service name and the object path.
  231. // Never returns NULL.
  232. //
  233. // The bus will own all object proxies created by the bus, to ensure
  234. // that the object proxies are detached from remote objects at the
  235. // shutdown time of the bus.
  236. //
  237. // The object proxy is used to call methods of remote objects, and
  238. // receive signals from them.
  239. //
  240. // |service_name| looks like "org.freedesktop.NetworkManager", and
  241. // |object_path| looks like "/org/freedesktop/NetworkManager/Devices/0".
  242. //
  243. // Must be called in the origin thread.
  244. virtual ObjectProxy* GetObjectProxy(const std::string& service_name,
  245. const ObjectPath& object_path);
  246. // Same as above, but also takes a bitfield of ObjectProxy::Options.
  247. // See object_proxy.h for available options.
  248. virtual ObjectProxy* GetObjectProxyWithOptions(
  249. const std::string& service_name,
  250. const ObjectPath& object_path,
  251. int options);
  252. // Removes the previously created object proxy for the given service
  253. // name and the object path and releases its memory.
  254. //
  255. // If and object proxy for the given service name and object was
  256. // created with GetObjectProxy, this function removes it from the
  257. // bus object and detaches the ObjectProxy, invalidating any pointer
  258. // previously acquired for it with GetObjectProxy. A subsequent call
  259. // to GetObjectProxy will return a new object.
  260. //
  261. // All the object proxies are detached from remote objects at the
  262. // shutdown time of the bus, but they can be detached early to reduce
  263. // memory footprint and used match rules for the bus connection.
  264. //
  265. // |service_name| looks like "org.freedesktop.NetworkManager", and
  266. // |object_path| looks like "/org/freedesktop/NetworkManager/Devices/0".
  267. // |callback| is called when the object proxy is successfully removed and
  268. // detached.
  269. //
  270. // The function returns true when there is an object proxy matching the
  271. // |service_name| and |object_path| to remove, and calls |callback| when it
  272. // is removed. Otherwise, it returns false and the |callback| function is
  273. // never called. The |callback| argument must not be null.
  274. //
  275. // Must be called in the origin thread.
  276. virtual bool RemoveObjectProxy(const std::string& service_name,
  277. const ObjectPath& object_path,
  278. base::OnceClosure callback);
  279. // Same as above, but also takes a bitfield of ObjectProxy::Options.
  280. // See object_proxy.h for available options.
  281. virtual bool RemoveObjectProxyWithOptions(const std::string& service_name,
  282. const ObjectPath& object_path,
  283. int options,
  284. base::OnceClosure callback);
  285. // Gets the exported object for the given object path.
  286. // The caller must not delete the returned object.
  287. //
  288. // Returns an existing exported object if the bus object already owns
  289. // the exported object for the given object path. Never returns NULL.
  290. //
  291. // The bus will own all exported objects created by the bus, to ensure
  292. // that the exported objects are unregistered at the shutdown time of
  293. // the bus.
  294. //
  295. // The exported object is used to export methods of local objects, and
  296. // send signal from them.
  297. //
  298. // Must be called in the origin thread.
  299. virtual ExportedObject* GetExportedObject(const ObjectPath& object_path);
  300. // Unregisters the exported object for the given object path |object_path|.
  301. //
  302. // Getting an exported object for the same object path after this call
  303. // will return a new object, method calls on any remaining copies of the
  304. // previous object will not be called.
  305. //
  306. // Must be called in the origin thread.
  307. virtual void UnregisterExportedObject(const ObjectPath& object_path);
  308. // Gets an object manager for the given remote object path |object_path|
  309. // exported by the service |service_name|.
  310. //
  311. // Returns an existing object manager if the bus object already owns a
  312. // matching object manager, never returns NULL.
  313. //
  314. // The caller must not delete the returned object, the bus retains ownership
  315. // of all object managers.
  316. //
  317. // Must be called in the origin thread.
  318. virtual ObjectManager* GetObjectManager(const std::string& service_name,
  319. const ObjectPath& object_path);
  320. // Unregisters the object manager for the given remote object path
  321. // |object_path| exported by the service |service_name|.
  322. //
  323. // Getting an object manager for the same remote object after this call
  324. // will return a new object, method calls on any remaining copies of the
  325. // previous object are not permitted.
  326. //
  327. // This method will asynchronously clean up any match rules that have been
  328. // added for the object manager and invoke |callback| when the operation is
  329. // complete. If this method returns false, then |callback| is never called.
  330. // The |callback| argument must not be null.
  331. //
  332. // Must be called in the origin thread.
  333. virtual bool RemoveObjectManager(const std::string& service_name,
  334. const ObjectPath& object_path,
  335. base::OnceClosure callback);
  336. // Shuts down the bus and blocks until it's done. More specifically, this
  337. // function does the following:
  338. //
  339. // - Unregisters the object paths
  340. // - Releases the service names
  341. // - Closes the connection to dbus-daemon.
  342. //
  343. // This function can be called multiple times and it is no-op for the 2nd time
  344. // calling.
  345. //
  346. // BLOCKING CALL.
  347. virtual void ShutdownAndBlock();
  348. // Similar to ShutdownAndBlock(), but this function is used to
  349. // synchronously shut down the bus that uses the D-Bus thread. This
  350. // function is intended to be used at the very end of the browser
  351. // shutdown, where it makes more sense to shut down the bus
  352. // synchronously, than trying to make it asynchronous.
  353. //
  354. // BLOCKING CALL, but must be called in the origin thread.
  355. virtual void ShutdownOnDBusThreadAndBlock();
  356. // Returns true if the shutdown has been completed.
  357. bool shutdown_completed() { return shutdown_completed_; }
  358. //
  359. // The public functions below are not intended to be used in client
  360. // code. These are used to implement ObjectProxy and ExportedObject.
  361. //
  362. // Connects the bus to the dbus-daemon.
  363. // Returns true on success, or the bus is already connected.
  364. //
  365. // BLOCKING CALL.
  366. virtual bool Connect();
  367. // Disconnects the bus from the dbus-daemon.
  368. // Safe to call multiple times and no operation after the first call.
  369. // Do not call for shared connection it will be released by libdbus.
  370. //
  371. // BLOCKING CALL.
  372. virtual void ClosePrivateConnection();
  373. // Requests the ownership of the service name given by |service_name|.
  374. // See also RequestOwnershipAndBlock().
  375. //
  376. // |on_ownership_callback| is called when the service name is obtained
  377. // or failed to be obtained, in the origin thread.
  378. //
  379. // Must be called in the origin thread.
  380. virtual void RequestOwnership(const std::string& service_name,
  381. ServiceOwnershipOptions options,
  382. OnOwnershipCallback on_ownership_callback);
  383. // Requests the ownership of the given service name.
  384. // Returns true on success, or the the service name is already obtained.
  385. //
  386. // Note that it's important to expose methods before requesting a service
  387. // name with this method. See also ExportedObject::ExportMethodAndBlock()
  388. // for details.
  389. //
  390. // BLOCKING CALL.
  391. virtual bool RequestOwnershipAndBlock(const std::string& service_name,
  392. ServiceOwnershipOptions options);
  393. // Releases the ownership of the given service name.
  394. // Returns true on success.
  395. //
  396. // BLOCKING CALL.
  397. virtual bool ReleaseOwnership(const std::string& service_name);
  398. // Sets up async operations.
  399. // Returns true on success, or it's already set up.
  400. // This function needs to be called before starting async operations.
  401. //
  402. // BLOCKING CALL.
  403. virtual bool SetUpAsyncOperations();
  404. // Sends a message to the bus and blocks until the response is
  405. // received. Used to implement synchronous method calls.
  406. //
  407. // BLOCKING CALL.
  408. virtual DBusMessage* SendWithReplyAndBlock(DBusMessage* request,
  409. int timeout_ms,
  410. DBusError* error);
  411. // Requests to send a message to the bus. The reply is handled with
  412. // |pending_call| at a later time.
  413. //
  414. // BLOCKING CALL.
  415. virtual void SendWithReply(DBusMessage* request,
  416. DBusPendingCall** pending_call,
  417. int timeout_ms);
  418. // Requests to send a message to the bus. The message serial number will
  419. // be stored in |serial|.
  420. //
  421. // BLOCKING CALL.
  422. virtual void Send(DBusMessage* request, uint32_t* serial);
  423. // Adds the message filter function. |filter_function| will be called
  424. // when incoming messages are received.
  425. //
  426. // When a new incoming message arrives, filter functions are called in
  427. // the order that they were added until the the incoming message is
  428. // handled by a filter function.
  429. //
  430. // The same filter function associated with the same user data cannot be
  431. // added more than once.
  432. //
  433. // BLOCKING CALL.
  434. virtual void AddFilterFunction(DBusHandleMessageFunction filter_function,
  435. void* user_data);
  436. // Removes the message filter previously added by AddFilterFunction().
  437. //
  438. // BLOCKING CALL.
  439. virtual void RemoveFilterFunction(DBusHandleMessageFunction filter_function,
  440. void* user_data);
  441. // Adds the match rule. Messages that match the rule will be processed
  442. // by the filter functions added by AddFilterFunction().
  443. //
  444. // You cannot specify which filter function to use for a match rule.
  445. // Instead, you should check if an incoming message is what you are
  446. // interested in, in the filter functions.
  447. //
  448. // The same match rule can be added more than once and should be removed
  449. // as many times as it was added.
  450. //
  451. // The match rule looks like:
  452. // "type='signal', interface='org.chromium.SomeInterface'".
  453. //
  454. // See "Message Bus Message Routing" section in the D-Bus specification
  455. // for details about match rules:
  456. // http://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing
  457. //
  458. // BLOCKING CALL.
  459. virtual void AddMatch(const std::string& match_rule, DBusError* error);
  460. // Removes the match rule previously added by AddMatch().
  461. // Returns false if the requested match rule is unknown or has already been
  462. // removed. Otherwise, returns true and sets |error| accordingly.
  463. //
  464. // BLOCKING CALL.
  465. virtual bool RemoveMatch(const std::string& match_rule, DBusError* error);
  466. // Tries to register the object path. Returns true on success.
  467. // Returns false if the object path is already registered.
  468. //
  469. // |message_function| in |vtable| will be called every time when a new
  470. // |message sent to the object path arrives.
  471. //
  472. // The same object path must not be added more than once.
  473. //
  474. // See also documentation of |dbus_connection_try_register_object_path| at
  475. // http://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html
  476. //
  477. // BLOCKING CALL.
  478. virtual bool TryRegisterObjectPath(const ObjectPath& object_path,
  479. const DBusObjectPathVTable* vtable,
  480. void* user_data,
  481. DBusError* error);
  482. // Tries to register the object path and its sub paths.
  483. // Returns true on success.
  484. // Returns false if the object path is already registered.
  485. //
  486. // |message_function| in |vtable| will be called every time when a new
  487. // message sent to the object path (or hierarchically below) arrives.
  488. //
  489. // The same object path must not be added more than once.
  490. //
  491. // See also documentation of |dbus_connection_try_register_fallback| at
  492. // http://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html
  493. //
  494. // BLOCKING CALL.
  495. virtual bool TryRegisterFallback(const ObjectPath& object_path,
  496. const DBusObjectPathVTable* vtable,
  497. void* user_data,
  498. DBusError* error);
  499. // Unregister the object path.
  500. //
  501. // BLOCKING CALL.
  502. virtual void UnregisterObjectPath(const ObjectPath& object_path);
  503. // Returns the task runner of the D-Bus thread.
  504. virtual base::SequencedTaskRunner* GetDBusTaskRunner();
  505. // Returns the task runner of the thread that created the bus.
  506. virtual base::SequencedTaskRunner* GetOriginTaskRunner();
  507. // Returns true if the bus has the D-Bus thread.
  508. virtual bool HasDBusThread();
  509. // Check whether the current thread is on the origin thread (the thread
  510. // that created the bus). If not, DCHECK will fail.
  511. virtual void AssertOnOriginThread();
  512. // Check whether the current thread is on the D-Bus thread. If not,
  513. // DCHECK will fail. If the D-Bus thread is not supplied, it calls
  514. // AssertOnOriginThread().
  515. virtual void AssertOnDBusThread();
  516. // Gets the owner for |service_name| via org.freedesktop.DBus.GetNameOwner.
  517. // Returns the owner name, if any, or an empty string on failure.
  518. // |options| specifies where to printing error messages or not.
  519. //
  520. // BLOCKING CALL.
  521. virtual std::string GetServiceOwnerAndBlock(const std::string& service_name,
  522. GetServiceOwnerOption options);
  523. // A non-blocking version of GetServiceOwnerAndBlock().
  524. // Must be called in the origin thread.
  525. virtual void GetServiceOwner(const std::string& service_name,
  526. GetServiceOwnerCallback callback);
  527. // Whenever the owner for |service_name| changes, run |callback| with the
  528. // name of the new owner. If the owner goes away, then |callback| receives
  529. // an empty string.
  530. //
  531. // Any unique (service_name, callback) can be used. Duplicate are ignored.
  532. // |service_name| must not be empty and |callback| must not be null.
  533. //
  534. // Must be called in the origin thread.
  535. virtual void ListenForServiceOwnerChange(
  536. const std::string& service_name,
  537. const ServiceOwnerChangeCallback& callback);
  538. // Stop listening for |service_name| owner changes for |callback|.
  539. // Any unique (service_name, callback) can be used. Non-registered callbacks
  540. // for a given service name are ignored.
  541. // |service_name| must not be empty and |callback| must not be null.
  542. //
  543. // Must be called in the origin thread.
  544. virtual void UnlistenForServiceOwnerChange(
  545. const std::string& service_name,
  546. const ServiceOwnerChangeCallback& callback);
  547. // Return the unique name of the bus connection if it is connected to
  548. // D-BUS. Otherwise, return an empty string.
  549. std::string GetConnectionName();
  550. // Returns true if the bus is connected to D-Bus.
  551. virtual bool IsConnected();
  552. protected:
  553. // This is protected, so we can define sub classes.
  554. virtual ~Bus();
  555. private:
  556. using TryRegisterObjectPathFunction =
  557. dbus_bool_t(DBusConnection* connection,
  558. const char* object_path,
  559. const DBusObjectPathVTable* vtable,
  560. void* user_data,
  561. DBusError* error);
  562. friend class base::RefCountedThreadSafe<Bus>;
  563. bool TryRegisterObjectPathInternal(
  564. const ObjectPath& object_path,
  565. const DBusObjectPathVTable* vtable,
  566. void* user_data,
  567. DBusError* error,
  568. TryRegisterObjectPathFunction* register_function);
  569. // Helper function used for RemoveObjectProxy().
  570. void RemoveObjectProxyInternal(scoped_refptr<dbus::ObjectProxy> object_proxy,
  571. base::OnceClosure callback);
  572. // Helper functions used for RemoveObjectManager().
  573. void RemoveObjectManagerInternal(
  574. scoped_refptr<dbus::ObjectManager> object_manager,
  575. base::OnceClosure callback);
  576. void RemoveObjectManagerInternalHelper(
  577. scoped_refptr<dbus::ObjectManager> object_manager,
  578. base::OnceClosure callback);
  579. // Helper function used for UnregisterExportedObject().
  580. void UnregisterExportedObjectInternal(
  581. scoped_refptr<dbus::ExportedObject> exported_object);
  582. // Helper function used for ShutdownOnDBusThreadAndBlock().
  583. void ShutdownOnDBusThreadAndBlockInternal();
  584. // Helper function used for RequestOwnership().
  585. void RequestOwnershipInternal(const std::string& service_name,
  586. ServiceOwnershipOptions options,
  587. OnOwnershipCallback on_ownership_callback);
  588. // Helper function used for GetServiceOwner().
  589. void GetServiceOwnerInternal(const std::string& service_name,
  590. GetServiceOwnerCallback callback);
  591. // Helper function used for ListenForServiceOwnerChange().
  592. void ListenForServiceOwnerChangeInternal(
  593. const std::string& service_name,
  594. const ServiceOwnerChangeCallback& callback);
  595. // Helper function used for UnListenForServiceOwnerChange().
  596. void UnlistenForServiceOwnerChangeInternal(
  597. const std::string& service_name,
  598. const ServiceOwnerChangeCallback& callback);
  599. // Processes the all incoming data to the connection, if any.
  600. //
  601. // BLOCKING CALL.
  602. void ProcessAllIncomingDataIfAny();
  603. // Called when a watch object is added. Used to start monitoring the
  604. // file descriptor used for D-Bus communication.
  605. dbus_bool_t OnAddWatch(DBusWatch* raw_watch);
  606. // Called when a watch object is removed.
  607. void OnRemoveWatch(DBusWatch* raw_watch);
  608. // Called when the "enabled" status of |raw_watch| is toggled.
  609. void OnToggleWatch(DBusWatch* raw_watch);
  610. // Called when a timeout object is added. Used to start monitoring
  611. // timeout for method calls.
  612. dbus_bool_t OnAddTimeout(DBusTimeout* raw_timeout);
  613. // Called when a timeout object is removed.
  614. void OnRemoveTimeout(DBusTimeout* raw_timeout);
  615. // Called when the "enabled" status of |raw_timeout| is toggled.
  616. void OnToggleTimeout(DBusTimeout* raw_timeout);
  617. // Called when the dispatch status (i.e. if any incoming data is
  618. // available) is changed.
  619. void OnDispatchStatusChanged(DBusConnection* connection,
  620. DBusDispatchStatus status);
  621. // Called when a service owner change occurs.
  622. void OnServiceOwnerChanged(DBusMessage* message);
  623. // Callback helper functions. Redirects to the corresponding member function.
  624. static dbus_bool_t OnAddWatchThunk(DBusWatch* raw_watch, void* data);
  625. static void OnRemoveWatchThunk(DBusWatch* raw_watch, void* data);
  626. static void OnToggleWatchThunk(DBusWatch* raw_watch, void* data);
  627. static dbus_bool_t OnAddTimeoutThunk(DBusTimeout* raw_timeout, void* data);
  628. static void OnRemoveTimeoutThunk(DBusTimeout* raw_timeout, void* data);
  629. static void OnToggleTimeoutThunk(DBusTimeout* raw_timeout, void* data);
  630. static void OnDispatchStatusChangedThunk(DBusConnection* connection,
  631. DBusDispatchStatus status,
  632. void* data);
  633. // Calls OnConnectionDisconnected if the Disconnected signal is received.
  634. static DBusHandlerResult OnConnectionDisconnectedFilter(
  635. DBusConnection* connection,
  636. DBusMessage* message,
  637. void* user_data);
  638. // Calls OnServiceOwnerChanged for a NameOwnerChanged signal.
  639. static DBusHandlerResult OnServiceOwnerChangedFilter(
  640. DBusConnection* connection,
  641. DBusMessage* message,
  642. void* user_data);
  643. const BusType bus_type_;
  644. const ConnectionType connection_type_;
  645. scoped_refptr<base::SequencedTaskRunner> dbus_task_runner_;
  646. base::WaitableEvent on_shutdown_;
  647. raw_ptr<DBusConnection, DanglingUntriaged> connection_;
  648. base::PlatformThreadId origin_thread_id_;
  649. scoped_refptr<base::SequencedTaskRunner> origin_task_runner_;
  650. std::set<std::string> owned_service_names_;
  651. // The following sets are used to check if rules/object_paths/filters
  652. // are properly cleaned up before destruction of the bus object.
  653. // Since it's not an error to add the same match rule twice, the repeated
  654. // match rules are counted in a map.
  655. std::map<std::string, int> match_rules_added_;
  656. std::set<ObjectPath> registered_object_paths_;
  657. std::set<std::pair<DBusHandleMessageFunction, void*>> filter_functions_added_;
  658. // ObjectProxyTable is used to hold the object proxies created by the
  659. // bus object. Key is a pair; the first part is a concatenated string of
  660. // service name + object path, like
  661. // "org.chromium.TestService/org/chromium/TestObject".
  662. // The second part is the ObjectProxy::Options for the proxy.
  663. typedef std::map<std::pair<std::string, int>,
  664. scoped_refptr<dbus::ObjectProxy>> ObjectProxyTable;
  665. ObjectProxyTable object_proxy_table_;
  666. // ExportedObjectTable is used to hold the exported objects created by
  667. // the bus object. Key is a concatenated string of service name +
  668. // object path, like "org.chromium.TestService/org/chromium/TestObject".
  669. typedef std::map<const dbus::ObjectPath,
  670. scoped_refptr<dbus::ExportedObject>> ExportedObjectTable;
  671. ExportedObjectTable exported_object_table_;
  672. // ObjectManagerTable is used to hold the object managers created by the
  673. // bus object. Key is a concatenated string of service name + object path,
  674. // like "org.chromium.TestService/org/chromium/TestObject".
  675. typedef std::map<std::string,
  676. scoped_refptr<dbus::ObjectManager>> ObjectManagerTable;
  677. ObjectManagerTable object_manager_table_;
  678. // A map of NameOwnerChanged signals to listen for and the callbacks to run
  679. // on the origin thread when the owner changes.
  680. // Only accessed on the DBus thread.
  681. // Key: Service name
  682. // Value: Vector of callbacks. Unique and expected to be small. Not using
  683. // std::set here because base::RepeatingCallbacks don't have a '<'
  684. // operator.
  685. typedef std::map<std::string, std::vector<ServiceOwnerChangeCallback>>
  686. ServiceOwnerChangedListenerMap;
  687. ServiceOwnerChangedListenerMap service_owner_changed_listener_map_;
  688. bool async_operations_set_up_;
  689. bool shutdown_completed_;
  690. // Counters to make sure that OnAddWatch()/OnRemoveWatch() and
  691. // OnAddTimeout()/OnRemoveTimeout() are balanced.
  692. int num_pending_watches_;
  693. int num_pending_timeouts_;
  694. std::string address_;
  695. };
  696. } // namespace dbus
  697. #endif // DBUS_BUS_H_