blob: e62058e0dc34d5c50f290d1cdae88deebd0c8bba [file] [log] [blame]
adamk@chromium.org35c0eef2012-02-11 06:45:23 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09004
5#include "dbus/bus.h"
6
avi0ad0ce02015-12-23 03:12:45 +09007#include <stddef.h>
8
fdorayc4aba522017-04-18 22:40:21 +09009#include <memory>
10
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090011#include "base/bind.h"
fdorayc4aba522017-04-18 22:40:21 +090012#include "base/files/file_descriptor_watcher_posix.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090013#include "base/logging.h"
Wezfc5d5952017-07-12 11:50:17 +090014#include "base/memory/weak_ptr.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090015#include "base/stl_util.h"
avi@chromium.org66c0f912013-06-21 04:40:12 +090016#include "base/strings/stringprintf.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090017#include "base/threading/thread.h"
18#include "base/threading/thread_restrictions.h"
fdorayd34de9b2016-06-21 21:43:12 +090019#include "base/threading/thread_task_runner_handle.h"
avi@chromium.org78a7e7b2013-06-29 00:20:02 +090020#include "base/time/time.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090021#include "dbus/exported_object.h"
thestig@chromium.orgc2482f12013-06-11 07:52:34 +090022#include "dbus/message.h"
keybuk@chromium.org09715012013-03-26 03:20:08 +090023#include "dbus/object_manager.h"
24#include "dbus/object_path.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090025#include "dbus/object_proxy.h"
26#include "dbus/scoped_dbus_error.h"
27
28namespace dbus {
29
30namespace {
31
nona@chromium.org5a44d2b2013-02-08 19:53:39 +090032const char kDisconnectedSignal[] = "Disconnected";
33const char kDisconnectedMatchRule[] =
34 "type='signal', path='/org/freedesktop/DBus/Local',"
35 "interface='org.freedesktop.DBus.Local', member='Disconnected'";
36
thestig@chromium.orgc2482f12013-06-11 07:52:34 +090037// The NameOwnerChanged member in org.freedesktop.DBus
38const char kNameOwnerChangedSignal[] = "NameOwnerChanged";
39
40// The match rule used to filter for changes to a given service name owner.
41const char kServiceNameOwnerChangeMatchRule[] =
42 "type='signal',interface='org.freedesktop.DBus',"
43 "member='NameOwnerChanged',path='/org/freedesktop/DBus',"
44 "sender='org.freedesktop.DBus',arg0='%s'";
45
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090046// The class is used for watching the file descriptor used for D-Bus
47// communication.
fdorayc4aba522017-04-18 22:40:21 +090048class Watch {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090049 public:
fdorayc4aba522017-04-18 22:40:21 +090050 explicit Watch(DBusWatch* watch) : raw_watch_(watch) {
Wezfc5d5952017-07-12 11:50:17 +090051 dbus_watch_set_data(raw_watch_, this, nullptr);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090052 }
53
Wezfc5d5952017-07-12 11:50:17 +090054 ~Watch() { dbus_watch_set_data(raw_watch_, nullptr, nullptr); }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090055
56 // Returns true if the underlying file descriptor is ready to be watched.
57 bool IsReadyToBeWatched() {
58 return dbus_watch_get_enabled(raw_watch_);
59 }
60
61 // Starts watching the underlying file descriptor.
62 void StartWatching() {
63 const int file_descriptor = dbus_watch_get_unix_fd(raw_watch_);
fdorayc4aba522017-04-18 22:40:21 +090064 const unsigned int flags = dbus_watch_get_flags(raw_watch_);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090065
fdorayc4aba522017-04-18 22:40:21 +090066 // Using base::Unretained(this) is safe because watches are automatically
67 // canceled when |read_watcher_| and |write_watcher_| are destroyed.
68 if (flags & DBUS_WATCH_READABLE) {
69 read_watcher_ = base::FileDescriptorWatcher::WatchReadable(
70 file_descriptor,
71 base::Bind(&Watch::OnFileReady, base::Unretained(this),
72 DBUS_WATCH_READABLE));
73 }
74 if (flags & DBUS_WATCH_WRITABLE) {
75 write_watcher_ = base::FileDescriptorWatcher::WatchWritable(
76 file_descriptor,
77 base::Bind(&Watch::OnFileReady, base::Unretained(this),
78 DBUS_WATCH_WRITABLE));
79 }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090080 }
81
82 // Stops watching the underlying file descriptor.
83 void StopWatching() {
fdorayc4aba522017-04-18 22:40:21 +090084 read_watcher_.reset();
85 write_watcher_.reset();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090086 }
87
88 private:
fdorayc4aba522017-04-18 22:40:21 +090089 void OnFileReady(unsigned int flags) {
90 CHECK(dbus_watch_handle(raw_watch_, flags)) << "Unable to allocate memory";
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090091 }
92
93 DBusWatch* raw_watch_;
fdorayc4aba522017-04-18 22:40:21 +090094 std::unique_ptr<base::FileDescriptorWatcher::Controller> read_watcher_;
95 std::unique_ptr<base::FileDescriptorWatcher::Controller> write_watcher_;
Wezfc5d5952017-07-12 11:50:17 +090096
97 DISALLOW_COPY_AND_ASSIGN(Watch);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090098};
99
100// The class is used for monitoring the timeout used for D-Bus method
101// calls.
Wezfc5d5952017-07-12 11:50:17 +0900102class Timeout {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900103 public:
thestig@chromium.org074b1db2013-02-20 10:36:53 +0900104 explicit Timeout(DBusTimeout* timeout)
Wezfc5d5952017-07-12 11:50:17 +0900105 : raw_timeout_(timeout), weak_ptr_factory_(this) {
106 // Associated |this| with the underlying DBusTimeout.
107 dbus_timeout_set_data(raw_timeout_, this, nullptr);
108 }
109
110 ~Timeout() {
111 // Remove the association between |this| and the |raw_timeout_|.
112 dbus_timeout_set_data(raw_timeout_, nullptr, nullptr);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900113 }
114
115 // Returns true if the timeout is ready to be monitored.
116 bool IsReadyToBeMonitored() {
117 return dbus_timeout_get_enabled(raw_timeout_);
118 }
119
120 // Starts monitoring the timeout.
thestig@chromium.orgf0b7eac2013-06-13 15:37:19 +0900121 void StartMonitoring(Bus* bus) {
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900122 bus->GetDBusTaskRunner()->PostDelayedTask(
123 FROM_HERE,
Wezfc5d5952017-07-12 11:50:17 +0900124 base::Bind(&Timeout::HandleTimeout, weak_ptr_factory_.GetWeakPtr()),
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900125 GetInterval());
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900126 }
127
128 // Stops monitoring the timeout.
Wezfc5d5952017-07-12 11:50:17 +0900129 void StopMonitoring() { weak_ptr_factory_.InvalidateWeakPtrs(); }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900130
tedvessenes@gmail.com8d7a8762012-03-11 10:12:20 +0900131 base::TimeDelta GetInterval() {
132 return base::TimeDelta::FromMilliseconds(
133 dbus_timeout_get_interval(raw_timeout_));
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900134 }
135
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900136 private:
Wezfc5d5952017-07-12 11:50:17 +0900137 // Calls DBus to handle the timeout.
138 void HandleTimeout() { CHECK(dbus_timeout_handle(raw_timeout_)); }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900139
140 DBusTimeout* raw_timeout_;
Wezfc5d5952017-07-12 11:50:17 +0900141
142 base::WeakPtrFactory<Timeout> weak_ptr_factory_;
143
144 DISALLOW_COPY_AND_ASSIGN(Timeout);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900145};
146
147} // namespace
148
149Bus::Options::Options()
150 : bus_type(SESSION),
mdm@chromium.org45f2c6a2011-09-07 05:03:24 +0900151 connection_type(PRIVATE) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900152}
153
Chris Watkins635e8902017-11-29 16:44:11 +0900154Bus::Options::~Options() = default;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900155
156Bus::Bus(const Options& options)
157 : bus_type_(options.bus_type),
158 connection_type_(options.connection_type),
thestig@chromium.org074b1db2013-02-20 10:36:53 +0900159 dbus_task_runner_(options.dbus_task_runner),
gabd7e26bc2016-06-02 21:26:55 +0900160 on_shutdown_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
161 base::WaitableEvent::InitialState::NOT_SIGNALED),
Wezfc5d5952017-07-12 11:50:17 +0900162 connection_(nullptr),
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900163 origin_thread_id_(base::PlatformThread::CurrentId()),
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900164 async_operations_set_up_(false),
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900165 shutdown_completed_(false),
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900166 num_pending_watches_(0),
nona@chromium.org9f638e02012-04-19 12:20:03 +0900167 num_pending_timeouts_(0),
hashimoto76b0cff2014-12-09 13:50:23 +0900168 address_(options.address) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900169 // This is safe to call multiple times.
170 dbus_threads_init_default();
satorux@chromium.orgcff09492011-09-09 07:28:42 +0900171 // The origin message loop is unnecessary if the client uses synchronous
172 // functions only.
fdorayd34de9b2016-06-21 21:43:12 +0900173 if (base::ThreadTaskRunnerHandle::IsSet())
174 origin_task_runner_ = base::ThreadTaskRunnerHandle::Get();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900175}
176
177Bus::~Bus() {
178 DCHECK(!connection_);
179 DCHECK(owned_service_names_.empty());
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900180 DCHECK(match_rules_added_.empty());
181 DCHECK(filter_functions_added_.empty());
182 DCHECK(registered_object_paths_.empty());
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900183 DCHECK_EQ(0, num_pending_watches_);
jamescook@chromium.org255cd352011-11-24 16:00:43 +0900184 // TODO(satorux): This check fails occasionally in browser_tests for tests
185 // that run very quickly. Perhaps something does not have time to clean up.
186 // Despite the check failing, the tests seem to run fine. crosbug.com/23416
187 // DCHECK_EQ(0, num_pending_timeouts_);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900188}
189
190ObjectProxy* Bus::GetObjectProxy(const std::string& service_name,
keybuk@google.combf4649a2012-02-15 06:29:06 +0900191 const ObjectPath& object_path) {
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900192 return GetObjectProxyWithOptions(service_name, object_path,
193 ObjectProxy::DEFAULT_OPTIONS);
194}
195
196ObjectProxy* Bus::GetObjectProxyWithOptions(const std::string& service_name,
thestig@chromium.orgf0b7eac2013-06-13 15:37:19 +0900197 const ObjectPath& object_path,
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900198 int options) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900199 AssertOnOriginThread();
200
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900201 // Check if we already have the requested object proxy.
keybuk@google.combf4649a2012-02-15 06:29:06 +0900202 const ObjectProxyTable::key_type key(service_name + object_path.value(),
203 options);
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900204 ObjectProxyTable::iterator iter = object_proxy_table_.find(key);
205 if (iter != object_proxy_table_.end()) {
rsleevi@chromium.orgc5cb8592013-06-03 08:38:09 +0900206 return iter->second.get();
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900207 }
208
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900209 scoped_refptr<ObjectProxy> object_proxy =
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900210 new ObjectProxy(this, service_name, object_path, options);
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900211 object_proxy_table_[key] = object_proxy;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900212
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900213 return object_proxy.get();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900214}
215
deymo@chromium.org6d168a72013-01-30 05:29:12 +0900216bool Bus::RemoveObjectProxy(const std::string& service_name,
217 const ObjectPath& object_path,
218 const base::Closure& callback) {
219 return RemoveObjectProxyWithOptions(service_name, object_path,
220 ObjectProxy::DEFAULT_OPTIONS,
221 callback);
222}
223
224bool Bus::RemoveObjectProxyWithOptions(const std::string& service_name,
thestig@chromium.orgf0b7eac2013-06-13 15:37:19 +0900225 const ObjectPath& object_path,
deymo@chromium.org6d168a72013-01-30 05:29:12 +0900226 int options,
227 const base::Closure& callback) {
228 AssertOnOriginThread();
229
230 // Check if we 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()) {
stevenjb@chromium.orgb53cfb32013-10-08 07:56:57 +0900235 scoped_refptr<ObjectProxy> object_proxy = iter->second;
236 object_proxy_table_.erase(iter);
armansitof4364642014-09-06 02:49:34 +0900237 // Object is present. Remove it now and Detach on the DBus thread.
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900238 GetDBusTaskRunner()->PostTask(
239 FROM_HERE,
240 base::Bind(&Bus::RemoveObjectProxyInternal,
stevenjb@chromium.orgb53cfb32013-10-08 07:56:57 +0900241 this, object_proxy, callback));
deymo@chromium.org6d168a72013-01-30 05:29:12 +0900242 return true;
243 }
244 return false;
245}
246
thestig@chromium.orgf0b7eac2013-06-13 15:37:19 +0900247void Bus::RemoveObjectProxyInternal(scoped_refptr<ObjectProxy> object_proxy,
248 const base::Closure& callback) {
deymo@chromium.org6d168a72013-01-30 05:29:12 +0900249 AssertOnDBusThread();
250
Wezfc5d5952017-07-12 11:50:17 +0900251 object_proxy->Detach();
deymo@chromium.org6d168a72013-01-30 05:29:12 +0900252
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900253 GetOriginTaskRunner()->PostTask(FROM_HERE, callback);
deymo@chromium.org6d168a72013-01-30 05:29:12 +0900254}
255
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900256ExportedObject* Bus::GetExportedObject(const ObjectPath& object_path) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900257 AssertOnOriginThread();
258
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900259 // Check if we already have the requested exported object.
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900260 ExportedObjectTable::iterator iter = exported_object_table_.find(object_path);
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900261 if (iter != exported_object_table_.end()) {
rsleevi@chromium.orgc5cb8592013-06-03 08:38:09 +0900262 return iter->second.get();
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900263 }
264
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900265 scoped_refptr<ExportedObject> exported_object =
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900266 new ExportedObject(this, object_path);
267 exported_object_table_[object_path] = exported_object;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900268
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900269 return exported_object.get();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900270}
271
keybuk@chromium.orgd2ca8f32012-03-14 10:18:35 +0900272void Bus::UnregisterExportedObject(const ObjectPath& object_path) {
273 AssertOnOriginThread();
274
275 // Remove the registered object from the table first, to allow a new
276 // GetExportedObject() call to return a new object, rather than this one.
277 ExportedObjectTable::iterator iter = exported_object_table_.find(object_path);
278 if (iter == exported_object_table_.end())
279 return;
280
281 scoped_refptr<ExportedObject> exported_object = iter->second;
282 exported_object_table_.erase(iter);
283
284 // Post the task to perform the final unregistration to the D-Bus thread.
285 // Since the registration also happens on the D-Bus thread in
thestig@chromium.org074b1db2013-02-20 10:36:53 +0900286 // TryRegisterObjectPath(), and the task runner we post to is a
287 // SequencedTaskRunner, there is a guarantee that this will happen before any
288 // future registration call.
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900289 GetDBusTaskRunner()->PostTask(
290 FROM_HERE,
291 base::Bind(&Bus::UnregisterExportedObjectInternal,
292 this, exported_object));
keybuk@chromium.orgd2ca8f32012-03-14 10:18:35 +0900293}
294
295void Bus::UnregisterExportedObjectInternal(
thestig@chromium.orgf0b7eac2013-06-13 15:37:19 +0900296 scoped_refptr<ExportedObject> exported_object) {
keybuk@chromium.orgd2ca8f32012-03-14 10:18:35 +0900297 AssertOnDBusThread();
298
299 exported_object->Unregister();
300}
301
keybuk@chromium.org09715012013-03-26 03:20:08 +0900302ObjectManager* Bus::GetObjectManager(const std::string& service_name,
303 const ObjectPath& object_path) {
304 AssertOnOriginThread();
305
306 // Check if we already have the requested object manager.
307 const ObjectManagerTable::key_type key(service_name + object_path.value());
308 ObjectManagerTable::iterator iter = object_manager_table_.find(key);
309 if (iter != object_manager_table_.end()) {
rsleevi@chromium.orgc5cb8592013-06-03 08:38:09 +0900310 return iter->second.get();
keybuk@chromium.org09715012013-03-26 03:20:08 +0900311 }
312
313 scoped_refptr<ObjectManager> object_manager =
314 new ObjectManager(this, service_name, object_path);
315 object_manager_table_[key] = object_manager;
316
317 return object_manager.get();
318}
319
armansitof4364642014-09-06 02:49:34 +0900320bool Bus::RemoveObjectManager(const std::string& service_name,
321 const ObjectPath& object_path,
322 const base::Closure& callback) {
keybuk@chromium.org09715012013-03-26 03:20:08 +0900323 AssertOnOriginThread();
armansitof4364642014-09-06 02:49:34 +0900324 DCHECK(!callback.is_null());
keybuk@chromium.org09715012013-03-26 03:20:08 +0900325
326 const ObjectManagerTable::key_type key(service_name + object_path.value());
327 ObjectManagerTable::iterator iter = object_manager_table_.find(key);
328 if (iter == object_manager_table_.end())
armansitof4364642014-09-06 02:49:34 +0900329 return false;
keybuk@chromium.org09715012013-03-26 03:20:08 +0900330
armansitof4364642014-09-06 02:49:34 +0900331 // ObjectManager is present. Remove it now and CleanUp on the DBus thread.
keybuk@chromium.org09715012013-03-26 03:20:08 +0900332 scoped_refptr<ObjectManager> object_manager = iter->second;
333 object_manager_table_.erase(iter);
armansitof4364642014-09-06 02:49:34 +0900334
335 GetDBusTaskRunner()->PostTask(
336 FROM_HERE,
337 base::Bind(&Bus::RemoveObjectManagerInternal,
338 this, object_manager, callback));
339
340 return true;
341}
342
343void Bus::RemoveObjectManagerInternal(
344 scoped_refptr<dbus::ObjectManager> object_manager,
345 const base::Closure& callback) {
346 AssertOnDBusThread();
347 DCHECK(object_manager.get());
348
349 object_manager->CleanUp();
350
351 // The ObjectManager has to be deleted on the origin thread since it was
352 // created there.
353 GetOriginTaskRunner()->PostTask(
354 FROM_HERE,
355 base::Bind(&Bus::RemoveObjectManagerInternalHelper,
356 this, object_manager, callback));
357}
358
359void Bus::RemoveObjectManagerInternalHelper(
360 scoped_refptr<dbus::ObjectManager> object_manager,
361 const base::Closure& callback) {
362 AssertOnOriginThread();
Wezfc5d5952017-07-12 11:50:17 +0900363 DCHECK(object_manager);
armansitof4364642014-09-06 02:49:34 +0900364
365 // Release the object manager and run the callback.
Wezfc5d5952017-07-12 11:50:17 +0900366 object_manager = nullptr;
armansitof4364642014-09-06 02:49:34 +0900367 callback.Run();
keybuk@chromium.org09715012013-03-26 03:20:08 +0900368}
369
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900370bool Bus::Connect() {
371 // dbus_bus_get_private() and dbus_bus_get() are blocking calls.
372 AssertOnDBusThread();
373
374 // Check if it's already initialized.
375 if (connection_)
376 return true;
377
378 ScopedDBusError error;
nona@chromium.org9f638e02012-04-19 12:20:03 +0900379 if (bus_type_ == CUSTOM_ADDRESS) {
380 if (connection_type_ == PRIVATE) {
381 connection_ = dbus_connection_open_private(address_.c_str(), error.get());
382 } else {
383 connection_ = dbus_connection_open(address_.c_str(), error.get());
384 }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900385 } else {
nona@chromium.org9f638e02012-04-19 12:20:03 +0900386 const DBusBusType dbus_bus_type = static_cast<DBusBusType>(bus_type_);
387 if (connection_type_ == PRIVATE) {
388 connection_ = dbus_bus_get_private(dbus_bus_type, error.get());
389 } else {
390 connection_ = dbus_bus_get(dbus_bus_type, error.get());
391 }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900392 }
393 if (!connection_) {
394 LOG(ERROR) << "Failed to connect to the bus: "
tfarina@chromium.org56cc3fc2012-10-30 01:43:26 +0900395 << (error.is_set() ? error.message() : "");
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900396 return false;
397 }
nona@chromium.orgeeaf2412012-11-02 17:04:14 +0900398
399 if (bus_type_ == CUSTOM_ADDRESS) {
400 // We should call dbus_bus_register here, otherwise unique name can not be
401 // acquired. According to dbus specification, it is responsible to call
402 // org.freedesktop.DBus.Hello method at the beging of bus connection to
403 // acquire unique name. In the case of dbus_bus_get, dbus_bus_register is
404 // called internally.
405 if (!dbus_bus_register(connection_, error.get())) {
406 LOG(ERROR) << "Failed to register the bus component: "
407 << (error.is_set() ? error.message() : "");
408 return false;
409 }
410 }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900411 // We shouldn't exit on the disconnected signal.
412 dbus_connection_set_exit_on_disconnect(connection_, false);
413
nona@chromium.org5a44d2b2013-02-08 19:53:39 +0900414 // Watch Disconnected signal.
415 AddFilterFunction(Bus::OnConnectionDisconnectedFilter, this);
416 AddMatch(kDisconnectedMatchRule, error.get());
417
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900418 return true;
419}
420
nona@chromium.org1de76fd2013-02-16 01:44:40 +0900421void Bus::ClosePrivateConnection() {
422 // dbus_connection_close is blocking call.
423 AssertOnDBusThread();
424 DCHECK_EQ(PRIVATE, connection_type_)
425 << "non-private connection should not be closed";
426 dbus_connection_close(connection_);
427}
428
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900429void Bus::ShutdownAndBlock() {
430 AssertOnDBusThread();
431
nona@chromium.org5a44d2b2013-02-08 19:53:39 +0900432 if (shutdown_completed_)
433 return; // Already shutdowned, just return.
434
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900435 // Unregister the exported objects.
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900436 for (ExportedObjectTable::iterator iter = exported_object_table_.begin();
437 iter != exported_object_table_.end(); ++iter) {
438 iter->second->Unregister();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900439 }
440
441 // Release all service names.
442 for (std::set<std::string>::iterator iter = owned_service_names_.begin();
443 iter != owned_service_names_.end();) {
444 // This is a bit tricky but we should increment the iter here as
445 // ReleaseOwnership() may remove |service_name| from the set.
446 const std::string& service_name = *iter++;
447 ReleaseOwnership(service_name);
448 }
449 if (!owned_service_names_.empty()) {
450 LOG(ERROR) << "Failed to release all service names. # of services left: "
451 << owned_service_names_.size();
452 }
453
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900454 // Detach from the remote objects.
satorux@chromium.orgdccbb7b2011-08-24 04:25:20 +0900455 for (ObjectProxyTable::iterator iter = object_proxy_table_.begin();
456 iter != object_proxy_table_.end(); ++iter) {
457 iter->second->Detach();
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900458 }
459
armansitof4364642014-09-06 02:49:34 +0900460 // Clean up the object managers.
461 for (ObjectManagerTable::iterator iter = object_manager_table_.begin();
462 iter != object_manager_table_.end(); ++iter) {
463 iter->second->CleanUp();
464 }
465
satorux@chromium.orgf06eb892011-10-13 09:45:26 +0900466 // Release object proxies and exported objects here. We should do this
467 // here rather than in the destructor to avoid memory leaks due to
468 // cyclic references.
469 object_proxy_table_.clear();
470 exported_object_table_.clear();
471
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900472 // Private connection should be closed.
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900473 if (connection_) {
nona@chromium.org5a44d2b2013-02-08 19:53:39 +0900474 // Remove Disconnected watcher.
475 ScopedDBusError error;
476 RemoveFilterFunction(Bus::OnConnectionDisconnectedFilter, this);
477 RemoveMatch(kDisconnectedMatchRule, error.get());
478
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900479 if (connection_type_ == PRIVATE)
nona@chromium.org1de76fd2013-02-16 01:44:40 +0900480 ClosePrivateConnection();
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900481 // dbus_connection_close() won't unref.
482 dbus_connection_unref(connection_);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900483 }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900484
Wezfc5d5952017-07-12 11:50:17 +0900485 connection_ = nullptr;
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900486 shutdown_completed_ = true;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900487}
488
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900489void Bus::ShutdownOnDBusThreadAndBlock() {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900490 AssertOnOriginThread();
Wezfc5d5952017-07-12 11:50:17 +0900491 DCHECK(dbus_task_runner_);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900492
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900493 GetDBusTaskRunner()->PostTask(
494 FROM_HERE,
495 base::Bind(&Bus::ShutdownOnDBusThreadAndBlockInternal, this));
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900496
jam@chromium.org17554342012-04-27 04:08:58 +0900497 // http://crbug.com/125222
498 base::ThreadRestrictions::ScopedAllowWait allow_wait;
499
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900500 // Wait until the shutdown is complete on the D-Bus thread.
501 // The shutdown should not hang, but set timeout just in case.
502 const int kTimeoutSecs = 3;
503 const base::TimeDelta timeout(base::TimeDelta::FromSeconds(kTimeoutSecs));
504 const bool signaled = on_shutdown_.TimedWait(timeout);
505 LOG_IF(ERROR, !signaled) << "Failed to shutdown the bus";
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900506}
507
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900508void Bus::RequestOwnership(const std::string& service_name,
cmasone@chromium.org989857e2013-07-31 15:34:59 +0900509 ServiceOwnershipOptions options,
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900510 OnOwnershipCallback on_ownership_callback) {
511 AssertOnOriginThread();
512
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900513 GetDBusTaskRunner()->PostTask(
514 FROM_HERE,
515 base::Bind(&Bus::RequestOwnershipInternal,
516 this, service_name, options, on_ownership_callback));
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900517}
518
519void Bus::RequestOwnershipInternal(const std::string& service_name,
cmasone@chromium.org989857e2013-07-31 15:34:59 +0900520 ServiceOwnershipOptions options,
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900521 OnOwnershipCallback on_ownership_callback) {
522 AssertOnDBusThread();
523
524 bool success = Connect();
525 if (success)
cmasone@chromium.org989857e2013-07-31 15:34:59 +0900526 success = RequestOwnershipAndBlock(service_name, options);
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900527
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900528 GetOriginTaskRunner()->PostTask(FROM_HERE,
529 base::Bind(on_ownership_callback,
530 service_name,
531 success));
keybuk@chromium.org9cb73f02012-03-10 10:12:52 +0900532}
533
cmasone@chromium.org989857e2013-07-31 15:34:59 +0900534bool Bus::RequestOwnershipAndBlock(const std::string& service_name,
535 ServiceOwnershipOptions options) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900536 DCHECK(connection_);
537 // dbus_bus_request_name() is a blocking call.
538 AssertOnDBusThread();
539
540 // Check if we already own the service name.
541 if (owned_service_names_.find(service_name) != owned_service_names_.end()) {
542 return true;
543 }
544
545 ScopedDBusError error;
546 const int result = dbus_bus_request_name(connection_,
547 service_name.c_str(),
cmasone@chromium.org989857e2013-07-31 15:34:59 +0900548 options,
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900549 error.get());
550 if (result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
satorux@chromium.orgc6ac7572011-09-01 03:02:43 +0900551 LOG(ERROR) << "Failed to get the ownership of " << service_name << ": "
tfarina@chromium.org56cc3fc2012-10-30 01:43:26 +0900552 << (error.is_set() ? error.message() : "");
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900553 return false;
554 }
555 owned_service_names_.insert(service_name);
556 return true;
557}
558
559bool Bus::ReleaseOwnership(const std::string& service_name) {
560 DCHECK(connection_);
561 // dbus_bus_request_name() is a blocking call.
562 AssertOnDBusThread();
563
564 // Check if we already own the service name.
565 std::set<std::string>::iterator found =
566 owned_service_names_.find(service_name);
567 if (found == owned_service_names_.end()) {
568 LOG(ERROR) << service_name << " is not owned by the bus";
569 return false;
570 }
571
572 ScopedDBusError error;
573 const int result = dbus_bus_release_name(connection_, service_name.c_str(),
574 error.get());
575 if (result == DBUS_RELEASE_NAME_REPLY_RELEASED) {
576 owned_service_names_.erase(found);
577 return true;
578 } else {
satorux@chromium.orgc6ac7572011-09-01 03:02:43 +0900579 LOG(ERROR) << "Failed to release the ownership of " << service_name << ": "
cmasone@chromium.org989857e2013-07-31 15:34:59 +0900580 << (error.is_set() ? error.message() : "")
581 << ", result code: " << result;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900582 return false;
583 }
584}
585
586bool Bus::SetUpAsyncOperations() {
587 DCHECK(connection_);
588 AssertOnDBusThread();
589
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900590 if (async_operations_set_up_)
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900591 return true;
592
593 // Process all the incoming data if any, so that OnDispatchStatus() will
594 // be called when the incoming data is ready.
595 ProcessAllIncomingDataIfAny();
596
Wezfc5d5952017-07-12 11:50:17 +0900597 bool success = dbus_connection_set_watch_functions(
598 connection_, &Bus::OnAddWatchThunk, &Bus::OnRemoveWatchThunk,
599 &Bus::OnToggleWatchThunk, this, nullptr);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900600 CHECK(success) << "Unable to allocate memory";
601
Wezfc5d5952017-07-12 11:50:17 +0900602 success = dbus_connection_set_timeout_functions(
603 connection_, &Bus::OnAddTimeoutThunk, &Bus::OnRemoveTimeoutThunk,
604 &Bus::OnToggleTimeoutThunk, this, nullptr);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900605 CHECK(success) << "Unable to allocate memory";
606
607 dbus_connection_set_dispatch_status_function(
Wezfc5d5952017-07-12 11:50:17 +0900608 connection_, &Bus::OnDispatchStatusChangedThunk, this, nullptr);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900609
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900610 async_operations_set_up_ = true;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900611
612 return true;
613}
614
615DBusMessage* Bus::SendWithReplyAndBlock(DBusMessage* request,
616 int timeout_ms,
617 DBusError* error) {
618 DCHECK(connection_);
619 AssertOnDBusThread();
620
621 return dbus_connection_send_with_reply_and_block(
622 connection_, request, timeout_ms, error);
623}
624
625void Bus::SendWithReply(DBusMessage* request,
626 DBusPendingCall** pending_call,
627 int timeout_ms) {
628 DCHECK(connection_);
629 AssertOnDBusThread();
630
631 const bool success = dbus_connection_send_with_reply(
632 connection_, request, pending_call, timeout_ms);
633 CHECK(success) << "Unable to allocate memory";
634}
635
avi0ad0ce02015-12-23 03:12:45 +0900636void Bus::Send(DBusMessage* request, uint32_t* serial) {
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900637 DCHECK(connection_);
638 AssertOnDBusThread();
639
640 const bool success = dbus_connection_send(connection_, request, serial);
641 CHECK(success) << "Unable to allocate memory";
642}
643
hashimoto46be6e92014-12-04 16:41:55 +0900644void Bus::AddFilterFunction(DBusHandleMessageFunction filter_function,
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900645 void* user_data) {
646 DCHECK(connection_);
647 AssertOnDBusThread();
648
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900649 std::pair<DBusHandleMessageFunction, void*> filter_data_pair =
650 std::make_pair(filter_function, user_data);
651 if (filter_functions_added_.find(filter_data_pair) !=
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900652 filter_functions_added_.end()) {
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900653 VLOG(1) << "Filter function already exists: " << filter_function
654 << " with associated data: " << user_data;
hashimoto46be6e92014-12-04 16:41:55 +0900655 return;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900656 }
657
Wezfc5d5952017-07-12 11:50:17 +0900658 const bool success = dbus_connection_add_filter(connection_, filter_function,
659 user_data, nullptr);
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900660 CHECK(success) << "Unable to allocate memory";
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900661 filter_functions_added_.insert(filter_data_pair);
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900662}
663
hashimoto46be6e92014-12-04 16:41:55 +0900664void Bus::RemoveFilterFunction(DBusHandleMessageFunction filter_function,
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900665 void* user_data) {
666 DCHECK(connection_);
667 AssertOnDBusThread();
668
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900669 std::pair<DBusHandleMessageFunction, void*> filter_data_pair =
670 std::make_pair(filter_function, user_data);
671 if (filter_functions_added_.find(filter_data_pair) ==
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900672 filter_functions_added_.end()) {
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900673 VLOG(1) << "Requested to remove an unknown filter function: "
674 << filter_function
675 << " with associated data: " << user_data;
hashimoto46be6e92014-12-04 16:41:55 +0900676 return;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900677 }
678
679 dbus_connection_remove_filter(connection_, filter_function, user_data);
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900680 filter_functions_added_.erase(filter_data_pair);
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900681}
682
683void Bus::AddMatch(const std::string& match_rule, DBusError* error) {
684 DCHECK(connection_);
685 AssertOnDBusThread();
686
deymo@chromium.org7894ebf2013-01-31 15:08:02 +0900687 std::map<std::string, int>::iterator iter =
688 match_rules_added_.find(match_rule);
689 if (iter != match_rules_added_.end()) {
690 // The already existing rule's counter is incremented.
691 iter->second++;
692
satorux@chromium.orga3a97932011-10-13 08:47:13 +0900693 VLOG(1) << "Match rule already exists: " << match_rule;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900694 return;
695 }
696
697 dbus_bus_add_match(connection_, match_rule.c_str(), error);
deymo@chromium.org7894ebf2013-01-31 15:08:02 +0900698 match_rules_added_[match_rule] = 1;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900699}
700
deymo@chromium.org7894ebf2013-01-31 15:08:02 +0900701bool Bus::RemoveMatch(const std::string& match_rule, DBusError* error) {
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900702 DCHECK(connection_);
703 AssertOnDBusThread();
704
deymo@chromium.org7894ebf2013-01-31 15:08:02 +0900705 std::map<std::string, int>::iterator iter =
706 match_rules_added_.find(match_rule);
707 if (iter == match_rules_added_.end()) {
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900708 LOG(ERROR) << "Requested to remove an unknown match rule: " << match_rule;
deymo@chromium.org7894ebf2013-01-31 15:08:02 +0900709 return false;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900710 }
711
deymo@chromium.org7894ebf2013-01-31 15:08:02 +0900712 // The rule's counter is decremented and the rule is deleted when reachs 0.
713 iter->second--;
714 if (iter->second == 0) {
715 dbus_bus_remove_match(connection_, match_rule.c_str(), error);
716 match_rules_added_.erase(match_rule);
717 }
718 return true;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900719}
720
keybuk@google.combf4649a2012-02-15 06:29:06 +0900721bool Bus::TryRegisterObjectPath(const ObjectPath& object_path,
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900722 const DBusObjectPathVTable* vtable,
723 void* user_data,
724 DBusError* error) {
725 DCHECK(connection_);
726 AssertOnDBusThread();
727
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900728 if (registered_object_paths_.find(object_path) !=
729 registered_object_paths_.end()) {
keybuk@google.combf4649a2012-02-15 06:29:06 +0900730 LOG(ERROR) << "Object path already registered: " << object_path.value();
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900731 return false;
732 }
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900733
734 const bool success = dbus_connection_try_register_object_path(
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900735 connection_,
keybuk@google.combf4649a2012-02-15 06:29:06 +0900736 object_path.value().c_str(),
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900737 vtable,
738 user_data,
739 error);
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900740 if (success)
741 registered_object_paths_.insert(object_path);
742 return success;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900743}
744
keybuk@google.combf4649a2012-02-15 06:29:06 +0900745void Bus::UnregisterObjectPath(const ObjectPath& object_path) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900746 DCHECK(connection_);
747 AssertOnDBusThread();
748
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900749 if (registered_object_paths_.find(object_path) ==
750 registered_object_paths_.end()) {
751 LOG(ERROR) << "Requested to unregister an unknown object path: "
keybuk@google.combf4649a2012-02-15 06:29:06 +0900752 << object_path.value();
satorux@chromium.org326a6f82011-08-27 16:26:34 +0900753 return;
754 }
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900755
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900756 const bool success = dbus_connection_unregister_object_path(
757 connection_,
keybuk@google.combf4649a2012-02-15 06:29:06 +0900758 object_path.value().c_str());
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900759 CHECK(success) << "Unable to allocate memory";
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900760 registered_object_paths_.erase(object_path);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900761}
762
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900763void Bus::ShutdownOnDBusThreadAndBlockInternal() {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900764 AssertOnDBusThread();
765
766 ShutdownAndBlock();
satorux@chromium.orgd336d452011-09-02 15:56:23 +0900767 on_shutdown_.Signal();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900768}
769
770void Bus::ProcessAllIncomingDataIfAny() {
771 AssertOnDBusThread();
772
773 // As mentioned at the class comment in .h file, connection_ can be NULL.
nona@chromium.org5a44d2b2013-02-08 19:53:39 +0900774 if (!connection_)
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900775 return;
776
nona@chromium.org5a44d2b2013-02-08 19:53:39 +0900777 // It is safe and necessary to call dbus_connection_get_dispatch_status even
hashimoto76b0cff2014-12-09 13:50:23 +0900778 // if the connection is lost.
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900779 if (dbus_connection_get_dispatch_status(connection_) ==
780 DBUS_DISPATCH_DATA_REMAINS) {
781 while (dbus_connection_dispatch(connection_) ==
thestig@chromium.orgf0b7eac2013-06-13 15:37:19 +0900782 DBUS_DISPATCH_DATA_REMAINS) {
783 }
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900784 }
785}
786
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900787base::TaskRunner* Bus::GetDBusTaskRunner() {
Wezfc5d5952017-07-12 11:50:17 +0900788 if (dbus_task_runner_)
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900789 return dbus_task_runner_.get();
790 else
791 return GetOriginTaskRunner();
haruki@chromium.org4a1f9562013-05-08 20:57:14 +0900792}
793
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900794base::TaskRunner* Bus::GetOriginTaskRunner() {
Wezfc5d5952017-07-12 11:50:17 +0900795 DCHECK(origin_task_runner_);
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900796 return origin_task_runner_.get();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900797}
798
799bool Bus::HasDBusThread() {
Wezfc5d5952017-07-12 11:50:17 +0900800 return dbus_task_runner_ != nullptr;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900801}
802
803void Bus::AssertOnOriginThread() {
804 DCHECK_EQ(origin_thread_id_, base::PlatformThread::CurrentId());
805}
806
807void Bus::AssertOnDBusThread() {
Francois Dorayed9daa62017-10-20 22:50:37 +0900808 base::AssertBlockingAllowed();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900809
Wezfc5d5952017-07-12 11:50:17 +0900810 if (dbus_task_runner_) {
peary20791de92017-05-19 09:38:52 +0900811 DCHECK(dbus_task_runner_->RunsTasksInCurrentSequence());
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900812 } else {
813 AssertOnOriginThread();
814 }
815}
816
thestig@chromium.org56057f22013-05-05 00:48:37 +0900817std::string Bus::GetServiceOwnerAndBlock(const std::string& service_name,
818 GetServiceOwnerOption options) {
819 AssertOnDBusThread();
820
821 MethodCall get_name_owner_call("org.freedesktop.DBus", "GetNameOwner");
822 MessageWriter writer(&get_name_owner_call);
823 writer.AppendString(service_name);
824 VLOG(1) << "Method call: " << get_name_owner_call.ToString();
825
826 const ObjectPath obj_path("/org/freedesktop/DBus");
827 if (!get_name_owner_call.SetDestination("org.freedesktop.DBus") ||
828 !get_name_owner_call.SetPath(obj_path)) {
829 if (options == REPORT_ERRORS)
830 LOG(ERROR) << "Failed to get name owner.";
831 return "";
832 }
833
834 ScopedDBusError error;
835 DBusMessage* response_message =
836 SendWithReplyAndBlock(get_name_owner_call.raw_message(),
837 ObjectProxy::TIMEOUT_USE_DEFAULT,
838 error.get());
839 if (!response_message) {
840 if (options == REPORT_ERRORS) {
841 LOG(ERROR) << "Failed to get name owner. Got " << error.name() << ": "
842 << error.message();
843 }
844 return "";
845 }
846
dcheng30c5a172016-04-09 07:55:04 +0900847 std::unique_ptr<Response> response(
848 Response::FromRawMessage(response_message));
thestig@chromium.org56057f22013-05-05 00:48:37 +0900849 MessageReader reader(response.get());
850
851 std::string service_owner;
852 if (!reader.PopString(&service_owner))
853 service_owner.clear();
854 return service_owner;
855}
856
857void Bus::GetServiceOwner(const std::string& service_name,
858 const GetServiceOwnerCallback& callback) {
859 AssertOnOriginThread();
860
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900861 GetDBusTaskRunner()->PostTask(
thestig@chromium.org56057f22013-05-05 00:48:37 +0900862 FROM_HERE,
863 base::Bind(&Bus::GetServiceOwnerInternal, this, service_name, callback));
864}
865
866void Bus::GetServiceOwnerInternal(const std::string& service_name,
867 const GetServiceOwnerCallback& callback) {
868 AssertOnDBusThread();
869
870 std::string service_owner;
871 if (Connect())
thestig@chromium.org493b0ea2013-05-09 05:47:18 +0900872 service_owner = GetServiceOwnerAndBlock(service_name, SUPPRESS_ERRORS);
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900873 GetOriginTaskRunner()->PostTask(FROM_HERE,
874 base::Bind(callback, service_owner));
thestig@chromium.org56057f22013-05-05 00:48:37 +0900875}
876
thestig@chromium.orgc2482f12013-06-11 07:52:34 +0900877void Bus::ListenForServiceOwnerChange(
878 const std::string& service_name,
879 const GetServiceOwnerCallback& callback) {
880 AssertOnOriginThread();
881 DCHECK(!service_name.empty());
882 DCHECK(!callback.is_null());
883
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900884 GetDBusTaskRunner()->PostTask(
885 FROM_HERE,
886 base::Bind(&Bus::ListenForServiceOwnerChangeInternal,
887 this, service_name, callback));
thestig@chromium.orgc2482f12013-06-11 07:52:34 +0900888}
889
890void Bus::ListenForServiceOwnerChangeInternal(
891 const std::string& service_name,
892 const GetServiceOwnerCallback& callback) {
893 AssertOnDBusThread();
894 DCHECK(!service_name.empty());
895 DCHECK(!callback.is_null());
896
897 if (!Connect() || !SetUpAsyncOperations())
898 return;
899
hashimoto46be6e92014-12-04 16:41:55 +0900900 if (service_owner_changed_listener_map_.empty())
901 AddFilterFunction(Bus::OnServiceOwnerChangedFilter, this);
thestig@chromium.orgc2482f12013-06-11 07:52:34 +0900902
903 ServiceOwnerChangedListenerMap::iterator it =
904 service_owner_changed_listener_map_.find(service_name);
905 if (it == service_owner_changed_listener_map_.end()) {
906 // Add a match rule for the new service name.
907 const std::string name_owner_changed_match_rule =
908 base::StringPrintf(kServiceNameOwnerChangeMatchRule,
909 service_name.c_str());
910 ScopedDBusError error;
911 AddMatch(name_owner_changed_match_rule, error.get());
912 if (error.is_set()) {
913 LOG(ERROR) << "Failed to add match rule for " << service_name
914 << ". Got " << error.name() << ": " << error.message();
915 return;
916 }
917
918 service_owner_changed_listener_map_[service_name].push_back(callback);
919 return;
920 }
921
922 // Check if the callback has already been added.
923 std::vector<GetServiceOwnerCallback>& callbacks = it->second;
924 for (size_t i = 0; i < callbacks.size(); ++i) {
925 if (callbacks[i].Equals(callback))
926 return;
927 }
928 callbacks.push_back(callback);
929}
930
931void Bus::UnlistenForServiceOwnerChange(
932 const std::string& service_name,
933 const GetServiceOwnerCallback& callback) {
934 AssertOnOriginThread();
935 DCHECK(!service_name.empty());
936 DCHECK(!callback.is_null());
937
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900938 GetDBusTaskRunner()->PostTask(
939 FROM_HERE,
940 base::Bind(&Bus::UnlistenForServiceOwnerChangeInternal,
941 this, service_name, callback));
thestig@chromium.orgc2482f12013-06-11 07:52:34 +0900942}
943
944void Bus::UnlistenForServiceOwnerChangeInternal(
945 const std::string& service_name,
946 const GetServiceOwnerCallback& callback) {
947 AssertOnDBusThread();
948 DCHECK(!service_name.empty());
949 DCHECK(!callback.is_null());
950
951 ServiceOwnerChangedListenerMap::iterator it =
952 service_owner_changed_listener_map_.find(service_name);
953 if (it == service_owner_changed_listener_map_.end())
954 return;
955
956 std::vector<GetServiceOwnerCallback>& callbacks = it->second;
957 for (size_t i = 0; i < callbacks.size(); ++i) {
958 if (callbacks[i].Equals(callback)) {
959 callbacks.erase(callbacks.begin() + i);
960 break; // There can be only one.
961 }
962 }
963 if (!callbacks.empty())
964 return;
965
966 // Last callback for |service_name| has been removed, remove match rule.
967 const std::string name_owner_changed_match_rule =
968 base::StringPrintf(kServiceNameOwnerChangeMatchRule,
969 service_name.c_str());
970 ScopedDBusError error;
971 RemoveMatch(name_owner_changed_match_rule, error.get());
972 // And remove |service_owner_changed_listener_map_| entry.
973 service_owner_changed_listener_map_.erase(it);
974
hashimoto46be6e92014-12-04 16:41:55 +0900975 if (service_owner_changed_listener_map_.empty())
976 RemoveFilterFunction(Bus::OnServiceOwnerChangedFilter, this);
thestig@chromium.orgc2482f12013-06-11 07:52:34 +0900977}
978
zqiua84d25f2015-07-08 11:08:30 +0900979std::string Bus::GetConnectionName() {
980 if (!connection_)
981 return "";
982 return dbus_bus_get_unique_name(connection_);
983}
984
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900985dbus_bool_t Bus::OnAddWatch(DBusWatch* raw_watch) {
986 AssertOnDBusThread();
987
988 // watch will be deleted when raw_watch is removed in OnRemoveWatch().
989 Watch* watch = new Watch(raw_watch);
990 if (watch->IsReadyToBeWatched()) {
991 watch->StartWatching();
992 }
993 ++num_pending_watches_;
994 return true;
995}
996
997void Bus::OnRemoveWatch(DBusWatch* raw_watch) {
998 AssertOnDBusThread();
999
1000 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
1001 delete watch;
1002 --num_pending_watches_;
1003}
1004
1005void Bus::OnToggleWatch(DBusWatch* raw_watch) {
1006 AssertOnDBusThread();
1007
1008 Watch* watch = static_cast<Watch*>(dbus_watch_get_data(raw_watch));
fdorayc4aba522017-04-18 22:40:21 +09001009 if (watch->IsReadyToBeWatched())
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001010 watch->StartWatching();
fdorayc4aba522017-04-18 22:40:21 +09001011 else
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001012 watch->StopWatching();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001013}
1014
1015dbus_bool_t Bus::OnAddTimeout(DBusTimeout* raw_timeout) {
1016 AssertOnDBusThread();
1017
Wezfc5d5952017-07-12 11:50:17 +09001018 // |timeout| will be deleted by OnRemoveTimeoutThunk().
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001019 Timeout* timeout = new Timeout(raw_timeout);
1020 if (timeout->IsReadyToBeMonitored()) {
1021 timeout->StartMonitoring(this);
1022 }
1023 ++num_pending_timeouts_;
1024 return true;
1025}
1026
1027void Bus::OnRemoveTimeout(DBusTimeout* raw_timeout) {
1028 AssertOnDBusThread();
1029
1030 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
Wezfc5d5952017-07-12 11:50:17 +09001031 delete timeout;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001032 --num_pending_timeouts_;
1033}
1034
1035void Bus::OnToggleTimeout(DBusTimeout* raw_timeout) {
1036 AssertOnDBusThread();
1037
1038 Timeout* timeout = static_cast<Timeout*>(dbus_timeout_get_data(raw_timeout));
1039 if (timeout->IsReadyToBeMonitored()) {
1040 timeout->StartMonitoring(this);
1041 } else {
1042 timeout->StopMonitoring();
1043 }
1044}
1045
1046void Bus::OnDispatchStatusChanged(DBusConnection* connection,
1047 DBusDispatchStatus status) {
1048 DCHECK_EQ(connection, connection_);
1049 AssertOnDBusThread();
1050
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001051 // We cannot call ProcessAllIncomingDataIfAny() here, as calling
1052 // dbus_connection_dispatch() inside DBusDispatchStatusFunction is
1053 // prohibited by the D-Bus library. Hence, we post a task here instead.
1054 // See comments for dbus_connection_set_dispatch_status_function().
hashimoto@chromium.org955f6482013-09-26 13:32:29 +09001055 GetDBusTaskRunner()->PostTask(FROM_HERE,
1056 base::Bind(&Bus::ProcessAllIncomingDataIfAny,
1057 this));
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001058}
1059
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001060void Bus::OnServiceOwnerChanged(DBusMessage* message) {
1061 DCHECK(message);
1062 AssertOnDBusThread();
1063
1064 // |message| will be unrefed on exit of the function. Increment the
1065 // reference so we can use it in Signal::FromRawMessage() below.
1066 dbus_message_ref(message);
dcheng30c5a172016-04-09 07:55:04 +09001067 std::unique_ptr<Signal> signal(Signal::FromRawMessage(message));
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001068
1069 // Confirm the validity of the NameOwnerChanged signal.
1070 if (signal->GetMember() != kNameOwnerChangedSignal ||
1071 signal->GetInterface() != DBUS_INTERFACE_DBUS ||
1072 signal->GetSender() != DBUS_SERVICE_DBUS) {
1073 return;
1074 }
1075
1076 MessageReader reader(signal.get());
1077 std::string service_name;
1078 std::string old_owner;
1079 std::string new_owner;
1080 if (!reader.PopString(&service_name) ||
1081 !reader.PopString(&old_owner) ||
1082 !reader.PopString(&new_owner)) {
1083 return;
1084 }
1085
1086 ServiceOwnerChangedListenerMap::const_iterator it =
1087 service_owner_changed_listener_map_.find(service_name);
1088 if (it == service_owner_changed_listener_map_.end())
1089 return;
1090
1091 const std::vector<GetServiceOwnerCallback>& callbacks = it->second;
1092 for (size_t i = 0; i < callbacks.size(); ++i) {
hashimoto@chromium.org955f6482013-09-26 13:32:29 +09001093 GetOriginTaskRunner()->PostTask(FROM_HERE,
1094 base::Bind(callbacks[i], new_owner));
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001095 }
1096}
1097
1098// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001099dbus_bool_t Bus::OnAddWatchThunk(DBusWatch* raw_watch, void* data) {
1100 Bus* self = static_cast<Bus*>(data);
1101 return self->OnAddWatch(raw_watch);
1102}
1103
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001104// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001105void Bus::OnRemoveWatchThunk(DBusWatch* raw_watch, void* data) {
1106 Bus* self = static_cast<Bus*>(data);
jhawkins@chromium.org957fc4c2012-04-28 04:40:42 +09001107 self->OnRemoveWatch(raw_watch);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001108}
1109
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001110// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001111void Bus::OnToggleWatchThunk(DBusWatch* raw_watch, void* data) {
1112 Bus* self = static_cast<Bus*>(data);
jhawkins@chromium.org957fc4c2012-04-28 04:40:42 +09001113 self->OnToggleWatch(raw_watch);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001114}
1115
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001116// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001117dbus_bool_t Bus::OnAddTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1118 Bus* self = static_cast<Bus*>(data);
1119 return self->OnAddTimeout(raw_timeout);
1120}
1121
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001122// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001123void Bus::OnRemoveTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1124 Bus* self = static_cast<Bus*>(data);
jhawkins@chromium.org957fc4c2012-04-28 04:40:42 +09001125 self->OnRemoveTimeout(raw_timeout);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001126}
1127
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001128// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001129void Bus::OnToggleTimeoutThunk(DBusTimeout* raw_timeout, void* data) {
1130 Bus* self = static_cast<Bus*>(data);
jhawkins@chromium.org957fc4c2012-04-28 04:40:42 +09001131 self->OnToggleTimeout(raw_timeout);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001132}
1133
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001134// static
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001135void Bus::OnDispatchStatusChangedThunk(DBusConnection* connection,
1136 DBusDispatchStatus status,
1137 void* data) {
1138 Bus* self = static_cast<Bus*>(data);
jhawkins@chromium.org957fc4c2012-04-28 04:40:42 +09001139 self->OnDispatchStatusChanged(connection, status);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001140}
1141
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001142// static
nona@chromium.org5a44d2b2013-02-08 19:53:39 +09001143DBusHandlerResult Bus::OnConnectionDisconnectedFilter(
thestig@chromium.org074b1db2013-02-20 10:36:53 +09001144 DBusConnection* connection,
1145 DBusMessage* message,
1146 void* data) {
nona@chromium.org5a44d2b2013-02-08 19:53:39 +09001147 if (dbus_message_is_signal(message,
1148 DBUS_INTERFACE_LOCAL,
1149 kDisconnectedSignal)) {
hashimoto76b0cff2014-12-09 13:50:23 +09001150 // Abort when the connection is lost.
1151 LOG(FATAL) << "D-Bus connection was disconnected. Aborting.";
nona@chromium.org5a44d2b2013-02-08 19:53:39 +09001152 }
1153 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1154}
1155
thestig@chromium.orgc2482f12013-06-11 07:52:34 +09001156// static
1157DBusHandlerResult Bus::OnServiceOwnerChangedFilter(
1158 DBusConnection* connection,
1159 DBusMessage* message,
1160 void* data) {
1161 if (dbus_message_is_signal(message,
1162 DBUS_INTERFACE_DBUS,
1163 kNameOwnerChangedSignal)) {
1164 Bus* self = static_cast<Bus*>(data);
1165 self->OnServiceOwnerChanged(message);
1166 }
1167 // Always return unhandled to let others, e.g. ObjectProxies, handle the same
1168 // signal.
1169 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1170}
1171
satorux@chromium.org163f1cb2011-08-18 05:58:12 +09001172} // namespace dbus