Roll src/third_party/WebKit f298044:aa8346d (svn 202628:202629)
[chromium-blink-merge.git] / dbus / bus.cc
blob3a4fe219f748d43ed1969f70c593637ec6831619
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/stl_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/threading/thread.h"
13 #include "base/threading/thread_restrictions.h"
14 #include "base/time/time.h"
15 #include "dbus/exported_object.h"
16 #include "dbus/message.h"
17 #include "dbus/object_manager.h"
18 #include "dbus/object_path.h"
19 #include "dbus/object_proxy.h"
20 #include "dbus/scoped_dbus_error.h"
22 namespace dbus {
24 namespace {
26 const char kDisconnectedSignal[] = "Disconnected";
27 const char kDisconnectedMatchRule[] =
28 "type='signal', path='/org/freedesktop/DBus/Local',"
29 "interface='org.freedesktop.DBus.Local', member='Disconnected'";
31 // The NameOwnerChanged member in org.freedesktop.DBus
32 const char kNameOwnerChangedSignal[] = "NameOwnerChanged";
34 // The match rule used to filter for changes to a given service name owner.
35 const char kServiceNameOwnerChangeMatchRule[] =
36 "type='signal',interface='org.freedesktop.DBus',"
37 "member='NameOwnerChanged',path='/org/freedesktop/DBus',"
38 "sender='org.freedesktop.DBus',arg0='%s'";
40 // The class is used for watching the file descriptor used for D-Bus
41 // communication.
42 class Watch : public base::MessagePumpLibevent::Watcher {
43 public:
44 explicit Watch(DBusWatch* watch)
45 : raw_watch_(watch) {
46 dbus_watch_set_data(raw_watch_, this, NULL);
49 ~Watch() override { dbus_watch_set_data(raw_watch_, NULL, NULL); }
51 // Returns true if the underlying file descriptor is ready to be watched.
52 bool IsReadyToBeWatched() {
53 return dbus_watch_get_enabled(raw_watch_);
56 // Starts watching the underlying file descriptor.
57 void StartWatching() {
58 const int file_descriptor = dbus_watch_get_unix_fd(raw_watch_);
59 const int flags = dbus_watch_get_flags(raw_watch_);
61 base::MessageLoopForIO::Mode mode = base::MessageLoopForIO::WATCH_READ;
62 if ((flags & DBUS_WATCH_READABLE) && (flags & DBUS_WATCH_WRITABLE))
63 mode = base::MessageLoopForIO::WATCH_READ_WRITE;
64 else if (flags & DBUS_WATCH_READABLE)
65 mode = base::MessageLoopForIO::WATCH_READ;
66 else if (flags & DBUS_WATCH_WRITABLE)
67 mode = base::MessageLoopForIO::WATCH_WRITE;
68 else
69 NOTREACHED();
71 const bool persistent = true; // Watch persistently.
72 const bool success = base::MessageLoopForIO::current()->WatchFileDescriptor(
73 file_descriptor, persistent, mode, &file_descriptor_watcher_, this);
74 CHECK(success) << "Unable to allocate memory";
77 // Stops watching the underlying file descriptor.
78 void StopWatching() {
79 file_descriptor_watcher_.StopWatchingFileDescriptor();
82 private:
83 // Implement MessagePumpLibevent::Watcher.
84 void OnFileCanReadWithoutBlocking(int file_descriptor) override {
85 const bool success = dbus_watch_handle(raw_watch_, DBUS_WATCH_READABLE);
86 CHECK(success) << "Unable to allocate memory";
89 // Implement MessagePumpLibevent::Watcher.
90 void OnFileCanWriteWithoutBlocking(int file_descriptor) override {
91 const bool success = dbus_watch_handle(raw_watch_, DBUS_WATCH_WRITABLE);
92 CHECK(success) << "Unable to allocate memory";
95 DBusWatch* raw_watch_;
96 base::MessagePumpLibevent::FileDescriptorWatcher file_descriptor_watcher_;
99 // The class is used for monitoring the timeout used for D-Bus method
100 // calls.
102 // Unlike Watch, Timeout is a ref counted object, to ensure that |this| of
103 // the object is is alive when HandleTimeout() is called. It's unlikely
104 // but it may be possible that HandleTimeout() is called after
105 // Bus::OnRemoveTimeout(). That's why we don't simply delete the object in
106 // Bus::OnRemoveTimeout().
107 class Timeout : public base::RefCountedThreadSafe<Timeout> {
108 public:
109 explicit Timeout(DBusTimeout* timeout)
110 : raw_timeout_(timeout),
111 monitoring_is_active_(false),
112 is_completed(false) {
113 dbus_timeout_set_data(raw_timeout_, this, NULL);
114 AddRef(); // Balanced on Complete().
117 // Returns true if the timeout is ready to be monitored.
118 bool IsReadyToBeMonitored() {
119 return dbus_timeout_get_enabled(raw_timeout_);
122 // Starts monitoring the timeout.
123 void StartMonitoring(Bus* bus) {
124 bus->GetDBusTaskRunner()->PostDelayedTask(
125 FROM_HERE,
126 base::Bind(&Timeout::HandleTimeout, this),
127 GetInterval());
128 monitoring_is_active_ = true;
131 // Stops monitoring the timeout.
132 void StopMonitoring() {
133 // We cannot take back the delayed task we posted in
134 // StartMonitoring(), so we just mark the monitoring is inactive now.
135 monitoring_is_active_ = false;
138 // Returns the interval.
139 base::TimeDelta GetInterval() {
140 return base::TimeDelta::FromMilliseconds(
141 dbus_timeout_get_interval(raw_timeout_));
144 // Cleans up the raw_timeout and marks that timeout is completed.
145 // See the class comment above for why we are doing this.
146 void Complete() {
147 dbus_timeout_set_data(raw_timeout_, NULL, NULL);
148 is_completed = true;
149 Release();
152 private:
153 friend class base::RefCountedThreadSafe<Timeout>;
154 ~Timeout() {
157 // Handles the timeout.
158 void HandleTimeout() {
159 // If the timeout is marked completed, we should do nothing. This can
160 // occur if this function is called after Bus::OnRemoveTimeout().
161 if (is_completed)
162 return;
163 // Skip if monitoring is canceled.
164 if (!monitoring_is_active_)
165 return;
167 const bool success = dbus_timeout_handle(raw_timeout_);
168 CHECK(success) << "Unable to allocate memory";
171 DBusTimeout* raw_timeout_;
172 bool monitoring_is_active_;
173 bool is_completed;
176 } // namespace
178 Bus::Options::Options()
179 : bus_type(SESSION),
180 connection_type(PRIVATE) {
183 Bus::Options::~Options() {
186 Bus::Bus(const Options& options)
187 : bus_type_(options.bus_type),
188 connection_type_(options.connection_type),
189 dbus_task_runner_(options.dbus_task_runner),
190 on_shutdown_(false /* manual_reset */, false /* initially_signaled */),
191 connection_(NULL),
192 origin_thread_id_(base::PlatformThread::CurrentId()),
193 async_operations_set_up_(false),
194 shutdown_completed_(false),
195 num_pending_watches_(0),
196 num_pending_timeouts_(0),
197 address_(options.address) {
198 // This is safe to call multiple times.
199 dbus_threads_init_default();
200 // The origin message loop is unnecessary if the client uses synchronous
201 // functions only.
202 if (base::MessageLoop::current())
203 origin_task_runner_ = base::MessageLoop::current()->task_runner();
206 Bus::~Bus() {
207 DCHECK(!connection_);
208 DCHECK(owned_service_names_.empty());
209 DCHECK(match_rules_added_.empty());
210 DCHECK(filter_functions_added_.empty());
211 DCHECK(registered_object_paths_.empty());
212 DCHECK_EQ(0, num_pending_watches_);
213 // TODO(satorux): This check fails occasionally in browser_tests for tests
214 // that run very quickly. Perhaps something does not have time to clean up.
215 // Despite the check failing, the tests seem to run fine. crosbug.com/23416
216 // DCHECK_EQ(0, num_pending_timeouts_);
219 ObjectProxy* Bus::GetObjectProxy(const std::string& service_name,
220 const ObjectPath& object_path) {
221 return GetObjectProxyWithOptions(service_name, object_path,
222 ObjectProxy::DEFAULT_OPTIONS);
225 ObjectProxy* Bus::GetObjectProxyWithOptions(const std::string& service_name,
226 const ObjectPath& object_path,
227 int options) {
228 AssertOnOriginThread();
230 // Check if we already have the requested object proxy.
231 const ObjectProxyTable::key_type key(service_name + object_path.value(),
232 options);
233 ObjectProxyTable::iterator iter = object_proxy_table_.find(key);
234 if (iter != object_proxy_table_.end()) {
235 return iter->second.get();
238 scoped_refptr<ObjectProxy> object_proxy =
239 new ObjectProxy(this, service_name, object_path, options);
240 object_proxy_table_[key] = object_proxy;
242 return object_proxy.get();
245 bool Bus::RemoveObjectProxy(const std::string& service_name,
246 const ObjectPath& object_path,
247 const base::Closure& callback) {
248 return RemoveObjectProxyWithOptions(service_name, object_path,
249 ObjectProxy::DEFAULT_OPTIONS,
250 callback);
253 bool Bus::RemoveObjectProxyWithOptions(const std::string& service_name,
254 const ObjectPath& object_path,
255 int options,
256 const base::Closure& callback) {
257 AssertOnOriginThread();
259 // Check if we have the requested object proxy.
260 const ObjectProxyTable::key_type key(service_name + object_path.value(),
261 options);
262 ObjectProxyTable::iterator iter = object_proxy_table_.find(key);
263 if (iter != object_proxy_table_.end()) {
264 scoped_refptr<ObjectProxy> object_proxy = iter->second;
265 object_proxy_table_.erase(iter);
266 // Object is present. Remove it now and Detach on the DBus thread.
267 GetDBusTaskRunner()->PostTask(
268 FROM_HERE,
269 base::Bind(&Bus::RemoveObjectProxyInternal,
270 this, object_proxy, callback));
271 return true;
273 return false;
276 void Bus::RemoveObjectProxyInternal(scoped_refptr<ObjectProxy> object_proxy,
277 const base::Closure& callback) {
278 AssertOnDBusThread();
280 object_proxy.get()->Detach();
282 GetOriginTaskRunner()->PostTask(FROM_HERE, callback);
285 ExportedObject* Bus::GetExportedObject(const ObjectPath& object_path) {
286 AssertOnOriginThread();
288 // Check if we already have the requested exported object.
289 ExportedObjectTable::iterator iter = exported_object_table_.find(object_path);
290 if (iter != exported_object_table_.end()) {
291 return iter->second.get();
294 scoped_refptr<ExportedObject> exported_object =
295 new ExportedObject(this, object_path);
296 exported_object_table_[object_path] = exported_object;
298 return exported_object.get();
301 void Bus::UnregisterExportedObject(const ObjectPath& object_path) {
302 AssertOnOriginThread();
304 // Remove the registered object from the table first, to allow a new
305 // GetExportedObject() call to return a new object, rather than this one.
306 ExportedObjectTable::iterator iter = exported_object_table_.find(object_path);
307 if (iter == exported_object_table_.end())
308 return;
310 scoped_refptr<ExportedObject> exported_object = iter->second;
311 exported_object_table_.erase(iter);
313 // Post the task to perform the final unregistration to the D-Bus thread.
314 // Since the registration also happens on the D-Bus thread in
315 // TryRegisterObjectPath(), and the task runner we post to is a
316 // SequencedTaskRunner, there is a guarantee that this will happen before any
317 // future registration call.
318 GetDBusTaskRunner()->PostTask(
319 FROM_HERE,
320 base::Bind(&Bus::UnregisterExportedObjectInternal,
321 this, exported_object));
324 void Bus::UnregisterExportedObjectInternal(
325 scoped_refptr<ExportedObject> exported_object) {
326 AssertOnDBusThread();
328 exported_object->Unregister();
331 ObjectManager* Bus::GetObjectManager(const std::string& service_name,
332 const ObjectPath& object_path) {
333 AssertOnOriginThread();
335 // Check if we already have the requested object manager.
336 const ObjectManagerTable::key_type key(service_name + object_path.value());
337 ObjectManagerTable::iterator iter = object_manager_table_.find(key);
338 if (iter != object_manager_table_.end()) {
339 return iter->second.get();
342 scoped_refptr<ObjectManager> object_manager =
343 new ObjectManager(this, service_name, object_path);
344 object_manager_table_[key] = object_manager;
346 return object_manager.get();
349 bool Bus::RemoveObjectManager(const std::string& service_name,
350 const ObjectPath& object_path,
351 const base::Closure& callback) {
352 AssertOnOriginThread();
353 DCHECK(!callback.is_null());
355 const ObjectManagerTable::key_type key(service_name + object_path.value());
356 ObjectManagerTable::iterator iter = object_manager_table_.find(key);
357 if (iter == object_manager_table_.end())
358 return false;
360 // ObjectManager is present. Remove it now and CleanUp on the DBus thread.
361 scoped_refptr<ObjectManager> object_manager = iter->second;
362 object_manager_table_.erase(iter);
364 GetDBusTaskRunner()->PostTask(
365 FROM_HERE,
366 base::Bind(&Bus::RemoveObjectManagerInternal,
367 this, object_manager, callback));
369 return true;
372 void Bus::RemoveObjectManagerInternal(
373 scoped_refptr<dbus::ObjectManager> object_manager,
374 const base::Closure& callback) {
375 AssertOnDBusThread();
376 DCHECK(object_manager.get());
378 object_manager->CleanUp();
380 // The ObjectManager has to be deleted on the origin thread since it was
381 // created there.
382 GetOriginTaskRunner()->PostTask(
383 FROM_HERE,
384 base::Bind(&Bus::RemoveObjectManagerInternalHelper,
385 this, object_manager, callback));
388 void Bus::RemoveObjectManagerInternalHelper(
389 scoped_refptr<dbus::ObjectManager> object_manager,
390 const base::Closure& callback) {
391 AssertOnOriginThread();
392 DCHECK(object_manager.get());
394 // Release the object manager and run the callback.
395 object_manager = NULL;
396 callback.Run();
399 void Bus::GetManagedObjects() {
400 for (ObjectManagerTable::iterator iter = object_manager_table_.begin();
401 iter != object_manager_table_.end(); ++iter) {
402 iter->second->GetManagedObjects();
406 bool Bus::Connect() {
407 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
408 AssertOnDBusThread();
410 // Check if it's already initialized.
411 if (connection_)
412 return true;
414 ScopedDBusError error;
415 if (bus_type_ == CUSTOM_ADDRESS) {
416 if (connection_type_ == PRIVATE) {
417 connection_ = dbus_connection_open_private(address_.c_str(), error.get());
418 } else {
419 connection_ = dbus_connection_open(address_.c_str(), error.get());
421 } else {
422 const DBusBusType dbus_bus_type = static_cast<DBusBusType>(bus_type_);
423 if (connection_type_ == PRIVATE) {
424 connection_ = dbus_bus_get_private(dbus_bus_type, error.get());
425 } else {
426 connection_ = dbus_bus_get(dbus_bus_type, error.get());
429 if (!connection_) {
430 LOG(ERROR) << "Failed to connect to the bus: "
431 << (error.is_set() ? error.message() : "");
432 return false;
435 if (bus_type_ == CUSTOM_ADDRESS) {
436 // We should call dbus_bus_register here, otherwise unique name can not be
437 // acquired. According to dbus specification, it is responsible to call
438 // org.freedesktop.DBus.Hello method at the beging of bus connection to
439 // acquire unique name. In the case of dbus_bus_get, dbus_bus_register is
440 // called internally.
441 if (!dbus_bus_register(connection_, error.get())) {
442 LOG(ERROR) << "Failed to register the bus component: "
443 << (error.is_set() ? error.message() : "");
444 return false;
447 // We shouldn't exit on the disconnected signal.
448 dbus_connection_set_exit_on_disconnect(connection_, false);
450 // Watch Disconnected signal.
451 AddFilterFunction(Bus::OnConnectionDisconnectedFilter, this);
452 AddMatch(kDisconnectedMatchRule, error.get());
454 return true;
457 void Bus::ClosePrivateConnection() {
458 // dbus_connection_close is blocking call.
459 AssertOnDBusThread();
460 DCHECK_EQ(PRIVATE, connection_type_)
461 << "non-private connection should not be closed";
462 dbus_connection_close(connection_);
465 void Bus::ShutdownAndBlock() {
466 AssertOnDBusThread();
468 if (shutdown_completed_)
469 return; // Already shutdowned, just return.
471 // Unregister the exported objects.
472 for (ExportedObjectTable::iterator iter = exported_object_table_.begin();
473 iter != exported_object_table_.end(); ++iter) {
474 iter->second->Unregister();
477 // Release all service names.
478 for (std::set<std::string>::iterator iter = owned_service_names_.begin();
479 iter != owned_service_names_.end();) {
480 // This is a bit tricky but we should increment the iter here as
481 // ReleaseOwnership() may remove |service_name| from the set.
482 const std::string& service_name = *iter++;
483 ReleaseOwnership(service_name);
485 if (!owned_service_names_.empty()) {
486 LOG(ERROR) << "Failed to release all service names. # of services left: "
487 << owned_service_names_.size();
490 // Detach from the remote objects.
491 for (ObjectProxyTable::iterator iter = object_proxy_table_.begin();
492 iter != object_proxy_table_.end(); ++iter) {
493 iter->second->Detach();
496 // Clean up the object managers.
497 for (ObjectManagerTable::iterator iter = object_manager_table_.begin();
498 iter != object_manager_table_.end(); ++iter) {
499 iter->second->CleanUp();
502 // Release object proxies and exported objects here. We should do this
503 // here rather than in the destructor to avoid memory leaks due to
504 // cyclic references.
505 object_proxy_table_.clear();
506 exported_object_table_.clear();
508 // Private connection should be closed.
509 if (connection_) {
510 // Remove Disconnected watcher.
511 ScopedDBusError error;
512 RemoveFilterFunction(Bus::OnConnectionDisconnectedFilter, this);
513 RemoveMatch(kDisconnectedMatchRule, error.get());
515 if (connection_type_ == PRIVATE)
516 ClosePrivateConnection();
517 // dbus_connection_close() won't unref.
518 dbus_connection_unref(connection_);
521 connection_ = NULL;
522 shutdown_completed_ = true;
525 void Bus::ShutdownOnDBusThreadAndBlock() {
526 AssertOnOriginThread();
527 DCHECK(dbus_task_runner_.get());
529 GetDBusTaskRunner()->PostTask(
530 FROM_HERE,
531 base::Bind(&Bus::ShutdownOnDBusThreadAndBlockInternal, this));
533 // http://crbug.com/125222
534 base::ThreadRestrictions::ScopedAllowWait allow_wait;
536 // Wait until the shutdown is complete on the D-Bus thread.
537 // The shutdown should not hang, but set timeout just in case.
538 const int kTimeoutSecs = 3;
539 const base::TimeDelta timeout(base::TimeDelta::FromSeconds(kTimeoutSecs));
540 const bool signaled = on_shutdown_.TimedWait(timeout);
541 LOG_IF(ERROR, !signaled) << "Failed to shutdown the bus";
544 void Bus::RequestOwnership(const std::string& service_name,
545 ServiceOwnershipOptions options,
546 OnOwnershipCallback on_ownership_callback) {
547 AssertOnOriginThread();
549 GetDBusTaskRunner()->PostTask(
550 FROM_HERE,
551 base::Bind(&Bus::RequestOwnershipInternal,
552 this, service_name, options, on_ownership_callback));
555 void Bus::RequestOwnershipInternal(const std::string& service_name,
556 ServiceOwnershipOptions options,
557 OnOwnershipCallback on_ownership_callback) {
558 AssertOnDBusThread();
560 bool success = Connect();
561 if (success)
562 success = RequestOwnershipAndBlock(service_name, options);
564 GetOriginTaskRunner()->PostTask(FROM_HERE,
565 base::Bind(on_ownership_callback,
566 service_name,
567 success));
570 bool Bus::RequestOwnershipAndBlock(const std::string& service_name,
571 ServiceOwnershipOptions options) {
572 DCHECK(connection_);
573 // dbus_bus_request_name() is a blocking call.
574 AssertOnDBusThread();
576 // Check if we already own the service name.
577 if (owned_service_names_.find(service_name) != owned_service_names_.end()) {
578 return true;
581 ScopedDBusError error;
582 const int result = dbus_bus_request_name(connection_,
583 service_name.c_str(),
584 options,
585 error.get());
586 if (result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
587 LOG(ERROR) << "Failed to get the ownership of " << service_name << ": "
588 << (error.is_set() ? error.message() : "");
589 return false;
591 owned_service_names_.insert(service_name);
592 return true;
595 bool Bus::ReleaseOwnership(const std::string& service_name) {
596 DCHECK(connection_);
597 // dbus_bus_request_name() is a blocking call.
598 AssertOnDBusThread();
600 // Check if we already own the service name.
601 std::set<std::string>::iterator found =
602 owned_service_names_.find(service_name);
603 if (found == owned_service_names_.end()) {
604 LOG(ERROR) << service_name << " is not owned by the bus";
605 return false;
608 ScopedDBusError error;
609 const int result = dbus_bus_release_name(connection_, service_name.c_str(),
610 error.get());
611 if (result == DBUS_RELEASE_NAME_REPLY_RELEASED) {
612 owned_service_names_.erase(found);
613 return true;
614 } else {
615 LOG(ERROR) << "Failed to release the ownership of " << service_name << ": "
616 << (error.is_set() ? error.message() : "")
617 << ", result code: " << result;
618 return false;
622 bool Bus::SetUpAsyncOperations() {
623 DCHECK(connection_);
624 AssertOnDBusThread();
626 if (async_operations_set_up_)
627 return true;
629 // Process all the incoming data if any, so that OnDispatchStatus() will
630 // be called when the incoming data is ready.
631 ProcessAllIncomingDataIfAny();
633 bool success = dbus_connection_set_watch_functions(connection_,
634 &Bus::OnAddWatchThunk,
635 &Bus::OnRemoveWatchThunk,
636 &Bus::OnToggleWatchThunk,
637 this,
638 NULL);
639 CHECK(success) << "Unable to allocate memory";
641 success = dbus_connection_set_timeout_functions(connection_,
642 &Bus::OnAddTimeoutThunk,
643 &Bus::OnRemoveTimeoutThunk,
644 &Bus::OnToggleTimeoutThunk,
645 this,
646 NULL);
647 CHECK(success) << "Unable to allocate memory";
649 dbus_connection_set_dispatch_status_function(
650 connection_,
651 &Bus::OnDispatchStatusChangedThunk,
652 this,
653 NULL);
655 async_operations_set_up_ = true;
657 return true;
660 DBusMessage* Bus::SendWithReplyAndBlock(DBusMessage* request,
661 int timeout_ms,
662 DBusError* error) {
663 DCHECK(connection_);
664 AssertOnDBusThread();
666 return dbus_connection_send_with_reply_and_block(
667 connection_, request, timeout_ms, error);
670 void Bus::SendWithReply(DBusMessage* request,
671 DBusPendingCall** pending_call,
672 int timeout_ms) {
673 DCHECK(connection_);
674 AssertOnDBusThread();
676 const bool success = dbus_connection_send_with_reply(
677 connection_, request, pending_call, timeout_ms);
678 CHECK(success) << "Unable to allocate memory";
681 void Bus::Send(DBusMessage* request, uint32* serial) {
682 DCHECK(connection_);
683 AssertOnDBusThread();
685 const bool success = dbus_connection_send(connection_, request, serial);
686 CHECK(success) << "Unable to allocate memory";
689 void Bus::AddFilterFunction(DBusHandleMessageFunction filter_function,
690 void* user_data) {
691 DCHECK(connection_);
692 AssertOnDBusThread();
694 std::pair<DBusHandleMessageFunction, void*> filter_data_pair =
695 std::make_pair(filter_function, user_data);
696 if (filter_functions_added_.find(filter_data_pair) !=
697 filter_functions_added_.end()) {
698 VLOG(1) << "Filter function already exists: " << filter_function
699 << " with associated data: " << user_data;
700 return;
703 const bool success = dbus_connection_add_filter(
704 connection_, filter_function, user_data, NULL);
705 CHECK(success) << "Unable to allocate memory";
706 filter_functions_added_.insert(filter_data_pair);
709 void Bus::RemoveFilterFunction(DBusHandleMessageFunction filter_function,
710 void* user_data) {
711 DCHECK(connection_);
712 AssertOnDBusThread();
714 std::pair<DBusHandleMessageFunction, void*> filter_data_pair =
715 std::make_pair(filter_function, user_data);
716 if (filter_functions_added_.find(filter_data_pair) ==
717 filter_functions_added_.end()) {
718 VLOG(1) << "Requested to remove an unknown filter function: "
719 << filter_function
720 << " with associated data: " << user_data;
721 return;
724 dbus_connection_remove_filter(connection_, filter_function, user_data);
725 filter_functions_added_.erase(filter_data_pair);
728 void Bus::AddMatch(const std::string& match_rule, DBusError* error) {
729 DCHECK(connection_);
730 AssertOnDBusThread();
732 std::map<std::string, int>::iterator iter =
733 match_rules_added_.find(match_rule);
734 if (iter != match_rules_added_.end()) {
735 // The already existing rule's counter is incremented.
736 iter->second++;
738 VLOG(1) << "Match rule already exists: " << match_rule;
739 return;
742 dbus_bus_add_match(connection_, match_rule.c_str(), error);
743 match_rules_added_[match_rule] = 1;
746 bool Bus::RemoveMatch(const std::string& match_rule, DBusError* error) {
747 DCHECK(connection_);
748 AssertOnDBusThread();
750 std::map<std::string, int>::iterator iter =
751 match_rules_added_.find(match_rule);
752 if (iter == match_rules_added_.end()) {
753 LOG(ERROR) << "Requested to remove an unknown match rule: " << match_rule;
754 return false;
757 // The rule's counter is decremented and the rule is deleted when reachs 0.
758 iter->second--;
759 if (iter->second == 0) {
760 dbus_bus_remove_match(connection_, match_rule.c_str(), error);
761 match_rules_added_.erase(match_rule);
763 return true;
766 bool Bus::TryRegisterObjectPath(const ObjectPath& object_path,
767 const DBusObjectPathVTable* vtable,
768 void* user_data,
769 DBusError* error) {
770 DCHECK(connection_);
771 AssertOnDBusThread();
773 if (registered_object_paths_.find(object_path) !=
774 registered_object_paths_.end()) {
775 LOG(ERROR) << "Object path already registered: " << object_path.value();
776 return false;
779 const bool success = dbus_connection_try_register_object_path(
780 connection_,
781 object_path.value().c_str(),
782 vtable,
783 user_data,
784 error);
785 if (success)
786 registered_object_paths_.insert(object_path);
787 return success;
790 void Bus::UnregisterObjectPath(const ObjectPath& object_path) {
791 DCHECK(connection_);
792 AssertOnDBusThread();
794 if (registered_object_paths_.find(object_path) ==
795 registered_object_paths_.end()) {
796 LOG(ERROR) << "Requested to unregister an unknown object path: "
797 << object_path.value();
798 return;
801 const bool success = dbus_connection_unregister_object_path(
802 connection_,
803 object_path.value().c_str());
804 CHECK(success) << "Unable to allocate memory";
805 registered_object_paths_.erase(object_path);
808 void Bus::ShutdownOnDBusThreadAndBlockInternal() {
809 AssertOnDBusThread();
811 ShutdownAndBlock();
812 on_shutdown_.Signal();
815 void Bus::ProcessAllIncomingDataIfAny() {
816 AssertOnDBusThread();
818 // As mentioned at the class comment in .h file, connection_ can be NULL.
819 if (!connection_)
820 return;
822 // It is safe and necessary to call dbus_connection_get_dispatch_status even
823 // if the connection is lost.
824 if (dbus_connection_get_dispatch_status(connection_) ==
825 DBUS_DISPATCH_DATA_REMAINS) {
826 while (dbus_connection_dispatch(connection_) ==
827 DBUS_DISPATCH_DATA_REMAINS) {
832 base::TaskRunner* Bus::GetDBusTaskRunner() {
833 if (dbus_task_runner_.get())
834 return dbus_task_runner_.get();
835 else
836 return GetOriginTaskRunner();
839 base::TaskRunner* Bus::GetOriginTaskRunner() {
840 DCHECK(origin_task_runner_.get());
841 return origin_task_runner_.get();
844 bool Bus::HasDBusThread() {
845 return dbus_task_runner_.get() != NULL;
848 void Bus::AssertOnOriginThread() {
849 DCHECK_EQ(origin_thread_id_, base::PlatformThread::CurrentId());
852 void Bus::AssertOnDBusThread() {
853 base::ThreadRestrictions::AssertIOAllowed();
855 if (dbus_task_runner_.get()) {
856 DCHECK(dbus_task_runner_->RunsTasksOnCurrentThread());
857 } else {
858 AssertOnOriginThread();
862 std::string Bus::GetServiceOwnerAndBlock(const std::string& service_name,
863 GetServiceOwnerOption options) {
864 AssertOnDBusThread();
866 MethodCall get_name_owner_call("org.freedesktop.DBus", "GetNameOwner");
867 MessageWriter writer(&get_name_owner_call);
868 writer.AppendString(service_name);
869 VLOG(1) << "Method call: " << get_name_owner_call.ToString();
871 const ObjectPath obj_path("/org/freedesktop/DBus");
872 if (!get_name_owner_call.SetDestination("org.freedesktop.DBus") ||
873 !get_name_owner_call.SetPath(obj_path)) {
874 if (options == REPORT_ERRORS)
875 LOG(ERROR) << "Failed to get name owner.";
876 return "";
879 ScopedDBusError error;
880 DBusMessage* response_message =
881 SendWithReplyAndBlock(get_name_owner_call.raw_message(),
882 ObjectProxy::TIMEOUT_USE_DEFAULT,
883 error.get());
884 if (!response_message) {
885 if (options == REPORT_ERRORS) {
886 LOG(ERROR) << "Failed to get name owner. Got " << error.name() << ": "
887 << error.message();
889 return "";
892 scoped_ptr<Response> response(Response::FromRawMessage(response_message));
893 MessageReader reader(response.get());
895 std::string service_owner;
896 if (!reader.PopString(&service_owner))
897 service_owner.clear();
898 return service_owner;
901 void Bus::GetServiceOwner(const std::string& service_name,
902 const GetServiceOwnerCallback& callback) {
903 AssertOnOriginThread();
905 GetDBusTaskRunner()->PostTask(
906 FROM_HERE,
907 base::Bind(&Bus::GetServiceOwnerInternal, this, service_name, callback));
910 void Bus::GetServiceOwnerInternal(const std::string& service_name,
911 const GetServiceOwnerCallback& callback) {
912 AssertOnDBusThread();
914 std::string service_owner;
915 if (Connect())
916 service_owner = GetServiceOwnerAndBlock(service_name, SUPPRESS_ERRORS);
917 GetOriginTaskRunner()->PostTask(FROM_HERE,
918 base::Bind(callback, service_owner));
921 void Bus::ListenForServiceOwnerChange(
922 const std::string& service_name,
923 const GetServiceOwnerCallback& callback) {
924 AssertOnOriginThread();
925 DCHECK(!service_name.empty());
926 DCHECK(!callback.is_null());
928 GetDBusTaskRunner()->PostTask(
929 FROM_HERE,
930 base::Bind(&Bus::ListenForServiceOwnerChangeInternal,
931 this, service_name, callback));
934 void Bus::ListenForServiceOwnerChangeInternal(
935 const std::string& service_name,
936 const GetServiceOwnerCallback& callback) {
937 AssertOnDBusThread();
938 DCHECK(!service_name.empty());
939 DCHECK(!callback.is_null());
941 if (!Connect() || !SetUpAsyncOperations())
942 return;
944 if (service_owner_changed_listener_map_.empty())
945 AddFilterFunction(Bus::OnServiceOwnerChangedFilter, this);
947 ServiceOwnerChangedListenerMap::iterator it =
948 service_owner_changed_listener_map_.find(service_name);
949 if (it == service_owner_changed_listener_map_.end()) {
950 // Add a match rule for the new service name.
951 const std::string name_owner_changed_match_rule =
952 base::StringPrintf(kServiceNameOwnerChangeMatchRule,
953 service_name.c_str());
954 ScopedDBusError error;
955 AddMatch(name_owner_changed_match_rule, error.get());
956 if (error.is_set()) {
957 LOG(ERROR) << "Failed to add match rule for " << service_name
958 << ". Got " << error.name() << ": " << error.message();
959 return;
962 service_owner_changed_listener_map_[service_name].push_back(callback);
963 return;
966 // Check if the callback has already been added.
967 std::vector<GetServiceOwnerCallback>& callbacks = it->second;
968 for (size_t i = 0; i < callbacks.size(); ++i) {
969 if (callbacks[i].Equals(callback))
970 return;
972 callbacks.push_back(callback);
975 void Bus::UnlistenForServiceOwnerChange(
976 const std::string& service_name,
977 const GetServiceOwnerCallback& callback) {
978 AssertOnOriginThread();
979 DCHECK(!service_name.empty());
980 DCHECK(!callback.is_null());
982 GetDBusTaskRunner()->PostTask(
983 FROM_HERE,
984 base::Bind(&Bus::UnlistenForServiceOwnerChangeInternal,
985 this, service_name, callback));
988 void Bus::UnlistenForServiceOwnerChangeInternal(
989 const std::string& service_name,
990 const GetServiceOwnerCallback& callback) {
991 AssertOnDBusThread();
992 DCHECK(!service_name.empty());
993 DCHECK(!callback.is_null());
995 ServiceOwnerChangedListenerMap::iterator it =
996 service_owner_changed_listener_map_.find(service_name);
997 if (it == service_owner_changed_listener_map_.end())
998 return;
1000 std::vector<GetServiceOwnerCallback>& callbacks = it->second;
1001 for (size_t i = 0; i < callbacks.size(); ++i) {
1002 if (callbacks[i].Equals(callback)) {
1003 callbacks.erase(callbacks.begin() + i);
1004 break; // There can be only one.
1007 if (!callbacks.empty())
1008 return;
1010 // Last callback for |service_name| has been removed, remove match rule.
1011 const std::string name_owner_changed_match_rule =
1012 base::StringPrintf(kServiceNameOwnerChangeMatchRule,
1013 service_name.c_str());
1014 ScopedDBusError error;
1015 RemoveMatch(name_owner_changed_match_rule, error.get());
1016 // And remove |service_owner_changed_listener_map_| entry.
1017 service_owner_changed_listener_map_.erase(it);
1019 if (service_owner_changed_listener_map_.empty())
1020 RemoveFilterFunction(Bus::OnServiceOwnerChangedFilter, this);
1023 std::string Bus::GetConnectionName() {
1024 if (!connection_)
1025 return "";
1026 return dbus_bus_get_unique_name(connection_);
1029 dbus_bool_t Bus::OnAddWatch(DBusWatch* raw_watch) {
1030 AssertOnDBusThread();
1032 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
1033 Watch* watch = new Watch(raw_watch);
1034 if (watch->IsReadyToBeWatched()) {
1035 watch->StartWatching();
1037 ++num_pending_watches_;
1038 return true;
1041 void Bus::OnRemoveWatch(DBusWatch* raw_watch) {
1042 AssertOnDBusThread();
1044 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
1045 delete watch;
1046 --num_pending_watches_;
1049 void Bus::OnToggleWatch(DBusWatch* raw_watch) {
1050 AssertOnDBusThread();
1052 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
1053 if (watch->IsReadyToBeWatched()) {
1054 watch->StartWatching();
1055 } else {
1056 // It's safe to call this if StartWatching() wasn't called, per
1057 // message_pump_libevent.h.
1058 watch->StopWatching();
1062 dbus_bool_t Bus::OnAddTimeout(DBusTimeout* raw_timeout) {
1063 AssertOnDBusThread();
1065 // timeout will be deleted when raw_timeout is removed in
1066 // OnRemoveTimeoutThunk().
1067 Timeout* timeout = new Timeout(raw_timeout);
1068 if (timeout->IsReadyToBeMonitored()) {
1069 timeout->StartMonitoring(this);
1071 ++num_pending_timeouts_;
1072 return true;
1075 void Bus::OnRemoveTimeout(DBusTimeout* raw_timeout) {
1076 AssertOnDBusThread();
1078 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
1079 timeout->Complete();
1080 --num_pending_timeouts_;
1083 void Bus::OnToggleTimeout(DBusTimeout* raw_timeout) {
1084 AssertOnDBusThread();
1086 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
1087 if (timeout->IsReadyToBeMonitored()) {
1088 timeout->StartMonitoring(this);
1089 } else {
1090 timeout->StopMonitoring();
1094 void Bus::OnDispatchStatusChanged(DBusConnection* connection,
1095 DBusDispatchStatus status) {
1096 DCHECK_EQ(connection, connection_);
1097 AssertOnDBusThread();
1099 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
1100 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
1101 // prohibited by the D-Bus library. Hence, we post a task here instead.
1102 // See comments for dbus_connection_set_dispatch_status_function().
1103 GetDBusTaskRunner()->PostTask(FROM_HERE,
1104 base::Bind(&Bus::ProcessAllIncomingDataIfAny,
1105 this));
1108 void Bus::OnServiceOwnerChanged(DBusMessage* message) {
1109 DCHECK(message);
1110 AssertOnDBusThread();
1112 // |message| will be unrefed on exit of the function. Increment the
1113 // reference so we can use it in Signal::FromRawMessage() below.
1114 dbus_message_ref(message);
1115 scoped_ptr<Signal> signal(Signal::FromRawMessage(message));
1117 // Confirm the validity of the NameOwnerChanged signal.
1118 if (signal->GetMember() != kNameOwnerChangedSignal ||
1119 signal->GetInterface() != DBUS_INTERFACE_DBUS ||
1120 signal->GetSender() != DBUS_SERVICE_DBUS) {
1121 return;
1124 MessageReader reader(signal.get());
1125 std::string service_name;
1126 std::string old_owner;
1127 std::string new_owner;
1128 if (!reader.PopString(&service_name) ||
1129 !reader.PopString(&old_owner) ||
1130 !reader.PopString(&new_owner)) {
1131 return;
1134 ServiceOwnerChangedListenerMap::const_iterator it =
1135 service_owner_changed_listener_map_.find(service_name);
1136 if (it == service_owner_changed_listener_map_.end())
1137 return;
1139 const std::vector<GetServiceOwnerCallback>& callbacks = it->second;
1140 for (size_t i = 0; i < callbacks.size(); ++i) {
1141 GetOriginTaskRunner()->PostTask(FROM_HERE,
1142 base::Bind(callbacks[i], new_owner));
1146 // static
1147 dbus_bool_t Bus::OnAddWatchThunk(DBusWatch* raw_watch, void* data) {
1148 Bus* self = static_cast<Bus*>(data);
1149 return self->OnAddWatch(raw_watch);
1152 // static
1153 void Bus::OnRemoveWatchThunk(DBusWatch* raw_watch, void* data) {
1154 Bus* self = static_cast<Bus*>(data);
1155 self->OnRemoveWatch(raw_watch);
1158 // static
1159 void Bus::OnToggleWatchThunk(DBusWatch* raw_watch, void* data) {
1160 Bus* self = static_cast<Bus*>(data);
1161 self->OnToggleWatch(raw_watch);
1164 // static
1165 dbus_bool_t Bus::OnAddTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1166 Bus* self = static_cast<Bus*>(data);
1167 return self->OnAddTimeout(raw_timeout);
1170 // static
1171 void Bus::OnRemoveTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1172 Bus* self = static_cast<Bus*>(data);
1173 self->OnRemoveTimeout(raw_timeout);
1176 // static
1177 void Bus::OnToggleTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1178 Bus* self = static_cast<Bus*>(data);
1179 self->OnToggleTimeout(raw_timeout);
1182 // static
1183 void Bus::OnDispatchStatusChangedThunk(DBusConnection* connection,
1184 DBusDispatchStatus status,
1185 void* data) {
1186 Bus* self = static_cast<Bus*>(data);
1187 self->OnDispatchStatusChanged(connection, status);
1190 // static
1191 DBusHandlerResult Bus::OnConnectionDisconnectedFilter(
1192 DBusConnection* connection,
1193 DBusMessage* message,
1194 void* data) {
1195 if (dbus_message_is_signal(message,
1196 DBUS_INTERFACE_LOCAL,
1197 kDisconnectedSignal)) {
1198 // Abort when the connection is lost.
1199 LOG(FATAL) << "D-Bus connection was disconnected. Aborting.";
1201 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1204 // static
1205 DBusHandlerResult Bus::OnServiceOwnerChangedFilter(
1206 DBusConnection* connection,
1207 DBusMessage* message,
1208 void* data) {
1209 if (dbus_message_is_signal(message,
1210 DBUS_INTERFACE_DBUS,
1211 kNameOwnerChangedSignal)) {
1212 Bus* self = static_cast<Bus*>(data);
1213 self->OnServiceOwnerChanged(message);
1215 // Always return unhandled to let others, e.g. ObjectProxies, handle the same
1216 // signal.
1217 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1220 } // namespace dbus