blink-test: Add enterRunLoop() and exitRunLoop() in TestBlinkWebUnitTestSupport.
[chromium-blink-merge.git] / dbus / bus.cc
blob2f1300a25e3fc87f122014df9d3ef5c4f9016281
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.
5 #include "dbus/bus.h"
7 #include "base/bind.h"
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"
23 namespace dbus {
25 namespace {
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
42 // communication.
43 class Watch : public base::MessagePumpLibevent::Watcher {
44 public:
45 explicit Watch(DBusWatch* watch)
46 : raw_watch_(watch) {
47 dbus_watch_set_data(raw_watch_, this, NULL);
50 ~Watch() override { dbus_watch_set_data(raw_watch_, NULL, NULL); }
52 // Returns true if the underlying file descriptor is ready to be watched.
53 bool IsReadyToBeWatched() {
54 return dbus_watch_get_enabled(raw_watch_);
57 // Starts watching the underlying file descriptor.
58 void StartWatching() {
59 const int file_descriptor = dbus_watch_get_unix_fd(raw_watch_);
60 const int flags = dbus_watch_get_flags(raw_watch_);
62 base::MessageLoopForIO::Mode mode = base::MessageLoopForIO::WATCH_READ;
63 if ((flags & DBUS_WATCH_READABLE) && (flags & DBUS_WATCH_WRITABLE))
64 mode = base::MessageLoopForIO::WATCH_READ_WRITE;
65 else if (flags & DBUS_WATCH_READABLE)
66 mode = base::MessageLoopForIO::WATCH_READ;
67 else if (flags & DBUS_WATCH_WRITABLE)
68 mode = base::MessageLoopForIO::WATCH_WRITE;
69 else
70 NOTREACHED();
72 const bool persistent = true; // Watch persistently.
73 const bool success = base::MessageLoopForIO::current()->WatchFileDescriptor(
74 file_descriptor, persistent, mode, &file_descriptor_watcher_, this);
75 CHECK(success) << "Unable to allocate memory";
78 // Stops watching the underlying file descriptor.
79 void StopWatching() {
80 file_descriptor_watcher_.StopWatchingFileDescriptor();
83 private:
84 // Implement MessagePumpLibevent::Watcher.
85 void OnFileCanReadWithoutBlocking(int file_descriptor) override {
86 const bool success = dbus_watch_handle(raw_watch_, DBUS_WATCH_READABLE);
87 CHECK(success) << "Unable to allocate memory";
90 // Implement MessagePumpLibevent::Watcher.
91 void OnFileCanWriteWithoutBlocking(int file_descriptor) override {
92 const bool success = dbus_watch_handle(raw_watch_, DBUS_WATCH_WRITABLE);
93 CHECK(success) << "Unable to allocate memory";
96 DBusWatch* raw_watch_;
97 base::MessagePumpLibevent::FileDescriptorWatcher file_descriptor_watcher_;
100 // The class is used for monitoring the timeout used for D-Bus method
101 // calls.
103 // Unlike Watch, Timeout is a ref counted object, to ensure that |this| of
104 // the object is is alive when HandleTimeout() is called. It's unlikely
105 // but it may be possible that HandleTimeout() is called after
106 // Bus::OnRemoveTimeout(). That's why we don't simply delete the object in
107 // Bus::OnRemoveTimeout().
108 class Timeout : public base::RefCountedThreadSafe<Timeout> {
109 public:
110 explicit Timeout(DBusTimeout* timeout)
111 : raw_timeout_(timeout),
112 monitoring_is_active_(false),
113 is_completed(false) {
114 dbus_timeout_set_data(raw_timeout_, this, NULL);
115 AddRef(); // Balanced on Complete().
118 // Returns true if the timeout is ready to be monitored.
119 bool IsReadyToBeMonitored() {
120 return dbus_timeout_get_enabled(raw_timeout_);
123 // Starts monitoring the timeout.
124 void StartMonitoring(Bus* bus) {
125 bus->GetDBusTaskRunner()->PostDelayedTask(
126 FROM_HERE,
127 base::Bind(&Timeout::HandleTimeout, this),
128 GetInterval());
129 monitoring_is_active_ = true;
132 // Stops monitoring the timeout.
133 void StopMonitoring() {
134 // We cannot take back the delayed task we posted in
135 // StartMonitoring(), so we just mark the monitoring is inactive now.
136 monitoring_is_active_ = false;
139 // Returns the interval.
140 base::TimeDelta GetInterval() {
141 return base::TimeDelta::FromMilliseconds(
142 dbus_timeout_get_interval(raw_timeout_));
145 // Cleans up the raw_timeout and marks that timeout is completed.
146 // See the class comment above for why we are doing this.
147 void Complete() {
148 dbus_timeout_set_data(raw_timeout_, NULL, NULL);
149 is_completed = true;
150 Release();
153 private:
154 friend class base::RefCountedThreadSafe<Timeout>;
155 ~Timeout() {
158 // Handles the timeout.
159 void HandleTimeout() {
160 // If the timeout is marked completed, we should do nothing. This can
161 // occur if this function is called after Bus::OnRemoveTimeout().
162 if (is_completed)
163 return;
164 // Skip if monitoring is canceled.
165 if (!monitoring_is_active_)
166 return;
168 const bool success = dbus_timeout_handle(raw_timeout_);
169 CHECK(success) << "Unable to allocate memory";
172 DBusTimeout* raw_timeout_;
173 bool monitoring_is_active_;
174 bool is_completed;
177 } // namespace
179 Bus::Options::Options()
180 : bus_type(SESSION),
181 connection_type(PRIVATE) {
184 Bus::Options::~Options() {
187 Bus::Bus(const Options& options)
188 : bus_type_(options.bus_type),
189 connection_type_(options.connection_type),
190 dbus_task_runner_(options.dbus_task_runner),
191 on_shutdown_(false /* manual_reset */, false /* initially_signaled */),
192 connection_(NULL),
193 origin_thread_id_(base::PlatformThread::CurrentId()),
194 async_operations_set_up_(false),
195 shutdown_completed_(false),
196 num_pending_watches_(0),
197 num_pending_timeouts_(0),
198 address_(options.address) {
199 // This is safe to call multiple times.
200 dbus_threads_init_default();
201 // The origin message loop is unnecessary if the client uses synchronous
202 // functions only.
203 if (base::MessageLoop::current())
204 origin_task_runner_ = base::MessageLoop::current()->message_loop_proxy();
207 Bus::~Bus() {
208 DCHECK(!connection_);
209 DCHECK(owned_service_names_.empty());
210 DCHECK(match_rules_added_.empty());
211 DCHECK(filter_functions_added_.empty());
212 DCHECK(registered_object_paths_.empty());
213 DCHECK_EQ(0, num_pending_watches_);
214 // TODO(satorux): This check fails occasionally in browser_tests for tests
215 // that run very quickly. Perhaps something does not have time to clean up.
216 // Despite the check failing, the tests seem to run fine. crosbug.com/23416
217 // DCHECK_EQ(0, num_pending_timeouts_);
220 ObjectProxy* Bus::GetObjectProxy(const std::string& service_name,
221 const ObjectPath& object_path) {
222 return GetObjectProxyWithOptions(service_name, object_path,
223 ObjectProxy::DEFAULT_OPTIONS);
226 ObjectProxy* Bus::GetObjectProxyWithOptions(const std::string& service_name,
227 const ObjectPath& object_path,
228 int options) {
229 AssertOnOriginThread();
231 // Check if we already have the requested object proxy.
232 const ObjectProxyTable::key_type key(service_name + object_path.value(),
233 options);
234 ObjectProxyTable::iterator iter = object_proxy_table_.find(key);
235 if (iter != object_proxy_table_.end()) {
236 return iter->second.get();
239 scoped_refptr<ObjectProxy> object_proxy =
240 new ObjectProxy(this, service_name, object_path, options);
241 object_proxy_table_[key] = object_proxy;
243 return object_proxy.get();
246 bool Bus::RemoveObjectProxy(const std::string& service_name,
247 const ObjectPath& object_path,
248 const base::Closure& callback) {
249 return RemoveObjectProxyWithOptions(service_name, object_path,
250 ObjectProxy::DEFAULT_OPTIONS,
251 callback);
254 bool Bus::RemoveObjectProxyWithOptions(const std::string& service_name,
255 const ObjectPath& object_path,
256 int options,
257 const base::Closure& callback) {
258 AssertOnOriginThread();
260 // Check if we have the requested object proxy.
261 const ObjectProxyTable::key_type key(service_name + object_path.value(),
262 options);
263 ObjectProxyTable::iterator iter = object_proxy_table_.find(key);
264 if (iter != object_proxy_table_.end()) {
265 scoped_refptr<ObjectProxy> object_proxy = iter->second;
266 object_proxy_table_.erase(iter);
267 // Object is present. Remove it now and Detach on the DBus thread.
268 GetDBusTaskRunner()->PostTask(
269 FROM_HERE,
270 base::Bind(&Bus::RemoveObjectProxyInternal,
271 this, object_proxy, callback));
272 return true;
274 return false;
277 void Bus::RemoveObjectProxyInternal(scoped_refptr<ObjectProxy> object_proxy,
278 const base::Closure& callback) {
279 AssertOnDBusThread();
281 object_proxy.get()->Detach();
283 GetOriginTaskRunner()->PostTask(FROM_HERE, callback);
286 ExportedObject* Bus::GetExportedObject(const ObjectPath& object_path) {
287 AssertOnOriginThread();
289 // Check if we already have the requested exported object.
290 ExportedObjectTable::iterator iter = exported_object_table_.find(object_path);
291 if (iter != exported_object_table_.end()) {
292 return iter->second.get();
295 scoped_refptr<ExportedObject> exported_object =
296 new ExportedObject(this, object_path);
297 exported_object_table_[object_path] = exported_object;
299 return exported_object.get();
302 void Bus::UnregisterExportedObject(const ObjectPath& object_path) {
303 AssertOnOriginThread();
305 // Remove the registered object from the table first, to allow a new
306 // GetExportedObject() call to return a new object, rather than this one.
307 ExportedObjectTable::iterator iter = exported_object_table_.find(object_path);
308 if (iter == exported_object_table_.end())
309 return;
311 scoped_refptr<ExportedObject> exported_object = iter->second;
312 exported_object_table_.erase(iter);
314 // Post the task to perform the final unregistration to the D-Bus thread.
315 // Since the registration also happens on the D-Bus thread in
316 // TryRegisterObjectPath(), and the task runner we post to is a
317 // SequencedTaskRunner, there is a guarantee that this will happen before any
318 // future registration call.
319 GetDBusTaskRunner()->PostTask(
320 FROM_HERE,
321 base::Bind(&Bus::UnregisterExportedObjectInternal,
322 this, exported_object));
325 void Bus::UnregisterExportedObjectInternal(
326 scoped_refptr<ExportedObject> exported_object) {
327 AssertOnDBusThread();
329 exported_object->Unregister();
332 ObjectManager* Bus::GetObjectManager(const std::string& service_name,
333 const ObjectPath& object_path) {
334 AssertOnOriginThread();
336 // Check if we already have the requested object manager.
337 const ObjectManagerTable::key_type key(service_name + object_path.value());
338 ObjectManagerTable::iterator iter = object_manager_table_.find(key);
339 if (iter != object_manager_table_.end()) {
340 return iter->second.get();
343 scoped_refptr<ObjectManager> object_manager =
344 new ObjectManager(this, service_name, object_path);
345 object_manager_table_[key] = object_manager;
347 return object_manager.get();
350 bool Bus::RemoveObjectManager(const std::string& service_name,
351 const ObjectPath& object_path,
352 const base::Closure& callback) {
353 AssertOnOriginThread();
354 DCHECK(!callback.is_null());
356 const ObjectManagerTable::key_type key(service_name + object_path.value());
357 ObjectManagerTable::iterator iter = object_manager_table_.find(key);
358 if (iter == object_manager_table_.end())
359 return false;
361 // ObjectManager is present. Remove it now and CleanUp on the DBus thread.
362 scoped_refptr<ObjectManager> object_manager = iter->second;
363 object_manager_table_.erase(iter);
365 GetDBusTaskRunner()->PostTask(
366 FROM_HERE,
367 base::Bind(&Bus::RemoveObjectManagerInternal,
368 this, object_manager, callback));
370 return true;
373 void Bus::RemoveObjectManagerInternal(
374 scoped_refptr<dbus::ObjectManager> object_manager,
375 const base::Closure& callback) {
376 AssertOnDBusThread();
377 DCHECK(object_manager.get());
379 object_manager->CleanUp();
381 // The ObjectManager has to be deleted on the origin thread since it was
382 // created there.
383 GetOriginTaskRunner()->PostTask(
384 FROM_HERE,
385 base::Bind(&Bus::RemoveObjectManagerInternalHelper,
386 this, object_manager, callback));
389 void Bus::RemoveObjectManagerInternalHelper(
390 scoped_refptr<dbus::ObjectManager> object_manager,
391 const base::Closure& callback) {
392 AssertOnOriginThread();
393 DCHECK(object_manager.get());
395 // Release the object manager and run the callback.
396 object_manager = NULL;
397 callback.Run();
400 void Bus::GetManagedObjects() {
401 for (ObjectManagerTable::iterator iter = object_manager_table_.begin();
402 iter != object_manager_table_.end(); ++iter) {
403 iter->second->GetManagedObjects();
407 bool Bus::Connect() {
408 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
409 AssertOnDBusThread();
411 // Check if it's already initialized.
412 if (connection_)
413 return true;
415 ScopedDBusError error;
416 if (bus_type_ == CUSTOM_ADDRESS) {
417 if (connection_type_ == PRIVATE) {
418 connection_ = dbus_connection_open_private(address_.c_str(), error.get());
419 } else {
420 connection_ = dbus_connection_open(address_.c_str(), error.get());
422 } else {
423 const DBusBusType dbus_bus_type = static_cast<DBusBusType>(bus_type_);
424 if (connection_type_ == PRIVATE) {
425 connection_ = dbus_bus_get_private(dbus_bus_type, error.get());
426 } else {
427 connection_ = dbus_bus_get(dbus_bus_type, error.get());
430 if (!connection_) {
431 LOG(ERROR) << "Failed to connect to the bus: "
432 << (error.is_set() ? error.message() : "");
433 return false;
436 if (bus_type_ == CUSTOM_ADDRESS) {
437 // We should call dbus_bus_register here, otherwise unique name can not be
438 // acquired. According to dbus specification, it is responsible to call
439 // org.freedesktop.DBus.Hello method at the beging of bus connection to
440 // acquire unique name. In the case of dbus_bus_get, dbus_bus_register is
441 // called internally.
442 if (!dbus_bus_register(connection_, error.get())) {
443 LOG(ERROR) << "Failed to register the bus component: "
444 << (error.is_set() ? error.message() : "");
445 return false;
448 // We shouldn't exit on the disconnected signal.
449 dbus_connection_set_exit_on_disconnect(connection_, false);
451 // Watch Disconnected signal.
452 AddFilterFunction(Bus::OnConnectionDisconnectedFilter, this);
453 AddMatch(kDisconnectedMatchRule, error.get());
455 return true;
458 void Bus::ClosePrivateConnection() {
459 // dbus_connection_close is blocking call.
460 AssertOnDBusThread();
461 DCHECK_EQ(PRIVATE, connection_type_)
462 << "non-private connection should not be closed";
463 dbus_connection_close(connection_);
466 void Bus::ShutdownAndBlock() {
467 AssertOnDBusThread();
469 if (shutdown_completed_)
470 return; // Already shutdowned, just return.
472 // Unregister the exported objects.
473 for (ExportedObjectTable::iterator iter = exported_object_table_.begin();
474 iter != exported_object_table_.end(); ++iter) {
475 iter->second->Unregister();
478 // Release all service names.
479 for (std::set<std::string>::iterator iter = owned_service_names_.begin();
480 iter != owned_service_names_.end();) {
481 // This is a bit tricky but we should increment the iter here as
482 // ReleaseOwnership() may remove |service_name| from the set.
483 const std::string& service_name = *iter++;
484 ReleaseOwnership(service_name);
486 if (!owned_service_names_.empty()) {
487 LOG(ERROR) << "Failed to release all service names. # of services left: "
488 << owned_service_names_.size();
491 // Detach from the remote objects.
492 for (ObjectProxyTable::iterator iter = object_proxy_table_.begin();
493 iter != object_proxy_table_.end(); ++iter) {
494 iter->second->Detach();
497 // Clean up the object managers.
498 for (ObjectManagerTable::iterator iter = object_manager_table_.begin();
499 iter != object_manager_table_.end(); ++iter) {
500 iter->second->CleanUp();
503 // Release object proxies and exported objects here. We should do this
504 // here rather than in the destructor to avoid memory leaks due to
505 // cyclic references.
506 object_proxy_table_.clear();
507 exported_object_table_.clear();
509 // Private connection should be closed.
510 if (connection_) {
511 // Remove Disconnected watcher.
512 ScopedDBusError error;
513 RemoveFilterFunction(Bus::OnConnectionDisconnectedFilter, this);
514 RemoveMatch(kDisconnectedMatchRule, error.get());
516 if (connection_type_ == PRIVATE)
517 ClosePrivateConnection();
518 // dbus_connection_close() won't unref.
519 dbus_connection_unref(connection_);
522 connection_ = NULL;
523 shutdown_completed_ = true;
526 void Bus::ShutdownOnDBusThreadAndBlock() {
527 AssertOnOriginThread();
528 DCHECK(dbus_task_runner_.get());
530 GetDBusTaskRunner()->PostTask(
531 FROM_HERE,
532 base::Bind(&Bus::ShutdownOnDBusThreadAndBlockInternal, this));
534 // http://crbug.com/125222
535 base::ThreadRestrictions::ScopedAllowWait allow_wait;
537 // Wait until the shutdown is complete on the D-Bus thread.
538 // The shutdown should not hang, but set timeout just in case.
539 const int kTimeoutSecs = 3;
540 const base::TimeDelta timeout(base::TimeDelta::FromSeconds(kTimeoutSecs));
541 const bool signaled = on_shutdown_.TimedWait(timeout);
542 LOG_IF(ERROR, !signaled) << "Failed to shutdown the bus";
545 void Bus::RequestOwnership(const std::string& service_name,
546 ServiceOwnershipOptions options,
547 OnOwnershipCallback on_ownership_callback) {
548 AssertOnOriginThread();
550 GetDBusTaskRunner()->PostTask(
551 FROM_HERE,
552 base::Bind(&Bus::RequestOwnershipInternal,
553 this, service_name, options, on_ownership_callback));
556 void Bus::RequestOwnershipInternal(const std::string& service_name,
557 ServiceOwnershipOptions options,
558 OnOwnershipCallback on_ownership_callback) {
559 AssertOnDBusThread();
561 bool success = Connect();
562 if (success)
563 success = RequestOwnershipAndBlock(service_name, options);
565 GetOriginTaskRunner()->PostTask(FROM_HERE,
566 base::Bind(on_ownership_callback,
567 service_name,
568 success));
571 bool Bus::RequestOwnershipAndBlock(const std::string& service_name,
572 ServiceOwnershipOptions options) {
573 DCHECK(connection_);
574 // dbus_bus_request_name() is a blocking call.
575 AssertOnDBusThread();
577 // Check if we already own the service name.
578 if (owned_service_names_.find(service_name) != owned_service_names_.end()) {
579 return true;
582 ScopedDBusError error;
583 const int result = dbus_bus_request_name(connection_,
584 service_name.c_str(),
585 options,
586 error.get());
587 if (result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
588 LOG(ERROR) << "Failed to get the ownership of " << service_name << ": "
589 << (error.is_set() ? error.message() : "");
590 return false;
592 owned_service_names_.insert(service_name);
593 return true;
596 bool Bus::ReleaseOwnership(const std::string& service_name) {
597 DCHECK(connection_);
598 // dbus_bus_request_name() is a blocking call.
599 AssertOnDBusThread();
601 // Check if we already own the service name.
602 std::set<std::string>::iterator found =
603 owned_service_names_.find(service_name);
604 if (found == owned_service_names_.end()) {
605 LOG(ERROR) << service_name << " is not owned by the bus";
606 return false;
609 ScopedDBusError error;
610 const int result = dbus_bus_release_name(connection_, service_name.c_str(),
611 error.get());
612 if (result == DBUS_RELEASE_NAME_REPLY_RELEASED) {
613 owned_service_names_.erase(found);
614 return true;
615 } else {
616 LOG(ERROR) << "Failed to release the ownership of " << service_name << ": "
617 << (error.is_set() ? error.message() : "")
618 << ", result code: " << result;
619 return false;
623 bool Bus::SetUpAsyncOperations() {
624 DCHECK(connection_);
625 AssertOnDBusThread();
627 if (async_operations_set_up_)
628 return true;
630 // Process all the incoming data if any, so that OnDispatchStatus() will
631 // be called when the incoming data is ready.
632 ProcessAllIncomingDataIfAny();
634 bool success = dbus_connection_set_watch_functions(connection_,
635 &Bus::OnAddWatchThunk,
636 &Bus::OnRemoveWatchThunk,
637 &Bus::OnToggleWatchThunk,
638 this,
639 NULL);
640 CHECK(success) << "Unable to allocate memory";
642 success = dbus_connection_set_timeout_functions(connection_,
643 &Bus::OnAddTimeoutThunk,
644 &Bus::OnRemoveTimeoutThunk,
645 &Bus::OnToggleTimeoutThunk,
646 this,
647 NULL);
648 CHECK(success) << "Unable to allocate memory";
650 dbus_connection_set_dispatch_status_function(
651 connection_,
652 &Bus::OnDispatchStatusChangedThunk,
653 this,
654 NULL);
656 async_operations_set_up_ = true;
658 return true;
661 DBusMessage* Bus::SendWithReplyAndBlock(DBusMessage* request,
662 int timeout_ms,
663 DBusError* error) {
664 DCHECK(connection_);
665 AssertOnDBusThread();
667 return dbus_connection_send_with_reply_and_block(
668 connection_, request, timeout_ms, error);
671 void Bus::SendWithReply(DBusMessage* request,
672 DBusPendingCall** pending_call,
673 int timeout_ms) {
674 DCHECK(connection_);
675 AssertOnDBusThread();
677 const bool success = dbus_connection_send_with_reply(
678 connection_, request, pending_call, timeout_ms);
679 CHECK(success) << "Unable to allocate memory";
682 void Bus::Send(DBusMessage* request, uint32* serial) {
683 DCHECK(connection_);
684 AssertOnDBusThread();
686 const bool success = dbus_connection_send(connection_, request, serial);
687 CHECK(success) << "Unable to allocate memory";
690 void Bus::AddFilterFunction(DBusHandleMessageFunction filter_function,
691 void* user_data) {
692 DCHECK(connection_);
693 AssertOnDBusThread();
695 std::pair<DBusHandleMessageFunction, void*> filter_data_pair =
696 std::make_pair(filter_function, user_data);
697 if (filter_functions_added_.find(filter_data_pair) !=
698 filter_functions_added_.end()) {
699 VLOG(1) << "Filter function already exists: " << filter_function
700 << " with associated data: " << user_data;
701 return;
704 const bool success = dbus_connection_add_filter(
705 connection_, filter_function, user_data, NULL);
706 CHECK(success) << "Unable to allocate memory";
707 filter_functions_added_.insert(filter_data_pair);
710 void Bus::RemoveFilterFunction(DBusHandleMessageFunction filter_function,
711 void* user_data) {
712 DCHECK(connection_);
713 AssertOnDBusThread();
715 std::pair<DBusHandleMessageFunction, void*> filter_data_pair =
716 std::make_pair(filter_function, user_data);
717 if (filter_functions_added_.find(filter_data_pair) ==
718 filter_functions_added_.end()) {
719 VLOG(1) << "Requested to remove an unknown filter function: "
720 << filter_function
721 << " with associated data: " << user_data;
722 return;
725 dbus_connection_remove_filter(connection_, filter_function, user_data);
726 filter_functions_added_.erase(filter_data_pair);
729 void Bus::AddMatch(const std::string& match_rule, DBusError* error) {
730 DCHECK(connection_);
731 AssertOnDBusThread();
733 std::map<std::string, int>::iterator iter =
734 match_rules_added_.find(match_rule);
735 if (iter != match_rules_added_.end()) {
736 // The already existing rule's counter is incremented.
737 iter->second++;
739 VLOG(1) << "Match rule already exists: " << match_rule;
740 return;
743 dbus_bus_add_match(connection_, match_rule.c_str(), error);
744 match_rules_added_[match_rule] = 1;
747 bool Bus::RemoveMatch(const std::string& match_rule, DBusError* error) {
748 DCHECK(connection_);
749 AssertOnDBusThread();
751 std::map<std::string, int>::iterator iter =
752 match_rules_added_.find(match_rule);
753 if (iter == match_rules_added_.end()) {
754 LOG(ERROR) << "Requested to remove an unknown match rule: " << match_rule;
755 return false;
758 // The rule's counter is decremented and the rule is deleted when reachs 0.
759 iter->second--;
760 if (iter->second == 0) {
761 dbus_bus_remove_match(connection_, match_rule.c_str(), error);
762 match_rules_added_.erase(match_rule);
764 return true;
767 bool Bus::TryRegisterObjectPath(const ObjectPath& object_path,
768 const DBusObjectPathVTable* vtable,
769 void* user_data,
770 DBusError* error) {
771 DCHECK(connection_);
772 AssertOnDBusThread();
774 if (registered_object_paths_.find(object_path) !=
775 registered_object_paths_.end()) {
776 LOG(ERROR) << "Object path already registered: " << object_path.value();
777 return false;
780 const bool success = dbus_connection_try_register_object_path(
781 connection_,
782 object_path.value().c_str(),
783 vtable,
784 user_data,
785 error);
786 if (success)
787 registered_object_paths_.insert(object_path);
788 return success;
791 void Bus::UnregisterObjectPath(const ObjectPath& object_path) {
792 DCHECK(connection_);
793 AssertOnDBusThread();
795 if (registered_object_paths_.find(object_path) ==
796 registered_object_paths_.end()) {
797 LOG(ERROR) << "Requested to unregister an unknown object path: "
798 << object_path.value();
799 return;
802 const bool success = dbus_connection_unregister_object_path(
803 connection_,
804 object_path.value().c_str());
805 CHECK(success) << "Unable to allocate memory";
806 registered_object_paths_.erase(object_path);
809 void Bus::ShutdownOnDBusThreadAndBlockInternal() {
810 AssertOnDBusThread();
812 ShutdownAndBlock();
813 on_shutdown_.Signal();
816 void Bus::ProcessAllIncomingDataIfAny() {
817 AssertOnDBusThread();
819 // As mentioned at the class comment in .h file, connection_ can be NULL.
820 if (!connection_)
821 return;
823 // It is safe and necessary to call dbus_connection_get_dispatch_status even
824 // if the connection is lost.
825 if (dbus_connection_get_dispatch_status(connection_) ==
826 DBUS_DISPATCH_DATA_REMAINS) {
827 while (dbus_connection_dispatch(connection_) ==
828 DBUS_DISPATCH_DATA_REMAINS) {
833 base::TaskRunner* Bus::GetDBusTaskRunner() {
834 if (dbus_task_runner_.get())
835 return dbus_task_runner_.get();
836 else
837 return GetOriginTaskRunner();
840 base::TaskRunner* Bus::GetOriginTaskRunner() {
841 DCHECK(origin_task_runner_.get());
842 return origin_task_runner_.get();
845 bool Bus::HasDBusThread() {
846 return dbus_task_runner_.get() != NULL;
849 void Bus::AssertOnOriginThread() {
850 DCHECK_EQ(origin_thread_id_, base::PlatformThread::CurrentId());
853 void Bus::AssertOnDBusThread() {
854 base::ThreadRestrictions::AssertIOAllowed();
856 if (dbus_task_runner_.get()) {
857 DCHECK(dbus_task_runner_->RunsTasksOnCurrentThread());
858 } else {
859 AssertOnOriginThread();
863 std::string Bus::GetServiceOwnerAndBlock(const std::string& service_name,
864 GetServiceOwnerOption options) {
865 AssertOnDBusThread();
867 MethodCall get_name_owner_call("org.freedesktop.DBus", "GetNameOwner");
868 MessageWriter writer(&get_name_owner_call);
869 writer.AppendString(service_name);
870 VLOG(1) << "Method call: " << get_name_owner_call.ToString();
872 const ObjectPath obj_path("/org/freedesktop/DBus");
873 if (!get_name_owner_call.SetDestination("org.freedesktop.DBus") ||
874 !get_name_owner_call.SetPath(obj_path)) {
875 if (options == REPORT_ERRORS)
876 LOG(ERROR) << "Failed to get name owner.";
877 return "";
880 ScopedDBusError error;
881 DBusMessage* response_message =
882 SendWithReplyAndBlock(get_name_owner_call.raw_message(),
883 ObjectProxy::TIMEOUT_USE_DEFAULT,
884 error.get());
885 if (!response_message) {
886 if (options == REPORT_ERRORS) {
887 LOG(ERROR) << "Failed to get name owner. Got " << error.name() << ": "
888 << error.message();
890 return "";
893 scoped_ptr<Response> response(Response::FromRawMessage(response_message));
894 MessageReader reader(response.get());
896 std::string service_owner;
897 if (!reader.PopString(&service_owner))
898 service_owner.clear();
899 return service_owner;
902 void Bus::GetServiceOwner(const std::string& service_name,
903 const GetServiceOwnerCallback& callback) {
904 AssertOnOriginThread();
906 GetDBusTaskRunner()->PostTask(
907 FROM_HERE,
908 base::Bind(&Bus::GetServiceOwnerInternal, this, service_name, callback));
911 void Bus::GetServiceOwnerInternal(const std::string& service_name,
912 const GetServiceOwnerCallback& callback) {
913 AssertOnDBusThread();
915 std::string service_owner;
916 if (Connect())
917 service_owner = GetServiceOwnerAndBlock(service_name, SUPPRESS_ERRORS);
918 GetOriginTaskRunner()->PostTask(FROM_HERE,
919 base::Bind(callback, service_owner));
922 void Bus::ListenForServiceOwnerChange(
923 const std::string& service_name,
924 const GetServiceOwnerCallback& callback) {
925 AssertOnOriginThread();
926 DCHECK(!service_name.empty());
927 DCHECK(!callback.is_null());
929 GetDBusTaskRunner()->PostTask(
930 FROM_HERE,
931 base::Bind(&Bus::ListenForServiceOwnerChangeInternal,
932 this, service_name, callback));
935 void Bus::ListenForServiceOwnerChangeInternal(
936 const std::string& service_name,
937 const GetServiceOwnerCallback& callback) {
938 AssertOnDBusThread();
939 DCHECK(!service_name.empty());
940 DCHECK(!callback.is_null());
942 if (!Connect() || !SetUpAsyncOperations())
943 return;
945 if (service_owner_changed_listener_map_.empty())
946 AddFilterFunction(Bus::OnServiceOwnerChangedFilter, this);
948 ServiceOwnerChangedListenerMap::iterator it =
949 service_owner_changed_listener_map_.find(service_name);
950 if (it == service_owner_changed_listener_map_.end()) {
951 // Add a match rule for the new service name.
952 const std::string name_owner_changed_match_rule =
953 base::StringPrintf(kServiceNameOwnerChangeMatchRule,
954 service_name.c_str());
955 ScopedDBusError error;
956 AddMatch(name_owner_changed_match_rule, error.get());
957 if (error.is_set()) {
958 LOG(ERROR) << "Failed to add match rule for " << service_name
959 << ". Got " << error.name() << ": " << error.message();
960 return;
963 service_owner_changed_listener_map_[service_name].push_back(callback);
964 return;
967 // Check if the callback has already been added.
968 std::vector<GetServiceOwnerCallback>& callbacks = it->second;
969 for (size_t i = 0; i < callbacks.size(); ++i) {
970 if (callbacks[i].Equals(callback))
971 return;
973 callbacks.push_back(callback);
976 void Bus::UnlistenForServiceOwnerChange(
977 const std::string& service_name,
978 const GetServiceOwnerCallback& callback) {
979 AssertOnOriginThread();
980 DCHECK(!service_name.empty());
981 DCHECK(!callback.is_null());
983 GetDBusTaskRunner()->PostTask(
984 FROM_HERE,
985 base::Bind(&Bus::UnlistenForServiceOwnerChangeInternal,
986 this, service_name, callback));
989 void Bus::UnlistenForServiceOwnerChangeInternal(
990 const std::string& service_name,
991 const GetServiceOwnerCallback& callback) {
992 AssertOnDBusThread();
993 DCHECK(!service_name.empty());
994 DCHECK(!callback.is_null());
996 ServiceOwnerChangedListenerMap::iterator it =
997 service_owner_changed_listener_map_.find(service_name);
998 if (it == service_owner_changed_listener_map_.end())
999 return;
1001 std::vector<GetServiceOwnerCallback>& callbacks = it->second;
1002 for (size_t i = 0; i < callbacks.size(); ++i) {
1003 if (callbacks[i].Equals(callback)) {
1004 callbacks.erase(callbacks.begin() + i);
1005 break; // There can be only one.
1008 if (!callbacks.empty())
1009 return;
1011 // Last callback for |service_name| has been removed, remove match rule.
1012 const std::string name_owner_changed_match_rule =
1013 base::StringPrintf(kServiceNameOwnerChangeMatchRule,
1014 service_name.c_str());
1015 ScopedDBusError error;
1016 RemoveMatch(name_owner_changed_match_rule, error.get());
1017 // And remove |service_owner_changed_listener_map_| entry.
1018 service_owner_changed_listener_map_.erase(it);
1020 if (service_owner_changed_listener_map_.empty())
1021 RemoveFilterFunction(Bus::OnServiceOwnerChangedFilter, this);
1024 dbus_bool_t Bus::OnAddWatch(DBusWatch* raw_watch) {
1025 AssertOnDBusThread();
1027 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
1028 Watch* watch = new Watch(raw_watch);
1029 if (watch->IsReadyToBeWatched()) {
1030 watch->StartWatching();
1032 ++num_pending_watches_;
1033 return true;
1036 void Bus::OnRemoveWatch(DBusWatch* raw_watch) {
1037 AssertOnDBusThread();
1039 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
1040 delete watch;
1041 --num_pending_watches_;
1044 void Bus::OnToggleWatch(DBusWatch* raw_watch) {
1045 AssertOnDBusThread();
1047 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
1048 if (watch->IsReadyToBeWatched()) {
1049 watch->StartWatching();
1050 } else {
1051 // It's safe to call this if StartWatching() wasn't called, per
1052 // message_pump_libevent.h.
1053 watch->StopWatching();
1057 dbus_bool_t Bus::OnAddTimeout(DBusTimeout* raw_timeout) {
1058 AssertOnDBusThread();
1060 // timeout will be deleted when raw_timeout is removed in
1061 // OnRemoveTimeoutThunk().
1062 Timeout* timeout = new Timeout(raw_timeout);
1063 if (timeout->IsReadyToBeMonitored()) {
1064 timeout->StartMonitoring(this);
1066 ++num_pending_timeouts_;
1067 return true;
1070 void Bus::OnRemoveTimeout(DBusTimeout* raw_timeout) {
1071 AssertOnDBusThread();
1073 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
1074 timeout->Complete();
1075 --num_pending_timeouts_;
1078 void Bus::OnToggleTimeout(DBusTimeout* raw_timeout) {
1079 AssertOnDBusThread();
1081 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
1082 if (timeout->IsReadyToBeMonitored()) {
1083 timeout->StartMonitoring(this);
1084 } else {
1085 timeout->StopMonitoring();
1089 void Bus::OnDispatchStatusChanged(DBusConnection* connection,
1090 DBusDispatchStatus status) {
1091 DCHECK_EQ(connection, connection_);
1092 AssertOnDBusThread();
1094 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
1095 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
1096 // prohibited by the D-Bus library. Hence, we post a task here instead.
1097 // See comments for dbus_connection_set_dispatch_status_function().
1098 GetDBusTaskRunner()->PostTask(FROM_HERE,
1099 base::Bind(&Bus::ProcessAllIncomingDataIfAny,
1100 this));
1103 void Bus::OnServiceOwnerChanged(DBusMessage* message) {
1104 DCHECK(message);
1105 AssertOnDBusThread();
1107 // |message| will be unrefed on exit of the function. Increment the
1108 // reference so we can use it in Signal::FromRawMessage() below.
1109 dbus_message_ref(message);
1110 scoped_ptr<Signal> signal(Signal::FromRawMessage(message));
1112 // Confirm the validity of the NameOwnerChanged signal.
1113 if (signal->GetMember() != kNameOwnerChangedSignal ||
1114 signal->GetInterface() != DBUS_INTERFACE_DBUS ||
1115 signal->GetSender() != DBUS_SERVICE_DBUS) {
1116 return;
1119 MessageReader reader(signal.get());
1120 std::string service_name;
1121 std::string old_owner;
1122 std::string new_owner;
1123 if (!reader.PopString(&service_name) ||
1124 !reader.PopString(&old_owner) ||
1125 !reader.PopString(&new_owner)) {
1126 return;
1129 ServiceOwnerChangedListenerMap::const_iterator it =
1130 service_owner_changed_listener_map_.find(service_name);
1131 if (it == service_owner_changed_listener_map_.end())
1132 return;
1134 const std::vector<GetServiceOwnerCallback>& callbacks = it->second;
1135 for (size_t i = 0; i < callbacks.size(); ++i) {
1136 GetOriginTaskRunner()->PostTask(FROM_HERE,
1137 base::Bind(callbacks[i], new_owner));
1141 // static
1142 dbus_bool_t Bus::OnAddWatchThunk(DBusWatch* raw_watch, void* data) {
1143 Bus* self = static_cast<Bus*>(data);
1144 return self->OnAddWatch(raw_watch);
1147 // static
1148 void Bus::OnRemoveWatchThunk(DBusWatch* raw_watch, void* data) {
1149 Bus* self = static_cast<Bus*>(data);
1150 self->OnRemoveWatch(raw_watch);
1153 // static
1154 void Bus::OnToggleWatchThunk(DBusWatch* raw_watch, void* data) {
1155 Bus* self = static_cast<Bus*>(data);
1156 self->OnToggleWatch(raw_watch);
1159 // static
1160 dbus_bool_t Bus::OnAddTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1161 Bus* self = static_cast<Bus*>(data);
1162 return self->OnAddTimeout(raw_timeout);
1165 // static
1166 void Bus::OnRemoveTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1167 Bus* self = static_cast<Bus*>(data);
1168 self->OnRemoveTimeout(raw_timeout);
1171 // static
1172 void Bus::OnToggleTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1173 Bus* self = static_cast<Bus*>(data);
1174 self->OnToggleTimeout(raw_timeout);
1177 // static
1178 void Bus::OnDispatchStatusChangedThunk(DBusConnection* connection,
1179 DBusDispatchStatus status,
1180 void* data) {
1181 Bus* self = static_cast<Bus*>(data);
1182 self->OnDispatchStatusChanged(connection, status);
1185 // static
1186 DBusHandlerResult Bus::OnConnectionDisconnectedFilter(
1187 DBusConnection* connection,
1188 DBusMessage* message,
1189 void* data) {
1190 if (dbus_message_is_signal(message,
1191 DBUS_INTERFACE_LOCAL,
1192 kDisconnectedSignal)) {
1193 // Abort when the connection is lost.
1194 LOG(FATAL) << "D-Bus connection was disconnected. Aborting.";
1196 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1199 // static
1200 DBusHandlerResult Bus::OnServiceOwnerChangedFilter(
1201 DBusConnection* connection,
1202 DBusMessage* message,
1203 void* data) {
1204 if (dbus_message_is_signal(message,
1205 DBUS_INTERFACE_DBUS,
1206 kNameOwnerChangedSignal)) {
1207 Bus* self = static_cast<Bus*>(data);
1208 self->OnServiceOwnerChanged(message);
1210 // Always return unhandled to let others, e.g. ObjectProxies, handle the same
1211 // signal.
1212 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1215 } // namespace dbus