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.
8 #include "base/logging.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/stl_util.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/threading/thread.h"
14 #include "base/threading/thread_restrictions.h"
15 #include "base/time/time.h"
16 #include "dbus/exported_object.h"
17 #include "dbus/message.h"
18 #include "dbus/object_manager.h"
19 #include "dbus/object_path.h"
20 #include "dbus/object_proxy.h"
21 #include "dbus/scoped_dbus_error.h"
27 const char kDisconnectedSignal
[] = "Disconnected";
28 const char kDisconnectedMatchRule
[] =
29 "type='signal', path='/org/freedesktop/DBus/Local',"
30 "interface='org.freedesktop.DBus.Local', member='Disconnected'";
32 // The NameOwnerChanged member in org.freedesktop.DBus
33 const char kNameOwnerChangedSignal
[] = "NameOwnerChanged";
35 // The match rule used to filter for changes to a given service name owner.
36 const char kServiceNameOwnerChangeMatchRule
[] =
37 "type='signal',interface='org.freedesktop.DBus',"
38 "member='NameOwnerChanged',path='/org/freedesktop/DBus',"
39 "sender='org.freedesktop.DBus',arg0='%s'";
41 // The class is used for watching the file descriptor used for D-Bus
43 class Watch
: public base::MessagePumpLibevent::Watcher
{
45 explicit Watch(DBusWatch
* watch
)
47 dbus_watch_set_data(raw_watch_
, this, NULL
);
51 dbus_watch_set_data(raw_watch_
, NULL
, NULL
);
54 // Returns true if the underlying file descriptor is ready to be watched.
55 bool IsReadyToBeWatched() {
56 return dbus_watch_get_enabled(raw_watch_
);
59 // Starts watching the underlying file descriptor.
60 void StartWatching() {
61 const int file_descriptor
= dbus_watch_get_unix_fd(raw_watch_
);
62 const int flags
= dbus_watch_get_flags(raw_watch_
);
64 base::MessageLoopForIO::Mode mode
= base::MessageLoopForIO::WATCH_READ
;
65 if ((flags
& DBUS_WATCH_READABLE
) && (flags
& DBUS_WATCH_WRITABLE
))
66 mode
= base::MessageLoopForIO::WATCH_READ_WRITE
;
67 else if (flags
& DBUS_WATCH_READABLE
)
68 mode
= base::MessageLoopForIO::WATCH_READ
;
69 else if (flags
& DBUS_WATCH_WRITABLE
)
70 mode
= base::MessageLoopForIO::WATCH_WRITE
;
74 const bool persistent
= true; // Watch persistently.
75 const bool success
= base::MessageLoopForIO::current()->WatchFileDescriptor(
76 file_descriptor
, persistent
, mode
, &file_descriptor_watcher_
, this);
77 CHECK(success
) << "Unable to allocate memory";
80 // Stops watching the underlying file descriptor.
82 file_descriptor_watcher_
.StopWatchingFileDescriptor();
86 // Implement MessagePumpLibevent::Watcher.
87 virtual void OnFileCanReadWithoutBlocking(int file_descriptor
) override
{
88 const bool success
= dbus_watch_handle(raw_watch_
, DBUS_WATCH_READABLE
);
89 CHECK(success
) << "Unable to allocate memory";
92 // Implement MessagePumpLibevent::Watcher.
93 virtual void OnFileCanWriteWithoutBlocking(int file_descriptor
) override
{
94 const bool success
= dbus_watch_handle(raw_watch_
, DBUS_WATCH_WRITABLE
);
95 CHECK(success
) << "Unable to allocate memory";
98 DBusWatch
* raw_watch_
;
99 base::MessagePumpLibevent::FileDescriptorWatcher file_descriptor_watcher_
;
102 // The class is used for monitoring the timeout used for D-Bus method
105 // Unlike Watch, Timeout is a ref counted object, to ensure that |this| of
106 // the object is is alive when HandleTimeout() is called. It's unlikely
107 // but it may be possible that HandleTimeout() is called after
108 // Bus::OnRemoveTimeout(). That's why we don't simply delete the object in
109 // Bus::OnRemoveTimeout().
110 class Timeout
: public base::RefCountedThreadSafe
<Timeout
> {
112 explicit Timeout(DBusTimeout
* timeout
)
113 : raw_timeout_(timeout
),
114 monitoring_is_active_(false),
115 is_completed(false) {
116 dbus_timeout_set_data(raw_timeout_
, this, NULL
);
117 AddRef(); // Balanced on Complete().
120 // Returns true if the timeout is ready to be monitored.
121 bool IsReadyToBeMonitored() {
122 return dbus_timeout_get_enabled(raw_timeout_
);
125 // Starts monitoring the timeout.
126 void StartMonitoring(Bus
* bus
) {
127 bus
->GetDBusTaskRunner()->PostDelayedTask(
129 base::Bind(&Timeout::HandleTimeout
, this),
131 monitoring_is_active_
= true;
134 // Stops monitoring the timeout.
135 void StopMonitoring() {
136 // We cannot take back the delayed task we posted in
137 // StartMonitoring(), so we just mark the monitoring is inactive now.
138 monitoring_is_active_
= false;
141 // Returns the interval.
142 base::TimeDelta
GetInterval() {
143 return base::TimeDelta::FromMilliseconds(
144 dbus_timeout_get_interval(raw_timeout_
));
147 // Cleans up the raw_timeout and marks that timeout is completed.
148 // See the class comment above for why we are doing this.
150 dbus_timeout_set_data(raw_timeout_
, NULL
, NULL
);
156 friend class base::RefCountedThreadSafe
<Timeout
>;
160 // Handles the timeout.
161 void HandleTimeout() {
162 // If the timeout is marked completed, we should do nothing. This can
163 // occur if this function is called after Bus::OnRemoveTimeout().
166 // Skip if monitoring is canceled.
167 if (!monitoring_is_active_
)
170 const bool success
= dbus_timeout_handle(raw_timeout_
);
171 CHECK(success
) << "Unable to allocate memory";
174 DBusTimeout
* raw_timeout_
;
175 bool monitoring_is_active_
;
181 Bus::Options::Options()
183 connection_type(PRIVATE
) {
186 Bus::Options::~Options() {
189 Bus::Bus(const Options
& options
)
190 : bus_type_(options
.bus_type
),
191 connection_type_(options
.connection_type
),
192 dbus_task_runner_(options
.dbus_task_runner
),
193 on_shutdown_(false /* manual_reset */, false /* initially_signaled */),
195 origin_thread_id_(base::PlatformThread::CurrentId()),
196 async_operations_set_up_(false),
197 shutdown_completed_(false),
198 num_pending_watches_(0),
199 num_pending_timeouts_(0),
200 address_(options
.address
) {
201 // This is safe to call multiple times.
202 dbus_threads_init_default();
203 // The origin message loop is unnecessary if the client uses synchronous
205 if (base::MessageLoop::current())
206 origin_task_runner_
= base::MessageLoop::current()->message_loop_proxy();
210 DCHECK(!connection_
);
211 DCHECK(owned_service_names_
.empty());
212 DCHECK(match_rules_added_
.empty());
213 DCHECK(filter_functions_added_
.empty());
214 DCHECK(registered_object_paths_
.empty());
215 DCHECK_EQ(0, num_pending_watches_
);
216 // TODO(satorux): This check fails occasionally in browser_tests for tests
217 // that run very quickly. Perhaps something does not have time to clean up.
218 // Despite the check failing, the tests seem to run fine. crosbug.com/23416
219 // DCHECK_EQ(0, num_pending_timeouts_);
222 ObjectProxy
* Bus::GetObjectProxy(const std::string
& service_name
,
223 const ObjectPath
& object_path
) {
224 return GetObjectProxyWithOptions(service_name
, object_path
,
225 ObjectProxy::DEFAULT_OPTIONS
);
228 ObjectProxy
* Bus::GetObjectProxyWithOptions(const std::string
& service_name
,
229 const ObjectPath
& object_path
,
231 AssertOnOriginThread();
233 // Check if we already have the requested object proxy.
234 const ObjectProxyTable::key_type
key(service_name
+ object_path
.value(),
236 ObjectProxyTable::iterator iter
= object_proxy_table_
.find(key
);
237 if (iter
!= object_proxy_table_
.end()) {
238 return iter
->second
.get();
241 scoped_refptr
<ObjectProxy
> object_proxy
=
242 new ObjectProxy(this, service_name
, object_path
, options
);
243 object_proxy_table_
[key
] = object_proxy
;
245 return object_proxy
.get();
248 bool Bus::RemoveObjectProxy(const std::string
& service_name
,
249 const ObjectPath
& object_path
,
250 const base::Closure
& callback
) {
251 return RemoveObjectProxyWithOptions(service_name
, object_path
,
252 ObjectProxy::DEFAULT_OPTIONS
,
256 bool Bus::RemoveObjectProxyWithOptions(const std::string
& service_name
,
257 const ObjectPath
& object_path
,
259 const base::Closure
& callback
) {
260 AssertOnOriginThread();
262 // Check if we have the requested object proxy.
263 const ObjectProxyTable::key_type
key(service_name
+ object_path
.value(),
265 ObjectProxyTable::iterator iter
= object_proxy_table_
.find(key
);
266 if (iter
!= object_proxy_table_
.end()) {
267 scoped_refptr
<ObjectProxy
> object_proxy
= iter
->second
;
268 object_proxy_table_
.erase(iter
);
269 // Object is present. Remove it now and Detach on the DBus thread.
270 GetDBusTaskRunner()->PostTask(
272 base::Bind(&Bus::RemoveObjectProxyInternal
,
273 this, object_proxy
, callback
));
279 void Bus::RemoveObjectProxyInternal(scoped_refptr
<ObjectProxy
> object_proxy
,
280 const base::Closure
& callback
) {
281 AssertOnDBusThread();
283 object_proxy
.get()->Detach();
285 GetOriginTaskRunner()->PostTask(FROM_HERE
, callback
);
288 ExportedObject
* Bus::GetExportedObject(const ObjectPath
& object_path
) {
289 AssertOnOriginThread();
291 // Check if we already have the requested exported object.
292 ExportedObjectTable::iterator iter
= exported_object_table_
.find(object_path
);
293 if (iter
!= exported_object_table_
.end()) {
294 return iter
->second
.get();
297 scoped_refptr
<ExportedObject
> exported_object
=
298 new ExportedObject(this, object_path
);
299 exported_object_table_
[object_path
] = exported_object
;
301 return exported_object
.get();
304 void Bus::UnregisterExportedObject(const ObjectPath
& object_path
) {
305 AssertOnOriginThread();
307 // Remove the registered object from the table first, to allow a new
308 // GetExportedObject() call to return a new object, rather than this one.
309 ExportedObjectTable::iterator iter
= exported_object_table_
.find(object_path
);
310 if (iter
== exported_object_table_
.end())
313 scoped_refptr
<ExportedObject
> exported_object
= iter
->second
;
314 exported_object_table_
.erase(iter
);
316 // Post the task to perform the final unregistration to the D-Bus thread.
317 // Since the registration also happens on the D-Bus thread in
318 // TryRegisterObjectPath(), and the task runner we post to is a
319 // SequencedTaskRunner, there is a guarantee that this will happen before any
320 // future registration call.
321 GetDBusTaskRunner()->PostTask(
323 base::Bind(&Bus::UnregisterExportedObjectInternal
,
324 this, exported_object
));
327 void Bus::UnregisterExportedObjectInternal(
328 scoped_refptr
<ExportedObject
> exported_object
) {
329 AssertOnDBusThread();
331 exported_object
->Unregister();
334 ObjectManager
* Bus::GetObjectManager(const std::string
& service_name
,
335 const ObjectPath
& object_path
) {
336 AssertOnOriginThread();
338 // Check if we already have the requested object manager.
339 const ObjectManagerTable::key_type
key(service_name
+ object_path
.value());
340 ObjectManagerTable::iterator iter
= object_manager_table_
.find(key
);
341 if (iter
!= object_manager_table_
.end()) {
342 return iter
->second
.get();
345 scoped_refptr
<ObjectManager
> object_manager
=
346 new ObjectManager(this, service_name
, object_path
);
347 object_manager_table_
[key
] = object_manager
;
349 return object_manager
.get();
352 bool Bus::RemoveObjectManager(const std::string
& service_name
,
353 const ObjectPath
& object_path
,
354 const base::Closure
& callback
) {
355 AssertOnOriginThread();
356 DCHECK(!callback
.is_null());
358 const ObjectManagerTable::key_type
key(service_name
+ object_path
.value());
359 ObjectManagerTable::iterator iter
= object_manager_table_
.find(key
);
360 if (iter
== object_manager_table_
.end())
363 // ObjectManager is present. Remove it now and CleanUp on the DBus thread.
364 scoped_refptr
<ObjectManager
> object_manager
= iter
->second
;
365 object_manager_table_
.erase(iter
);
367 GetDBusTaskRunner()->PostTask(
369 base::Bind(&Bus::RemoveObjectManagerInternal
,
370 this, object_manager
, callback
));
375 void Bus::RemoveObjectManagerInternal(
376 scoped_refptr
<dbus::ObjectManager
> object_manager
,
377 const base::Closure
& callback
) {
378 AssertOnDBusThread();
379 DCHECK(object_manager
.get());
381 object_manager
->CleanUp();
383 // The ObjectManager has to be deleted on the origin thread since it was
385 GetOriginTaskRunner()->PostTask(
387 base::Bind(&Bus::RemoveObjectManagerInternalHelper
,
388 this, object_manager
, callback
));
391 void Bus::RemoveObjectManagerInternalHelper(
392 scoped_refptr
<dbus::ObjectManager
> object_manager
,
393 const base::Closure
& callback
) {
394 AssertOnOriginThread();
395 DCHECK(object_manager
.get());
397 // Release the object manager and run the callback.
398 object_manager
= NULL
;
402 void Bus::GetManagedObjects() {
403 for (ObjectManagerTable::iterator iter
= object_manager_table_
.begin();
404 iter
!= object_manager_table_
.end(); ++iter
) {
405 iter
->second
->GetManagedObjects();
409 bool Bus::Connect() {
410 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
411 AssertOnDBusThread();
413 // Check if it's already initialized.
417 ScopedDBusError error
;
418 if (bus_type_
== CUSTOM_ADDRESS
) {
419 if (connection_type_
== PRIVATE
) {
420 connection_
= dbus_connection_open_private(address_
.c_str(), error
.get());
422 connection_
= dbus_connection_open(address_
.c_str(), error
.get());
425 const DBusBusType dbus_bus_type
= static_cast<DBusBusType
>(bus_type_
);
426 if (connection_type_
== PRIVATE
) {
427 connection_
= dbus_bus_get_private(dbus_bus_type
, error
.get());
429 connection_
= dbus_bus_get(dbus_bus_type
, error
.get());
433 LOG(ERROR
) << "Failed to connect to the bus: "
434 << (error
.is_set() ? error
.message() : "");
438 if (bus_type_
== CUSTOM_ADDRESS
) {
439 // We should call dbus_bus_register here, otherwise unique name can not be
440 // acquired. According to dbus specification, it is responsible to call
441 // org.freedesktop.DBus.Hello method at the beging of bus connection to
442 // acquire unique name. In the case of dbus_bus_get, dbus_bus_register is
443 // called internally.
444 if (!dbus_bus_register(connection_
, error
.get())) {
445 LOG(ERROR
) << "Failed to register the bus component: "
446 << (error
.is_set() ? error
.message() : "");
450 // We shouldn't exit on the disconnected signal.
451 dbus_connection_set_exit_on_disconnect(connection_
, false);
453 // Watch Disconnected signal.
454 AddFilterFunction(Bus::OnConnectionDisconnectedFilter
, this);
455 AddMatch(kDisconnectedMatchRule
, error
.get());
460 void Bus::ClosePrivateConnection() {
461 // dbus_connection_close is blocking call.
462 AssertOnDBusThread();
463 DCHECK_EQ(PRIVATE
, connection_type_
)
464 << "non-private connection should not be closed";
465 dbus_connection_close(connection_
);
468 void Bus::ShutdownAndBlock() {
469 AssertOnDBusThread();
471 if (shutdown_completed_
)
472 return; // Already shutdowned, just return.
474 // Unregister the exported objects.
475 for (ExportedObjectTable::iterator iter
= exported_object_table_
.begin();
476 iter
!= exported_object_table_
.end(); ++iter
) {
477 iter
->second
->Unregister();
480 // Release all service names.
481 for (std::set
<std::string
>::iterator iter
= owned_service_names_
.begin();
482 iter
!= owned_service_names_
.end();) {
483 // This is a bit tricky but we should increment the iter here as
484 // ReleaseOwnership() may remove |service_name| from the set.
485 const std::string
& service_name
= *iter
++;
486 ReleaseOwnership(service_name
);
488 if (!owned_service_names_
.empty()) {
489 LOG(ERROR
) << "Failed to release all service names. # of services left: "
490 << owned_service_names_
.size();
493 // Detach from the remote objects.
494 for (ObjectProxyTable::iterator iter
= object_proxy_table_
.begin();
495 iter
!= object_proxy_table_
.end(); ++iter
) {
496 iter
->second
->Detach();
499 // Clean up the object managers.
500 for (ObjectManagerTable::iterator iter
= object_manager_table_
.begin();
501 iter
!= object_manager_table_
.end(); ++iter
) {
502 iter
->second
->CleanUp();
505 // Release object proxies and exported objects here. We should do this
506 // here rather than in the destructor to avoid memory leaks due to
507 // cyclic references.
508 object_proxy_table_
.clear();
509 exported_object_table_
.clear();
511 // Private connection should be closed.
513 // Remove Disconnected watcher.
514 ScopedDBusError error
;
515 RemoveFilterFunction(Bus::OnConnectionDisconnectedFilter
, this);
516 RemoveMatch(kDisconnectedMatchRule
, error
.get());
518 if (connection_type_
== PRIVATE
)
519 ClosePrivateConnection();
520 // dbus_connection_close() won't unref.
521 dbus_connection_unref(connection_
);
525 shutdown_completed_
= true;
528 void Bus::ShutdownOnDBusThreadAndBlock() {
529 AssertOnOriginThread();
530 DCHECK(dbus_task_runner_
.get());
532 GetDBusTaskRunner()->PostTask(
534 base::Bind(&Bus::ShutdownOnDBusThreadAndBlockInternal
, this));
536 // http://crbug.com/125222
537 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
539 // Wait until the shutdown is complete on the D-Bus thread.
540 // The shutdown should not hang, but set timeout just in case.
541 const int kTimeoutSecs
= 3;
542 const base::TimeDelta
timeout(base::TimeDelta::FromSeconds(kTimeoutSecs
));
543 const bool signaled
= on_shutdown_
.TimedWait(timeout
);
544 LOG_IF(ERROR
, !signaled
) << "Failed to shutdown the bus";
547 void Bus::RequestOwnership(const std::string
& service_name
,
548 ServiceOwnershipOptions options
,
549 OnOwnershipCallback on_ownership_callback
) {
550 AssertOnOriginThread();
552 GetDBusTaskRunner()->PostTask(
554 base::Bind(&Bus::RequestOwnershipInternal
,
555 this, service_name
, options
, on_ownership_callback
));
558 void Bus::RequestOwnershipInternal(const std::string
& service_name
,
559 ServiceOwnershipOptions options
,
560 OnOwnershipCallback on_ownership_callback
) {
561 AssertOnDBusThread();
563 bool success
= Connect();
565 success
= RequestOwnershipAndBlock(service_name
, options
);
567 GetOriginTaskRunner()->PostTask(FROM_HERE
,
568 base::Bind(on_ownership_callback
,
573 bool Bus::RequestOwnershipAndBlock(const std::string
& service_name
,
574 ServiceOwnershipOptions options
) {
576 // dbus_bus_request_name() is a blocking call.
577 AssertOnDBusThread();
579 // Check if we already own the service name.
580 if (owned_service_names_
.find(service_name
) != owned_service_names_
.end()) {
584 ScopedDBusError error
;
585 const int result
= dbus_bus_request_name(connection_
,
586 service_name
.c_str(),
589 if (result
!= DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
) {
590 LOG(ERROR
) << "Failed to get the ownership of " << service_name
<< ": "
591 << (error
.is_set() ? error
.message() : "");
594 owned_service_names_
.insert(service_name
);
598 bool Bus::ReleaseOwnership(const std::string
& service_name
) {
600 // dbus_bus_request_name() is a blocking call.
601 AssertOnDBusThread();
603 // Check if we already own the service name.
604 std::set
<std::string
>::iterator found
=
605 owned_service_names_
.find(service_name
);
606 if (found
== owned_service_names_
.end()) {
607 LOG(ERROR
) << service_name
<< " is not owned by the bus";
611 ScopedDBusError error
;
612 const int result
= dbus_bus_release_name(connection_
, service_name
.c_str(),
614 if (result
== DBUS_RELEASE_NAME_REPLY_RELEASED
) {
615 owned_service_names_
.erase(found
);
618 LOG(ERROR
) << "Failed to release the ownership of " << service_name
<< ": "
619 << (error
.is_set() ? error
.message() : "")
620 << ", result code: " << result
;
625 bool Bus::SetUpAsyncOperations() {
627 AssertOnDBusThread();
629 if (async_operations_set_up_
)
632 // Process all the incoming data if any, so that OnDispatchStatus() will
633 // be called when the incoming data is ready.
634 ProcessAllIncomingDataIfAny();
636 bool success
= dbus_connection_set_watch_functions(connection_
,
637 &Bus::OnAddWatchThunk
,
638 &Bus::OnRemoveWatchThunk
,
639 &Bus::OnToggleWatchThunk
,
642 CHECK(success
) << "Unable to allocate memory";
644 success
= dbus_connection_set_timeout_functions(connection_
,
645 &Bus::OnAddTimeoutThunk
,
646 &Bus::OnRemoveTimeoutThunk
,
647 &Bus::OnToggleTimeoutThunk
,
650 CHECK(success
) << "Unable to allocate memory";
652 dbus_connection_set_dispatch_status_function(
654 &Bus::OnDispatchStatusChangedThunk
,
658 async_operations_set_up_
= true;
663 DBusMessage
* Bus::SendWithReplyAndBlock(DBusMessage
* request
,
667 AssertOnDBusThread();
669 return dbus_connection_send_with_reply_and_block(
670 connection_
, request
, timeout_ms
, error
);
673 void Bus::SendWithReply(DBusMessage
* request
,
674 DBusPendingCall
** pending_call
,
677 AssertOnDBusThread();
679 const bool success
= dbus_connection_send_with_reply(
680 connection_
, request
, pending_call
, timeout_ms
);
681 CHECK(success
) << "Unable to allocate memory";
684 void Bus::Send(DBusMessage
* request
, uint32
* serial
) {
686 AssertOnDBusThread();
688 const bool success
= dbus_connection_send(connection_
, request
, serial
);
689 CHECK(success
) << "Unable to allocate memory";
692 void Bus::AddFilterFunction(DBusHandleMessageFunction filter_function
,
695 AssertOnDBusThread();
697 std::pair
<DBusHandleMessageFunction
, void*> filter_data_pair
=
698 std::make_pair(filter_function
, user_data
);
699 if (filter_functions_added_
.find(filter_data_pair
) !=
700 filter_functions_added_
.end()) {
701 VLOG(1) << "Filter function already exists: " << filter_function
702 << " with associated data: " << user_data
;
706 const bool success
= dbus_connection_add_filter(
707 connection_
, filter_function
, user_data
, NULL
);
708 CHECK(success
) << "Unable to allocate memory";
709 filter_functions_added_
.insert(filter_data_pair
);
712 void Bus::RemoveFilterFunction(DBusHandleMessageFunction filter_function
,
715 AssertOnDBusThread();
717 std::pair
<DBusHandleMessageFunction
, void*> filter_data_pair
=
718 std::make_pair(filter_function
, user_data
);
719 if (filter_functions_added_
.find(filter_data_pair
) ==
720 filter_functions_added_
.end()) {
721 VLOG(1) << "Requested to remove an unknown filter function: "
723 << " with associated data: " << user_data
;
727 dbus_connection_remove_filter(connection_
, filter_function
, user_data
);
728 filter_functions_added_
.erase(filter_data_pair
);
731 void Bus::AddMatch(const std::string
& match_rule
, DBusError
* error
) {
733 AssertOnDBusThread();
735 std::map
<std::string
, int>::iterator iter
=
736 match_rules_added_
.find(match_rule
);
737 if (iter
!= match_rules_added_
.end()) {
738 // The already existing rule's counter is incremented.
741 VLOG(1) << "Match rule already exists: " << match_rule
;
745 dbus_bus_add_match(connection_
, match_rule
.c_str(), error
);
746 match_rules_added_
[match_rule
] = 1;
749 bool Bus::RemoveMatch(const std::string
& match_rule
, DBusError
* error
) {
751 AssertOnDBusThread();
753 std::map
<std::string
, int>::iterator iter
=
754 match_rules_added_
.find(match_rule
);
755 if (iter
== match_rules_added_
.end()) {
756 LOG(ERROR
) << "Requested to remove an unknown match rule: " << match_rule
;
760 // The rule's counter is decremented and the rule is deleted when reachs 0.
762 if (iter
->second
== 0) {
763 dbus_bus_remove_match(connection_
, match_rule
.c_str(), error
);
764 match_rules_added_
.erase(match_rule
);
769 bool Bus::TryRegisterObjectPath(const ObjectPath
& object_path
,
770 const DBusObjectPathVTable
* vtable
,
774 AssertOnDBusThread();
776 if (registered_object_paths_
.find(object_path
) !=
777 registered_object_paths_
.end()) {
778 LOG(ERROR
) << "Object path already registered: " << object_path
.value();
782 const bool success
= dbus_connection_try_register_object_path(
784 object_path
.value().c_str(),
789 registered_object_paths_
.insert(object_path
);
793 void Bus::UnregisterObjectPath(const ObjectPath
& object_path
) {
795 AssertOnDBusThread();
797 if (registered_object_paths_
.find(object_path
) ==
798 registered_object_paths_
.end()) {
799 LOG(ERROR
) << "Requested to unregister an unknown object path: "
800 << object_path
.value();
804 const bool success
= dbus_connection_unregister_object_path(
806 object_path
.value().c_str());
807 CHECK(success
) << "Unable to allocate memory";
808 registered_object_paths_
.erase(object_path
);
811 void Bus::ShutdownOnDBusThreadAndBlockInternal() {
812 AssertOnDBusThread();
815 on_shutdown_
.Signal();
818 void Bus::ProcessAllIncomingDataIfAny() {
819 AssertOnDBusThread();
821 // As mentioned at the class comment in .h file, connection_ can be NULL.
825 // It is safe and necessary to call dbus_connection_get_dispatch_status even
826 // if the connection is lost.
827 if (dbus_connection_get_dispatch_status(connection_
) ==
828 DBUS_DISPATCH_DATA_REMAINS
) {
829 while (dbus_connection_dispatch(connection_
) ==
830 DBUS_DISPATCH_DATA_REMAINS
) {
835 base::TaskRunner
* Bus::GetDBusTaskRunner() {
836 if (dbus_task_runner_
.get())
837 return dbus_task_runner_
.get();
839 return GetOriginTaskRunner();
842 base::TaskRunner
* Bus::GetOriginTaskRunner() {
843 DCHECK(origin_task_runner_
.get());
844 return origin_task_runner_
.get();
847 bool Bus::HasDBusThread() {
848 return dbus_task_runner_
.get() != NULL
;
851 void Bus::AssertOnOriginThread() {
852 DCHECK_EQ(origin_thread_id_
, base::PlatformThread::CurrentId());
855 void Bus::AssertOnDBusThread() {
856 base::ThreadRestrictions::AssertIOAllowed();
858 if (dbus_task_runner_
.get()) {
859 DCHECK(dbus_task_runner_
->RunsTasksOnCurrentThread());
861 AssertOnOriginThread();
865 std::string
Bus::GetServiceOwnerAndBlock(const std::string
& service_name
,
866 GetServiceOwnerOption options
) {
867 AssertOnDBusThread();
869 MethodCall
get_name_owner_call("org.freedesktop.DBus", "GetNameOwner");
870 MessageWriter
writer(&get_name_owner_call
);
871 writer
.AppendString(service_name
);
872 VLOG(1) << "Method call: " << get_name_owner_call
.ToString();
874 const ObjectPath
obj_path("/org/freedesktop/DBus");
875 if (!get_name_owner_call
.SetDestination("org.freedesktop.DBus") ||
876 !get_name_owner_call
.SetPath(obj_path
)) {
877 if (options
== REPORT_ERRORS
)
878 LOG(ERROR
) << "Failed to get name owner.";
882 ScopedDBusError error
;
883 DBusMessage
* response_message
=
884 SendWithReplyAndBlock(get_name_owner_call
.raw_message(),
885 ObjectProxy::TIMEOUT_USE_DEFAULT
,
887 if (!response_message
) {
888 if (options
== REPORT_ERRORS
) {
889 LOG(ERROR
) << "Failed to get name owner. Got " << error
.name() << ": "
895 scoped_ptr
<Response
> response(Response::FromRawMessage(response_message
));
896 MessageReader
reader(response
.get());
898 std::string service_owner
;
899 if (!reader
.PopString(&service_owner
))
900 service_owner
.clear();
901 return service_owner
;
904 void Bus::GetServiceOwner(const std::string
& service_name
,
905 const GetServiceOwnerCallback
& callback
) {
906 AssertOnOriginThread();
908 GetDBusTaskRunner()->PostTask(
910 base::Bind(&Bus::GetServiceOwnerInternal
, this, service_name
, callback
));
913 void Bus::GetServiceOwnerInternal(const std::string
& service_name
,
914 const GetServiceOwnerCallback
& callback
) {
915 AssertOnDBusThread();
917 std::string service_owner
;
919 service_owner
= GetServiceOwnerAndBlock(service_name
, SUPPRESS_ERRORS
);
920 GetOriginTaskRunner()->PostTask(FROM_HERE
,
921 base::Bind(callback
, service_owner
));
924 void Bus::ListenForServiceOwnerChange(
925 const std::string
& service_name
,
926 const GetServiceOwnerCallback
& callback
) {
927 AssertOnOriginThread();
928 DCHECK(!service_name
.empty());
929 DCHECK(!callback
.is_null());
931 GetDBusTaskRunner()->PostTask(
933 base::Bind(&Bus::ListenForServiceOwnerChangeInternal
,
934 this, service_name
, callback
));
937 void Bus::ListenForServiceOwnerChangeInternal(
938 const std::string
& service_name
,
939 const GetServiceOwnerCallback
& callback
) {
940 AssertOnDBusThread();
941 DCHECK(!service_name
.empty());
942 DCHECK(!callback
.is_null());
944 if (!Connect() || !SetUpAsyncOperations())
947 if (service_owner_changed_listener_map_
.empty())
948 AddFilterFunction(Bus::OnServiceOwnerChangedFilter
, this);
950 ServiceOwnerChangedListenerMap::iterator it
=
951 service_owner_changed_listener_map_
.find(service_name
);
952 if (it
== service_owner_changed_listener_map_
.end()) {
953 // Add a match rule for the new service name.
954 const std::string name_owner_changed_match_rule
=
955 base::StringPrintf(kServiceNameOwnerChangeMatchRule
,
956 service_name
.c_str());
957 ScopedDBusError error
;
958 AddMatch(name_owner_changed_match_rule
, error
.get());
959 if (error
.is_set()) {
960 LOG(ERROR
) << "Failed to add match rule for " << service_name
961 << ". Got " << error
.name() << ": " << error
.message();
965 service_owner_changed_listener_map_
[service_name
].push_back(callback
);
969 // Check if the callback has already been added.
970 std::vector
<GetServiceOwnerCallback
>& callbacks
= it
->second
;
971 for (size_t i
= 0; i
< callbacks
.size(); ++i
) {
972 if (callbacks
[i
].Equals(callback
))
975 callbacks
.push_back(callback
);
978 void Bus::UnlistenForServiceOwnerChange(
979 const std::string
& service_name
,
980 const GetServiceOwnerCallback
& callback
) {
981 AssertOnOriginThread();
982 DCHECK(!service_name
.empty());
983 DCHECK(!callback
.is_null());
985 GetDBusTaskRunner()->PostTask(
987 base::Bind(&Bus::UnlistenForServiceOwnerChangeInternal
,
988 this, service_name
, callback
));
991 void Bus::UnlistenForServiceOwnerChangeInternal(
992 const std::string
& service_name
,
993 const GetServiceOwnerCallback
& callback
) {
994 AssertOnDBusThread();
995 DCHECK(!service_name
.empty());
996 DCHECK(!callback
.is_null());
998 ServiceOwnerChangedListenerMap::iterator it
=
999 service_owner_changed_listener_map_
.find(service_name
);
1000 if (it
== service_owner_changed_listener_map_
.end())
1003 std::vector
<GetServiceOwnerCallback
>& callbacks
= it
->second
;
1004 for (size_t i
= 0; i
< callbacks
.size(); ++i
) {
1005 if (callbacks
[i
].Equals(callback
)) {
1006 callbacks
.erase(callbacks
.begin() + i
);
1007 break; // There can be only one.
1010 if (!callbacks
.empty())
1013 // Last callback for |service_name| has been removed, remove match rule.
1014 const std::string name_owner_changed_match_rule
=
1015 base::StringPrintf(kServiceNameOwnerChangeMatchRule
,
1016 service_name
.c_str());
1017 ScopedDBusError error
;
1018 RemoveMatch(name_owner_changed_match_rule
, error
.get());
1019 // And remove |service_owner_changed_listener_map_| entry.
1020 service_owner_changed_listener_map_
.erase(it
);
1022 if (service_owner_changed_listener_map_
.empty())
1023 RemoveFilterFunction(Bus::OnServiceOwnerChangedFilter
, this);
1026 dbus_bool_t
Bus::OnAddWatch(DBusWatch
* raw_watch
) {
1027 AssertOnDBusThread();
1029 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
1030 Watch
* watch
= new Watch(raw_watch
);
1031 if (watch
->IsReadyToBeWatched()) {
1032 watch
->StartWatching();
1034 ++num_pending_watches_
;
1038 void Bus::OnRemoveWatch(DBusWatch
* raw_watch
) {
1039 AssertOnDBusThread();
1041 Watch
* watch
= static_cast<Watch
*>(dbus_watch_get_data(raw_watch
));
1043 --num_pending_watches_
;
1046 void Bus::OnToggleWatch(DBusWatch
* raw_watch
) {
1047 AssertOnDBusThread();
1049 Watch
* watch
= static_cast<Watch
*>(dbus_watch_get_data(raw_watch
));
1050 if (watch
->IsReadyToBeWatched()) {
1051 watch
->StartWatching();
1053 // It's safe to call this if StartWatching() wasn't called, per
1054 // message_pump_libevent.h.
1055 watch
->StopWatching();
1059 dbus_bool_t
Bus::OnAddTimeout(DBusTimeout
* raw_timeout
) {
1060 AssertOnDBusThread();
1062 // timeout will be deleted when raw_timeout is removed in
1063 // OnRemoveTimeoutThunk().
1064 Timeout
* timeout
= new Timeout(raw_timeout
);
1065 if (timeout
->IsReadyToBeMonitored()) {
1066 timeout
->StartMonitoring(this);
1068 ++num_pending_timeouts_
;
1072 void Bus::OnRemoveTimeout(DBusTimeout
* raw_timeout
) {
1073 AssertOnDBusThread();
1075 Timeout
* timeout
= static_cast<Timeout
*>(dbus_timeout_get_data(raw_timeout
));
1076 timeout
->Complete();
1077 --num_pending_timeouts_
;
1080 void Bus::OnToggleTimeout(DBusTimeout
* raw_timeout
) {
1081 AssertOnDBusThread();
1083 Timeout
* timeout
= static_cast<Timeout
*>(dbus_timeout_get_data(raw_timeout
));
1084 if (timeout
->IsReadyToBeMonitored()) {
1085 timeout
->StartMonitoring(this);
1087 timeout
->StopMonitoring();
1091 void Bus::OnDispatchStatusChanged(DBusConnection
* connection
,
1092 DBusDispatchStatus status
) {
1093 DCHECK_EQ(connection
, connection_
);
1094 AssertOnDBusThread();
1096 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
1097 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
1098 // prohibited by the D-Bus library. Hence, we post a task here instead.
1099 // See comments for dbus_connection_set_dispatch_status_function().
1100 GetDBusTaskRunner()->PostTask(FROM_HERE
,
1101 base::Bind(&Bus::ProcessAllIncomingDataIfAny
,
1105 void Bus::OnServiceOwnerChanged(DBusMessage
* message
) {
1107 AssertOnDBusThread();
1109 // |message| will be unrefed on exit of the function. Increment the
1110 // reference so we can use it in Signal::FromRawMessage() below.
1111 dbus_message_ref(message
);
1112 scoped_ptr
<Signal
> signal(Signal::FromRawMessage(message
));
1114 // Confirm the validity of the NameOwnerChanged signal.
1115 if (signal
->GetMember() != kNameOwnerChangedSignal
||
1116 signal
->GetInterface() != DBUS_INTERFACE_DBUS
||
1117 signal
->GetSender() != DBUS_SERVICE_DBUS
) {
1121 MessageReader
reader(signal
.get());
1122 std::string service_name
;
1123 std::string old_owner
;
1124 std::string new_owner
;
1125 if (!reader
.PopString(&service_name
) ||
1126 !reader
.PopString(&old_owner
) ||
1127 !reader
.PopString(&new_owner
)) {
1131 ServiceOwnerChangedListenerMap::const_iterator it
=
1132 service_owner_changed_listener_map_
.find(service_name
);
1133 if (it
== service_owner_changed_listener_map_
.end())
1136 const std::vector
<GetServiceOwnerCallback
>& callbacks
= it
->second
;
1137 for (size_t i
= 0; i
< callbacks
.size(); ++i
) {
1138 GetOriginTaskRunner()->PostTask(FROM_HERE
,
1139 base::Bind(callbacks
[i
], new_owner
));
1144 dbus_bool_t
Bus::OnAddWatchThunk(DBusWatch
* raw_watch
, void* data
) {
1145 Bus
* self
= static_cast<Bus
*>(data
);
1146 return self
->OnAddWatch(raw_watch
);
1150 void Bus::OnRemoveWatchThunk(DBusWatch
* raw_watch
, void* data
) {
1151 Bus
* self
= static_cast<Bus
*>(data
);
1152 self
->OnRemoveWatch(raw_watch
);
1156 void Bus::OnToggleWatchThunk(DBusWatch
* raw_watch
, void* data
) {
1157 Bus
* self
= static_cast<Bus
*>(data
);
1158 self
->OnToggleWatch(raw_watch
);
1162 dbus_bool_t
Bus::OnAddTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
1163 Bus
* self
= static_cast<Bus
*>(data
);
1164 return self
->OnAddTimeout(raw_timeout
);
1168 void Bus::OnRemoveTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
1169 Bus
* self
= static_cast<Bus
*>(data
);
1170 self
->OnRemoveTimeout(raw_timeout
);
1174 void Bus::OnToggleTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
1175 Bus
* self
= static_cast<Bus
*>(data
);
1176 self
->OnToggleTimeout(raw_timeout
);
1180 void Bus::OnDispatchStatusChangedThunk(DBusConnection
* connection
,
1181 DBusDispatchStatus status
,
1183 Bus
* self
= static_cast<Bus
*>(data
);
1184 self
->OnDispatchStatusChanged(connection
, status
);
1188 DBusHandlerResult
Bus::OnConnectionDisconnectedFilter(
1189 DBusConnection
* connection
,
1190 DBusMessage
* message
,
1192 if (dbus_message_is_signal(message
,
1193 DBUS_INTERFACE_LOCAL
,
1194 kDisconnectedSignal
)) {
1195 // Abort when the connection is lost.
1196 LOG(FATAL
) << "D-Bus connection was disconnected. Aborting.";
1198 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1202 DBusHandlerResult
Bus::OnServiceOwnerChangedFilter(
1203 DBusConnection
* connection
,
1204 DBusMessage
* message
,
1206 if (dbus_message_is_signal(message
,
1207 DBUS_INTERFACE_DBUS
,
1208 kNameOwnerChangedSignal
)) {
1209 Bus
* self
= static_cast<Bus
*>(data
);
1210 self
->OnServiceOwnerChanged(message
);
1212 // Always return unhandled to let others, e.g. ObjectProxies, handle the same
1214 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;