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.
4
5 #include "dbus/message.h"
6
7 #include <string>
8
9 #include "base/format_macros.h"
10 #include "base/logging.h"
11 #include "base/numerics/safe_conversions.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "dbus/object_path.h"
16
17 #if defined(USE_SYSTEM_PROTOBUF)
18 #include <google/protobuf/message_lite.h>
19 #else
20 #include "third_party/protobuf/src/google/protobuf/message_lite.h"
21 #endif
22
23 namespace {
24
25 // Appends the header name and the value to |output|, if the value is
26 // not empty.
AppendStringHeader(const std::string & header_name,const std::string & header_value,std::string * output)27 void AppendStringHeader(const std::string& header_name,
28 const std::string& header_value,
29 std::string* output) {
30 if (!header_value.empty()) {
31 *output += header_name + ": " + header_value + "\n";
32 }
33 }
34
35 // Appends the header name and the value to |output|, if the value is
36 // nonzero.
AppendUint32Header(const std::string & header_name,uint32_t header_value,std::string * output)37 void AppendUint32Header(const std::string& header_name,
38 uint32_t header_value,
39 std::string* output) {
40 if (header_value != 0) {
41 *output += (header_name + ": " + base::UintToString(header_value) + "\n");
42 }
43 }
44
45 } // namespace
46
47 namespace dbus {
48
IsDBusTypeUnixFdSupported()49 bool IsDBusTypeUnixFdSupported() {
50 int major = 0, minor = 0, micro = 0;
51 dbus_get_version(&major, &minor, µ);
52 return major >= 1 && minor >= 4;
53 }
54
Message()55 Message::Message()
56 : raw_message_(NULL) {
57 }
58
~Message()59 Message::~Message() {
60 if (raw_message_)
61 dbus_message_unref(raw_message_);
62 }
63
Init(DBusMessage * raw_message)64 void Message::Init(DBusMessage* raw_message) {
65 DCHECK(!raw_message_);
66 raw_message_ = raw_message;
67 }
68
GetMessageType()69 Message::MessageType Message::GetMessageType() {
70 if (!raw_message_)
71 return MESSAGE_INVALID;
72 const int type = dbus_message_get_type(raw_message_);
73 return static_cast<Message::MessageType>(type);
74 }
75
GetMessageTypeAsString()76 std::string Message::GetMessageTypeAsString() {
77 switch (GetMessageType()) {
78 case MESSAGE_INVALID:
79 return "MESSAGE_INVALID";
80 case MESSAGE_METHOD_CALL:
81 return "MESSAGE_METHOD_CALL";
82 case MESSAGE_METHOD_RETURN:
83 return "MESSAGE_METHOD_RETURN";
84 case MESSAGE_SIGNAL:
85 return "MESSAGE_SIGNAL";
86 case MESSAGE_ERROR:
87 return "MESSAGE_ERROR";
88 }
89 NOTREACHED();
90 return std::string();
91 }
92
ToStringInternal(const std::string & indent,MessageReader * reader)93 std::string Message::ToStringInternal(const std::string& indent,
94 MessageReader* reader) {
95 const char* kBrokenMessage = "[broken message]";
96 std::string output;
97 while (reader->HasMoreData()) {
98 const DataType type = reader->GetDataType();
99 switch (type) {
100 case BYTE: {
101 uint8_t value = 0;
102 if (!reader->PopByte(&value))
103 return kBrokenMessage;
104 output += indent + "byte " + base::UintToString(value) + "\n";
105 break;
106 }
107 case BOOL: {
108 bool value = false;
109 if (!reader->PopBool(&value))
110 return kBrokenMessage;
111 output += indent + "bool " + (value ? "true" : "false") + "\n";
112 break;
113 }
114 case INT16: {
115 int16_t value = 0;
116 if (!reader->PopInt16(&value))
117 return kBrokenMessage;
118 output += indent + "int16_t " + base::IntToString(value) + "\n";
119 break;
120 }
121 case UINT16: {
122 uint16_t value = 0;
123 if (!reader->PopUint16(&value))
124 return kBrokenMessage;
125 output += indent + "uint16_t " + base::UintToString(value) + "\n";
126 break;
127 }
128 case INT32: {
129 int32_t value = 0;
130 if (!reader->PopInt32(&value))
131 return kBrokenMessage;
132 output += indent + "int32_t " + base::IntToString(value) + "\n";
133 break;
134 }
135 case UINT32: {
136 uint32_t value = 0;
137 if (!reader->PopUint32(&value))
138 return kBrokenMessage;
139 output += indent + "uint32_t " + base::UintToString(value) + "\n";
140 break;
141 }
142 case INT64: {
143 int64_t value = 0;
144 if (!reader->PopInt64(&value))
145 return kBrokenMessage;
146 output += (indent + "int64_t " + base::Int64ToString(value) + "\n");
147 break;
148 }
149 case UINT64: {
150 uint64_t value = 0;
151 if (!reader->PopUint64(&value))
152 return kBrokenMessage;
153 output += (indent + "uint64_t " + base::Uint64ToString(value) + "\n");
154 break;
155 }
156 case DOUBLE: {
157 double value = 0;
158 if (!reader->PopDouble(&value))
159 return kBrokenMessage;
160 output += indent + "double " + base::DoubleToString(value) + "\n";
161 break;
162 }
163 case STRING: {
164 std::string value;
165 if (!reader->PopString(&value))
166 return kBrokenMessage;
167 // Truncate if the string is longer than the limit.
168 const size_t kTruncateLength = 100;
169 if (value.size() < kTruncateLength) {
170 output += indent + "string \"" + value + "\"\n";
171 } else {
172 std::string truncated;
173 base::TruncateUTF8ToByteSize(value, kTruncateLength, &truncated);
174 base::StringAppendF(&truncated, "... (%" PRIuS " bytes in total)",
175 value.size());
176 output += indent + "string \"" + truncated + "\"\n";
177 }
178 break;
179 }
180 case OBJECT_PATH: {
181 ObjectPath value;
182 if (!reader->PopObjectPath(&value))
183 return kBrokenMessage;
184 output += indent + "object_path \"" + value.value() + "\"\n";
185 break;
186 }
187 case ARRAY: {
188 MessageReader sub_reader(this);
189 if (!reader->PopArray(&sub_reader))
190 return kBrokenMessage;
191 output += indent + "array [\n";
192 output += ToStringInternal(indent + " ", &sub_reader);
193 output += indent + "]\n";
194 break;
195 }
196 case STRUCT: {
197 MessageReader sub_reader(this);
198 if (!reader->PopStruct(&sub_reader))
199 return kBrokenMessage;
200 output += indent + "struct {\n";
201 output += ToStringInternal(indent + " ", &sub_reader);
202 output += indent + "}\n";
203 break;
204 }
205 case DICT_ENTRY: {
206 MessageReader sub_reader(this);
207 if (!reader->PopDictEntry(&sub_reader))
208 return kBrokenMessage;
209 output += indent + "dict entry {\n";
210 output += ToStringInternal(indent + " ", &sub_reader);
211 output += indent + "}\n";
212 break;
213 }
214 case VARIANT: {
215 MessageReader sub_reader(this);
216 if (!reader->PopVariant(&sub_reader))
217 return kBrokenMessage;
218 output += indent + "variant ";
219 output += ToStringInternal(indent + " ", &sub_reader);
220 break;
221 }
222 case UNIX_FD: {
223 CHECK(IsDBusTypeUnixFdSupported());
224
225 base::ScopedFD file_descriptor;
226 if (!reader->PopFileDescriptor(&file_descriptor))
227 return kBrokenMessage;
228 output += indent + "fd#" +
229 base::IntToString(file_descriptor.get()) + "\n";
230 break;
231 }
232 default:
233 LOG(FATAL) << "Unknown type: " << type;
234 }
235 }
236 return output;
237 }
238
239 // The returned string consists of message headers such as
240 // destination if any, followed by a blank line, and the message
241 // payload. For example, a MethodCall's ToString() will look like:
242 //
243 // destination: com.example.Service
244 // path: /com/example/Object
245 // interface: com.example.Interface
246 // member: SomeMethod
247 //
248 // string \"payload\"
249 // ...
ToString()250 std::string Message::ToString() {
251 if (!raw_message_)
252 return std::string();
253
254 // Generate headers first.
255 std::string headers;
256 AppendStringHeader("message_type", GetMessageTypeAsString(), &headers);
257 AppendStringHeader("destination", GetDestination(), &headers);
258 AppendStringHeader("path", GetPath().value(), &headers);
259 AppendStringHeader("interface", GetInterface(), &headers);
260 AppendStringHeader("member", GetMember(), &headers);
261 AppendStringHeader("error_name", GetErrorName(), &headers);
262 AppendStringHeader("sender", GetSender(), &headers);
263 AppendStringHeader("signature", GetSignature(), &headers);
264 AppendUint32Header("serial", GetSerial(), &headers);
265 AppendUint32Header("reply_serial", GetReplySerial(), &headers);
266
267 // Generate the payload.
268 MessageReader reader(this);
269 return headers + "\n" + ToStringInternal(std::string(), &reader);
270 }
271
SetDestination(const std::string & destination)272 bool Message::SetDestination(const std::string& destination) {
273 return dbus_message_set_destination(raw_message_, destination.c_str());
274 }
275
SetPath(const ObjectPath & path)276 bool Message::SetPath(const ObjectPath& path) {
277 return dbus_message_set_path(raw_message_, path.value().c_str());
278 }
279
SetInterface(const std::string & interface)280 bool Message::SetInterface(const std::string& interface) {
281 return dbus_message_set_interface(raw_message_, interface.c_str());
282 }
283
SetMember(const std::string & member)284 bool Message::SetMember(const std::string& member) {
285 return dbus_message_set_member(raw_message_, member.c_str());
286 }
287
SetErrorName(const std::string & error_name)288 bool Message::SetErrorName(const std::string& error_name) {
289 return dbus_message_set_error_name(raw_message_, error_name.c_str());
290 }
291
SetSender(const std::string & sender)292 bool Message::SetSender(const std::string& sender) {
293 return dbus_message_set_sender(raw_message_, sender.c_str());
294 }
295
SetSerial(uint32_t serial)296 void Message::SetSerial(uint32_t serial) {
297 dbus_message_set_serial(raw_message_, serial);
298 }
299
SetReplySerial(uint32_t reply_serial)300 void Message::SetReplySerial(uint32_t reply_serial) {
301 dbus_message_set_reply_serial(raw_message_, reply_serial);
302 }
303
GetDestination()304 std::string Message::GetDestination() {
305 const char* destination = dbus_message_get_destination(raw_message_);
306 return destination ? destination : "";
307 }
308
GetPath()309 ObjectPath Message::GetPath() {
310 const char* path = dbus_message_get_path(raw_message_);
311 return ObjectPath(path ? path : "");
312 }
313
GetInterface()314 std::string Message::GetInterface() {
315 const char* interface = dbus_message_get_interface(raw_message_);
316 return interface ? interface : "";
317 }
318
GetMember()319 std::string Message::GetMember() {
320 const char* member = dbus_message_get_member(raw_message_);
321 return member ? member : "";
322 }
323
GetErrorName()324 std::string Message::GetErrorName() {
325 const char* error_name = dbus_message_get_error_name(raw_message_);
326 return error_name ? error_name : "";
327 }
328
GetSender()329 std::string Message::GetSender() {
330 const char* sender = dbus_message_get_sender(raw_message_);
331 return sender ? sender : "";
332 }
333
GetSignature()334 std::string Message::GetSignature() {
335 const char* signature = dbus_message_get_signature(raw_message_);
336 return signature ? signature : "";
337 }
338
GetSerial()339 uint32_t Message::GetSerial() {
340 return dbus_message_get_serial(raw_message_);
341 }
342
GetReplySerial()343 uint32_t Message::GetReplySerial() {
344 return dbus_message_get_reply_serial(raw_message_);
345 }
346
347 //
348 // MethodCall implementation.
349 //
350
MethodCall(const std::string & interface_name,const std::string & method_name)351 MethodCall::MethodCall(const std::string& interface_name,
352 const std::string& method_name)
353 : Message() {
354 Init(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL));
355
356 CHECK(SetInterface(interface_name));
357 CHECK(SetMember(method_name));
358 }
359
MethodCall()360 MethodCall::MethodCall() : Message() {
361 }
362
FromRawMessage(DBusMessage * raw_message)363 MethodCall* MethodCall::FromRawMessage(DBusMessage* raw_message) {
364 DCHECK_EQ(DBUS_MESSAGE_TYPE_METHOD_CALL, dbus_message_get_type(raw_message));
365
366 MethodCall* method_call = new MethodCall;
367 method_call->Init(raw_message);
368 return method_call;
369 }
370
371 //
372 // Signal implementation.
373 //
Signal(const std::string & interface_name,const std::string & method_name)374 Signal::Signal(const std::string& interface_name,
375 const std::string& method_name)
376 : Message() {
377 Init(dbus_message_new(DBUS_MESSAGE_TYPE_SIGNAL));
378
379 CHECK(SetInterface(interface_name));
380 CHECK(SetMember(method_name));
381 }
382
Signal()383 Signal::Signal() : Message() {
384 }
385
FromRawMessage(DBusMessage * raw_message)386 Signal* Signal::FromRawMessage(DBusMessage* raw_message) {
387 DCHECK_EQ(DBUS_MESSAGE_TYPE_SIGNAL, dbus_message_get_type(raw_message));
388
389 Signal* signal = new Signal;
390 signal->Init(raw_message);
391 return signal;
392 }
393
394 //
395 // Response implementation.
396 //
397
Response()398 Response::Response() : Message() {
399 }
400
FromRawMessage(DBusMessage * raw_message)401 std::unique_ptr<Response> Response::FromRawMessage(DBusMessage* raw_message) {
402 DCHECK_EQ(DBUS_MESSAGE_TYPE_METHOD_RETURN,
403 dbus_message_get_type(raw_message));
404
405 std::unique_ptr<Response> response(new Response);
406 response->Init(raw_message);
407 return response;
408 }
409
FromMethodCall(MethodCall * method_call)410 std::unique_ptr<Response> Response::FromMethodCall(MethodCall* method_call) {
411 std::unique_ptr<Response> response(new Response);
412 response->Init(dbus_message_new_method_return(method_call->raw_message()));
413 return response;
414 }
415
CreateEmpty()416 std::unique_ptr<Response> Response::CreateEmpty() {
417 std::unique_ptr<Response> response(new Response);
418 response->Init(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN));
419 return response;
420 }
421
422 //
423 // ErrorResponse implementation.
424 //
425
ErrorResponse()426 ErrorResponse::ErrorResponse() : Response() {
427 }
428
FromRawMessage(DBusMessage * raw_message)429 std::unique_ptr<ErrorResponse> ErrorResponse::FromRawMessage(
430 DBusMessage* raw_message) {
431 DCHECK_EQ(DBUS_MESSAGE_TYPE_ERROR, dbus_message_get_type(raw_message));
432
433 std::unique_ptr<ErrorResponse> response(new ErrorResponse);
434 response->Init(raw_message);
435 return response;
436 }
437
FromMethodCall(MethodCall * method_call,const std::string & error_name,const std::string & error_message)438 std::unique_ptr<ErrorResponse> ErrorResponse::FromMethodCall(
439 MethodCall* method_call,
440 const std::string& error_name,
441 const std::string& error_message) {
442 std::unique_ptr<ErrorResponse> response(new ErrorResponse);
443 response->Init(dbus_message_new_error(method_call->raw_message(),
444 error_name.c_str(),
445 error_message.c_str()));
446 return response;
447 }
448
449 //
450 // MessageWriter implementation.
451 //
452
MessageWriter(Message * message)453 MessageWriter::MessageWriter(Message* message)
454 : message_(message),
455 container_is_open_(false) {
456 memset(&raw_message_iter_, 0, sizeof(raw_message_iter_));
457 if (message)
458 dbus_message_iter_init_append(message_->raw_message(), &raw_message_iter_);
459 }
460
~MessageWriter()461 MessageWriter::~MessageWriter() {
462 }
463
AppendByte(uint8_t value)464 void MessageWriter::AppendByte(uint8_t value) {
465 AppendBasic(DBUS_TYPE_BYTE, &value);
466 }
467
AppendBool(bool value)468 void MessageWriter::AppendBool(bool value) {
469 // The size of dbus_bool_t and the size of bool are different. The
470 // former is always 4 per dbus-types.h, whereas the latter is usually 1.
471 // dbus_message_iter_append_basic() used in AppendBasic() expects four
472 // bytes for DBUS_TYPE_BOOLEAN, so we must pass a dbus_bool_t, instead
473 // of a bool, to AppendBasic().
474 dbus_bool_t dbus_value = value;
475 AppendBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
476 }
477
AppendInt16(int16_t value)478 void MessageWriter::AppendInt16(int16_t value) {
479 AppendBasic(DBUS_TYPE_INT16, &value);
480 }
481
AppendUint16(uint16_t value)482 void MessageWriter::AppendUint16(uint16_t value) {
483 AppendBasic(DBUS_TYPE_UINT16, &value);
484 }
485
AppendInt32(int32_t value)486 void MessageWriter::AppendInt32(int32_t value) {
487 AppendBasic(DBUS_TYPE_INT32, &value);
488 }
489
AppendUint32(uint32_t value)490 void MessageWriter::AppendUint32(uint32_t value) {
491 AppendBasic(DBUS_TYPE_UINT32, &value);
492 }
493
AppendInt64(int64_t value)494 void MessageWriter::AppendInt64(int64_t value) {
495 AppendBasic(DBUS_TYPE_INT64, &value);
496 }
497
AppendUint64(uint64_t value)498 void MessageWriter::AppendUint64(uint64_t value) {
499 AppendBasic(DBUS_TYPE_UINT64, &value);
500 }
501
AppendDouble(double value)502 void MessageWriter::AppendDouble(double value) {
503 AppendBasic(DBUS_TYPE_DOUBLE, &value);
504 }
505
AppendString(const std::string & value)506 void MessageWriter::AppendString(const std::string& value) {
507 // D-Bus Specification (0.19) says a string "must be valid UTF-8".
508 CHECK(base::IsStringUTF8(value));
509 const char* pointer = value.c_str();
510 AppendBasic(DBUS_TYPE_STRING, &pointer);
511 // TODO(satorux): It may make sense to return an error here, as the
512 // input string can be large. If needed, we could add something like
513 // bool AppendStringWithErrorChecking().
514 }
515
AppendObjectPath(const ObjectPath & value)516 void MessageWriter::AppendObjectPath(const ObjectPath& value) {
517 CHECK(value.IsValid());
518 const char* pointer = value.value().c_str();
519 AppendBasic(DBUS_TYPE_OBJECT_PATH, &pointer);
520 }
521
522 // Ideally, client shouldn't need to supply the signature string, but
523 // the underlying D-Bus library requires us to supply this before
524 // appending contents to array and variant. It's technically possible
525 // for us to design API that doesn't require the signature but it will
526 // complicate the implementation so we decided to have the signature
527 // parameter. Hopefully, variants are less used in request messages from
528 // client side than response message from server side, so this should
529 // not be a big issue.
OpenArray(const std::string & signature,MessageWriter * writer)530 void MessageWriter::OpenArray(const std::string& signature,
531 MessageWriter* writer) {
532 DCHECK(!container_is_open_);
533
534 const bool success = dbus_message_iter_open_container(
535 &raw_message_iter_,
536 DBUS_TYPE_ARRAY,
537 signature.c_str(),
538 &writer->raw_message_iter_);
539 CHECK(success) << "Unable to allocate memory";
540 container_is_open_ = true;
541 }
542
OpenVariant(const std::string & signature,MessageWriter * writer)543 void MessageWriter::OpenVariant(const std::string& signature,
544 MessageWriter* writer) {
545 DCHECK(!container_is_open_);
546
547 const bool success = dbus_message_iter_open_container(
548 &raw_message_iter_,
549 DBUS_TYPE_VARIANT,
550 signature.c_str(),
551 &writer->raw_message_iter_);
552 CHECK(success) << "Unable to allocate memory";
553 container_is_open_ = true;
554 }
555
OpenStruct(MessageWriter * writer)556 void MessageWriter::OpenStruct(MessageWriter* writer) {
557 DCHECK(!container_is_open_);
558
559 const bool success = dbus_message_iter_open_container(
560 &raw_message_iter_,
561 DBUS_TYPE_STRUCT,
562 NULL, // Signature should be NULL.
563 &writer->raw_message_iter_);
564 CHECK(success) << "Unable to allocate memory";
565 container_is_open_ = true;
566 }
567
OpenDictEntry(MessageWriter * writer)568 void MessageWriter::OpenDictEntry(MessageWriter* writer) {
569 DCHECK(!container_is_open_);
570
571 const bool success = dbus_message_iter_open_container(
572 &raw_message_iter_,
573 DBUS_TYPE_DICT_ENTRY,
574 NULL, // Signature should be NULL.
575 &writer->raw_message_iter_);
576 CHECK(success) << "Unable to allocate memory";
577 container_is_open_ = true;
578 }
579
CloseContainer(MessageWriter * writer)580 void MessageWriter::CloseContainer(MessageWriter* writer) {
581 DCHECK(container_is_open_);
582
583 const bool success = dbus_message_iter_close_container(
584 &raw_message_iter_, &writer->raw_message_iter_);
585 CHECK(success) << "Unable to allocate memory";
586 container_is_open_ = false;
587 }
588
AppendArrayOfBytes(const uint8_t * values,size_t length)589 void MessageWriter::AppendArrayOfBytes(const uint8_t* values, size_t length) {
590 DCHECK(!container_is_open_);
591 MessageWriter array_writer(message_);
592 OpenArray("y", &array_writer);
593 const bool success = dbus_message_iter_append_fixed_array(
594 &(array_writer.raw_message_iter_),
595 DBUS_TYPE_BYTE,
596 &values,
597 static_cast<int>(length));
598 CHECK(success) << "Unable to allocate memory";
599 CloseContainer(&array_writer);
600 }
601
AppendArrayOfDoubles(const double * values,size_t length)602 void MessageWriter::AppendArrayOfDoubles(const double* values, size_t length) {
603 DCHECK(!container_is_open_);
604 MessageWriter array_writer(message_);
605 OpenArray("d", &array_writer);
606 const bool success = dbus_message_iter_append_fixed_array(
607 &(array_writer.raw_message_iter_),
608 DBUS_TYPE_DOUBLE,
609 &values,
610 static_cast<int>(length));
611 CHECK(success) << "Unable to allocate memory";
612 CloseContainer(&array_writer);
613 }
614
AppendArrayOfStrings(const std::vector<std::string> & strings)615 void MessageWriter::AppendArrayOfStrings(
616 const std::vector<std::string>& strings) {
617 DCHECK(!container_is_open_);
618 MessageWriter array_writer(message_);
619 OpenArray("s", &array_writer);
620 for (size_t i = 0; i < strings.size(); ++i) {
621 array_writer.AppendString(strings[i]);
622 }
623 CloseContainer(&array_writer);
624 }
625
AppendArrayOfObjectPaths(const std::vector<ObjectPath> & object_paths)626 void MessageWriter::AppendArrayOfObjectPaths(
627 const std::vector<ObjectPath>& object_paths) {
628 DCHECK(!container_is_open_);
629 MessageWriter array_writer(message_);
630 OpenArray("o", &array_writer);
631 for (size_t i = 0; i < object_paths.size(); ++i) {
632 array_writer.AppendObjectPath(object_paths[i]);
633 }
634 CloseContainer(&array_writer);
635 }
636
AppendProtoAsArrayOfBytes(const google::protobuf::MessageLite & protobuf)637 bool MessageWriter::AppendProtoAsArrayOfBytes(
638 const google::protobuf::MessageLite& protobuf) {
639 std::string serialized_proto;
640 if (!protobuf.SerializeToString(&serialized_proto)) {
641 LOG(ERROR) << "Unable to serialize supplied protocol buffer";
642 return false;
643 }
644 AppendArrayOfBytes(reinterpret_cast<const uint8_t*>(serialized_proto.data()),
645 serialized_proto.size());
646 return true;
647 }
648
AppendVariantOfByte(uint8_t value)649 void MessageWriter::AppendVariantOfByte(uint8_t value) {
650 AppendVariantOfBasic(DBUS_TYPE_BYTE, &value);
651 }
652
AppendVariantOfBool(bool value)653 void MessageWriter::AppendVariantOfBool(bool value) {
654 // See the comment at MessageWriter::AppendBool().
655 dbus_bool_t dbus_value = value;
656 AppendVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
657 }
658
AppendVariantOfInt16(int16_t value)659 void MessageWriter::AppendVariantOfInt16(int16_t value) {
660 AppendVariantOfBasic(DBUS_TYPE_INT16, &value);
661 }
662
AppendVariantOfUint16(uint16_t value)663 void MessageWriter::AppendVariantOfUint16(uint16_t value) {
664 AppendVariantOfBasic(DBUS_TYPE_UINT16, &value);
665 }
666
AppendVariantOfInt32(int32_t value)667 void MessageWriter::AppendVariantOfInt32(int32_t value) {
668 AppendVariantOfBasic(DBUS_TYPE_INT32, &value);
669 }
670
AppendVariantOfUint32(uint32_t value)671 void MessageWriter::AppendVariantOfUint32(uint32_t value) {
672 AppendVariantOfBasic(DBUS_TYPE_UINT32, &value);
673 }
674
AppendVariantOfInt64(int64_t value)675 void MessageWriter::AppendVariantOfInt64(int64_t value) {
676 AppendVariantOfBasic(DBUS_TYPE_INT64, &value);
677 }
678
AppendVariantOfUint64(uint64_t value)679 void MessageWriter::AppendVariantOfUint64(uint64_t value) {
680 AppendVariantOfBasic(DBUS_TYPE_UINT64, &value);
681 }
682
AppendVariantOfDouble(double value)683 void MessageWriter::AppendVariantOfDouble(double value) {
684 AppendVariantOfBasic(DBUS_TYPE_DOUBLE, &value);
685 }
686
AppendVariantOfString(const std::string & value)687 void MessageWriter::AppendVariantOfString(const std::string& value) {
688 const char* pointer = value.c_str();
689 AppendVariantOfBasic(DBUS_TYPE_STRING, &pointer);
690 }
691
AppendVariantOfObjectPath(const ObjectPath & value)692 void MessageWriter::AppendVariantOfObjectPath(const ObjectPath& value) {
693 const char* pointer = value.value().c_str();
694 AppendVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &pointer);
695 }
696
AppendBasic(int dbus_type,const void * value)697 void MessageWriter::AppendBasic(int dbus_type, const void* value) {
698 DCHECK(!container_is_open_);
699
700 const bool success = dbus_message_iter_append_basic(
701 &raw_message_iter_, dbus_type, value);
702 // dbus_message_iter_append_basic() fails only when there is not enough
703 // memory. We don't return this error as there is nothing we can do when
704 // it fails to allocate memory for a byte etc.
705 CHECK(success) << "Unable to allocate memory";
706 }
707
AppendVariantOfBasic(int dbus_type,const void * value)708 void MessageWriter::AppendVariantOfBasic(int dbus_type, const void* value) {
709 const std::string signature(1u, // length
710 base::checked_cast<char>(dbus_type));
711 MessageWriter variant_writer(message_);
712 OpenVariant(signature, &variant_writer);
713 variant_writer.AppendBasic(dbus_type, value);
714 CloseContainer(&variant_writer);
715 }
716
AppendFileDescriptor(int value)717 void MessageWriter::AppendFileDescriptor(int value) {
718 CHECK(IsDBusTypeUnixFdSupported());
719 AppendBasic(DBUS_TYPE_UNIX_FD, &value); // This duplicates the FD.
720 }
721
722 //
723 // MessageReader implementation.
724 //
725
MessageReader(Message * message)726 MessageReader::MessageReader(Message* message)
727 : message_(message) {
728 memset(&raw_message_iter_, 0, sizeof(raw_message_iter_));
729 if (message)
730 dbus_message_iter_init(message_->raw_message(), &raw_message_iter_);
731 }
732
733
~MessageReader()734 MessageReader::~MessageReader() {
735 }
736
HasMoreData()737 bool MessageReader::HasMoreData() {
738 const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
739 return dbus_type != DBUS_TYPE_INVALID;
740 }
741
PopByte(uint8_t * value)742 bool MessageReader::PopByte(uint8_t* value) {
743 return PopBasic(DBUS_TYPE_BYTE, value);
744 }
745
PopBool(bool * value)746 bool MessageReader::PopBool(bool* value) {
747 // Like MessageWriter::AppendBool(), we should copy |value| to
748 // dbus_bool_t, as dbus_message_iter_get_basic() used in PopBasic()
749 // expects four bytes for DBUS_TYPE_BOOLEAN.
750 dbus_bool_t dbus_value = FALSE;
751 const bool success = PopBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
752 *value = static_cast<bool>(dbus_value);
753 return success;
754 }
755
PopInt16(int16_t * value)756 bool MessageReader::PopInt16(int16_t* value) {
757 return PopBasic(DBUS_TYPE_INT16, value);
758 }
759
PopUint16(uint16_t * value)760 bool MessageReader::PopUint16(uint16_t* value) {
761 return PopBasic(DBUS_TYPE_UINT16, value);
762 }
763
PopInt32(int32_t * value)764 bool MessageReader::PopInt32(int32_t* value) {
765 return PopBasic(DBUS_TYPE_INT32, value);
766 }
767
PopUint32(uint32_t * value)768 bool MessageReader::PopUint32(uint32_t* value) {
769 return PopBasic(DBUS_TYPE_UINT32, value);
770 }
771
PopInt64(int64_t * value)772 bool MessageReader::PopInt64(int64_t* value) {
773 return PopBasic(DBUS_TYPE_INT64, value);
774 }
775
PopUint64(uint64_t * value)776 bool MessageReader::PopUint64(uint64_t* value) {
777 return PopBasic(DBUS_TYPE_UINT64, value);
778 }
779
PopDouble(double * value)780 bool MessageReader::PopDouble(double* value) {
781 return PopBasic(DBUS_TYPE_DOUBLE, value);
782 }
783
PopString(std::string * value)784 bool MessageReader::PopString(std::string* value) {
785 char* tmp_value = NULL;
786 const bool success = PopBasic(DBUS_TYPE_STRING, &tmp_value);
787 if (success)
788 value->assign(tmp_value);
789 return success;
790 }
791
PopObjectPath(ObjectPath * value)792 bool MessageReader::PopObjectPath(ObjectPath* value) {
793 char* tmp_value = NULL;
794 const bool success = PopBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
795 if (success)
796 *value = ObjectPath(tmp_value);
797 return success;
798 }
799
PopArray(MessageReader * sub_reader)800 bool MessageReader::PopArray(MessageReader* sub_reader) {
801 return PopContainer(DBUS_TYPE_ARRAY, sub_reader);
802 }
803
PopStruct(MessageReader * sub_reader)804 bool MessageReader::PopStruct(MessageReader* sub_reader) {
805 return PopContainer(DBUS_TYPE_STRUCT, sub_reader);
806 }
807
PopDictEntry(MessageReader * sub_reader)808 bool MessageReader::PopDictEntry(MessageReader* sub_reader) {
809 return PopContainer(DBUS_TYPE_DICT_ENTRY, sub_reader);
810 }
811
PopVariant(MessageReader * sub_reader)812 bool MessageReader::PopVariant(MessageReader* sub_reader) {
813 return PopContainer(DBUS_TYPE_VARIANT, sub_reader);
814 }
815
PopArrayOfBytes(const uint8_t ** bytes,size_t * length)816 bool MessageReader::PopArrayOfBytes(const uint8_t** bytes, size_t* length) {
817 MessageReader array_reader(message_);
818 if (!PopArray(&array_reader))
819 return false;
820 // An empty array is allowed.
821 if (!array_reader.HasMoreData()) {
822 *length = 0;
823 *bytes = NULL;
824 return true;
825 }
826 if (!array_reader.CheckDataType(DBUS_TYPE_BYTE))
827 return false;
828 int int_length = 0;
829 dbus_message_iter_get_fixed_array(&array_reader.raw_message_iter_,
830 bytes,
831 &int_length);
832 *length = static_cast<size_t>(int_length);
833 return true;
834 }
835
PopArrayOfDoubles(const double ** doubles,size_t * length)836 bool MessageReader::PopArrayOfDoubles(const double** doubles, size_t* length) {
837 MessageReader array_reader(message_);
838 if (!PopArray(&array_reader))
839 return false;
840 if (!array_reader.HasMoreData()) {
841 *length = 0;
842 *doubles = nullptr;
843 return true;
844 }
845 if (!array_reader.CheckDataType(DBUS_TYPE_DOUBLE))
846 return false;
847 int int_length = 0;
848 dbus_message_iter_get_fixed_array(&array_reader.raw_message_iter_,
849 doubles,
850 &int_length);
851 *length = static_cast<size_t>(int_length);
852 return true;
853 }
854
PopArrayOfStrings(std::vector<std::string> * strings)855 bool MessageReader::PopArrayOfStrings(
856 std::vector<std::string> *strings) {
857 strings->clear();
858 MessageReader array_reader(message_);
859 if (!PopArray(&array_reader))
860 return false;
861 while (array_reader.HasMoreData()) {
862 std::string string;
863 if (!array_reader.PopString(&string))
864 return false;
865 strings->push_back(string);
866 }
867 return true;
868 }
869
PopArrayOfObjectPaths(std::vector<ObjectPath> * object_paths)870 bool MessageReader::PopArrayOfObjectPaths(
871 std::vector<ObjectPath> *object_paths) {
872 object_paths->clear();
873 MessageReader array_reader(message_);
874 if (!PopArray(&array_reader))
875 return false;
876 while (array_reader.HasMoreData()) {
877 ObjectPath object_path;
878 if (!array_reader.PopObjectPath(&object_path))
879 return false;
880 object_paths->push_back(object_path);
881 }
882 return true;
883 }
884
PopArrayOfBytesAsProto(google::protobuf::MessageLite * protobuf)885 bool MessageReader::PopArrayOfBytesAsProto(
886 google::protobuf::MessageLite* protobuf) {
887 DCHECK(protobuf != NULL);
888 const char* serialized_buf = NULL;
889 size_t buf_size = 0;
890 if (!PopArrayOfBytes(reinterpret_cast<const uint8_t**>(&serialized_buf),
891 &buf_size)) {
892 LOG(ERROR) << "Error reading array of bytes";
893 return false;
894 }
895 if (!protobuf->ParseFromArray(serialized_buf, buf_size)) {
896 LOG(ERROR) << "Failed to parse protocol buffer from array";
897 return false;
898 }
899 return true;
900 }
901
PopVariantOfByte(uint8_t * value)902 bool MessageReader::PopVariantOfByte(uint8_t* value) {
903 return PopVariantOfBasic(DBUS_TYPE_BYTE, value);
904 }
905
PopVariantOfBool(bool * value)906 bool MessageReader::PopVariantOfBool(bool* value) {
907 // See the comment at MessageReader::PopBool().
908 dbus_bool_t dbus_value = FALSE;
909 const bool success = PopVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
910 *value = static_cast<bool>(dbus_value);
911 return success;
912 }
913
PopVariantOfInt16(int16_t * value)914 bool MessageReader::PopVariantOfInt16(int16_t* value) {
915 return PopVariantOfBasic(DBUS_TYPE_INT16, value);
916 }
917
PopVariantOfUint16(uint16_t * value)918 bool MessageReader::PopVariantOfUint16(uint16_t* value) {
919 return PopVariantOfBasic(DBUS_TYPE_UINT16, value);
920 }
921
PopVariantOfInt32(int32_t * value)922 bool MessageReader::PopVariantOfInt32(int32_t* value) {
923 return PopVariantOfBasic(DBUS_TYPE_INT32, value);
924 }
925
PopVariantOfUint32(uint32_t * value)926 bool MessageReader::PopVariantOfUint32(uint32_t* value) {
927 return PopVariantOfBasic(DBUS_TYPE_UINT32, value);
928 }
929
PopVariantOfInt64(int64_t * value)930 bool MessageReader::PopVariantOfInt64(int64_t* value) {
931 return PopVariantOfBasic(DBUS_TYPE_INT64, value);
932 }
933
PopVariantOfUint64(uint64_t * value)934 bool MessageReader::PopVariantOfUint64(uint64_t* value) {
935 return PopVariantOfBasic(DBUS_TYPE_UINT64, value);
936 }
937
PopVariantOfDouble(double * value)938 bool MessageReader::PopVariantOfDouble(double* value) {
939 return PopVariantOfBasic(DBUS_TYPE_DOUBLE, value);
940 }
941
PopVariantOfString(std::string * value)942 bool MessageReader::PopVariantOfString(std::string* value) {
943 char* tmp_value = NULL;
944 const bool success = PopVariantOfBasic(DBUS_TYPE_STRING, &tmp_value);
945 if (success)
946 value->assign(tmp_value);
947 return success;
948 }
949
PopVariantOfObjectPath(ObjectPath * value)950 bool MessageReader::PopVariantOfObjectPath(ObjectPath* value) {
951 char* tmp_value = NULL;
952 const bool success = PopVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
953 if (success)
954 *value = ObjectPath(tmp_value);
955 return success;
956 }
957
GetDataType()958 Message::DataType MessageReader::GetDataType() {
959 const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
960 return static_cast<Message::DataType>(dbus_type);
961 }
962
GetDataSignature()963 std::string MessageReader::GetDataSignature() {
964 std::string signature;
965 char* raw_signature = dbus_message_iter_get_signature(&raw_message_iter_);
966 if (raw_signature) {
967 signature = raw_signature;
968 dbus_free(raw_signature);
969 }
970 return signature;
971 }
972
CheckDataType(int dbus_type)973 bool MessageReader::CheckDataType(int dbus_type) {
974 const int actual_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
975 if (actual_type != dbus_type) {
976 VLOG(1) << "Type " << dbus_type << " is expected but got "
977 << actual_type;
978 return false;
979 }
980 return true;
981 }
982
PopBasic(int dbus_type,void * value)983 bool MessageReader::PopBasic(int dbus_type, void* value) {
984 if (!CheckDataType(dbus_type))
985 return false;
986 // dbus_message_iter_get_basic() here should always work, as we have
987 // already checked the next item's data type in CheckDataType(). Note
988 // that dbus_message_iter_get_basic() is a void function.
989 dbus_message_iter_get_basic(&raw_message_iter_, value);
990 DCHECK(value);
991 dbus_message_iter_next(&raw_message_iter_);
992 return true;
993 }
994
PopContainer(int dbus_type,MessageReader * sub_reader)995 bool MessageReader::PopContainer(int dbus_type, MessageReader* sub_reader) {
996 DCHECK_NE(this, sub_reader);
997
998 if (!CheckDataType(dbus_type))
999 return false;
1000 dbus_message_iter_recurse(&raw_message_iter_,
1001 &sub_reader->raw_message_iter_);
1002 dbus_message_iter_next(&raw_message_iter_);
1003 return true;
1004 }
1005
PopVariantOfBasic(int dbus_type,void * value)1006 bool MessageReader::PopVariantOfBasic(int dbus_type, void* value) {
1007 MessageReader variant_reader(message_);
1008 if (!PopVariant(&variant_reader))
1009 return false;
1010 return variant_reader.PopBasic(dbus_type, value);
1011 }
1012
PopFileDescriptor(base::ScopedFD * value)1013 bool MessageReader::PopFileDescriptor(base::ScopedFD* value) {
1014 CHECK(IsDBusTypeUnixFdSupported());
1015
1016 int fd = -1;
1017 const bool success = PopBasic(DBUS_TYPE_UNIX_FD, &fd);
1018 if (!success)
1019 return false;
1020
1021 *value = base::ScopedFD(fd);
1022 return true;
1023 }
1024
1025 } // namespace dbus
1026