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 on_disconnected_closure_(options
.disconnected_callback
) {
202 // This is safe to call multiple times.
203 dbus_threads_init_default();
204 // The origin message loop is unnecessary if the client uses synchronous
206 if (base::MessageLoop::current())
207 origin_task_runner_
= base::MessageLoop::current()->message_loop_proxy();
211 DCHECK(!connection_
);
212 DCHECK(owned_service_names_
.empty());
213 DCHECK(match_rules_added_
.empty());
214 DCHECK(filter_functions_added_
.empty());
215 DCHECK(registered_object_paths_
.empty());
216 DCHECK_EQ(0, num_pending_watches_
);
217 // TODO(satorux): This check fails occasionally in browser_tests for tests
218 // that run very quickly. Perhaps something does not have time to clean up.
219 // Despite the check failing, the tests seem to run fine. crosbug.com/23416
220 // DCHECK_EQ(0, num_pending_timeouts_);
223 ObjectProxy
* Bus::GetObjectProxy(const std::string
& service_name
,
224 const ObjectPath
& object_path
) {
225 return GetObjectProxyWithOptions(service_name
, object_path
,
226 ObjectProxy::DEFAULT_OPTIONS
);
229 ObjectProxy
* Bus::GetObjectProxyWithOptions(const std::string
& service_name
,
230 const ObjectPath
& object_path
,
232 AssertOnOriginThread();
234 // Check if we already have the requested object proxy.
235 const ObjectProxyTable::key_type
key(service_name
+ object_path
.value(),
237 ObjectProxyTable::iterator iter
= object_proxy_table_
.find(key
);
238 if (iter
!= object_proxy_table_
.end()) {
239 return iter
->second
.get();
242 scoped_refptr
<ObjectProxy
> object_proxy
=
243 new ObjectProxy(this, service_name
, object_path
, options
);
244 object_proxy_table_
[key
] = object_proxy
;
246 return object_proxy
.get();
249 bool Bus::RemoveObjectProxy(const std::string
& service_name
,
250 const ObjectPath
& object_path
,
251 const base::Closure
& callback
) {
252 return RemoveObjectProxyWithOptions(service_name
, object_path
,
253 ObjectProxy::DEFAULT_OPTIONS
,
257 bool Bus::RemoveObjectProxyWithOptions(const std::string
& service_name
,
258 const ObjectPath
& object_path
,
260 const base::Closure
& callback
) {
261 AssertOnOriginThread();
263 // Check if we have the requested object proxy.
264 const ObjectProxyTable::key_type
key(service_name
+ object_path
.value(),
266 ObjectProxyTable::iterator iter
= object_proxy_table_
.find(key
);
267 if (iter
!= object_proxy_table_
.end()) {
268 scoped_refptr
<ObjectProxy
> object_proxy
= iter
->second
;
269 object_proxy_table_
.erase(iter
);
270 // Object is present. Remove it now and Detach on the DBus thread.
271 GetDBusTaskRunner()->PostTask(
273 base::Bind(&Bus::RemoveObjectProxyInternal
,
274 this, object_proxy
, callback
));
280 void Bus::RemoveObjectProxyInternal(scoped_refptr
<ObjectProxy
> object_proxy
,
281 const base::Closure
& callback
) {
282 AssertOnDBusThread();
284 object_proxy
.get()->Detach();
286 GetOriginTaskRunner()->PostTask(FROM_HERE
, callback
);
289 ExportedObject
* Bus::GetExportedObject(const ObjectPath
& object_path
) {
290 AssertOnOriginThread();
292 // Check if we already have the requested exported object.
293 ExportedObjectTable::iterator iter
= exported_object_table_
.find(object_path
);
294 if (iter
!= exported_object_table_
.end()) {
295 return iter
->second
.get();
298 scoped_refptr
<ExportedObject
> exported_object
=
299 new ExportedObject(this, object_path
);
300 exported_object_table_
[object_path
] = exported_object
;
302 return exported_object
.get();
305 void Bus::UnregisterExportedObject(const ObjectPath
& object_path
) {
306 AssertOnOriginThread();
308 // Remove the registered object from the table first, to allow a new
309 // GetExportedObject() call to return a new object, rather than this one.
310 ExportedObjectTable::iterator iter
= exported_object_table_
.find(object_path
);
311 if (iter
== exported_object_table_
.end())
314 scoped_refptr
<ExportedObject
> exported_object
= iter
->second
;
315 exported_object_table_
.erase(iter
);
317 // Post the task to perform the final unregistration to the D-Bus thread.
318 // Since the registration also happens on the D-Bus thread in
319 // TryRegisterObjectPath(), and the task runner we post to is a
320 // SequencedTaskRunner, there is a guarantee that this will happen before any
321 // future registration call.
322 GetDBusTaskRunner()->PostTask(
324 base::Bind(&Bus::UnregisterExportedObjectInternal
,
325 this, exported_object
));
328 void Bus::UnregisterExportedObjectInternal(
329 scoped_refptr
<ExportedObject
> exported_object
) {
330 AssertOnDBusThread();
332 exported_object
->Unregister();
335 ObjectManager
* Bus::GetObjectManager(const std::string
& service_name
,
336 const ObjectPath
& object_path
) {
337 AssertOnOriginThread();
339 // Check if we already have the requested object manager.
340 const ObjectManagerTable::key_type
key(service_name
+ object_path
.value());
341 ObjectManagerTable::iterator iter
= object_manager_table_
.find(key
);
342 if (iter
!= object_manager_table_
.end()) {
343 return iter
->second
.get();
346 scoped_refptr
<ObjectManager
> object_manager
=
347 new ObjectManager(this, service_name
, object_path
);
348 object_manager_table_
[key
] = object_manager
;
350 return object_manager
.get();
353 bool Bus::RemoveObjectManager(const std::string
& service_name
,
354 const ObjectPath
& object_path
,
355 const base::Closure
& callback
) {
356 AssertOnOriginThread();
357 DCHECK(!callback
.is_null());
359 const ObjectManagerTable::key_type
key(service_name
+ object_path
.value());
360 ObjectManagerTable::iterator iter
= object_manager_table_
.find(key
);
361 if (iter
== object_manager_table_
.end())
364 // ObjectManager is present. Remove it now and CleanUp on the DBus thread.
365 scoped_refptr
<ObjectManager
> object_manager
= iter
->second
;
366 object_manager_table_
.erase(iter
);
368 GetDBusTaskRunner()->PostTask(
370 base::Bind(&Bus::RemoveObjectManagerInternal
,
371 this, object_manager
, callback
));
376 void Bus::RemoveObjectManagerInternal(
377 scoped_refptr
<dbus::ObjectManager
> object_manager
,
378 const base::Closure
& callback
) {
379 AssertOnDBusThread();
380 DCHECK(object_manager
.get());
382 object_manager
->CleanUp();
384 // The ObjectManager has to be deleted on the origin thread since it was
386 GetOriginTaskRunner()->PostTask(
388 base::Bind(&Bus::RemoveObjectManagerInternalHelper
,
389 this, object_manager
, callback
));
392 void Bus::RemoveObjectManagerInternalHelper(
393 scoped_refptr
<dbus::ObjectManager
> object_manager
,
394 const base::Closure
& callback
) {
395 AssertOnOriginThread();
396 DCHECK(object_manager
.get());
398 // Release the object manager and run the callback.
399 object_manager
= NULL
;
403 void Bus::GetManagedObjects() {
404 for (ObjectManagerTable::iterator iter
= object_manager_table_
.begin();
405 iter
!= object_manager_table_
.end(); ++iter
) {
406 iter
->second
->GetManagedObjects();
410 bool Bus::Connect() {
411 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
412 AssertOnDBusThread();
414 // Check if it's already initialized.
418 ScopedDBusError error
;
419 if (bus_type_
== CUSTOM_ADDRESS
) {
420 if (connection_type_
== PRIVATE
) {
421 connection_
= dbus_connection_open_private(address_
.c_str(), error
.get());
423 connection_
= dbus_connection_open(address_
.c_str(), error
.get());
426 const DBusBusType dbus_bus_type
= static_cast<DBusBusType
>(bus_type_
);
427 if (connection_type_
== PRIVATE
) {
428 connection_
= dbus_bus_get_private(dbus_bus_type
, error
.get());
430 connection_
= dbus_bus_get(dbus_bus_type
, error
.get());
434 LOG(ERROR
) << "Failed to connect to the bus: "
435 << (error
.is_set() ? error
.message() : "");
439 if (bus_type_
== CUSTOM_ADDRESS
) {
440 // We should call dbus_bus_register here, otherwise unique name can not be
441 // acquired. According to dbus specification, it is responsible to call
442 // org.freedesktop.DBus.Hello method at the beging of bus connection to
443 // acquire unique name. In the case of dbus_bus_get, dbus_bus_register is
444 // called internally.
445 if (!dbus_bus_register(connection_
, error
.get())) {
446 LOG(ERROR
) << "Failed to register the bus component: "
447 << (error
.is_set() ? error
.message() : "");
451 // We shouldn't exit on the disconnected signal.
452 dbus_connection_set_exit_on_disconnect(connection_
, false);
454 // Watch Disconnected signal.
455 AddFilterFunction(Bus::OnConnectionDisconnectedFilter
, this);
456 AddMatch(kDisconnectedMatchRule
, error
.get());
461 void Bus::ClosePrivateConnection() {
462 // dbus_connection_close is blocking call.
463 AssertOnDBusThread();
464 DCHECK_EQ(PRIVATE
, connection_type_
)
465 << "non-private connection should not be closed";
466 dbus_connection_close(connection_
);
469 void Bus::ShutdownAndBlock() {
470 AssertOnDBusThread();
472 if (shutdown_completed_
)
473 return; // Already shutdowned, just return.
475 // Unregister the exported objects.
476 for (ExportedObjectTable::iterator iter
= exported_object_table_
.begin();
477 iter
!= exported_object_table_
.end(); ++iter
) {
478 iter
->second
->Unregister();
481 // Release all service names.
482 for (std::set
<std::string
>::iterator iter
= owned_service_names_
.begin();
483 iter
!= owned_service_names_
.end();) {
484 // This is a bit tricky but we should increment the iter here as
485 // ReleaseOwnership() may remove |service_name| from the set.
486 const std::string
& service_name
= *iter
++;
487 ReleaseOwnership(service_name
);
489 if (!owned_service_names_
.empty()) {
490 LOG(ERROR
) << "Failed to release all service names. # of services left: "
491 << owned_service_names_
.size();
494 // Detach from the remote objects.
495 for (ObjectProxyTable::iterator iter
= object_proxy_table_
.begin();
496 iter
!= object_proxy_table_
.end(); ++iter
) {
497 iter
->second
->Detach();
500 // Clean up the object managers.
501 for (ObjectManagerTable::iterator iter
= object_manager_table_
.begin();
502 iter
!= object_manager_table_
.end(); ++iter
) {
503 iter
->second
->CleanUp();
506 // Release object proxies and exported objects here. We should do this
507 // here rather than in the destructor to avoid memory leaks due to
508 // cyclic references.
509 object_proxy_table_
.clear();
510 exported_object_table_
.clear();
512 // Private connection should be closed.
514 // Remove Disconnected watcher.
515 ScopedDBusError error
;
516 RemoveFilterFunction(Bus::OnConnectionDisconnectedFilter
, this);
517 RemoveMatch(kDisconnectedMatchRule
, error
.get());
519 if (connection_type_
== PRIVATE
)
520 ClosePrivateConnection();
521 // dbus_connection_close() won't unref.
522 dbus_connection_unref(connection_
);
526 shutdown_completed_
= true;
529 void Bus::ShutdownOnDBusThreadAndBlock() {
530 AssertOnOriginThread();
531 DCHECK(dbus_task_runner_
.get());
533 GetDBusTaskRunner()->PostTask(
535 base::Bind(&Bus::ShutdownOnDBusThreadAndBlockInternal
, this));
537 // http://crbug.com/125222
538 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
540 // Wait until the shutdown is complete on the D-Bus thread.
541 // The shutdown should not hang, but set timeout just in case.
542 const int kTimeoutSecs
= 3;
543 const base::TimeDelta
timeout(base::TimeDelta::FromSeconds(kTimeoutSecs
));
544 const bool signaled
= on_shutdown_
.TimedWait(timeout
);
545 LOG_IF(ERROR
, !signaled
) << "Failed to shutdown the bus";
548 void Bus::RequestOwnership(const std::string
& service_name
,
549 ServiceOwnershipOptions options
,
550 OnOwnershipCallback on_ownership_callback
) {
551 AssertOnOriginThread();
553 GetDBusTaskRunner()->PostTask(
555 base::Bind(&Bus::RequestOwnershipInternal
,
556 this, service_name
, options
, on_ownership_callback
));
559 void Bus::RequestOwnershipInternal(const std::string
& service_name
,
560 ServiceOwnershipOptions options
,
561 OnOwnershipCallback on_ownership_callback
) {
562 AssertOnDBusThread();
564 bool success
= Connect();
566 success
= RequestOwnershipAndBlock(service_name
, options
);
568 GetOriginTaskRunner()->PostTask(FROM_HERE
,
569 base::Bind(on_ownership_callback
,
574 bool Bus::RequestOwnershipAndBlock(const std::string
& service_name
,
575 ServiceOwnershipOptions options
) {
577 // dbus_bus_request_name() is a blocking call.
578 AssertOnDBusThread();
580 // Check if we already own the service name.
581 if (owned_service_names_
.find(service_name
) != owned_service_names_
.end()) {
585 ScopedDBusError error
;
586 const int result
= dbus_bus_request_name(connection_
,
587 service_name
.c_str(),
590 if (result
!= DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
) {
591 LOG(ERROR
) << "Failed to get the ownership of " << service_name
<< ": "
592 << (error
.is_set() ? error
.message() : "");
595 owned_service_names_
.insert(service_name
);
599 bool Bus::ReleaseOwnership(const std::string
& service_name
) {
601 // dbus_bus_request_name() is a blocking call.
602 AssertOnDBusThread();
604 // Check if we already own the service name.
605 std::set
<std::string
>::iterator found
=
606 owned_service_names_
.find(service_name
);
607 if (found
== owned_service_names_
.end()) {
608 LOG(ERROR
) << service_name
<< " is not owned by the bus";
612 ScopedDBusError error
;
613 const int result
= dbus_bus_release_name(connection_
, service_name
.c_str(),
615 if (result
== DBUS_RELEASE_NAME_REPLY_RELEASED
) {
616 owned_service_names_
.erase(found
);
619 LOG(ERROR
) << "Failed to release the ownership of " << service_name
<< ": "
620 << (error
.is_set() ? error
.message() : "")
621 << ", result code: " << result
;
626 bool Bus::SetUpAsyncOperations() {
628 AssertOnDBusThread();
630 if (async_operations_set_up_
)
633 // Process all the incoming data if any, so that OnDispatchStatus() will
634 // be called when the incoming data is ready.
635 ProcessAllIncomingDataIfAny();
637 bool success
= dbus_connection_set_watch_functions(connection_
,
638 &Bus::OnAddWatchThunk
,
639 &Bus::OnRemoveWatchThunk
,
640 &Bus::OnToggleWatchThunk
,
643 CHECK(success
) << "Unable to allocate memory";
645 success
= dbus_connection_set_timeout_functions(connection_
,
646 &Bus::OnAddTimeoutThunk
,
647 &Bus::OnRemoveTimeoutThunk
,
648 &Bus::OnToggleTimeoutThunk
,
651 CHECK(success
) << "Unable to allocate memory";
653 dbus_connection_set_dispatch_status_function(
655 &Bus::OnDispatchStatusChangedThunk
,
659 async_operations_set_up_
= true;
664 DBusMessage
* Bus::SendWithReplyAndBlock(DBusMessage
* request
,
668 AssertOnDBusThread();
670 return dbus_connection_send_with_reply_and_block(
671 connection_
, request
, timeout_ms
, error
);
674 void Bus::SendWithReply(DBusMessage
* request
,
675 DBusPendingCall
** pending_call
,
678 AssertOnDBusThread();
680 const bool success
= dbus_connection_send_with_reply(
681 connection_
, request
, pending_call
, timeout_ms
);
682 CHECK(success
) << "Unable to allocate memory";
685 void Bus::Send(DBusMessage
* request
, uint32
* serial
) {
687 AssertOnDBusThread();
689 const bool success
= dbus_connection_send(connection_
, request
, serial
);
690 CHECK(success
) << "Unable to allocate memory";
693 void Bus::AddFilterFunction(DBusHandleMessageFunction filter_function
,
696 AssertOnDBusThread();
698 std::pair
<DBusHandleMessageFunction
, void*> filter_data_pair
=
699 std::make_pair(filter_function
, user_data
);
700 if (filter_functions_added_
.find(filter_data_pair
) !=
701 filter_functions_added_
.end()) {
702 VLOG(1) << "Filter function already exists: " << filter_function
703 << " with associated data: " << user_data
;
707 const bool success
= dbus_connection_add_filter(
708 connection_
, filter_function
, user_data
, NULL
);
709 CHECK(success
) << "Unable to allocate memory";
710 filter_functions_added_
.insert(filter_data_pair
);
713 void Bus::RemoveFilterFunction(DBusHandleMessageFunction filter_function
,
716 AssertOnDBusThread();
718 std::pair
<DBusHandleMessageFunction
, void*> filter_data_pair
=
719 std::make_pair(filter_function
, user_data
);
720 if (filter_functions_added_
.find(filter_data_pair
) ==
721 filter_functions_added_
.end()) {
722 VLOG(1) << "Requested to remove an unknown filter function: "
724 << " with associated data: " << user_data
;
728 dbus_connection_remove_filter(connection_
, filter_function
, user_data
);
729 filter_functions_added_
.erase(filter_data_pair
);
732 void Bus::AddMatch(const std::string
& match_rule
, DBusError
* error
) {
734 AssertOnDBusThread();
736 std::map
<std::string
, int>::iterator iter
=
737 match_rules_added_
.find(match_rule
);
738 if (iter
!= match_rules_added_
.end()) {
739 // The already existing rule's counter is incremented.
742 VLOG(1) << "Match rule already exists: " << match_rule
;
746 dbus_bus_add_match(connection_
, match_rule
.c_str(), error
);
747 match_rules_added_
[match_rule
] = 1;
750 bool Bus::RemoveMatch(const std::string
& match_rule
, DBusError
* error
) {
752 AssertOnDBusThread();
754 std::map
<std::string
, int>::iterator iter
=
755 match_rules_added_
.find(match_rule
);
756 if (iter
== match_rules_added_
.end()) {
757 LOG(ERROR
) << "Requested to remove an unknown match rule: " << match_rule
;
761 // The rule's counter is decremented and the rule is deleted when reachs 0.
763 if (iter
->second
== 0) {
764 dbus_bus_remove_match(connection_
, match_rule
.c_str(), error
);
765 match_rules_added_
.erase(match_rule
);
770 bool Bus::TryRegisterObjectPath(const ObjectPath
& object_path
,
771 const DBusObjectPathVTable
* vtable
,
775 AssertOnDBusThread();
777 if (registered_object_paths_
.find(object_path
) !=
778 registered_object_paths_
.end()) {
779 LOG(ERROR
) << "Object path already registered: " << object_path
.value();
783 const bool success
= dbus_connection_try_register_object_path(
785 object_path
.value().c_str(),
790 registered_object_paths_
.insert(object_path
);
794 void Bus::UnregisterObjectPath(const ObjectPath
& object_path
) {
796 AssertOnDBusThread();
798 if (registered_object_paths_
.find(object_path
) ==
799 registered_object_paths_
.end()) {
800 LOG(ERROR
) << "Requested to unregister an unknown object path: "
801 << object_path
.value();
805 const bool success
= dbus_connection_unregister_object_path(
807 object_path
.value().c_str());
808 CHECK(success
) << "Unable to allocate memory";
809 registered_object_paths_
.erase(object_path
);
812 void Bus::ShutdownOnDBusThreadAndBlockInternal() {
813 AssertOnDBusThread();
816 on_shutdown_
.Signal();
819 void Bus::ProcessAllIncomingDataIfAny() {
820 AssertOnDBusThread();
822 // As mentioned at the class comment in .h file, connection_ can be NULL.
826 // It is safe and necessary to call dbus_connection_get_dispatch_status even
827 // if the connection is lost. Otherwise we will miss "Disconnected" signal.
828 // (crbug.com/174431)
829 if (dbus_connection_get_dispatch_status(connection_
) ==
830 DBUS_DISPATCH_DATA_REMAINS
) {
831 while (dbus_connection_dispatch(connection_
) ==
832 DBUS_DISPATCH_DATA_REMAINS
) {
837 base::TaskRunner
* Bus::GetDBusTaskRunner() {
838 if (dbus_task_runner_
.get())
839 return dbus_task_runner_
.get();
841 return GetOriginTaskRunner();
844 base::TaskRunner
* Bus::GetOriginTaskRunner() {
845 DCHECK(origin_task_runner_
.get());
846 return origin_task_runner_
.get();
849 bool Bus::HasDBusThread() {
850 return dbus_task_runner_
.get() != NULL
;
853 void Bus::AssertOnOriginThread() {
854 DCHECK_EQ(origin_thread_id_
, base::PlatformThread::CurrentId());
857 void Bus::AssertOnDBusThread() {
858 base::ThreadRestrictions::AssertIOAllowed();
860 if (dbus_task_runner_
.get()) {
861 DCHECK(dbus_task_runner_
->RunsTasksOnCurrentThread());
863 AssertOnOriginThread();
867 std::string
Bus::GetServiceOwnerAndBlock(const std::string
& service_name
,
868 GetServiceOwnerOption options
) {
869 AssertOnDBusThread();
871 MethodCall
get_name_owner_call("org.freedesktop.DBus", "GetNameOwner");
872 MessageWriter
writer(&get_name_owner_call
);
873 writer
.AppendString(service_name
);
874 VLOG(1) << "Method call: " << get_name_owner_call
.ToString();
876 const ObjectPath
obj_path("/org/freedesktop/DBus");
877 if (!get_name_owner_call
.SetDestination("org.freedesktop.DBus") ||
878 !get_name_owner_call
.SetPath(obj_path
)) {
879 if (options
== REPORT_ERRORS
)
880 LOG(ERROR
) << "Failed to get name owner.";
884 ScopedDBusError error
;
885 DBusMessage
* response_message
=
886 SendWithReplyAndBlock(get_name_owner_call
.raw_message(),
887 ObjectProxy::TIMEOUT_USE_DEFAULT
,
889 if (!response_message
) {
890 if (options
== REPORT_ERRORS
) {
891 LOG(ERROR
) << "Failed to get name owner. Got " << error
.name() << ": "
897 scoped_ptr
<Response
> response(Response::FromRawMessage(response_message
));
898 MessageReader
reader(response
.get());
900 std::string service_owner
;
901 if (!reader
.PopString(&service_owner
))
902 service_owner
.clear();
903 return service_owner
;
906 void Bus::GetServiceOwner(const std::string
& service_name
,
907 const GetServiceOwnerCallback
& callback
) {
908 AssertOnOriginThread();
910 GetDBusTaskRunner()->PostTask(
912 base::Bind(&Bus::GetServiceOwnerInternal
, this, service_name
, callback
));
915 void Bus::GetServiceOwnerInternal(const std::string
& service_name
,
916 const GetServiceOwnerCallback
& callback
) {
917 AssertOnDBusThread();
919 std::string service_owner
;
921 service_owner
= GetServiceOwnerAndBlock(service_name
, SUPPRESS_ERRORS
);
922 GetOriginTaskRunner()->PostTask(FROM_HERE
,
923 base::Bind(callback
, service_owner
));
926 void Bus::ListenForServiceOwnerChange(
927 const std::string
& service_name
,
928 const GetServiceOwnerCallback
& callback
) {
929 AssertOnOriginThread();
930 DCHECK(!service_name
.empty());
931 DCHECK(!callback
.is_null());
933 GetDBusTaskRunner()->PostTask(
935 base::Bind(&Bus::ListenForServiceOwnerChangeInternal
,
936 this, service_name
, callback
));
939 void Bus::ListenForServiceOwnerChangeInternal(
940 const std::string
& service_name
,
941 const GetServiceOwnerCallback
& callback
) {
942 AssertOnDBusThread();
943 DCHECK(!service_name
.empty());
944 DCHECK(!callback
.is_null());
946 if (!Connect() || !SetUpAsyncOperations())
949 if (service_owner_changed_listener_map_
.empty())
950 AddFilterFunction(Bus::OnServiceOwnerChangedFilter
, this);
952 ServiceOwnerChangedListenerMap::iterator it
=
953 service_owner_changed_listener_map_
.find(service_name
);
954 if (it
== service_owner_changed_listener_map_
.end()) {
955 // Add a match rule for the new service name.
956 const std::string name_owner_changed_match_rule
=
957 base::StringPrintf(kServiceNameOwnerChangeMatchRule
,
958 service_name
.c_str());
959 ScopedDBusError error
;
960 AddMatch(name_owner_changed_match_rule
, error
.get());
961 if (error
.is_set()) {
962 LOG(ERROR
) << "Failed to add match rule for " << service_name
963 << ". Got " << error
.name() << ": " << error
.message();
967 service_owner_changed_listener_map_
[service_name
].push_back(callback
);
971 // Check if the callback has already been added.
972 std::vector
<GetServiceOwnerCallback
>& callbacks
= it
->second
;
973 for (size_t i
= 0; i
< callbacks
.size(); ++i
) {
974 if (callbacks
[i
].Equals(callback
))
977 callbacks
.push_back(callback
);
980 void Bus::UnlistenForServiceOwnerChange(
981 const std::string
& service_name
,
982 const GetServiceOwnerCallback
& callback
) {
983 AssertOnOriginThread();
984 DCHECK(!service_name
.empty());
985 DCHECK(!callback
.is_null());
987 GetDBusTaskRunner()->PostTask(
989 base::Bind(&Bus::UnlistenForServiceOwnerChangeInternal
,
990 this, service_name
, callback
));
993 void Bus::UnlistenForServiceOwnerChangeInternal(
994 const std::string
& service_name
,
995 const GetServiceOwnerCallback
& callback
) {
996 AssertOnDBusThread();
997 DCHECK(!service_name
.empty());
998 DCHECK(!callback
.is_null());
1000 ServiceOwnerChangedListenerMap::iterator it
=
1001 service_owner_changed_listener_map_
.find(service_name
);
1002 if (it
== service_owner_changed_listener_map_
.end())
1005 std::vector
<GetServiceOwnerCallback
>& callbacks
= it
->second
;
1006 for (size_t i
= 0; i
< callbacks
.size(); ++i
) {
1007 if (callbacks
[i
].Equals(callback
)) {
1008 callbacks
.erase(callbacks
.begin() + i
);
1009 break; // There can be only one.
1012 if (!callbacks
.empty())
1015 // Last callback for |service_name| has been removed, remove match rule.
1016 const std::string name_owner_changed_match_rule
=
1017 base::StringPrintf(kServiceNameOwnerChangeMatchRule
,
1018 service_name
.c_str());
1019 ScopedDBusError error
;
1020 RemoveMatch(name_owner_changed_match_rule
, error
.get());
1021 // And remove |service_owner_changed_listener_map_| entry.
1022 service_owner_changed_listener_map_
.erase(it
);
1024 if (service_owner_changed_listener_map_
.empty())
1025 RemoveFilterFunction(Bus::OnServiceOwnerChangedFilter
, this);
1028 dbus_bool_t
Bus::OnAddWatch(DBusWatch
* raw_watch
) {
1029 AssertOnDBusThread();
1031 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
1032 Watch
* watch
= new Watch(raw_watch
);
1033 if (watch
->IsReadyToBeWatched()) {
1034 watch
->StartWatching();
1036 ++num_pending_watches_
;
1040 void Bus::OnRemoveWatch(DBusWatch
* raw_watch
) {
1041 AssertOnDBusThread();
1043 Watch
* watch
= static_cast<Watch
*>(dbus_watch_get_data(raw_watch
));
1045 --num_pending_watches_
;
1048 void Bus::OnToggleWatch(DBusWatch
* raw_watch
) {
1049 AssertOnDBusThread();
1051 Watch
* watch
= static_cast<Watch
*>(dbus_watch_get_data(raw_watch
));
1052 if (watch
->IsReadyToBeWatched()) {
1053 watch
->StartWatching();
1055 // It's safe to call this if StartWatching() wasn't called, per
1056 // message_pump_libevent.h.
1057 watch
->StopWatching();
1061 dbus_bool_t
Bus::OnAddTimeout(DBusTimeout
* raw_timeout
) {
1062 AssertOnDBusThread();
1064 // timeout will be deleted when raw_timeout is removed in
1065 // OnRemoveTimeoutThunk().
1066 Timeout
* timeout
= new Timeout(raw_timeout
);
1067 if (timeout
->IsReadyToBeMonitored()) {
1068 timeout
->StartMonitoring(this);
1070 ++num_pending_timeouts_
;
1074 void Bus::OnRemoveTimeout(DBusTimeout
* raw_timeout
) {
1075 AssertOnDBusThread();
1077 Timeout
* timeout
= static_cast<Timeout
*>(dbus_timeout_get_data(raw_timeout
));
1078 timeout
->Complete();
1079 --num_pending_timeouts_
;
1082 void Bus::OnToggleTimeout(DBusTimeout
* raw_timeout
) {
1083 AssertOnDBusThread();
1085 Timeout
* timeout
= static_cast<Timeout
*>(dbus_timeout_get_data(raw_timeout
));
1086 if (timeout
->IsReadyToBeMonitored()) {
1087 timeout
->StartMonitoring(this);
1089 timeout
->StopMonitoring();
1093 void Bus::OnDispatchStatusChanged(DBusConnection
* connection
,
1094 DBusDispatchStatus status
) {
1095 DCHECK_EQ(connection
, connection_
);
1096 AssertOnDBusThread();
1098 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
1099 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
1100 // prohibited by the D-Bus library. Hence, we post a task here instead.
1101 // See comments for dbus_connection_set_dispatch_status_function().
1102 GetDBusTaskRunner()->PostTask(FROM_HERE
,
1103 base::Bind(&Bus::ProcessAllIncomingDataIfAny
,
1107 void Bus::OnConnectionDisconnected(DBusConnection
* connection
) {
1108 AssertOnDBusThread();
1110 if (!on_disconnected_closure_
.is_null())
1111 GetOriginTaskRunner()->PostTask(FROM_HERE
, on_disconnected_closure_
);
1115 DCHECK(!dbus_connection_get_is_connected(connection
));
1120 void Bus::OnServiceOwnerChanged(DBusMessage
* message
) {
1122 AssertOnDBusThread();
1124 // |message| will be unrefed on exit of the function. Increment the
1125 // reference so we can use it in Signal::FromRawMessage() below.
1126 dbus_message_ref(message
);
1127 scoped_ptr
<Signal
> signal(Signal::FromRawMessage(message
));
1129 // Confirm the validity of the NameOwnerChanged signal.
1130 if (signal
->GetMember() != kNameOwnerChangedSignal
||
1131 signal
->GetInterface() != DBUS_INTERFACE_DBUS
||
1132 signal
->GetSender() != DBUS_SERVICE_DBUS
) {
1136 MessageReader
reader(signal
.get());
1137 std::string service_name
;
1138 std::string old_owner
;
1139 std::string new_owner
;
1140 if (!reader
.PopString(&service_name
) ||
1141 !reader
.PopString(&old_owner
) ||
1142 !reader
.PopString(&new_owner
)) {
1146 ServiceOwnerChangedListenerMap::const_iterator it
=
1147 service_owner_changed_listener_map_
.find(service_name
);
1148 if (it
== service_owner_changed_listener_map_
.end())
1151 const std::vector
<GetServiceOwnerCallback
>& callbacks
= it
->second
;
1152 for (size_t i
= 0; i
< callbacks
.size(); ++i
) {
1153 GetOriginTaskRunner()->PostTask(FROM_HERE
,
1154 base::Bind(callbacks
[i
], new_owner
));
1159 dbus_bool_t
Bus::OnAddWatchThunk(DBusWatch
* raw_watch
, void* data
) {
1160 Bus
* self
= static_cast<Bus
*>(data
);
1161 return self
->OnAddWatch(raw_watch
);
1165 void Bus::OnRemoveWatchThunk(DBusWatch
* raw_watch
, void* data
) {
1166 Bus
* self
= static_cast<Bus
*>(data
);
1167 self
->OnRemoveWatch(raw_watch
);
1171 void Bus::OnToggleWatchThunk(DBusWatch
* raw_watch
, void* data
) {
1172 Bus
* self
= static_cast<Bus
*>(data
);
1173 self
->OnToggleWatch(raw_watch
);
1177 dbus_bool_t
Bus::OnAddTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
1178 Bus
* self
= static_cast<Bus
*>(data
);
1179 return self
->OnAddTimeout(raw_timeout
);
1183 void Bus::OnRemoveTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
1184 Bus
* self
= static_cast<Bus
*>(data
);
1185 self
->OnRemoveTimeout(raw_timeout
);
1189 void Bus::OnToggleTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
1190 Bus
* self
= static_cast<Bus
*>(data
);
1191 self
->OnToggleTimeout(raw_timeout
);
1195 void Bus::OnDispatchStatusChangedThunk(DBusConnection
* connection
,
1196 DBusDispatchStatus status
,
1198 Bus
* self
= static_cast<Bus
*>(data
);
1199 self
->OnDispatchStatusChanged(connection
, status
);
1203 DBusHandlerResult
Bus::OnConnectionDisconnectedFilter(
1204 DBusConnection
* connection
,
1205 DBusMessage
* message
,
1207 if (dbus_message_is_signal(message
,
1208 DBUS_INTERFACE_LOCAL
,
1209 kDisconnectedSignal
)) {
1210 Bus
* self
= static_cast<Bus
*>(data
);
1211 self
->OnConnectionDisconnected(connection
);
1212 return DBUS_HANDLER_RESULT_HANDLED
;
1214 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
1218 DBusHandlerResult
Bus::OnServiceOwnerChangedFilter(
1219 DBusConnection
* connection
,
1220 DBusMessage
* message
,
1222 if (dbus_message_is_signal(message
,
1223 DBUS_INTERFACE_DBUS
,
1224 kNameOwnerChangedSignal
)) {
1225 Bus
* self
= static_cast<Bus
*>(data
);
1226 self
->OnServiceOwnerChanged(message
);
1228 // Always return unhandled to let others, e.g. ObjectProxies, handle the same
1230 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;