1 // Copyright (c) 2011 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.
6 // - Handle "disconnected" signal.
10 #include "base/bind.h"
11 #include "base/logging.h"
12 #include "base/message_loop.h"
13 #include "base/message_loop_proxy.h"
14 #include "base/stl_util.h"
15 #include "base/threading/thread.h"
16 #include "base/threading/thread_restrictions.h"
17 #include "base/time.h"
18 #include "dbus/exported_object.h"
19 #include "dbus/object_proxy.h"
20 #include "dbus/scoped_dbus_error.h"
26 // The class is used for watching the file descriptor used for D-Bus
28 class Watch
: public base::MessagePumpLibevent::Watcher
{
30 Watch(DBusWatch
* watch
)
32 dbus_watch_set_data(raw_watch_
, this, NULL
);
36 dbus_watch_set_data(raw_watch_
, NULL
, NULL
);
39 // Returns true if the underlying file descriptor is ready to be watched.
40 bool IsReadyToBeWatched() {
41 return dbus_watch_get_enabled(raw_watch_
);
44 // Starts watching the underlying file descriptor.
45 void StartWatching() {
46 const int file_descriptor
= dbus_watch_get_unix_fd(raw_watch_
);
47 const int flags
= dbus_watch_get_flags(raw_watch_
);
49 MessageLoopForIO::Mode mode
= MessageLoopForIO::WATCH_READ
;
50 if ((flags
& DBUS_WATCH_READABLE
) && (flags
& DBUS_WATCH_WRITABLE
))
51 mode
= MessageLoopForIO::WATCH_READ_WRITE
;
52 else if (flags
& DBUS_WATCH_READABLE
)
53 mode
= MessageLoopForIO::WATCH_READ
;
54 else if (flags
& DBUS_WATCH_WRITABLE
)
55 mode
= MessageLoopForIO::WATCH_WRITE
;
59 const bool persistent
= true; // Watch persistently.
60 const bool success
= MessageLoopForIO::current()->WatchFileDescriptor(
64 &file_descriptor_watcher_
,
66 CHECK(success
) << "Unable to allocate memory";
69 // Stops watching the underlying file descriptor.
71 file_descriptor_watcher_
.StopWatchingFileDescriptor();
75 // Implement MessagePumpLibevent::Watcher.
76 virtual void OnFileCanReadWithoutBlocking(int file_descriptor
) {
77 const bool success
= dbus_watch_handle(raw_watch_
, DBUS_WATCH_READABLE
);
78 CHECK(success
) << "Unable to allocate memory";
81 // Implement MessagePumpLibevent::Watcher.
82 virtual void OnFileCanWriteWithoutBlocking(int file_descriptor
) {
83 const bool success
= dbus_watch_handle(raw_watch_
, DBUS_WATCH_WRITABLE
);
84 CHECK(success
) << "Unable to allocate memory";
87 DBusWatch
* raw_watch_
;
88 base::MessagePumpLibevent::FileDescriptorWatcher file_descriptor_watcher_
;
91 // The class is used for monitoring the timeout used for D-Bus method
94 // Unlike Watch, Timeout is a ref counted object, to ensure that |this| of
95 // the object is is alive when HandleTimeout() is called. It's unlikely
96 // but it may be possible that HandleTimeout() is called after
97 // Bus::OnRemoveTimeout(). That's why we don't simply delete the object in
98 // Bus::OnRemoveTimeout().
99 class Timeout
: public base::RefCountedThreadSafe
<Timeout
> {
101 Timeout(DBusTimeout
* timeout
)
102 : raw_timeout_(timeout
),
103 monitoring_is_active_(false),
104 is_completed(false) {
105 dbus_timeout_set_data(raw_timeout_
, this, NULL
);
106 AddRef(); // Balanced on Complete().
109 // Returns true if the timeout is ready to be monitored.
110 bool IsReadyToBeMonitored() {
111 return dbus_timeout_get_enabled(raw_timeout_
);
114 // Starts monitoring the timeout.
115 void StartMonitoring(dbus::Bus
* bus
) {
116 bus
->PostDelayedTaskToDBusThread(FROM_HERE
,
117 base::Bind(&Timeout::HandleTimeout
,
120 monitoring_is_active_
= true;
123 // Stops monitoring the timeout.
124 void StopMonitoring() {
125 // We cannot take back the delayed task we posted in
126 // StartMonitoring(), so we just mark the monitoring is inactive now.
127 monitoring_is_active_
= false;
130 // Returns the interval in milliseconds.
131 int GetIntervalInMs() {
132 return dbus_timeout_get_interval(raw_timeout_
);
135 // Cleans up the raw_timeout and marks that timeout is completed.
136 // See the class comment above for why we are doing this.
138 dbus_timeout_set_data(raw_timeout_
, NULL
, NULL
);
144 friend class base::RefCountedThreadSafe
<Timeout
>;
148 // Handles the timeout.
149 void HandleTimeout() {
150 // If the timeout is marked completed, we should do nothing. This can
151 // occur if this function is called after Bus::OnRemoveTimeout().
154 // Skip if monitoring is canceled.
155 if (!monitoring_is_active_
)
158 const bool success
= dbus_timeout_handle(raw_timeout_
);
159 CHECK(success
) << "Unable to allocate memory";
162 DBusTimeout
* raw_timeout_
;
163 bool monitoring_is_active_
;
169 Bus::Options::Options()
171 connection_type(PRIVATE
) {
174 Bus::Options::~Options() {
177 Bus::Bus(const Options
& options
)
178 : bus_type_(options
.bus_type
),
179 connection_type_(options
.connection_type
),
180 dbus_thread_message_loop_proxy_(options
.dbus_thread_message_loop_proxy
),
181 on_shutdown_(false /* manual_reset */, false /* initially_signaled */),
183 origin_thread_id_(base::PlatformThread::CurrentId()),
184 async_operations_set_up_(false),
185 shutdown_completed_(false),
186 num_pending_watches_(0),
187 num_pending_timeouts_(0) {
188 // This is safe to call multiple times.
189 dbus_threads_init_default();
190 // The origin message loop is unnecessary if the client uses synchronous
192 if (MessageLoop::current())
193 origin_message_loop_proxy_
= MessageLoop::current()->message_loop_proxy();
197 DCHECK(!connection_
);
198 DCHECK(owned_service_names_
.empty());
199 DCHECK(match_rules_added_
.empty());
200 DCHECK(filter_functions_added_
.empty());
201 DCHECK(registered_object_paths_
.empty());
202 DCHECK_EQ(0, num_pending_watches_
);
203 DCHECK_EQ(0, num_pending_timeouts_
);
206 ObjectProxy
* Bus::GetObjectProxy(const std::string
& service_name
,
207 const std::string
& object_path
) {
208 AssertOnOriginThread();
210 // Check if we already have the requested object proxy.
211 const std::string key
= service_name
+ object_path
;
212 ObjectProxyTable::iterator iter
= object_proxy_table_
.find(key
);
213 if (iter
!= object_proxy_table_
.end()) {
217 scoped_refptr
<ObjectProxy
> object_proxy
=
218 new ObjectProxy(this, service_name
, object_path
);
219 object_proxy_table_
[key
] = object_proxy
;
221 return object_proxy
.get();
224 ExportedObject
* Bus::GetExportedObject(const std::string
& service_name
,
225 const std::string
& object_path
) {
226 AssertOnOriginThread();
228 // Check if we already have the requested exported object.
229 const std::string key
= service_name
+ object_path
;
230 ExportedObjectTable::iterator iter
= exported_object_table_
.find(key
);
231 if (iter
!= exported_object_table_
.end()) {
235 scoped_refptr
<ExportedObject
> exported_object
=
236 new ExportedObject(this, service_name
, object_path
);
237 exported_object_table_
[key
] = exported_object
;
239 return exported_object
.get();
242 bool Bus::Connect() {
243 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
244 AssertOnDBusThread();
246 // Check if it's already initialized.
250 ScopedDBusError error
;
251 const DBusBusType dbus_bus_type
= static_cast<DBusBusType
>(bus_type_
);
252 if (connection_type_
== PRIVATE
) {
253 connection_
= dbus_bus_get_private(dbus_bus_type
, error
.get());
255 connection_
= dbus_bus_get(dbus_bus_type
, error
.get());
258 LOG(ERROR
) << "Failed to connect to the bus: "
259 << (dbus_error_is_set(error
.get()) ? error
.message() : "");
262 // We shouldn't exit on the disconnected signal.
263 dbus_connection_set_exit_on_disconnect(connection_
, false);
268 void Bus::ShutdownAndBlock() {
269 AssertOnDBusThread();
271 // Unregister the exported objects.
272 for (ExportedObjectTable::iterator iter
= exported_object_table_
.begin();
273 iter
!= exported_object_table_
.end(); ++iter
) {
274 iter
->second
->Unregister();
277 // Release all service names.
278 for (std::set
<std::string
>::iterator iter
= owned_service_names_
.begin();
279 iter
!= owned_service_names_
.end();) {
280 // This is a bit tricky but we should increment the iter here as
281 // ReleaseOwnership() may remove |service_name| from the set.
282 const std::string
& service_name
= *iter
++;
283 ReleaseOwnership(service_name
);
285 if (!owned_service_names_
.empty()) {
286 LOG(ERROR
) << "Failed to release all service names. # of services left: "
287 << owned_service_names_
.size();
290 // Detach from the remote objects.
291 for (ObjectProxyTable::iterator iter
= object_proxy_table_
.begin();
292 iter
!= object_proxy_table_
.end(); ++iter
) {
293 iter
->second
->Detach();
296 // Private connection should be closed.
298 if (connection_type_
== PRIVATE
)
299 dbus_connection_close(connection_
);
300 // dbus_connection_close() won't unref.
301 dbus_connection_unref(connection_
);
305 shutdown_completed_
= true;
308 void Bus::ShutdownOnDBusThreadAndBlock() {
309 AssertOnOriginThread();
310 DCHECK(dbus_thread_message_loop_proxy_
.get());
312 PostTaskToDBusThread(FROM_HERE
, base::Bind(
313 &Bus::ShutdownOnDBusThreadAndBlockInternal
,
316 // Wait until the shutdown is complete on the D-Bus thread.
317 // The shutdown should not hang, but set timeout just in case.
318 const int kTimeoutSecs
= 3;
319 const base::TimeDelta
timeout(base::TimeDelta::FromSeconds(kTimeoutSecs
));
320 const bool signaled
= on_shutdown_
.TimedWait(timeout
);
321 LOG_IF(ERROR
, !signaled
) << "Failed to shutdown the bus";
324 bool Bus::RequestOwnership(const std::string
& service_name
) {
326 // dbus_bus_request_name() is a blocking call.
327 AssertOnDBusThread();
329 // Check if we already own the service name.
330 if (owned_service_names_
.find(service_name
) != owned_service_names_
.end()) {
334 ScopedDBusError error
;
335 const int result
= dbus_bus_request_name(connection_
,
336 service_name
.c_str(),
337 DBUS_NAME_FLAG_DO_NOT_QUEUE
,
339 if (result
!= DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
) {
340 LOG(ERROR
) << "Failed to get the ownership of " << service_name
<< ": "
341 << (dbus_error_is_set(error
.get()) ? error
.message() : "");
344 owned_service_names_
.insert(service_name
);
348 bool Bus::ReleaseOwnership(const std::string
& service_name
) {
350 // dbus_bus_request_name() is a blocking call.
351 AssertOnDBusThread();
353 // Check if we already own the service name.
354 std::set
<std::string
>::iterator found
=
355 owned_service_names_
.find(service_name
);
356 if (found
== owned_service_names_
.end()) {
357 LOG(ERROR
) << service_name
<< " is not owned by the bus";
361 ScopedDBusError error
;
362 const int result
= dbus_bus_release_name(connection_
, service_name
.c_str(),
364 if (result
== DBUS_RELEASE_NAME_REPLY_RELEASED
) {
365 owned_service_names_
.erase(found
);
368 LOG(ERROR
) << "Failed to release the ownership of " << service_name
<< ": "
369 << (error
.is_set() ? error
.message() : "");
374 bool Bus::SetUpAsyncOperations() {
376 AssertOnDBusThread();
378 if (async_operations_set_up_
)
381 // Process all the incoming data if any, so that OnDispatchStatus() will
382 // be called when the incoming data is ready.
383 ProcessAllIncomingDataIfAny();
385 bool success
= dbus_connection_set_watch_functions(connection_
,
386 &Bus::OnAddWatchThunk
,
387 &Bus::OnRemoveWatchThunk
,
388 &Bus::OnToggleWatchThunk
,
391 CHECK(success
) << "Unable to allocate memory";
393 // TODO(satorux): Timeout is not yet implemented.
394 success
= dbus_connection_set_timeout_functions(connection_
,
395 &Bus::OnAddTimeoutThunk
,
396 &Bus::OnRemoveTimeoutThunk
,
397 &Bus::OnToggleTimeoutThunk
,
400 CHECK(success
) << "Unable to allocate memory";
402 dbus_connection_set_dispatch_status_function(
404 &Bus::OnDispatchStatusChangedThunk
,
408 async_operations_set_up_
= true;
413 DBusMessage
* Bus::SendWithReplyAndBlock(DBusMessage
* request
,
417 AssertOnDBusThread();
419 return dbus_connection_send_with_reply_and_block(
420 connection_
, request
, timeout_ms
, error
);
423 void Bus::SendWithReply(DBusMessage
* request
,
424 DBusPendingCall
** pending_call
,
427 AssertOnDBusThread();
429 const bool success
= dbus_connection_send_with_reply(
430 connection_
, request
, pending_call
, timeout_ms
);
431 CHECK(success
) << "Unable to allocate memory";
434 void Bus::Send(DBusMessage
* request
, uint32
* serial
) {
436 AssertOnDBusThread();
438 const bool success
= dbus_connection_send(connection_
, request
, serial
);
439 CHECK(success
) << "Unable to allocate memory";
442 void Bus::AddFilterFunction(DBusHandleMessageFunction filter_function
,
445 AssertOnDBusThread();
447 if (filter_functions_added_
.find(filter_function
) !=
448 filter_functions_added_
.end()) {
449 LOG(ERROR
) << "Filter function already exists: " << filter_function
;
453 const bool success
= dbus_connection_add_filter(
454 connection_
, filter_function
, user_data
, NULL
);
455 CHECK(success
) << "Unable to allocate memory";
456 filter_functions_added_
.insert(filter_function
);
459 void Bus::RemoveFilterFunction(DBusHandleMessageFunction filter_function
,
462 AssertOnDBusThread();
464 if (filter_functions_added_
.find(filter_function
) ==
465 filter_functions_added_
.end()) {
466 LOG(ERROR
) << "Requested to remove an unknown filter function: "
471 dbus_connection_remove_filter(connection_
, filter_function
, user_data
);
472 filter_functions_added_
.erase(filter_function
);
475 void Bus::AddMatch(const std::string
& match_rule
, DBusError
* error
) {
477 AssertOnDBusThread();
479 if (match_rules_added_
.find(match_rule
) != match_rules_added_
.end()) {
480 LOG(ERROR
) << "Match rule already exists: " << match_rule
;
484 dbus_bus_add_match(connection_
, match_rule
.c_str(), error
);
485 match_rules_added_
.insert(match_rule
);
488 void Bus::RemoveMatch(const std::string
& match_rule
, DBusError
* error
) {
490 AssertOnDBusThread();
492 if (match_rules_added_
.find(match_rule
) == match_rules_added_
.end()) {
493 LOG(ERROR
) << "Requested to remove an unknown match rule: " << match_rule
;
497 dbus_bus_remove_match(connection_
, match_rule
.c_str(), error
);
498 match_rules_added_
.erase(match_rule
);
501 bool Bus::TryRegisterObjectPath(const std::string
& object_path
,
502 const DBusObjectPathVTable
* vtable
,
506 AssertOnDBusThread();
508 if (registered_object_paths_
.find(object_path
) !=
509 registered_object_paths_
.end()) {
510 LOG(ERROR
) << "Object path already registered: " << object_path
;
514 const bool success
= dbus_connection_try_register_object_path(
521 registered_object_paths_
.insert(object_path
);
525 void Bus::UnregisterObjectPath(const std::string
& object_path
) {
527 AssertOnDBusThread();
529 if (registered_object_paths_
.find(object_path
) ==
530 registered_object_paths_
.end()) {
531 LOG(ERROR
) << "Requested to unregister an unknown object path: "
536 const bool success
= dbus_connection_unregister_object_path(
538 object_path
.c_str());
539 CHECK(success
) << "Unable to allocate memory";
540 registered_object_paths_
.erase(object_path
);
543 void Bus::ShutdownOnDBusThreadAndBlockInternal() {
544 AssertOnDBusThread();
547 on_shutdown_
.Signal();
550 void Bus::ProcessAllIncomingDataIfAny() {
551 AssertOnDBusThread();
553 // As mentioned at the class comment in .h file, connection_ can be NULL.
554 if (!connection_
|| !dbus_connection_get_is_connected(connection_
))
557 if (dbus_connection_get_dispatch_status(connection_
) ==
558 DBUS_DISPATCH_DATA_REMAINS
) {
559 while (dbus_connection_dispatch(connection_
) ==
560 DBUS_DISPATCH_DATA_REMAINS
);
564 void Bus::PostTaskToOriginThread(const tracked_objects::Location
& from_here
,
565 const base::Closure
& task
) {
566 DCHECK(origin_message_loop_proxy_
.get());
567 if (!origin_message_loop_proxy_
->PostTask(from_here
, task
)) {
568 LOG(WARNING
) << "Failed to post a task to the origin message loop";
572 void Bus::PostTaskToDBusThread(const tracked_objects::Location
& from_here
,
573 const base::Closure
& task
) {
574 if (dbus_thread_message_loop_proxy_
.get()) {
575 if (!dbus_thread_message_loop_proxy_
->PostTask(from_here
, task
)) {
576 LOG(WARNING
) << "Failed to post a task to the D-Bus thread message loop";
579 DCHECK(origin_message_loop_proxy_
.get());
580 if (!origin_message_loop_proxy_
->PostTask(from_here
, task
)) {
581 LOG(WARNING
) << "Failed to post a task to the origin message loop";
586 void Bus::PostDelayedTaskToDBusThread(
587 const tracked_objects::Location
& from_here
,
588 const base::Closure
& task
,
590 if (dbus_thread_message_loop_proxy_
.get()) {
591 if (!dbus_thread_message_loop_proxy_
->PostDelayedTask(
592 from_here
, task
, delay_ms
)) {
593 LOG(WARNING
) << "Failed to post a task to the D-Bus thread message loop";
596 DCHECK(origin_message_loop_proxy_
.get());
597 if (!origin_message_loop_proxy_
->PostDelayedTask(
598 from_here
, task
, delay_ms
)) {
599 LOG(WARNING
) << "Failed to post a task to the origin message loop";
604 bool Bus::HasDBusThread() {
605 return dbus_thread_message_loop_proxy_
.get() != NULL
;
608 void Bus::AssertOnOriginThread() {
609 DCHECK_EQ(origin_thread_id_
, base::PlatformThread::CurrentId());
612 void Bus::AssertOnDBusThread() {
613 base::ThreadRestrictions::AssertIOAllowed();
615 if (dbus_thread_message_loop_proxy_
.get()) {
616 DCHECK(dbus_thread_message_loop_proxy_
->BelongsToCurrentThread());
618 AssertOnOriginThread();
622 dbus_bool_t
Bus::OnAddWatch(DBusWatch
* raw_watch
) {
623 AssertOnDBusThread();
625 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
626 Watch
* watch
= new Watch(raw_watch
);
627 if (watch
->IsReadyToBeWatched()) {
628 watch
->StartWatching();
630 ++num_pending_watches_
;
634 void Bus::OnRemoveWatch(DBusWatch
* raw_watch
) {
635 AssertOnDBusThread();
637 Watch
* watch
= static_cast<Watch
*>(dbus_watch_get_data(raw_watch
));
639 --num_pending_watches_
;
642 void Bus::OnToggleWatch(DBusWatch
* raw_watch
) {
643 AssertOnDBusThread();
645 Watch
* watch
= static_cast<Watch
*>(dbus_watch_get_data(raw_watch
));
646 if (watch
->IsReadyToBeWatched()) {
647 watch
->StartWatching();
649 // It's safe to call this if StartWatching() wasn't called, per
650 // message_pump_libevent.h.
651 watch
->StopWatching();
655 dbus_bool_t
Bus::OnAddTimeout(DBusTimeout
* raw_timeout
) {
656 AssertOnDBusThread();
658 // timeout will be deleted when raw_timeout is removed in
659 // OnRemoveTimeoutThunk().
660 Timeout
* timeout
= new Timeout(raw_timeout
);
661 if (timeout
->IsReadyToBeMonitored()) {
662 timeout
->StartMonitoring(this);
664 ++num_pending_timeouts_
;
668 void Bus::OnRemoveTimeout(DBusTimeout
* raw_timeout
) {
669 AssertOnDBusThread();
671 Timeout
* timeout
= static_cast<Timeout
*>(dbus_timeout_get_data(raw_timeout
));
673 --num_pending_timeouts_
;
676 void Bus::OnToggleTimeout(DBusTimeout
* raw_timeout
) {
677 AssertOnDBusThread();
679 Timeout
* timeout
= static_cast<Timeout
*>(dbus_timeout_get_data(raw_timeout
));
680 if (timeout
->IsReadyToBeMonitored()) {
681 timeout
->StartMonitoring(this);
683 timeout
->StopMonitoring();
687 void Bus::OnDispatchStatusChanged(DBusConnection
* connection
,
688 DBusDispatchStatus status
) {
689 DCHECK_EQ(connection
, connection_
);
690 AssertOnDBusThread();
692 if (!dbus_connection_get_is_connected(connection
))
695 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
696 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
697 // prohibited by the D-Bus library. Hence, we post a task here instead.
698 // See comments for dbus_connection_set_dispatch_status_function().
699 PostTaskToDBusThread(FROM_HERE
,
700 base::Bind(&Bus::ProcessAllIncomingDataIfAny
,
704 dbus_bool_t
Bus::OnAddWatchThunk(DBusWatch
* raw_watch
, void* data
) {
705 Bus
* self
= static_cast<Bus
*>(data
);
706 return self
->OnAddWatch(raw_watch
);
709 void Bus::OnRemoveWatchThunk(DBusWatch
* raw_watch
, void* data
) {
710 Bus
* self
= static_cast<Bus
*>(data
);
711 return self
->OnRemoveWatch(raw_watch
);
714 void Bus::OnToggleWatchThunk(DBusWatch
* raw_watch
, void* data
) {
715 Bus
* self
= static_cast<Bus
*>(data
);
716 return self
->OnToggleWatch(raw_watch
);
719 dbus_bool_t
Bus::OnAddTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
720 Bus
* self
= static_cast<Bus
*>(data
);
721 return self
->OnAddTimeout(raw_timeout
);
724 void Bus::OnRemoveTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
725 Bus
* self
= static_cast<Bus
*>(data
);
726 return self
->OnRemoveTimeout(raw_timeout
);
729 void Bus::OnToggleTimeoutThunk(DBusTimeout
* raw_timeout
, void* data
) {
730 Bus
* self
= static_cast<Bus
*>(data
);
731 return self
->OnToggleTimeout(raw_timeout
);
734 void Bus::OnDispatchStatusChangedThunk(DBusConnection
* connection
,
735 DBusDispatchStatus status
,
737 Bus
* self
= static_cast<Bus
*>(data
);
738 return self
->OnDispatchStatusChanged(connection
, status
);