blob: 59584f2ce34fa750783b378d2f84f48485ebfdfc [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.
4
5#include "dbus/bus.h"
6
7#include "base/bind.h"
8#include "base/logging.h"
avi@chromium.orga29af562013-07-18 08:00:30 +09009#include "base/message_loop/message_loop.h"
satorux@chromium.org5a92cf32011-09-07 05:53:30 +090010#include "base/metrics/histogram.h"
tfarina@chromium.org0eed10b2013-04-18 06:42:40 +090011#include "base/strings/string_piece.h"
avi@chromium.orgffcdb952013-06-11 16:27:01 +090012#include "base/strings/stringprintf.h"
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +090013#include "base/task_runner_util.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090014#include "base/threading/thread.h"
15#include "base/threading/thread_restrictions.h"
stevenjb@chromium.org3199bd12012-11-15 06:03:29 +090016#include "dbus/dbus_statistics.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090017#include "dbus/message.h"
keybuk@google.combf4649a2012-02-15 06:29:06 +090018#include "dbus/object_path.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090019#include "dbus/object_proxy.h"
20#include "dbus/scoped_dbus_error.h"
armansitof4364642014-09-06 02:49:34 +090021#include "dbus/util.h"
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090022
thestig@chromium.org56057f22013-05-05 00:48:37 +090023namespace dbus {
24
satorux@chromium.org7f0c4512011-08-23 16:29:21 +090025namespace {
26
adamk@chromium.org35c0eef2012-02-11 06:45:23 +090027const char kErrorServiceUnknown[] = "org.freedesktop.DBus.Error.ServiceUnknown";
stevenjb@chromium.orgc415c482014-08-09 06:57:19 +090028const char kErrorObjectUnknown[] = "org.freedesktop.DBus.Error.UnknownObject";
adamk@chromium.org35c0eef2012-02-11 06:45:23 +090029
satorux@chromium.org5a92cf32011-09-07 05:53:30 +090030// Used for success ratio histograms. 1 for success, 0 for failure.
31const int kSuccessRatioHistogramMaxValue = 2;
32
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +090033// The path of D-Bus Object sending NameOwnerChanged signal.
stevenjb@chromium.org3199bd12012-11-15 06:03:29 +090034const char kDBusSystemObjectPath[] = "/org/freedesktop/DBus";
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +090035
thestig@chromium.org56057f22013-05-05 00:48:37 +090036// The D-Bus Object interface.
37const char kDBusSystemObjectInterface[] = "org.freedesktop.DBus";
38
39// The D-Bus Object address.
40const char kDBusSystemObjectAddress[] = "org.freedesktop.DBus";
41
42// The NameOwnerChanged member in |kDBusSystemObjectInterface|.
43const char kNameOwnerChangedMember[] = "NameOwnerChanged";
44
satorux@chromium.orgb1753152011-11-11 17:36:22 +090045// An empty function used for ObjectProxy::EmptyResponseCallback().
thestig@chromium.org56057f22013-05-05 00:48:37 +090046void EmptyResponseCallbackBody(Response* /*response*/) {
satorux@chromium.orgb1753152011-11-11 17:36:22 +090047}
48
satorux@chromium.org7f0c4512011-08-23 16:29:21 +090049} // namespace
50
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090051ObjectProxy::ObjectProxy(Bus* bus,
52 const std::string& service_name,
keybuk@google.combf4649a2012-02-15 06:29:06 +090053 const ObjectPath& object_path,
adamk@chromium.org35c0eef2012-02-11 06:45:23 +090054 int options)
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090055 : bus_(bus),
56 service_name_(service_name),
satorux@chromium.org7f0c4512011-08-23 16:29:21 +090057 object_path_(object_path),
adamk@chromium.org35c0eef2012-02-11 06:45:23 +090058 filter_added_(false),
59 ignore_service_unknown_errors_(
60 options & IGNORE_SERVICE_UNKNOWN_ERRORS) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090061}
62
63ObjectProxy::~ObjectProxy() {
64}
65
66// Originally we tried to make |method_call| a const reference, but we
67// gave up as dbus_connection_send_with_reply_and_block() takes a
68// non-const pointer of DBusMessage as the second parameter.
avakulenko1d8962b2014-09-17 10:44:09 +090069scoped_ptr<Response> ObjectProxy::CallMethodAndBlockWithErrorDetails(
70 MethodCall* method_call, int timeout_ms, ScopedDBusError* error) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090071 bus_->AssertOnDBusThread();
72
hashimoto@chromium.orgb0305512012-05-23 15:55:22 +090073 if (!bus_->Connect() ||
74 !method_call->SetDestination(service_name_) ||
75 !method_call->SetPath(object_path_))
yuki@chromium.orgd4eedf82013-02-07 18:46:24 +090076 return scoped_ptr<Response>();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090077
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090078 DBusMessage* request_message = method_call->raw_message();
79
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090080 // Send the message synchronously.
satorux@chromium.org5a92cf32011-09-07 05:53:30 +090081 const base::TimeTicks start_time = base::TimeTicks::Now();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090082 DBusMessage* response_message =
avakulenko1d8962b2014-09-17 10:44:09 +090083 bus_->SendWithReplyAndBlock(request_message, timeout_ms, error->get());
satorux@chromium.org5a92cf32011-09-07 05:53:30 +090084 // Record if the method call is successful, or not. 1 if successful.
85 UMA_HISTOGRAM_ENUMERATION("DBus.SyncMethodCallSuccess",
86 response_message ? 1 : 0,
87 kSuccessRatioHistogramMaxValue);
stevenjb@chromium.org3199bd12012-11-15 06:03:29 +090088 statistics::AddBlockingSentMethodCall(service_name_,
89 method_call->GetInterface(),
90 method_call->GetMember());
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090091
92 if (!response_message) {
satorux@chromium.org31bb21e2012-05-31 15:12:11 +090093 LogMethodCallFailure(method_call->GetInterface(),
94 method_call->GetMember(),
avakulenko1d8962b2014-09-17 10:44:09 +090095 error->is_set() ? error->name() : "unknown error type",
96 error->is_set() ? error->message() : "");
yuki@chromium.orgd4eedf82013-02-07 18:46:24 +090097 return scoped_ptr<Response>();
satorux@chromium.org163f1cb2011-08-18 05:58:12 +090098 }
satorux@chromium.org5a92cf32011-09-07 05:53:30 +090099 // Record time spent for the method call. Don't include failures.
100 UMA_HISTOGRAM_TIMES("DBus.SyncMethodCallTime",
101 base::TimeTicks::Now() - start_time);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900102
satorux@chromium.orgffa83a92011-08-24 12:32:06 +0900103 return Response::FromRawMessage(response_message);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900104}
105
avakulenko1d8962b2014-09-17 10:44:09 +0900106scoped_ptr<Response> ObjectProxy::CallMethodAndBlock(MethodCall* method_call,
107 int timeout_ms) {
108 ScopedDBusError error;
109 return CallMethodAndBlockWithErrorDetails(method_call, timeout_ms, &error);
110}
111
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900112void ObjectProxy::CallMethod(MethodCall* method_call,
113 int timeout_ms,
114 ResponseCallback callback) {
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900115 CallMethodWithErrorCallback(method_call, timeout_ms, callback,
116 base::Bind(&ObjectProxy::OnCallMethodError,
117 this,
satorux@chromium.org31bb21e2012-05-31 15:12:11 +0900118 method_call->GetInterface(),
119 method_call->GetMember(),
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900120 callback));
121}
122
123void ObjectProxy::CallMethodWithErrorCallback(MethodCall* method_call,
124 int timeout_ms,
125 ResponseCallback callback,
126 ErrorCallback error_callback) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900127 bus_->AssertOnOriginThread();
128
hashimoto@chromium.orgb0305512012-05-23 15:55:22 +0900129 const base::TimeTicks start_time = base::TimeTicks::Now();
130
131 if (!method_call->SetDestination(service_name_) ||
132 !method_call->SetPath(object_path_)) {
133 // In case of a failure, run the error callback with NULL.
134 DBusMessage* response_message = NULL;
135 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
136 this,
137 callback,
138 error_callback,
139 start_time,
140 response_message);
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900141 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
hashimoto@chromium.orgb0305512012-05-23 15:55:22 +0900142 return;
143 }
144
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900145 // Increment the reference count so we can safely reference the
146 // underlying request message until the method call is complete. This
147 // will be unref'ed in StartAsyncMethodCall().
148 DBusMessage* request_message = method_call->raw_message();
149 dbus_message_ref(request_message);
150
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900151 base::Closure task = base::Bind(&ObjectProxy::StartAsyncMethodCall,
152 this,
153 timeout_ms,
satorux@chromium.org47d706b2011-10-04 22:47:21 +0900154 request_message,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900155 callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900156 error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900157 start_time);
stevenjb@chromium.org3199bd12012-11-15 06:03:29 +0900158 statistics::AddSentMethodCall(service_name_,
159 method_call->GetInterface(),
160 method_call->GetMember());
161
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900162 // Wait for the response in the D-Bus thread.
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900163 bus_->GetDBusTaskRunner()->PostTask(FROM_HERE, task);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900164}
165
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900166void ObjectProxy::ConnectToSignal(const std::string& interface_name,
167 const std::string& signal_name,
168 SignalCallback signal_callback,
169 OnConnectedCallback on_connected_callback) {
170 bus_->AssertOnOriginThread();
171
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900172 base::PostTaskAndReplyWithResult(
173 bus_->GetDBusTaskRunner(),
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900174 FROM_HERE,
175 base::Bind(&ObjectProxy::ConnectToSignalInternal,
176 this,
177 interface_name,
178 signal_name,
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900179 signal_callback),
180 base::Bind(on_connected_callback,
181 interface_name,
182 signal_name));
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900183}
184
hashimoto@chromium.org4f3851c2013-09-27 16:12:03 +0900185void ObjectProxy::SetNameOwnerChangedCallback(
186 NameOwnerChangedCallback callback) {
187 bus_->AssertOnOriginThread();
188
189 name_owner_changed_callback_ = callback;
190}
191
hashimoto@chromium.orged268092013-10-02 16:53:09 +0900192void ObjectProxy::WaitForServiceToBeAvailable(
193 WaitForServiceToBeAvailableCallback callback) {
194 bus_->AssertOnOriginThread();
195
196 wait_for_service_to_be_available_callbacks_.push_back(callback);
197 bus_->GetDBusTaskRunner()->PostTask(
198 FROM_HERE,
199 base::Bind(&ObjectProxy::WaitForServiceToBeAvailableInternal, this));
200}
201
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900202void ObjectProxy::Detach() {
203 bus_->AssertOnDBusThread();
204
satorux@chromium.org66bc4c22011-10-06 09:20:53 +0900205 if (filter_added_) {
206 if (!bus_->RemoveFilterFunction(&ObjectProxy::HandleMessageThunk, this)) {
207 LOG(ERROR) << "Failed to remove filter function";
208 }
209 }
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900210
satorux@chromium.org5b3e4962011-11-24 07:08:38 +0900211 for (std::set<std::string>::iterator iter = match_rules_.begin();
212 iter != match_rules_.end(); ++iter) {
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900213 ScopedDBusError error;
satorux@chromium.org5b3e4962011-11-24 07:08:38 +0900214 bus_->RemoveMatch(*iter, error.get());
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900215 if (error.is_set()) {
216 // There is nothing we can do to recover, so just print the error.
satorux@chromium.org5b3e4962011-11-24 07:08:38 +0900217 LOG(ERROR) << "Failed to remove match rule: " << *iter;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900218 }
219 }
satorux@chromium.org5b3e4962011-11-24 07:08:38 +0900220 match_rules_.clear();
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900221}
222
satorux@chromium.orgb1753152011-11-11 17:36:22 +0900223// static
224ObjectProxy::ResponseCallback ObjectProxy::EmptyResponseCallback() {
225 return base::Bind(&EmptyResponseCallbackBody);
226}
227
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900228ObjectProxy::OnPendingCallIsCompleteData::OnPendingCallIsCompleteData(
229 ObjectProxy* in_object_proxy,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900230 ResponseCallback in_response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900231 ErrorCallback in_error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900232 base::TimeTicks in_start_time)
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900233 : object_proxy(in_object_proxy),
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900234 response_callback(in_response_callback),
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900235 error_callback(in_error_callback),
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900236 start_time(in_start_time) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900237}
238
239ObjectProxy::OnPendingCallIsCompleteData::~OnPendingCallIsCompleteData() {
240}
241
242void ObjectProxy::StartAsyncMethodCall(int timeout_ms,
satorux@chromium.org47d706b2011-10-04 22:47:21 +0900243 DBusMessage* request_message,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900244 ResponseCallback response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900245 ErrorCallback error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900246 base::TimeTicks start_time) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900247 bus_->AssertOnDBusThread();
248
249 if (!bus_->Connect() || !bus_->SetUpAsyncOperations()) {
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900250 // In case of a failure, run the error callback with NULL.
satorux@chromium.org47d706b2011-10-04 22:47:21 +0900251 DBusMessage* response_message = NULL;
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900252 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
253 this,
254 response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900255 error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900256 start_time,
satorux@chromium.org47d706b2011-10-04 22:47:21 +0900257 response_message);
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900258 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900259
260 dbus_message_unref(request_message);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900261 return;
262 }
263
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900264 DBusPendingCall* pending_call = NULL;
265
266 bus_->SendWithReply(request_message, &pending_call, timeout_ms);
267
268 // Prepare the data we'll be passing to OnPendingCallIsCompleteThunk().
269 // The data will be deleted in OnPendingCallIsCompleteThunk().
270 OnPendingCallIsCompleteData* data =
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900271 new OnPendingCallIsCompleteData(this, response_callback, error_callback,
272 start_time);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900273
274 // This returns false only when unable to allocate memory.
275 const bool success = dbus_pending_call_set_notify(
276 pending_call,
277 &ObjectProxy::OnPendingCallIsCompleteThunk,
278 data,
279 NULL);
280 CHECK(success) << "Unable to allocate memory";
281 dbus_pending_call_unref(pending_call);
282
283 // It's now safe to unref the request message.
284 dbus_message_unref(request_message);
285}
286
287void ObjectProxy::OnPendingCallIsComplete(DBusPendingCall* pending_call,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900288 ResponseCallback response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900289 ErrorCallback error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900290 base::TimeTicks start_time) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900291 bus_->AssertOnDBusThread();
292
293 DBusMessage* response_message = dbus_pending_call_steal_reply(pending_call);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900294 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
295 this,
296 response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900297 error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900298 start_time,
satorux@chromium.org47d706b2011-10-04 22:47:21 +0900299 response_message);
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900300 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900301}
302
303void ObjectProxy::RunResponseCallback(ResponseCallback response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900304 ErrorCallback error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900305 base::TimeTicks start_time,
satorux@chromium.org47d706b2011-10-04 22:47:21 +0900306 DBusMessage* response_message) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900307 bus_->AssertOnOriginThread();
308
satorux@chromium.orgb1753152011-11-11 17:36:22 +0900309 bool method_call_successful = false;
satorux@chromium.orgffa83a92011-08-24 12:32:06 +0900310 if (!response_message) {
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900311 // The response is not received.
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900312 error_callback.Run(NULL);
satorux@chromium.orgffa83a92011-08-24 12:32:06 +0900313 } else if (dbus_message_get_type(response_message) ==
314 DBUS_MESSAGE_TYPE_ERROR) {
315 // This will take |response_message| and release (unref) it.
thestig@chromium.org56057f22013-05-05 00:48:37 +0900316 scoped_ptr<ErrorResponse> error_response(
317 ErrorResponse::FromRawMessage(response_message));
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900318 error_callback.Run(error_response.get());
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900319 // Delete the message on the D-Bus thread. See below for why.
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900320 bus_->GetDBusTaskRunner()->PostTask(
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900321 FROM_HERE,
thestig@chromium.org56057f22013-05-05 00:48:37 +0900322 base::Bind(&base::DeletePointer<ErrorResponse>,
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900323 error_response.release()));
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900324 } else {
satorux@chromium.orgffa83a92011-08-24 12:32:06 +0900325 // This will take |response_message| and release (unref) it.
thestig@chromium.org56057f22013-05-05 00:48:37 +0900326 scoped_ptr<Response> response(Response::FromRawMessage(response_message));
satorux@chromium.orgc6ac7572011-09-01 03:02:43 +0900327 // The response is successfully received.
satorux@chromium.orgffa83a92011-08-24 12:32:06 +0900328 response_callback.Run(response.get());
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900329 // The message should be deleted on the D-Bus thread for a complicated
330 // reason:
331 //
332 // libdbus keeps track of the number of bytes in the incoming message
333 // queue to ensure that the data size in the queue is manageable. The
334 // bookkeeping is partly done via dbus_message_unref(), and immediately
335 // asks the client code (Chrome) to stop monitoring the underlying
336 // socket, if the number of bytes exceeds a certian number, which is set
337 // to 63MB, per dbus-transport.cc:
338 //
339 // /* Try to default to something that won't totally hose the system,
340 // * but doesn't impose too much of a limitation.
341 // */
342 // transport->max_live_messages_size = _DBUS_ONE_MEGABYTE * 63;
343 //
344 // The monitoring of the socket is done on the D-Bus thread (see Watch
345 // class in bus.cc), hence we should stop the monitoring from D-Bus
346 // thread, not from the current thread here, which is likely UI thread.
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900347 bus_->GetDBusTaskRunner()->PostTask(
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900348 FROM_HERE,
thestig@chromium.org56057f22013-05-05 00:48:37 +0900349 base::Bind(&base::DeletePointer<Response>, response.release()));
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900350
satorux@chromium.orgb1753152011-11-11 17:36:22 +0900351 method_call_successful = true;
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900352 // Record time spent for the method call. Don't include failures.
353 UMA_HISTOGRAM_TIMES("DBus.AsyncMethodCallTime",
354 base::TimeTicks::Now() - start_time);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900355 }
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900356 // Record if the method call is successful, or not. 1 if successful.
357 UMA_HISTOGRAM_ENUMERATION("DBus.AsyncMethodCallSuccess",
satorux@chromium.orgb1753152011-11-11 17:36:22 +0900358 method_call_successful,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900359 kSuccessRatioHistogramMaxValue);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900360}
361
362void ObjectProxy::OnPendingCallIsCompleteThunk(DBusPendingCall* pending_call,
363 void* user_data) {
364 OnPendingCallIsCompleteData* data =
365 reinterpret_cast<OnPendingCallIsCompleteData*>(user_data);
366 ObjectProxy* self = data->object_proxy;
367 self->OnPendingCallIsComplete(pending_call,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900368 data->response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900369 data->error_callback,
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900370 data->start_time);
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900371 delete data;
372}
373
hashimoto@chromium.orged268092013-10-02 16:53:09 +0900374bool ObjectProxy::ConnectToNameOwnerChangedSignal() {
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900375 bus_->AssertOnDBusThread();
376
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900377 if (!bus_->Connect() || !bus_->SetUpAsyncOperations())
378 return false;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900379
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900380 // We should add the filter only once. Otherwise, HandleMessage() will
381 // be called more than once.
382 if (!filter_added_) {
383 if (bus_->AddFilterFunction(&ObjectProxy::HandleMessageThunk, this)) {
384 filter_added_ = true;
385 } else {
386 LOG(ERROR) << "Failed to add filter function";
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900387 }
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900388 }
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900389 // Add a match_rule listening NameOwnerChanged for the well-known name
390 // |service_name_|.
391 const std::string name_owner_changed_match_rule =
392 base::StringPrintf(
393 "type='signal',interface='org.freedesktop.DBus',"
394 "member='NameOwnerChanged',path='/org/freedesktop/DBus',"
395 "sender='org.freedesktop.DBus',arg0='%s'",
396 service_name_.c_str());
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900397
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900398 const bool success =
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900399 AddMatchRuleWithoutCallback(name_owner_changed_match_rule,
400 "org.freedesktop.DBus.NameOwnerChanged");
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900401
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900402 // Try getting the current name owner. It's not guaranteed that we can get
403 // the name owner at this moment, as the service may not yet be started. If
404 // that's the case, we'll get the name owner via NameOwnerChanged signal,
405 // as soon as the service is started.
406 UpdateNameOwnerAndBlock();
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900407
hashimoto@chromium.orgce5c6152013-09-26 15:40:04 +0900408 return success;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900409}
410
hashimoto@chromium.orged268092013-10-02 16:53:09 +0900411bool ObjectProxy::ConnectToSignalInternal(const std::string& interface_name,
412 const std::string& signal_name,
413 SignalCallback signal_callback) {
414 bus_->AssertOnDBusThread();
415
416 if (!ConnectToNameOwnerChangedSignal())
417 return false;
418
419 const std::string absolute_signal_name =
armansitof4364642014-09-06 02:49:34 +0900420 GetAbsoluteMemberName(interface_name, signal_name);
hashimoto@chromium.orged268092013-10-02 16:53:09 +0900421
422 // Add a match rule so the signal goes through HandleMessage().
423 const std::string match_rule =
424 base::StringPrintf("type='signal', interface='%s', path='%s'",
425 interface_name.c_str(),
426 object_path_.value().c_str());
427 return AddMatchRuleWithCallback(match_rule,
428 absolute_signal_name,
429 signal_callback);
430}
431
432void ObjectProxy::WaitForServiceToBeAvailableInternal() {
433 bus_->AssertOnDBusThread();
434
435 if (!ConnectToNameOwnerChangedSignal()) { // Failed to connect to the signal.
436 const bool service_is_ready = false;
437 bus_->GetOriginTaskRunner()->PostTask(
438 FROM_HERE,
439 base::Bind(&ObjectProxy::RunWaitForServiceToBeAvailableCallbacks,
440 this, service_is_ready));
441 return;
442 }
443
444 const bool service_is_available = !service_name_owner_.empty();
445 if (service_is_available) { // Service is already available.
446 bus_->GetOriginTaskRunner()->PostTask(
447 FROM_HERE,
448 base::Bind(&ObjectProxy::RunWaitForServiceToBeAvailableCallbacks,
449 this, service_is_available));
450 return;
451 }
452}
453
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900454DBusHandlerResult ObjectProxy::HandleMessage(
455 DBusConnection* connection,
456 DBusMessage* raw_message) {
457 bus_->AssertOnDBusThread();
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900458
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900459 if (dbus_message_get_type(raw_message) != DBUS_MESSAGE_TYPE_SIGNAL)
460 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
461
462 // raw_message will be unrefed on exit of the function. Increment the
463 // reference so we can use it in Signal.
464 dbus_message_ref(raw_message);
465 scoped_ptr<Signal> signal(
466 Signal::FromRawMessage(raw_message));
467
keybuk@chromium.orgb929d752012-03-01 13:01:05 +0900468 // Verify the signal comes from the object we're proxying for, this is
469 // our last chance to return DBUS_HANDLER_RESULT_NOT_YET_HANDLED and
470 // allow other object proxies to handle instead.
thestig@chromium.org56057f22013-05-05 00:48:37 +0900471 const ObjectPath path = signal->GetPath();
keybuk@chromium.orgb929d752012-03-01 13:01:05 +0900472 if (path != object_path_) {
stevenjb@chromium.org3199bd12012-11-15 06:03:29 +0900473 if (path.value() == kDBusSystemObjectPath &&
thestig@chromium.org56057f22013-05-05 00:48:37 +0900474 signal->GetMember() == kNameOwnerChangedMember) {
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900475 // Handle NameOwnerChanged separately
haruki@chromium.orgc8d231a2012-11-14 20:02:59 +0900476 return HandleNameOwnerChanged(signal.Pass());
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900477 }
keybuk@chromium.orgb929d752012-03-01 13:01:05 +0900478 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
479 }
480
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900481 const std::string interface = signal->GetInterface();
482 const std::string member = signal->GetMember();
483
stevenjb@chromium.org3199bd12012-11-15 06:03:29 +0900484 statistics::AddReceivedSignal(service_name_, interface, member);
485
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900486 // Check if we know about the signal.
armansitof4364642014-09-06 02:49:34 +0900487 const std::string absolute_signal_name = GetAbsoluteMemberName(
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900488 interface, member);
489 MethodTable::const_iterator iter = method_table_.find(absolute_signal_name);
490 if (iter == method_table_.end()) {
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900491 // Don't know about the signal.
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900492 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
493 }
satorux@chromium.org63c284f2011-10-15 07:37:12 +0900494 VLOG(1) << "Signal received: " << signal->ToString();
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900495
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900496 std::string sender = signal->GetSender();
497 if (service_name_owner_ != sender) {
498 LOG(ERROR) << "Rejecting a message from a wrong sender.";
499 UMA_HISTOGRAM_COUNTS("DBus.RejectedSignalCount", 1);
500 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
501 }
502
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900503 const base::TimeTicks start_time = base::TimeTicks::Now();
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900504 if (bus_->HasDBusThread()) {
505 // Post a task to run the method in the origin thread.
506 // Transfer the ownership of |signal| to RunMethod().
507 // |released_signal| will be deleted in RunMethod().
508 Signal* released_signal = signal.release();
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900509 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE,
510 base::Bind(&ObjectProxy::RunMethod,
511 this,
512 start_time,
513 iter->second,
514 released_signal));
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900515 } else {
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900516 const base::TimeTicks start_time = base::TimeTicks::Now();
517 // If the D-Bus thread is not used, just call the callback on the
518 // current thread. Transfer the ownership of |signal| to RunMethod().
519 Signal* released_signal = signal.release();
520 RunMethod(start_time, iter->second, released_signal);
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900521 }
522
hashimoto@chromium.orgfb3930a2013-12-17 17:41:57 +0900523 // We don't return DBUS_HANDLER_RESULT_HANDLED for signals because other
524 // objects may be interested in them. (e.g. Signals from org.freedesktop.DBus)
525 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900526}
527
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900528void ObjectProxy::RunMethod(base::TimeTicks start_time,
keybuk@chromium.org2594a712013-04-24 09:12:35 +0900529 std::vector<SignalCallback> signal_callbacks,
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900530 Signal* signal) {
531 bus_->AssertOnOriginThread();
532
keybuk@chromium.org2594a712013-04-24 09:12:35 +0900533 for (std::vector<SignalCallback>::iterator iter = signal_callbacks.begin();
534 iter != signal_callbacks.end(); ++iter)
535 iter->Run(signal);
536
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900537 // Delete the message on the D-Bus thread. See comments in
538 // RunResponseCallback().
hashimoto@chromium.org955f6482013-09-26 13:32:29 +0900539 bus_->GetDBusTaskRunner()->PostTask(
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900540 FROM_HERE,
thestig@chromium.org56057f22013-05-05 00:48:37 +0900541 base::Bind(&base::DeletePointer<Signal>, signal));
satorux@chromium.org9f10a6e2012-06-02 11:53:20 +0900542
satorux@chromium.org5a92cf32011-09-07 05:53:30 +0900543 // Record time spent for handling the signal.
544 UMA_HISTOGRAM_TIMES("DBus.SignalHandleTime",
545 base::TimeTicks::Now() - start_time);
satorux@chromium.org7f0c4512011-08-23 16:29:21 +0900546}
547
548DBusHandlerResult ObjectProxy::HandleMessageThunk(
549 DBusConnection* connection,
550 DBusMessage* raw_message,
551 void* user_data) {
552 ObjectProxy* self = reinterpret_cast<ObjectProxy*>(user_data);
553 return self->HandleMessage(connection, raw_message);
554}
555
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900556void ObjectProxy::LogMethodCallFailure(
satorux@chromium.org31bb21e2012-05-31 15:12:11 +0900557 const base::StringPiece& interface_name,
558 const base::StringPiece& method_name,
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900559 const base::StringPiece& error_name,
560 const base::StringPiece& error_message) const {
stevenjb@chromium.orgc415c482014-08-09 06:57:19 +0900561 if (ignore_service_unknown_errors_ &&
562 (error_name == kErrorServiceUnknown || error_name == kErrorObjectUnknown))
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900563 return;
stevenjb@chromium.orgc415c482014-08-09 06:57:19 +0900564 logging::LogSeverity severity = logging::LOG_ERROR;
565 // "UnknownObject" indicates that an object or service is no longer available,
566 // e.g. a Shill network service has gone out of range. Treat these as warnings
567 // not errors.
568 if (error_name == kErrorObjectUnknown)
569 severity = logging::LOG_WARNING;
570 std::ostringstream msg;
571 msg << "Failed to call method: " << interface_name << "." << method_name
572 << ": object_path= " << object_path_.value()
573 << ": " << error_name << ": " << error_message;
574 logging::LogAtLevel(severity, msg.str());
adamk@chromium.org35c0eef2012-02-11 06:45:23 +0900575}
576
satorux@chromium.org31bb21e2012-05-31 15:12:11 +0900577void ObjectProxy::OnCallMethodError(const std::string& interface_name,
578 const std::string& method_name,
579 ResponseCallback response_callback,
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900580 ErrorResponse* error_response) {
581 if (error_response) {
582 // Error message may contain the error message as string.
thestig@chromium.org56057f22013-05-05 00:48:37 +0900583 MessageReader reader(error_response);
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900584 std::string error_message;
585 reader.PopString(&error_message);
satorux@chromium.org31bb21e2012-05-31 15:12:11 +0900586 LogMethodCallFailure(interface_name,
587 method_name,
588 error_response->GetErrorName(),
589 error_message);
hashimoto@chromium.org0d2477e2012-04-20 12:18:27 +0900590 }
591 response_callback.Run(NULL);
592}
593
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900594bool ObjectProxy::AddMatchRuleWithCallback(
595 const std::string& match_rule,
596 const std::string& absolute_signal_name,
597 SignalCallback signal_callback) {
598 DCHECK(!match_rule.empty());
599 DCHECK(!absolute_signal_name.empty());
600 bus_->AssertOnDBusThread();
601
602 if (match_rules_.find(match_rule) == match_rules_.end()) {
603 ScopedDBusError error;
604 bus_->AddMatch(match_rule, error.get());
605 if (error.is_set()) {
thestig@chromium.org56057f22013-05-05 00:48:37 +0900606 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
607 << error.name() << ": " << error.message();
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900608 return false;
609 } else {
610 // Store the match rule, so that we can remove this in Detach().
611 match_rules_.insert(match_rule);
612 // Add the signal callback to the method table.
keybuk@chromium.org2594a712013-04-24 09:12:35 +0900613 method_table_[absolute_signal_name].push_back(signal_callback);
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900614 return true;
615 }
616 } else {
617 // We already have the match rule.
keybuk@chromium.org2594a712013-04-24 09:12:35 +0900618 method_table_[absolute_signal_name].push_back(signal_callback);
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900619 return true;
620 }
621}
622
623bool ObjectProxy::AddMatchRuleWithoutCallback(
624 const std::string& match_rule,
625 const std::string& absolute_signal_name) {
626 DCHECK(!match_rule.empty());
627 DCHECK(!absolute_signal_name.empty());
628 bus_->AssertOnDBusThread();
629
630 if (match_rules_.find(match_rule) != match_rules_.end())
631 return true;
632
633 ScopedDBusError error;
634 bus_->AddMatch(match_rule, error.get());
635 if (error.is_set()) {
thestig@chromium.org56057f22013-05-05 00:48:37 +0900636 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
637 << error.name() << ": " << error.message();
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900638 return false;
639 }
640 // Store the match rule, so that we can remove this in Detach().
641 match_rules_.insert(match_rule);
642 return true;
643}
644
645void ObjectProxy::UpdateNameOwnerAndBlock() {
646 bus_->AssertOnDBusThread();
satorux@chromium.org9b1f85d2013-08-16 18:16:42 +0900647 // Errors should be suppressed here, as the service may not be yet running
648 // when connecting to signals of the service, which is just fine.
649 // The ObjectProxy will be notified when the service is launched via
650 // NameOwnerChanged signal. See also comments in ConnectToSignalInternal().
thestig@chromium.org56057f22013-05-05 00:48:37 +0900651 service_name_owner_ =
satorux@chromium.org9b1f85d2013-08-16 18:16:42 +0900652 bus_->GetServiceOwnerAndBlock(service_name_, Bus::SUPPRESS_ERRORS);
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900653}
654
haruki@chromium.orgc8d231a2012-11-14 20:02:59 +0900655DBusHandlerResult ObjectProxy::HandleNameOwnerChanged(
656 scoped_ptr<Signal> signal) {
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900657 DCHECK(signal);
658 bus_->AssertOnDBusThread();
659
660 // Confirm the validity of the NameOwnerChanged signal.
thestig@chromium.org56057f22013-05-05 00:48:37 +0900661 if (signal->GetMember() == kNameOwnerChangedMember &&
662 signal->GetInterface() == kDBusSystemObjectInterface &&
663 signal->GetSender() == kDBusSystemObjectAddress) {
haruki@chromium.orgc8d231a2012-11-14 20:02:59 +0900664 MessageReader reader(signal.get());
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900665 std::string name, old_owner, new_owner;
666 if (reader.PopString(&name) &&
667 reader.PopString(&old_owner) &&
668 reader.PopString(&new_owner) &&
669 name == service_name_) {
670 service_name_owner_ = new_owner;
hashimoto@chromium.org4f3851c2013-09-27 16:12:03 +0900671 bus_->GetOriginTaskRunner()->PostTask(
672 FROM_HERE,
673 base::Bind(&ObjectProxy::RunNameOwnerChangedCallback,
674 this, old_owner, new_owner));
hashimoto@chromium.orged268092013-10-02 16:53:09 +0900675
676 const bool service_is_available = !service_name_owner_.empty();
677 if (service_is_available) {
678 bus_->GetOriginTaskRunner()->PostTask(
679 FROM_HERE,
680 base::Bind(&ObjectProxy::RunWaitForServiceToBeAvailableCallbacks,
681 this, service_is_available));
682 }
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900683 }
684 }
685
keybuk@chromium.org359c9b62012-11-27 09:23:25 +0900686 // Always return unhandled to let other object proxies handle the same
687 // signal.
haruki@chromium.orgc5623ec2012-10-29 15:27:33 +0900688 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
689}
690
hashimoto@chromium.org4f3851c2013-09-27 16:12:03 +0900691void ObjectProxy::RunNameOwnerChangedCallback(const std::string& old_owner,
692 const std::string& new_owner) {
693 bus_->AssertOnOriginThread();
694 if (!name_owner_changed_callback_.is_null())
695 name_owner_changed_callback_.Run(old_owner, new_owner);
696}
697
hashimoto@chromium.orged268092013-10-02 16:53:09 +0900698void ObjectProxy::RunWaitForServiceToBeAvailableCallbacks(
699 bool service_is_available) {
700 bus_->AssertOnOriginThread();
701
702 std::vector<WaitForServiceToBeAvailableCallback> callbacks;
703 callbacks.swap(wait_for_service_to_be_available_callbacks_);
704 for (size_t i = 0; i < callbacks.size(); ++i)
705 callbacks[i].Run(service_is_available);
706}
707
satorux@chromium.org163f1cb2011-08-18 05:58:12 +0900708} // namespace dbus