Roll src/third_party/WebKit f298044:aa8346d (svn 202628:202629)
[chromium-blink-merge.git] / dbus / message.cc
blob0bf76d425a8a393c418d9e83a97456ecd74fcd5f
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/message.h"
7 #include <string>
9 #include "base/basictypes.h"
10 #include "base/format_macros.h"
11 #include "base/logging.h"
12 #include "base/numerics/safe_conversions.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "dbus/object_path.h"
18 #if defined(USE_SYSTEM_PROTOBUF)
19 #include <google/protobuf/message_lite.h>
20 #else
21 #include "third_party/protobuf/src/google/protobuf/message_lite.h"
22 #endif
24 namespace {
26 // Appends the header name and the value to |output|, if the value is
27 // not empty.
28 void AppendStringHeader(const std::string& header_name,
29 const std::string& header_value,
30 std::string* output) {
31 if (!header_value.empty()) {
32 *output += header_name + ": " + header_value + "\n";
36 // Appends the header name and the value to |output|, if the value is
37 // nonzero.
38 void AppendUint32Header(const std::string& header_name,
39 uint32 header_value,
40 std::string* output) {
41 if (header_value != 0) {
42 *output += (header_name + ": " + base::UintToString(header_value) + "\n");
46 } // namespace
48 namespace dbus {
50 bool IsDBusTypeUnixFdSupported() {
51 int major = 0, minor = 0, micro = 0;
52 dbus_get_version(&major, &minor, &micro);
53 return major >= 1 && minor >= 4;
56 Message::Message()
57 : raw_message_(NULL) {
60 Message::~Message() {
61 if (raw_message_)
62 dbus_message_unref(raw_message_);
65 void Message::Init(DBusMessage* raw_message) {
66 DCHECK(!raw_message_);
67 raw_message_ = raw_message;
70 Message::MessageType Message::GetMessageType() {
71 if (!raw_message_)
72 return MESSAGE_INVALID;
73 const int type = dbus_message_get_type(raw_message_);
74 return static_cast<Message::MessageType>(type);
77 std::string Message::GetMessageTypeAsString() {
78 switch (GetMessageType()) {
79 case MESSAGE_INVALID:
80 return "MESSAGE_INVALID";
81 case MESSAGE_METHOD_CALL:
82 return "MESSAGE_METHOD_CALL";
83 case MESSAGE_METHOD_RETURN:
84 return "MESSAGE_METHOD_RETURN";
85 case MESSAGE_SIGNAL:
86 return "MESSAGE_SIGNAL";
87 case MESSAGE_ERROR:
88 return "MESSAGE_ERROR";
90 NOTREACHED();
91 return std::string();
94 std::string Message::ToStringInternal(const std::string& indent,
95 MessageReader* reader) {
96 const char* kBrokenMessage = "[broken message]";
97 std::string output;
98 while (reader->HasMoreData()) {
99 const DataType type = reader->GetDataType();
100 switch (type) {
101 case BYTE: {
102 uint8 value = 0;
103 if (!reader->PopByte(&value))
104 return kBrokenMessage;
105 output += indent + "byte " + base::UintToString(value) + "\n";
106 break;
108 case BOOL: {
109 bool value = false;
110 if (!reader->PopBool(&value))
111 return kBrokenMessage;
112 output += indent + "bool " + (value ? "true" : "false") + "\n";
113 break;
115 case INT16: {
116 int16 value = 0;
117 if (!reader->PopInt16(&value))
118 return kBrokenMessage;
119 output += indent + "int16 " + base::IntToString(value) + "\n";
120 break;
122 case UINT16: {
123 uint16 value = 0;
124 if (!reader->PopUint16(&value))
125 return kBrokenMessage;
126 output += indent + "uint16 " + base::UintToString(value) + "\n";
127 break;
129 case INT32: {
130 int32 value = 0;
131 if (!reader->PopInt32(&value))
132 return kBrokenMessage;
133 output += indent + "int32 " + base::IntToString(value) + "\n";
134 break;
136 case UINT32: {
137 uint32 value = 0;
138 if (!reader->PopUint32(&value))
139 return kBrokenMessage;
140 output += indent + "uint32 " + base::UintToString(value) + "\n";
141 break;
143 case INT64: {
144 int64 value = 0;
145 if (!reader->PopInt64(&value))
146 return kBrokenMessage;
147 output += (indent + "int64 " + base::Int64ToString(value) + "\n");
148 break;
150 case UINT64: {
151 uint64 value = 0;
152 if (!reader->PopUint64(&value))
153 return kBrokenMessage;
154 output += (indent + "uint64 " + base::Uint64ToString(value) + "\n");
155 break;
157 case DOUBLE: {
158 double value = 0;
159 if (!reader->PopDouble(&value))
160 return kBrokenMessage;
161 output += indent + "double " + base::DoubleToString(value) + "\n";
162 break;
164 case STRING: {
165 std::string value;
166 if (!reader->PopString(&value))
167 return kBrokenMessage;
168 // Truncate if the string is longer than the limit.
169 const size_t kTruncateLength = 100;
170 if (value.size() < kTruncateLength) {
171 output += indent + "string \"" + value + "\"\n";
172 } else {
173 std::string truncated;
174 base::TruncateUTF8ToByteSize(value, kTruncateLength, &truncated);
175 base::StringAppendF(&truncated, "... (%" PRIuS " bytes in total)",
176 value.size());
177 output += indent + "string \"" + truncated + "\"\n";
179 break;
181 case OBJECT_PATH: {
182 ObjectPath value;
183 if (!reader->PopObjectPath(&value))
184 return kBrokenMessage;
185 output += indent + "object_path \"" + value.value() + "\"\n";
186 break;
188 case ARRAY: {
189 MessageReader sub_reader(this);
190 if (!reader->PopArray(&sub_reader))
191 return kBrokenMessage;
192 output += indent + "array [\n";
193 output += ToStringInternal(indent + " ", &sub_reader);
194 output += indent + "]\n";
195 break;
197 case STRUCT: {
198 MessageReader sub_reader(this);
199 if (!reader->PopStruct(&sub_reader))
200 return kBrokenMessage;
201 output += indent + "struct {\n";
202 output += ToStringInternal(indent + " ", &sub_reader);
203 output += indent + "}\n";
204 break;
206 case DICT_ENTRY: {
207 MessageReader sub_reader(this);
208 if (!reader->PopDictEntry(&sub_reader))
209 return kBrokenMessage;
210 output += indent + "dict entry {\n";
211 output += ToStringInternal(indent + " ", &sub_reader);
212 output += indent + "}\n";
213 break;
215 case VARIANT: {
216 MessageReader sub_reader(this);
217 if (!reader->PopVariant(&sub_reader))
218 return kBrokenMessage;
219 output += indent + "variant ";
220 output += ToStringInternal(indent + " ", &sub_reader);
221 break;
223 case UNIX_FD: {
224 CHECK(IsDBusTypeUnixFdSupported());
226 FileDescriptor file_descriptor;
227 if (!reader->PopFileDescriptor(&file_descriptor))
228 return kBrokenMessage;
229 output += indent + "fd#" +
230 base::IntToString(file_descriptor.value()) + "\n";
231 break;
233 default:
234 LOG(FATAL) << "Unknown type: " << type;
237 return output;
240 // The returned string consists of message headers such as
241 // destination if any, followed by a blank line, and the message
242 // payload. For example, a MethodCall's ToString() will look like:
244 // destination: com.example.Service
245 // path: /com/example/Object
246 // interface: com.example.Interface
247 // member: SomeMethod
249 // string \"payload\"
250 // ...
251 std::string Message::ToString() {
252 if (!raw_message_)
253 return std::string();
255 // Generate headers first.
256 std::string headers;
257 AppendStringHeader("message_type", GetMessageTypeAsString(), &headers);
258 AppendStringHeader("destination", GetDestination(), &headers);
259 AppendStringHeader("path", GetPath().value(), &headers);
260 AppendStringHeader("interface", GetInterface(), &headers);
261 AppendStringHeader("member", GetMember(), &headers);
262 AppendStringHeader("error_name", GetErrorName(), &headers);
263 AppendStringHeader("sender", GetSender(), &headers);
264 AppendStringHeader("signature", GetSignature(), &headers);
265 AppendUint32Header("serial", GetSerial(), &headers);
266 AppendUint32Header("reply_serial", GetReplySerial(), &headers);
268 // Generate the payload.
269 MessageReader reader(this);
270 return headers + "\n" + ToStringInternal(std::string(), &reader);
273 bool Message::SetDestination(const std::string& destination) {
274 return dbus_message_set_destination(raw_message_, destination.c_str());
277 bool Message::SetPath(const ObjectPath& path) {
278 return dbus_message_set_path(raw_message_, path.value().c_str());
281 bool Message::SetInterface(const std::string& interface) {
282 return dbus_message_set_interface(raw_message_, interface.c_str());
285 bool Message::SetMember(const std::string& member) {
286 return dbus_message_set_member(raw_message_, member.c_str());
289 bool Message::SetErrorName(const std::string& error_name) {
290 return dbus_message_set_error_name(raw_message_, error_name.c_str());
293 bool Message::SetSender(const std::string& sender) {
294 return dbus_message_set_sender(raw_message_, sender.c_str());
297 void Message::SetSerial(uint32 serial) {
298 dbus_message_set_serial(raw_message_, serial);
301 void Message::SetReplySerial(uint32 reply_serial) {
302 dbus_message_set_reply_serial(raw_message_, reply_serial);
305 std::string Message::GetDestination() {
306 const char* destination = dbus_message_get_destination(raw_message_);
307 return destination ? destination : "";
310 ObjectPath Message::GetPath() {
311 const char* path = dbus_message_get_path(raw_message_);
312 return ObjectPath(path ? path : "");
315 std::string Message::GetInterface() {
316 const char* interface = dbus_message_get_interface(raw_message_);
317 return interface ? interface : "";
320 std::string Message::GetMember() {
321 const char* member = dbus_message_get_member(raw_message_);
322 return member ? member : "";
325 std::string Message::GetErrorName() {
326 const char* error_name = dbus_message_get_error_name(raw_message_);
327 return error_name ? error_name : "";
330 std::string Message::GetSender() {
331 const char* sender = dbus_message_get_sender(raw_message_);
332 return sender ? sender : "";
335 std::string Message::GetSignature() {
336 const char* signature = dbus_message_get_signature(raw_message_);
337 return signature ? signature : "";
340 uint32 Message::GetSerial() {
341 return dbus_message_get_serial(raw_message_);
344 uint32 Message::GetReplySerial() {
345 return dbus_message_get_reply_serial(raw_message_);
349 // MethodCall implementation.
352 MethodCall::MethodCall(const std::string& interface_name,
353 const std::string& method_name)
354 : Message() {
355 Init(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL));
357 CHECK(SetInterface(interface_name));
358 CHECK(SetMember(method_name));
361 MethodCall::MethodCall() : Message() {
364 MethodCall* MethodCall::FromRawMessage(DBusMessage* raw_message) {
365 DCHECK_EQ(DBUS_MESSAGE_TYPE_METHOD_CALL, dbus_message_get_type(raw_message));
367 MethodCall* method_call = new MethodCall;
368 method_call->Init(raw_message);
369 return method_call;
373 // Signal implementation.
375 Signal::Signal(const std::string& interface_name,
376 const std::string& method_name)
377 : Message() {
378 Init(dbus_message_new(DBUS_MESSAGE_TYPE_SIGNAL));
380 CHECK(SetInterface(interface_name));
381 CHECK(SetMember(method_name));
384 Signal::Signal() : Message() {
387 Signal* Signal::FromRawMessage(DBusMessage* raw_message) {
388 DCHECK_EQ(DBUS_MESSAGE_TYPE_SIGNAL, dbus_message_get_type(raw_message));
390 Signal* signal = new Signal;
391 signal->Init(raw_message);
392 return signal;
396 // Response implementation.
399 Response::Response() : Message() {
402 scoped_ptr<Response> Response::FromRawMessage(DBusMessage* raw_message) {
403 DCHECK_EQ(DBUS_MESSAGE_TYPE_METHOD_RETURN,
404 dbus_message_get_type(raw_message));
406 scoped_ptr<Response> response(new Response);
407 response->Init(raw_message);
408 return response.Pass();
411 scoped_ptr<Response> Response::FromMethodCall(MethodCall* method_call) {
412 scoped_ptr<Response> response(new Response);
413 response->Init(dbus_message_new_method_return(method_call->raw_message()));
414 return response.Pass();
417 scoped_ptr<Response> Response::CreateEmpty() {
418 scoped_ptr<Response> response(new Response);
419 response->Init(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN));
420 return response.Pass();
424 // ErrorResponse implementation.
427 ErrorResponse::ErrorResponse() : Response() {
430 scoped_ptr<ErrorResponse> ErrorResponse::FromRawMessage(
431 DBusMessage* raw_message) {
432 DCHECK_EQ(DBUS_MESSAGE_TYPE_ERROR, dbus_message_get_type(raw_message));
434 scoped_ptr<ErrorResponse> response(new ErrorResponse);
435 response->Init(raw_message);
436 return response.Pass();
439 scoped_ptr<ErrorResponse> ErrorResponse::FromMethodCall(
440 MethodCall* method_call,
441 const std::string& error_name,
442 const std::string& error_message) {
443 scoped_ptr<ErrorResponse> response(new ErrorResponse);
444 response->Init(dbus_message_new_error(method_call->raw_message(),
445 error_name.c_str(),
446 error_message.c_str()));
447 return response.Pass();
451 // MessageWriter implementation.
454 MessageWriter::MessageWriter(Message* message)
455 : message_(message),
456 container_is_open_(false) {
457 memset(&raw_message_iter_, 0, sizeof(raw_message_iter_));
458 if (message)
459 dbus_message_iter_init_append(message_->raw_message(), &raw_message_iter_);
462 MessageWriter::~MessageWriter() {
465 void MessageWriter::AppendByte(uint8 value) {
466 AppendBasic(DBUS_TYPE_BYTE, &value);
469 void MessageWriter::AppendBool(bool value) {
470 // The size of dbus_bool_t and the size of bool are different. The
471 // former is always 4 per dbus-types.h, whereas the latter is usually 1.
472 // dbus_message_iter_append_basic() used in AppendBasic() expects four
473 // bytes for DBUS_TYPE_BOOLEAN, so we must pass a dbus_bool_t, instead
474 // of a bool, to AppendBasic().
475 dbus_bool_t dbus_value = value;
476 AppendBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
479 void MessageWriter::AppendInt16(int16 value) {
480 AppendBasic(DBUS_TYPE_INT16, &value);
483 void MessageWriter::AppendUint16(uint16 value) {
484 AppendBasic(DBUS_TYPE_UINT16, &value);
487 void MessageWriter::AppendInt32(int32 value) {
488 AppendBasic(DBUS_TYPE_INT32, &value);
491 void MessageWriter::AppendUint32(uint32 value) {
492 AppendBasic(DBUS_TYPE_UINT32, &value);
495 void MessageWriter::AppendInt64(int64 value) {
496 AppendBasic(DBUS_TYPE_INT64, &value);
499 void MessageWriter::AppendUint64(uint64 value) {
500 AppendBasic(DBUS_TYPE_UINT64, &value);
503 void MessageWriter::AppendDouble(double value) {
504 AppendBasic(DBUS_TYPE_DOUBLE, &value);
507 void MessageWriter::AppendString(const std::string& value) {
508 // D-Bus Specification (0.19) says a string "must be valid UTF-8".
509 CHECK(base::IsStringUTF8(value));
510 const char* pointer = value.c_str();
511 AppendBasic(DBUS_TYPE_STRING, &pointer);
512 // TODO(satorux): It may make sense to return an error here, as the
513 // input string can be large. If needed, we could add something like
514 // bool AppendStringWithErrorChecking().
517 void MessageWriter::AppendObjectPath(const ObjectPath& value) {
518 CHECK(value.IsValid());
519 const char* pointer = value.value().c_str();
520 AppendBasic(DBUS_TYPE_OBJECT_PATH, &pointer);
523 // Ideally, client shouldn't need to supply the signature string, but
524 // the underlying D-Bus library requires us to supply this before
525 // appending contents to array and variant. It's technically possible
526 // for us to design API that doesn't require the signature but it will
527 // complicate the implementation so we decided to have the signature
528 // parameter. Hopefully, variants are less used in request messages from
529 // client side than response message from server side, so this should
530 // not be a big issue.
531 void MessageWriter::OpenArray(const std::string& signature,
532 MessageWriter* writer) {
533 DCHECK(!container_is_open_);
535 const bool success = dbus_message_iter_open_container(
536 &raw_message_iter_,
537 DBUS_TYPE_ARRAY,
538 signature.c_str(),
539 &writer->raw_message_iter_);
540 CHECK(success) << "Unable to allocate memory";
541 container_is_open_ = true;
544 void MessageWriter::OpenVariant(const std::string& signature,
545 MessageWriter* writer) {
546 DCHECK(!container_is_open_);
548 const bool success = dbus_message_iter_open_container(
549 &raw_message_iter_,
550 DBUS_TYPE_VARIANT,
551 signature.c_str(),
552 &writer->raw_message_iter_);
553 CHECK(success) << "Unable to allocate memory";
554 container_is_open_ = true;
557 void MessageWriter::OpenStruct(MessageWriter* writer) {
558 DCHECK(!container_is_open_);
560 const bool success = dbus_message_iter_open_container(
561 &raw_message_iter_,
562 DBUS_TYPE_STRUCT,
563 NULL, // Signature should be NULL.
564 &writer->raw_message_iter_);
565 CHECK(success) << "Unable to allocate memory";
566 container_is_open_ = true;
569 void MessageWriter::OpenDictEntry(MessageWriter* writer) {
570 DCHECK(!container_is_open_);
572 const bool success = dbus_message_iter_open_container(
573 &raw_message_iter_,
574 DBUS_TYPE_DICT_ENTRY,
575 NULL, // Signature should be NULL.
576 &writer->raw_message_iter_);
577 CHECK(success) << "Unable to allocate memory";
578 container_is_open_ = true;
581 void MessageWriter::CloseContainer(MessageWriter* writer) {
582 DCHECK(container_is_open_);
584 const bool success = dbus_message_iter_close_container(
585 &raw_message_iter_, &writer->raw_message_iter_);
586 CHECK(success) << "Unable to allocate memory";
587 container_is_open_ = false;
590 void MessageWriter::AppendArrayOfBytes(const uint8* values, size_t length) {
591 DCHECK(!container_is_open_);
592 MessageWriter array_writer(message_);
593 OpenArray("y", &array_writer);
594 const bool success = dbus_message_iter_append_fixed_array(
595 &(array_writer.raw_message_iter_),
596 DBUS_TYPE_BYTE,
597 &values,
598 static_cast<int>(length));
599 CHECK(success) << "Unable to allocate memory";
600 CloseContainer(&array_writer);
603 void MessageWriter::AppendArrayOfStrings(
604 const std::vector<std::string>& strings) {
605 DCHECK(!container_is_open_);
606 MessageWriter array_writer(message_);
607 OpenArray("s", &array_writer);
608 for (size_t i = 0; i < strings.size(); ++i) {
609 array_writer.AppendString(strings[i]);
611 CloseContainer(&array_writer);
614 void MessageWriter::AppendArrayOfObjectPaths(
615 const std::vector<ObjectPath>& object_paths) {
616 DCHECK(!container_is_open_);
617 MessageWriter array_writer(message_);
618 OpenArray("o", &array_writer);
619 for (size_t i = 0; i < object_paths.size(); ++i) {
620 array_writer.AppendObjectPath(object_paths[i]);
622 CloseContainer(&array_writer);
625 bool MessageWriter::AppendProtoAsArrayOfBytes(
626 const google::protobuf::MessageLite& protobuf) {
627 std::string serialized_proto;
628 if (!protobuf.SerializeToString(&serialized_proto)) {
629 LOG(ERROR) << "Unable to serialize supplied protocol buffer";
630 return false;
632 AppendArrayOfBytes(reinterpret_cast<const uint8*>(serialized_proto.data()),
633 serialized_proto.size());
634 return true;
637 void MessageWriter::AppendVariantOfByte(uint8 value) {
638 AppendVariantOfBasic(DBUS_TYPE_BYTE, &value);
641 void MessageWriter::AppendVariantOfBool(bool value) {
642 // See the comment at MessageWriter::AppendBool().
643 dbus_bool_t dbus_value = value;
644 AppendVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
647 void MessageWriter::AppendVariantOfInt16(int16 value) {
648 AppendVariantOfBasic(DBUS_TYPE_INT16, &value);
651 void MessageWriter::AppendVariantOfUint16(uint16 value) {
652 AppendVariantOfBasic(DBUS_TYPE_UINT16, &value);
655 void MessageWriter::AppendVariantOfInt32(int32 value) {
656 AppendVariantOfBasic(DBUS_TYPE_INT32, &value);
659 void MessageWriter::AppendVariantOfUint32(uint32 value) {
660 AppendVariantOfBasic(DBUS_TYPE_UINT32, &value);
663 void MessageWriter::AppendVariantOfInt64(int64 value) {
664 AppendVariantOfBasic(DBUS_TYPE_INT64, &value);
667 void MessageWriter::AppendVariantOfUint64(uint64 value) {
668 AppendVariantOfBasic(DBUS_TYPE_UINT64, &value);
671 void MessageWriter::AppendVariantOfDouble(double value) {
672 AppendVariantOfBasic(DBUS_TYPE_DOUBLE, &value);
675 void MessageWriter::AppendVariantOfString(const std::string& value) {
676 const char* pointer = value.c_str();
677 AppendVariantOfBasic(DBUS_TYPE_STRING, &pointer);
680 void MessageWriter::AppendVariantOfObjectPath(const ObjectPath& value) {
681 const char* pointer = value.value().c_str();
682 AppendVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &pointer);
685 void MessageWriter::AppendBasic(int dbus_type, const void* value) {
686 DCHECK(!container_is_open_);
688 const bool success = dbus_message_iter_append_basic(
689 &raw_message_iter_, dbus_type, value);
690 // dbus_message_iter_append_basic() fails only when there is not enough
691 // memory. We don't return this error as there is nothing we can do when
692 // it fails to allocate memory for a byte etc.
693 CHECK(success) << "Unable to allocate memory";
696 void MessageWriter::AppendVariantOfBasic(int dbus_type, const void* value) {
697 const std::string signature(1u, // length
698 base::checked_cast<char>(dbus_type));
699 MessageWriter variant_writer(message_);
700 OpenVariant(signature, &variant_writer);
701 variant_writer.AppendBasic(dbus_type, value);
702 CloseContainer(&variant_writer);
705 void MessageWriter::AppendFileDescriptor(const FileDescriptor& value) {
706 CHECK(IsDBusTypeUnixFdSupported());
708 if (!value.is_valid()) {
709 // NB: sending a directory potentially enables sandbox escape
710 LOG(FATAL) << "Attempt to pass invalid file descriptor";
712 int fd = value.value();
713 AppendBasic(DBUS_TYPE_UNIX_FD, &fd);
717 // MessageReader implementation.
720 MessageReader::MessageReader(Message* message)
721 : message_(message) {
722 memset(&raw_message_iter_, 0, sizeof(raw_message_iter_));
723 if (message)
724 dbus_message_iter_init(message_->raw_message(), &raw_message_iter_);
728 MessageReader::~MessageReader() {
731 bool MessageReader::HasMoreData() {
732 const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
733 return dbus_type != DBUS_TYPE_INVALID;
736 bool MessageReader::PopByte(uint8* value) {
737 return PopBasic(DBUS_TYPE_BYTE, value);
740 bool MessageReader::PopBool(bool* value) {
741 // Like MessageWriter::AppendBool(), we should copy |value| to
742 // dbus_bool_t, as dbus_message_iter_get_basic() used in PopBasic()
743 // expects four bytes for DBUS_TYPE_BOOLEAN.
744 dbus_bool_t dbus_value = FALSE;
745 const bool success = PopBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
746 *value = static_cast<bool>(dbus_value);
747 return success;
750 bool MessageReader::PopInt16(int16* value) {
751 return PopBasic(DBUS_TYPE_INT16, value);
754 bool MessageReader::PopUint16(uint16* value) {
755 return PopBasic(DBUS_TYPE_UINT16, value);
758 bool MessageReader::PopInt32(int32* value) {
759 return PopBasic(DBUS_TYPE_INT32, value);
762 bool MessageReader::PopUint32(uint32* value) {
763 return PopBasic(DBUS_TYPE_UINT32, value);
766 bool MessageReader::PopInt64(int64* value) {
767 return PopBasic(DBUS_TYPE_INT64, value);
770 bool MessageReader::PopUint64(uint64* value) {
771 return PopBasic(DBUS_TYPE_UINT64, value);
774 bool MessageReader::PopDouble(double* value) {
775 return PopBasic(DBUS_TYPE_DOUBLE, value);
778 bool MessageReader::PopString(std::string* value) {
779 char* tmp_value = NULL;
780 const bool success = PopBasic(DBUS_TYPE_STRING, &tmp_value);
781 if (success)
782 value->assign(tmp_value);
783 return success;
786 bool MessageReader::PopObjectPath(ObjectPath* value) {
787 char* tmp_value = NULL;
788 const bool success = PopBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
789 if (success)
790 *value = ObjectPath(tmp_value);
791 return success;
794 bool MessageReader::PopArray(MessageReader* sub_reader) {
795 return PopContainer(DBUS_TYPE_ARRAY, sub_reader);
798 bool MessageReader::PopStruct(MessageReader* sub_reader) {
799 return PopContainer(DBUS_TYPE_STRUCT, sub_reader);
802 bool MessageReader::PopDictEntry(MessageReader* sub_reader) {
803 return PopContainer(DBUS_TYPE_DICT_ENTRY, sub_reader);
806 bool MessageReader::PopVariant(MessageReader* sub_reader) {
807 return PopContainer(DBUS_TYPE_VARIANT, sub_reader);
810 bool MessageReader::PopArrayOfBytes(const uint8** bytes, size_t* length) {
811 MessageReader array_reader(message_);
812 if (!PopArray(&array_reader))
813 return false;
814 // An empty array is allowed.
815 if (!array_reader.HasMoreData()) {
816 *length = 0;
817 *bytes = NULL;
818 return true;
820 if (!array_reader.CheckDataType(DBUS_TYPE_BYTE))
821 return false;
822 int int_length = 0;
823 dbus_message_iter_get_fixed_array(&array_reader.raw_message_iter_,
824 bytes,
825 &int_length);
826 *length = static_cast<int>(int_length);
827 return true;
830 bool MessageReader::PopArrayOfStrings(
831 std::vector<std::string> *strings) {
832 strings->clear();
833 MessageReader array_reader(message_);
834 if (!PopArray(&array_reader))
835 return false;
836 while (array_reader.HasMoreData()) {
837 std::string string;
838 if (!array_reader.PopString(&string))
839 return false;
840 strings->push_back(string);
842 return true;
845 bool MessageReader::PopArrayOfObjectPaths(
846 std::vector<ObjectPath> *object_paths) {
847 object_paths->clear();
848 MessageReader array_reader(message_);
849 if (!PopArray(&array_reader))
850 return false;
851 while (array_reader.HasMoreData()) {
852 ObjectPath object_path;
853 if (!array_reader.PopObjectPath(&object_path))
854 return false;
855 object_paths->push_back(object_path);
857 return true;
860 bool MessageReader::PopArrayOfBytesAsProto(
861 google::protobuf::MessageLite* protobuf) {
862 DCHECK(protobuf != NULL);
863 const char* serialized_buf = NULL;
864 size_t buf_size = 0;
865 if (!PopArrayOfBytes(
866 reinterpret_cast<const uint8**>(&serialized_buf), &buf_size)) {
867 LOG(ERROR) << "Error reading array of bytes";
868 return false;
870 if (!protobuf->ParseFromArray(serialized_buf, buf_size)) {
871 LOG(ERROR) << "Failed to parse protocol buffer from array";
872 return false;
874 return true;
877 bool MessageReader::PopVariantOfByte(uint8* value) {
878 return PopVariantOfBasic(DBUS_TYPE_BYTE, value);
881 bool MessageReader::PopVariantOfBool(bool* value) {
882 // See the comment at MessageReader::PopBool().
883 dbus_bool_t dbus_value = FALSE;
884 const bool success = PopVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
885 *value = static_cast<bool>(dbus_value);
886 return success;
889 bool MessageReader::PopVariantOfInt16(int16* value) {
890 return PopVariantOfBasic(DBUS_TYPE_INT16, value);
893 bool MessageReader::PopVariantOfUint16(uint16* value) {
894 return PopVariantOfBasic(DBUS_TYPE_UINT16, value);
897 bool MessageReader::PopVariantOfInt32(int32* value) {
898 return PopVariantOfBasic(DBUS_TYPE_INT32, value);
901 bool MessageReader::PopVariantOfUint32(uint32* value) {
902 return PopVariantOfBasic(DBUS_TYPE_UINT32, value);
905 bool MessageReader::PopVariantOfInt64(int64* value) {
906 return PopVariantOfBasic(DBUS_TYPE_INT64, value);
909 bool MessageReader::PopVariantOfUint64(uint64* value) {
910 return PopVariantOfBasic(DBUS_TYPE_UINT64, value);
913 bool MessageReader::PopVariantOfDouble(double* value) {
914 return PopVariantOfBasic(DBUS_TYPE_DOUBLE, value);
917 bool MessageReader::PopVariantOfString(std::string* value) {
918 char* tmp_value = NULL;
919 const bool success = PopVariantOfBasic(DBUS_TYPE_STRING, &tmp_value);
920 if (success)
921 value->assign(tmp_value);
922 return success;
925 bool MessageReader::PopVariantOfObjectPath(ObjectPath* value) {
926 char* tmp_value = NULL;
927 const bool success = PopVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
928 if (success)
929 *value = ObjectPath(tmp_value);
930 return success;
933 Message::DataType MessageReader::GetDataType() {
934 const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
935 return static_cast<Message::DataType>(dbus_type);
938 std::string MessageReader::GetDataSignature() {
939 std::string signature;
940 char* raw_signature = dbus_message_iter_get_signature(&raw_message_iter_);
941 if (raw_signature) {
942 signature = raw_signature;
943 dbus_free(raw_signature);
945 return signature;
948 bool MessageReader::CheckDataType(int dbus_type) {
949 const int actual_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
950 if (actual_type != dbus_type) {
951 VLOG(1) << "Type " << dbus_type << " is expected but got "
952 << actual_type;
953 return false;
955 return true;
958 bool MessageReader::PopBasic(int dbus_type, void* value) {
959 if (!CheckDataType(dbus_type))
960 return false;
961 // dbus_message_iter_get_basic() here should always work, as we have
962 // already checked the next item's data type in CheckDataType(). Note
963 // that dbus_message_iter_get_basic() is a void function.
964 dbus_message_iter_get_basic(&raw_message_iter_, value);
965 DCHECK(value);
966 dbus_message_iter_next(&raw_message_iter_);
967 return true;
970 bool MessageReader::PopContainer(int dbus_type, MessageReader* sub_reader) {
971 DCHECK_NE(this, sub_reader);
973 if (!CheckDataType(dbus_type))
974 return false;
975 dbus_message_iter_recurse(&raw_message_iter_,
976 &sub_reader->raw_message_iter_);
977 dbus_message_iter_next(&raw_message_iter_);
978 return true;
981 bool MessageReader::PopVariantOfBasic(int dbus_type, void* value) {
982 MessageReader variant_reader(message_);
983 if (!PopVariant(&variant_reader))
984 return false;
985 return variant_reader.PopBasic(dbus_type, value);
988 bool MessageReader::PopFileDescriptor(FileDescriptor* value) {
989 CHECK(IsDBusTypeUnixFdSupported());
991 int fd = -1;
992 const bool success = PopBasic(DBUS_TYPE_UNIX_FD, &fd);
993 if (!success)
994 return false;
996 value->PutValue(fd);
997 // NB: the caller must check validity before using the value
998 return true;
1001 } // namespace dbus