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