Optimize MetricsDetails classes to avoid a lot of redundant work.
[chromium-blink-merge.git] / dbus / object_proxy.cc
blobc11f1fefe826cea70c145cb5e2826b3c15350eb6
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "dbus/bus.h"
7 #include "base/bind.h"
8 #include "base/logging.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/metrics/histogram.h"
11 #include "base/strings/string_piece.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/task_runner_util.h"
14 #include "base/threading/thread.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "dbus/dbus_statistics.h"
17 #include "dbus/message.h"
18 #include "dbus/object_path.h"
19 #include "dbus/object_proxy.h"
20 #include "dbus/scoped_dbus_error.h"
21 #include "dbus/util.h"
23 namespace dbus {
25 namespace {
27 const char kErrorServiceUnknown[] = "org.freedesktop.DBus.Error.ServiceUnknown";
28 const char kErrorObjectUnknown[] = "org.freedesktop.DBus.Error.UnknownObject";
30 // Used for success ratio histograms. 1 for success, 0 for failure.
31 const int kSuccessRatioHistogramMaxValue = 2;
33 // The path of D-Bus Object sending NameOwnerChanged signal.
34 const char kDBusSystemObjectPath[] = "/org/freedesktop/DBus";
36 // The D-Bus Object interface.
37 const char kDBusSystemObjectInterface[] = "org.freedesktop.DBus";
39 // The D-Bus Object address.
40 const char kDBusSystemObjectAddress[] = "org.freedesktop.DBus";
42 // The NameOwnerChanged member in |kDBusSystemObjectInterface|.
43 const char kNameOwnerChangedMember[] = "NameOwnerChanged";
45 // An empty function used for ObjectProxy::EmptyResponseCallback().
46 void EmptyResponseCallbackBody(Response* /*response*/) {
49 } // namespace
51 ObjectProxy::ObjectProxy(Bus* bus,
52 const std::string& service_name,
53 const ObjectPath& object_path,
54 int options)
55 : bus_(bus),
56 service_name_(service_name),
57 object_path_(object_path),
58 ignore_service_unknown_errors_(
59 options & IGNORE_SERVICE_UNKNOWN_ERRORS) {
62 ObjectProxy::~ObjectProxy() {
65 // Originally we tried to make |method_call| a const reference, but we
66 // gave up as dbus_connection_send_with_reply_and_block() takes a
67 // non-const pointer of DBusMessage as the second parameter.
68 scoped_ptr<Response> ObjectProxy::CallMethodAndBlockWithErrorDetails(
69 MethodCall* method_call, int timeout_ms, ScopedDBusError* error) {
70 bus_->AssertOnDBusThread();
72 if (!bus_->Connect() ||
73 !method_call->SetDestination(service_name_) ||
74 !method_call->SetPath(object_path_))
75 return scoped_ptr<Response>();
77 DBusMessage* request_message = method_call->raw_message();
79 // Send the message synchronously.
80 const base::TimeTicks start_time = base::TimeTicks::Now();
81 DBusMessage* response_message =
82 bus_->SendWithReplyAndBlock(request_message, timeout_ms, error->get());
83 // Record if the method call is successful, or not. 1 if successful.
84 UMA_HISTOGRAM_ENUMERATION("DBus.SyncMethodCallSuccess",
85 response_message ? 1 : 0,
86 kSuccessRatioHistogramMaxValue);
87 statistics::AddBlockingSentMethodCall(service_name_,
88 method_call->GetInterface(),
89 method_call->GetMember());
91 if (!response_message) {
92 LogMethodCallFailure(method_call->GetInterface(),
93 method_call->GetMember(),
94 error->is_set() ? error->name() : "unknown error type",
95 error->is_set() ? error->message() : "");
96 return scoped_ptr<Response>();
98 // Record time spent for the method call. Don't include failures.
99 UMA_HISTOGRAM_TIMES("DBus.SyncMethodCallTime",
100 base::TimeTicks::Now() - start_time);
102 return Response::FromRawMessage(response_message);
105 scoped_ptr<Response> ObjectProxy::CallMethodAndBlock(MethodCall* method_call,
106 int timeout_ms) {
107 ScopedDBusError error;
108 return CallMethodAndBlockWithErrorDetails(method_call, timeout_ms, &error);
111 void ObjectProxy::CallMethod(MethodCall* method_call,
112 int timeout_ms,
113 ResponseCallback callback) {
114 CallMethodWithErrorCallback(method_call, timeout_ms, callback,
115 base::Bind(&ObjectProxy::OnCallMethodError,
116 this,
117 method_call->GetInterface(),
118 method_call->GetMember(),
119 callback));
122 void ObjectProxy::CallMethodWithErrorCallback(MethodCall* method_call,
123 int timeout_ms,
124 ResponseCallback callback,
125 ErrorCallback error_callback) {
126 bus_->AssertOnOriginThread();
128 const base::TimeTicks start_time = base::TimeTicks::Now();
130 if (!method_call->SetDestination(service_name_) ||
131 !method_call->SetPath(object_path_)) {
132 // In case of a failure, run the error callback with NULL.
133 DBusMessage* response_message = NULL;
134 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
135 this,
136 callback,
137 error_callback,
138 start_time,
139 response_message);
140 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
141 return;
144 // Increment the reference count so we can safely reference the
145 // underlying request message until the method call is complete. This
146 // will be unref'ed in StartAsyncMethodCall().
147 DBusMessage* request_message = method_call->raw_message();
148 dbus_message_ref(request_message);
150 base::Closure task = base::Bind(&ObjectProxy::StartAsyncMethodCall,
151 this,
152 timeout_ms,
153 request_message,
154 callback,
155 error_callback,
156 start_time);
157 statistics::AddSentMethodCall(service_name_,
158 method_call->GetInterface(),
159 method_call->GetMember());
161 // Wait for the response in the D-Bus thread.
162 bus_->GetDBusTaskRunner()->PostTask(FROM_HERE, task);
165 void ObjectProxy::ConnectToSignal(const std::string& interface_name,
166 const std::string& signal_name,
167 SignalCallback signal_callback,
168 OnConnectedCallback on_connected_callback) {
169 bus_->AssertOnOriginThread();
171 base::PostTaskAndReplyWithResult(
172 bus_->GetDBusTaskRunner(),
173 FROM_HERE,
174 base::Bind(&ObjectProxy::ConnectToSignalInternal,
175 this,
176 interface_name,
177 signal_name,
178 signal_callback),
179 base::Bind(on_connected_callback,
180 interface_name,
181 signal_name));
184 void ObjectProxy::SetNameOwnerChangedCallback(
185 NameOwnerChangedCallback callback) {
186 bus_->AssertOnOriginThread();
188 name_owner_changed_callback_ = callback;
191 void ObjectProxy::WaitForServiceToBeAvailable(
192 WaitForServiceToBeAvailableCallback callback) {
193 bus_->AssertOnOriginThread();
195 wait_for_service_to_be_available_callbacks_.push_back(callback);
196 bus_->GetDBusTaskRunner()->PostTask(
197 FROM_HERE,
198 base::Bind(&ObjectProxy::WaitForServiceToBeAvailableInternal, this));
201 void ObjectProxy::Detach() {
202 bus_->AssertOnDBusThread();
204 if (bus_->is_connected())
205 bus_->RemoveFilterFunction(&ObjectProxy::HandleMessageThunk, this);
207 for (std::set<std::string>::iterator iter = match_rules_.begin();
208 iter != match_rules_.end(); ++iter) {
209 ScopedDBusError error;
210 bus_->RemoveMatch(*iter, error.get());
211 if (error.is_set()) {
212 // There is nothing we can do to recover, so just print the error.
213 LOG(ERROR) << "Failed to remove match rule: " << *iter;
216 match_rules_.clear();
219 // static
220 ObjectProxy::ResponseCallback ObjectProxy::EmptyResponseCallback() {
221 return base::Bind(&EmptyResponseCallbackBody);
224 ObjectProxy::OnPendingCallIsCompleteData::OnPendingCallIsCompleteData(
225 ObjectProxy* in_object_proxy,
226 ResponseCallback in_response_callback,
227 ErrorCallback in_error_callback,
228 base::TimeTicks in_start_time)
229 : object_proxy(in_object_proxy),
230 response_callback(in_response_callback),
231 error_callback(in_error_callback),
232 start_time(in_start_time) {
235 ObjectProxy::OnPendingCallIsCompleteData::~OnPendingCallIsCompleteData() {
238 void ObjectProxy::StartAsyncMethodCall(int timeout_ms,
239 DBusMessage* request_message,
240 ResponseCallback response_callback,
241 ErrorCallback error_callback,
242 base::TimeTicks start_time) {
243 bus_->AssertOnDBusThread();
245 if (!bus_->Connect() || !bus_->SetUpAsyncOperations()) {
246 // In case of a failure, run the error callback with NULL.
247 DBusMessage* response_message = NULL;
248 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
249 this,
250 response_callback,
251 error_callback,
252 start_time,
253 response_message);
254 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
256 dbus_message_unref(request_message);
257 return;
260 DBusPendingCall* pending_call = NULL;
262 bus_->SendWithReply(request_message, &pending_call, timeout_ms);
264 // Prepare the data we'll be passing to OnPendingCallIsCompleteThunk().
265 // The data will be deleted in OnPendingCallIsCompleteThunk().
266 OnPendingCallIsCompleteData* data =
267 new OnPendingCallIsCompleteData(this, response_callback, error_callback,
268 start_time);
270 // This returns false only when unable to allocate memory.
271 const bool success = dbus_pending_call_set_notify(
272 pending_call,
273 &ObjectProxy::OnPendingCallIsCompleteThunk,
274 data,
275 NULL);
276 CHECK(success) << "Unable to allocate memory";
277 dbus_pending_call_unref(pending_call);
279 // It's now safe to unref the request message.
280 dbus_message_unref(request_message);
283 void ObjectProxy::OnPendingCallIsComplete(DBusPendingCall* pending_call,
284 ResponseCallback response_callback,
285 ErrorCallback error_callback,
286 base::TimeTicks start_time) {
287 bus_->AssertOnDBusThread();
289 DBusMessage* response_message = dbus_pending_call_steal_reply(pending_call);
290 base::Closure task = base::Bind(&ObjectProxy::RunResponseCallback,
291 this,
292 response_callback,
293 error_callback,
294 start_time,
295 response_message);
296 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE, task);
299 void ObjectProxy::RunResponseCallback(ResponseCallback response_callback,
300 ErrorCallback error_callback,
301 base::TimeTicks start_time,
302 DBusMessage* response_message) {
303 bus_->AssertOnOriginThread();
305 bool method_call_successful = false;
306 if (!response_message) {
307 // The response is not received.
308 error_callback.Run(NULL);
309 } else if (dbus_message_get_type(response_message) ==
310 DBUS_MESSAGE_TYPE_ERROR) {
311 // This will take |response_message| and release (unref) it.
312 scoped_ptr<ErrorResponse> error_response(
313 ErrorResponse::FromRawMessage(response_message));
314 error_callback.Run(error_response.get());
315 // Delete the message on the D-Bus thread. See below for why.
316 bus_->GetDBusTaskRunner()->PostTask(
317 FROM_HERE,
318 base::Bind(&base::DeletePointer<ErrorResponse>,
319 error_response.release()));
320 } else {
321 // This will take |response_message| and release (unref) it.
322 scoped_ptr<Response> response(Response::FromRawMessage(response_message));
323 // The response is successfully received.
324 response_callback.Run(response.get());
325 // The message should be deleted on the D-Bus thread for a complicated
326 // reason:
328 // libdbus keeps track of the number of bytes in the incoming message
329 // queue to ensure that the data size in the queue is manageable. The
330 // bookkeeping is partly done via dbus_message_unref(), and immediately
331 // asks the client code (Chrome) to stop monitoring the underlying
332 // socket, if the number of bytes exceeds a certian number, which is set
333 // to 63MB, per dbus-transport.cc:
335 // /* Try to default to something that won't totally hose the system,
336 // * but doesn't impose too much of a limitation.
337 // */
338 // transport->max_live_messages_size = _DBUS_ONE_MEGABYTE * 63;
340 // The monitoring of the socket is done on the D-Bus thread (see Watch
341 // class in bus.cc), hence we should stop the monitoring from D-Bus
342 // thread, not from the current thread here, which is likely UI thread.
343 bus_->GetDBusTaskRunner()->PostTask(
344 FROM_HERE,
345 base::Bind(&base::DeletePointer<Response>, response.release()));
347 method_call_successful = true;
348 // Record time spent for the method call. Don't include failures.
349 UMA_HISTOGRAM_TIMES("DBus.AsyncMethodCallTime",
350 base::TimeTicks::Now() - start_time);
352 // Record if the method call is successful, or not. 1 if successful.
353 UMA_HISTOGRAM_ENUMERATION("DBus.AsyncMethodCallSuccess",
354 method_call_successful,
355 kSuccessRatioHistogramMaxValue);
358 void ObjectProxy::OnPendingCallIsCompleteThunk(DBusPendingCall* pending_call,
359 void* user_data) {
360 OnPendingCallIsCompleteData* data =
361 reinterpret_cast<OnPendingCallIsCompleteData*>(user_data);
362 ObjectProxy* self = data->object_proxy;
363 self->OnPendingCallIsComplete(pending_call,
364 data->response_callback,
365 data->error_callback,
366 data->start_time);
367 delete data;
370 bool ObjectProxy::ConnectToNameOwnerChangedSignal() {
371 bus_->AssertOnDBusThread();
373 if (!bus_->Connect() || !bus_->SetUpAsyncOperations())
374 return false;
376 bus_->AddFilterFunction(&ObjectProxy::HandleMessageThunk, this);
378 // Add a match_rule listening NameOwnerChanged for the well-known name
379 // |service_name_|.
380 const std::string name_owner_changed_match_rule =
381 base::StringPrintf(
382 "type='signal',interface='org.freedesktop.DBus',"
383 "member='NameOwnerChanged',path='/org/freedesktop/DBus',"
384 "sender='org.freedesktop.DBus',arg0='%s'",
385 service_name_.c_str());
387 const bool success =
388 AddMatchRuleWithoutCallback(name_owner_changed_match_rule,
389 "org.freedesktop.DBus.NameOwnerChanged");
391 // Try getting the current name owner. It's not guaranteed that we can get
392 // the name owner at this moment, as the service may not yet be started. If
393 // that's the case, we'll get the name owner via NameOwnerChanged signal,
394 // as soon as the service is started.
395 UpdateNameOwnerAndBlock();
397 return success;
400 bool ObjectProxy::ConnectToSignalInternal(const std::string& interface_name,
401 const std::string& signal_name,
402 SignalCallback signal_callback) {
403 bus_->AssertOnDBusThread();
405 if (!ConnectToNameOwnerChangedSignal())
406 return false;
408 const std::string absolute_signal_name =
409 GetAbsoluteMemberName(interface_name, signal_name);
411 // Add a match rule so the signal goes through HandleMessage().
412 const std::string match_rule =
413 base::StringPrintf("type='signal', interface='%s', path='%s'",
414 interface_name.c_str(),
415 object_path_.value().c_str());
416 return AddMatchRuleWithCallback(match_rule,
417 absolute_signal_name,
418 signal_callback);
421 void ObjectProxy::WaitForServiceToBeAvailableInternal() {
422 bus_->AssertOnDBusThread();
424 if (!ConnectToNameOwnerChangedSignal()) { // Failed to connect to the signal.
425 const bool service_is_ready = false;
426 bus_->GetOriginTaskRunner()->PostTask(
427 FROM_HERE,
428 base::Bind(&ObjectProxy::RunWaitForServiceToBeAvailableCallbacks,
429 this, service_is_ready));
430 return;
433 const bool service_is_available = !service_name_owner_.empty();
434 if (service_is_available) { // Service is already available.
435 bus_->GetOriginTaskRunner()->PostTask(
436 FROM_HERE,
437 base::Bind(&ObjectProxy::RunWaitForServiceToBeAvailableCallbacks,
438 this, service_is_available));
439 return;
443 DBusHandlerResult ObjectProxy::HandleMessage(
444 DBusConnection* connection,
445 DBusMessage* raw_message) {
446 bus_->AssertOnDBusThread();
448 if (dbus_message_get_type(raw_message) != DBUS_MESSAGE_TYPE_SIGNAL)
449 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
451 // raw_message will be unrefed on exit of the function. Increment the
452 // reference so we can use it in Signal.
453 dbus_message_ref(raw_message);
454 scoped_ptr<Signal> signal(
455 Signal::FromRawMessage(raw_message));
457 // Verify the signal comes from the object we're proxying for, this is
458 // our last chance to return DBUS_HANDLER_RESULT_NOT_YET_HANDLED and
459 // allow other object proxies to handle instead.
460 const ObjectPath path = signal->GetPath();
461 if (path != object_path_) {
462 if (path.value() == kDBusSystemObjectPath &&
463 signal->GetMember() == kNameOwnerChangedMember) {
464 // Handle NameOwnerChanged separately
465 return HandleNameOwnerChanged(signal.Pass());
467 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
470 const std::string interface = signal->GetInterface();
471 const std::string member = signal->GetMember();
473 statistics::AddReceivedSignal(service_name_, interface, member);
475 // Check if we know about the signal.
476 const std::string absolute_signal_name = GetAbsoluteMemberName(
477 interface, member);
478 MethodTable::const_iterator iter = method_table_.find(absolute_signal_name);
479 if (iter == method_table_.end()) {
480 // Don't know about the signal.
481 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
483 VLOG(1) << "Signal received: " << signal->ToString();
485 std::string sender = signal->GetSender();
486 if (service_name_owner_ != sender) {
487 LOG(ERROR) << "Rejecting a message from a wrong sender.";
488 UMA_HISTOGRAM_COUNTS("DBus.RejectedSignalCount", 1);
489 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
492 const base::TimeTicks start_time = base::TimeTicks::Now();
493 if (bus_->HasDBusThread()) {
494 // Post a task to run the method in the origin thread.
495 // Transfer the ownership of |signal| to RunMethod().
496 // |released_signal| will be deleted in RunMethod().
497 Signal* released_signal = signal.release();
498 bus_->GetOriginTaskRunner()->PostTask(FROM_HERE,
499 base::Bind(&ObjectProxy::RunMethod,
500 this,
501 start_time,
502 iter->second,
503 released_signal));
504 } else {
505 const base::TimeTicks start_time = base::TimeTicks::Now();
506 // If the D-Bus thread is not used, just call the callback on the
507 // current thread. Transfer the ownership of |signal| to RunMethod().
508 Signal* released_signal = signal.release();
509 RunMethod(start_time, iter->second, released_signal);
512 // We don't return DBUS_HANDLER_RESULT_HANDLED for signals because other
513 // objects may be interested in them. (e.g. Signals from org.freedesktop.DBus)
514 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
517 void ObjectProxy::RunMethod(base::TimeTicks start_time,
518 std::vector<SignalCallback> signal_callbacks,
519 Signal* signal) {
520 bus_->AssertOnOriginThread();
522 for (std::vector<SignalCallback>::iterator iter = signal_callbacks.begin();
523 iter != signal_callbacks.end(); ++iter)
524 iter->Run(signal);
526 // Delete the message on the D-Bus thread. See comments in
527 // RunResponseCallback().
528 bus_->GetDBusTaskRunner()->PostTask(
529 FROM_HERE,
530 base::Bind(&base::DeletePointer<Signal>, signal));
532 // Record time spent for handling the signal.
533 UMA_HISTOGRAM_TIMES("DBus.SignalHandleTime",
534 base::TimeTicks::Now() - start_time);
537 DBusHandlerResult ObjectProxy::HandleMessageThunk(
538 DBusConnection* connection,
539 DBusMessage* raw_message,
540 void* user_data) {
541 ObjectProxy* self = reinterpret_cast<ObjectProxy*>(user_data);
542 return self->HandleMessage(connection, raw_message);
545 void ObjectProxy::LogMethodCallFailure(
546 const base::StringPiece& interface_name,
547 const base::StringPiece& method_name,
548 const base::StringPiece& error_name,
549 const base::StringPiece& error_message) const {
550 if (ignore_service_unknown_errors_ &&
551 (error_name == kErrorServiceUnknown || error_name == kErrorObjectUnknown))
552 return;
553 logging::LogSeverity severity = logging::LOG_ERROR;
554 // "UnknownObject" indicates that an object or service is no longer available,
555 // e.g. a Shill network service has gone out of range. Treat these as warnings
556 // not errors.
557 if (error_name == kErrorObjectUnknown)
558 severity = logging::LOG_WARNING;
559 std::ostringstream msg;
560 msg << "Failed to call method: " << interface_name << "." << method_name
561 << ": object_path= " << object_path_.value()
562 << ": " << error_name << ": " << error_message;
563 logging::LogAtLevel(severity, msg.str());
566 void ObjectProxy::OnCallMethodError(const std::string& interface_name,
567 const std::string& method_name,
568 ResponseCallback response_callback,
569 ErrorResponse* error_response) {
570 if (error_response) {
571 // Error message may contain the error message as string.
572 MessageReader reader(error_response);
573 std::string error_message;
574 reader.PopString(&error_message);
575 LogMethodCallFailure(interface_name,
576 method_name,
577 error_response->GetErrorName(),
578 error_message);
580 response_callback.Run(NULL);
583 bool ObjectProxy::AddMatchRuleWithCallback(
584 const std::string& match_rule,
585 const std::string& absolute_signal_name,
586 SignalCallback signal_callback) {
587 DCHECK(!match_rule.empty());
588 DCHECK(!absolute_signal_name.empty());
589 bus_->AssertOnDBusThread();
591 if (match_rules_.find(match_rule) == match_rules_.end()) {
592 ScopedDBusError error;
593 bus_->AddMatch(match_rule, error.get());
594 if (error.is_set()) {
595 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
596 << error.name() << ": " << error.message();
597 return false;
598 } else {
599 // Store the match rule, so that we can remove this in Detach().
600 match_rules_.insert(match_rule);
601 // Add the signal callback to the method table.
602 method_table_[absolute_signal_name].push_back(signal_callback);
603 return true;
605 } else {
606 // We already have the match rule.
607 method_table_[absolute_signal_name].push_back(signal_callback);
608 return true;
612 bool ObjectProxy::AddMatchRuleWithoutCallback(
613 const std::string& match_rule,
614 const std::string& absolute_signal_name) {
615 DCHECK(!match_rule.empty());
616 DCHECK(!absolute_signal_name.empty());
617 bus_->AssertOnDBusThread();
619 if (match_rules_.find(match_rule) != match_rules_.end())
620 return true;
622 ScopedDBusError error;
623 bus_->AddMatch(match_rule, error.get());
624 if (error.is_set()) {
625 LOG(ERROR) << "Failed to add match rule \"" << match_rule << "\". Got "
626 << error.name() << ": " << error.message();
627 return false;
629 // Store the match rule, so that we can remove this in Detach().
630 match_rules_.insert(match_rule);
631 return true;
634 void ObjectProxy::UpdateNameOwnerAndBlock() {
635 bus_->AssertOnDBusThread();
636 // Errors should be suppressed here, as the service may not be yet running
637 // when connecting to signals of the service, which is just fine.
638 // The ObjectProxy will be notified when the service is launched via
639 // NameOwnerChanged signal. See also comments in ConnectToSignalInternal().
640 service_name_owner_ =
641 bus_->GetServiceOwnerAndBlock(service_name_, Bus::SUPPRESS_ERRORS);
644 DBusHandlerResult ObjectProxy::HandleNameOwnerChanged(
645 scoped_ptr<Signal> signal) {
646 DCHECK(signal);
647 bus_->AssertOnDBusThread();
649 // Confirm the validity of the NameOwnerChanged signal.
650 if (signal->GetMember() == kNameOwnerChangedMember &&
651 signal->GetInterface() == kDBusSystemObjectInterface &&
652 signal->GetSender() == kDBusSystemObjectAddress) {
653 MessageReader reader(signal.get());
654 std::string name, old_owner, new_owner;
655 if (reader.PopString(&name) &&
656 reader.PopString(&old_owner) &&
657 reader.PopString(&new_owner) &&
658 name == service_name_) {
659 service_name_owner_ = new_owner;
660 bus_->GetOriginTaskRunner()->PostTask(
661 FROM_HERE,
662 base::Bind(&ObjectProxy::RunNameOwnerChangedCallback,
663 this, old_owner, new_owner));
665 const bool service_is_available = !service_name_owner_.empty();
666 if (service_is_available) {
667 bus_->GetOriginTaskRunner()->PostTask(
668 FROM_HERE,
669 base::Bind(&ObjectProxy::RunWaitForServiceToBeAvailableCallbacks,
670 this, service_is_available));
675 // Always return unhandled to let other object proxies handle the same
676 // signal.
677 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
680 void ObjectProxy::RunNameOwnerChangedCallback(const std::string& old_owner,
681 const std::string& new_owner) {
682 bus_->AssertOnOriginThread();
683 if (!name_owner_changed_callback_.is_null())
684 name_owner_changed_callback_.Run(old_owner, new_owner);
687 void ObjectProxy::RunWaitForServiceToBeAvailableCallbacks(
688 bool service_is_available) {
689 bus_->AssertOnOriginThread();
691 std::vector<WaitForServiceToBeAvailableCallback> callbacks;
692 callbacks.swap(wait_for_service_to_be_available_callbacks_);
693 for (size_t i = 0; i < callbacks.size(); ++i)
694 callbacks[i].Run(service_is_available);
697 } // namespace dbus