• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, &micro);
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         FileDescriptor file_descriptor;
226         if (!reader->PopFileDescriptor(&file_descriptor))
227           return kBrokenMessage;
228         output += indent + "fd#" +
229                   base::IntToString(file_descriptor.value()) + "\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(const FileDescriptor & value)717 void MessageWriter::AppendFileDescriptor(const FileDescriptor& value) {
718   CHECK(IsDBusTypeUnixFdSupported());
719 
720   if (!value.is_valid()) {
721     // NB: sending a directory potentially enables sandbox escape
722     LOG(FATAL) << "Attempt to pass invalid file descriptor";
723   }
724   int fd = value.value();
725   AppendBasic(DBUS_TYPE_UNIX_FD, &fd);
726 }
727 
728 //
729 // MessageReader implementation.
730 //
731 
MessageReader(Message * message)732 MessageReader::MessageReader(Message* message)
733     : message_(message) {
734   memset(&raw_message_iter_, 0, sizeof(raw_message_iter_));
735   if (message)
736     dbus_message_iter_init(message_->raw_message(), &raw_message_iter_);
737 }
738 
739 
~MessageReader()740 MessageReader::~MessageReader() {
741 }
742 
HasMoreData()743 bool MessageReader::HasMoreData() {
744   const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
745   return dbus_type != DBUS_TYPE_INVALID;
746 }
747 
PopByte(uint8_t * value)748 bool MessageReader::PopByte(uint8_t* value) {
749   return PopBasic(DBUS_TYPE_BYTE, value);
750 }
751 
PopBool(bool * value)752 bool MessageReader::PopBool(bool* value) {
753   // Like MessageWriter::AppendBool(), we should copy |value| to
754   // dbus_bool_t, as dbus_message_iter_get_basic() used in PopBasic()
755   // expects four bytes for DBUS_TYPE_BOOLEAN.
756   dbus_bool_t dbus_value = FALSE;
757   const bool success = PopBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
758   *value = static_cast<bool>(dbus_value);
759   return success;
760 }
761 
PopInt16(int16_t * value)762 bool MessageReader::PopInt16(int16_t* value) {
763   return PopBasic(DBUS_TYPE_INT16, value);
764 }
765 
PopUint16(uint16_t * value)766 bool MessageReader::PopUint16(uint16_t* value) {
767   return PopBasic(DBUS_TYPE_UINT16, value);
768 }
769 
PopInt32(int32_t * value)770 bool MessageReader::PopInt32(int32_t* value) {
771   return PopBasic(DBUS_TYPE_INT32, value);
772 }
773 
PopUint32(uint32_t * value)774 bool MessageReader::PopUint32(uint32_t* value) {
775   return PopBasic(DBUS_TYPE_UINT32, value);
776 }
777 
PopInt64(int64_t * value)778 bool MessageReader::PopInt64(int64_t* value) {
779   return PopBasic(DBUS_TYPE_INT64, value);
780 }
781 
PopUint64(uint64_t * value)782 bool MessageReader::PopUint64(uint64_t* value) {
783   return PopBasic(DBUS_TYPE_UINT64, value);
784 }
785 
PopDouble(double * value)786 bool MessageReader::PopDouble(double* value) {
787   return PopBasic(DBUS_TYPE_DOUBLE, value);
788 }
789 
PopString(std::string * value)790 bool MessageReader::PopString(std::string* value) {
791   char* tmp_value = NULL;
792   const bool success = PopBasic(DBUS_TYPE_STRING, &tmp_value);
793   if (success)
794     value->assign(tmp_value);
795   return success;
796 }
797 
PopObjectPath(ObjectPath * value)798 bool MessageReader::PopObjectPath(ObjectPath* value) {
799   char* tmp_value = NULL;
800   const bool success = PopBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
801   if (success)
802     *value = ObjectPath(tmp_value);
803   return success;
804 }
805 
PopArray(MessageReader * sub_reader)806 bool MessageReader::PopArray(MessageReader* sub_reader) {
807   return PopContainer(DBUS_TYPE_ARRAY, sub_reader);
808 }
809 
PopStruct(MessageReader * sub_reader)810 bool MessageReader::PopStruct(MessageReader* sub_reader) {
811   return PopContainer(DBUS_TYPE_STRUCT, sub_reader);
812 }
813 
PopDictEntry(MessageReader * sub_reader)814 bool MessageReader::PopDictEntry(MessageReader* sub_reader) {
815   return PopContainer(DBUS_TYPE_DICT_ENTRY, sub_reader);
816 }
817 
PopVariant(MessageReader * sub_reader)818 bool MessageReader::PopVariant(MessageReader* sub_reader) {
819   return PopContainer(DBUS_TYPE_VARIANT, sub_reader);
820 }
821 
PopArrayOfBytes(const uint8_t ** bytes,size_t * length)822 bool MessageReader::PopArrayOfBytes(const uint8_t** bytes, size_t* length) {
823   MessageReader array_reader(message_);
824   if (!PopArray(&array_reader))
825       return false;
826   // An empty array is allowed.
827   if (!array_reader.HasMoreData()) {
828     *length = 0;
829     *bytes = NULL;
830     return true;
831   }
832   if (!array_reader.CheckDataType(DBUS_TYPE_BYTE))
833     return false;
834   int int_length = 0;
835   dbus_message_iter_get_fixed_array(&array_reader.raw_message_iter_,
836                                     bytes,
837                                     &int_length);
838   *length = static_cast<size_t>(int_length);
839   return true;
840 }
841 
PopArrayOfDoubles(const double ** doubles,size_t * length)842 bool MessageReader::PopArrayOfDoubles(const double** doubles, size_t* length) {
843   MessageReader array_reader(message_);
844   if (!PopArray(&array_reader))
845     return false;
846   if (!array_reader.HasMoreData()) {
847     *length = 0;
848     *doubles = nullptr;
849     return true;
850   }
851   if (!array_reader.CheckDataType(DBUS_TYPE_DOUBLE))
852     return false;
853   int int_length = 0;
854   dbus_message_iter_get_fixed_array(&array_reader.raw_message_iter_,
855                                     doubles,
856                                     &int_length);
857   *length = static_cast<size_t>(int_length);
858   return true;
859 }
860 
PopArrayOfStrings(std::vector<std::string> * strings)861 bool MessageReader::PopArrayOfStrings(
862     std::vector<std::string> *strings) {
863   strings->clear();
864   MessageReader array_reader(message_);
865   if (!PopArray(&array_reader))
866     return false;
867   while (array_reader.HasMoreData()) {
868     std::string string;
869     if (!array_reader.PopString(&string))
870       return false;
871     strings->push_back(string);
872   }
873   return true;
874 }
875 
PopArrayOfObjectPaths(std::vector<ObjectPath> * object_paths)876 bool MessageReader::PopArrayOfObjectPaths(
877     std::vector<ObjectPath> *object_paths) {
878   object_paths->clear();
879   MessageReader array_reader(message_);
880   if (!PopArray(&array_reader))
881     return false;
882   while (array_reader.HasMoreData()) {
883     ObjectPath object_path;
884     if (!array_reader.PopObjectPath(&object_path))
885       return false;
886     object_paths->push_back(object_path);
887   }
888   return true;
889 }
890 
PopArrayOfBytesAsProto(google::protobuf::MessageLite * protobuf)891 bool MessageReader::PopArrayOfBytesAsProto(
892     google::protobuf::MessageLite* protobuf) {
893   DCHECK(protobuf != NULL);
894   const char* serialized_buf = NULL;
895   size_t buf_size = 0;
896   if (!PopArrayOfBytes(reinterpret_cast<const uint8_t**>(&serialized_buf),
897                        &buf_size)) {
898     LOG(ERROR) << "Error reading array of bytes";
899     return false;
900   }
901   if (!protobuf->ParseFromArray(serialized_buf, buf_size)) {
902     LOG(ERROR) << "Failed to parse protocol buffer from array";
903     return false;
904   }
905   return true;
906 }
907 
PopVariantOfByte(uint8_t * value)908 bool MessageReader::PopVariantOfByte(uint8_t* value) {
909   return PopVariantOfBasic(DBUS_TYPE_BYTE, value);
910 }
911 
PopVariantOfBool(bool * value)912 bool MessageReader::PopVariantOfBool(bool* value) {
913   // See the comment at MessageReader::PopBool().
914   dbus_bool_t dbus_value = FALSE;
915   const bool success = PopVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
916   *value = static_cast<bool>(dbus_value);
917   return success;
918 }
919 
PopVariantOfInt16(int16_t * value)920 bool MessageReader::PopVariantOfInt16(int16_t* value) {
921   return PopVariantOfBasic(DBUS_TYPE_INT16, value);
922 }
923 
PopVariantOfUint16(uint16_t * value)924 bool MessageReader::PopVariantOfUint16(uint16_t* value) {
925   return PopVariantOfBasic(DBUS_TYPE_UINT16, value);
926 }
927 
PopVariantOfInt32(int32_t * value)928 bool MessageReader::PopVariantOfInt32(int32_t* value) {
929   return PopVariantOfBasic(DBUS_TYPE_INT32, value);
930 }
931 
PopVariantOfUint32(uint32_t * value)932 bool MessageReader::PopVariantOfUint32(uint32_t* value) {
933   return PopVariantOfBasic(DBUS_TYPE_UINT32, value);
934 }
935 
PopVariantOfInt64(int64_t * value)936 bool MessageReader::PopVariantOfInt64(int64_t* value) {
937   return PopVariantOfBasic(DBUS_TYPE_INT64, value);
938 }
939 
PopVariantOfUint64(uint64_t * value)940 bool MessageReader::PopVariantOfUint64(uint64_t* value) {
941   return PopVariantOfBasic(DBUS_TYPE_UINT64, value);
942 }
943 
PopVariantOfDouble(double * value)944 bool MessageReader::PopVariantOfDouble(double* value) {
945   return PopVariantOfBasic(DBUS_TYPE_DOUBLE, value);
946 }
947 
PopVariantOfString(std::string * value)948 bool MessageReader::PopVariantOfString(std::string* value) {
949   char* tmp_value = NULL;
950   const bool success = PopVariantOfBasic(DBUS_TYPE_STRING, &tmp_value);
951   if (success)
952     value->assign(tmp_value);
953   return success;
954 }
955 
PopVariantOfObjectPath(ObjectPath * value)956 bool MessageReader::PopVariantOfObjectPath(ObjectPath* value) {
957   char* tmp_value = NULL;
958   const bool success = PopVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
959   if (success)
960     *value = ObjectPath(tmp_value);
961   return success;
962 }
963 
GetDataType()964 Message::DataType MessageReader::GetDataType() {
965   const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
966   return static_cast<Message::DataType>(dbus_type);
967 }
968 
GetDataSignature()969 std::string MessageReader::GetDataSignature() {
970   std::string signature;
971   char* raw_signature = dbus_message_iter_get_signature(&raw_message_iter_);
972   if (raw_signature) {
973     signature = raw_signature;
974     dbus_free(raw_signature);
975   }
976   return signature;
977 }
978 
CheckDataType(int dbus_type)979 bool MessageReader::CheckDataType(int dbus_type) {
980   const int actual_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
981   if (actual_type != dbus_type) {
982     VLOG(1) << "Type " << dbus_type  << " is expected but got "
983             << actual_type;
984     return false;
985   }
986   return true;
987 }
988 
PopBasic(int dbus_type,void * value)989 bool MessageReader::PopBasic(int dbus_type, void* value) {
990   if (!CheckDataType(dbus_type))
991     return false;
992   // dbus_message_iter_get_basic() here should always work, as we have
993   // already checked the next item's data type in CheckDataType(). Note
994   // that dbus_message_iter_get_basic() is a void function.
995   dbus_message_iter_get_basic(&raw_message_iter_, value);
996   DCHECK(value);
997   dbus_message_iter_next(&raw_message_iter_);
998   return true;
999 }
1000 
PopContainer(int dbus_type,MessageReader * sub_reader)1001 bool MessageReader::PopContainer(int dbus_type, MessageReader* sub_reader) {
1002   DCHECK_NE(this, sub_reader);
1003 
1004   if (!CheckDataType(dbus_type))
1005     return false;
1006   dbus_message_iter_recurse(&raw_message_iter_,
1007                             &sub_reader->raw_message_iter_);
1008   dbus_message_iter_next(&raw_message_iter_);
1009   return true;
1010 }
1011 
PopVariantOfBasic(int dbus_type,void * value)1012 bool MessageReader::PopVariantOfBasic(int dbus_type, void* value) {
1013   MessageReader variant_reader(message_);
1014   if (!PopVariant(&variant_reader))
1015     return false;
1016   return variant_reader.PopBasic(dbus_type, value);
1017 }
1018 
PopFileDescriptor(FileDescriptor * value)1019 bool MessageReader::PopFileDescriptor(FileDescriptor* value) {
1020   CHECK(IsDBusTypeUnixFdSupported());
1021 
1022   int fd = -1;
1023   const bool success = PopBasic(DBUS_TYPE_UNIX_FD, &fd);
1024   if (!success)
1025     return false;
1026 
1027   value->PutValue(fd);
1028   // NB: the caller must check validity before using the value
1029   return true;
1030 }
1031 
1032 }  // namespace dbus
1033