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
23namespace {
24
25// Appends the header name and the value to |output|, if the value is
26// not empty.
27void 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.
37void 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
47namespace dbus {
48
49bool IsDBusTypeUnixFdSupported() {
50  int major = 0, minor = 0, micro = 0;
51  dbus_get_version(&major, &minor, &micro);
52  return major >= 1 && minor >= 4;
53}
54
55Message::Message()
56    : raw_message_(NULL) {
57}
58
59Message::~Message() {
60  if (raw_message_)
61    dbus_message_unref(raw_message_);
62}
63
64void Message::Init(DBusMessage* raw_message) {
65  DCHECK(!raw_message_);
66  raw_message_ = raw_message;
67}
68
69Message::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
76std::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
93std::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// ...
250std::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
272bool Message::SetDestination(const std::string& destination) {
273  return dbus_message_set_destination(raw_message_, destination.c_str());
274}
275
276bool Message::SetPath(const ObjectPath& path) {
277  return dbus_message_set_path(raw_message_, path.value().c_str());
278}
279
280bool Message::SetInterface(const std::string& interface) {
281  return dbus_message_set_interface(raw_message_, interface.c_str());
282}
283
284bool Message::SetMember(const std::string& member) {
285  return dbus_message_set_member(raw_message_, member.c_str());
286}
287
288bool Message::SetErrorName(const std::string& error_name) {
289  return dbus_message_set_error_name(raw_message_, error_name.c_str());
290}
291
292bool Message::SetSender(const std::string& sender) {
293  return dbus_message_set_sender(raw_message_, sender.c_str());
294}
295
296void Message::SetSerial(uint32_t serial) {
297  dbus_message_set_serial(raw_message_, serial);
298}
299
300void Message::SetReplySerial(uint32_t reply_serial) {
301  dbus_message_set_reply_serial(raw_message_, reply_serial);
302}
303
304std::string Message::GetDestination() {
305  const char* destination = dbus_message_get_destination(raw_message_);
306  return destination ? destination : "";
307}
308
309ObjectPath Message::GetPath() {
310  const char* path = dbus_message_get_path(raw_message_);
311  return ObjectPath(path ? path : "");
312}
313
314std::string Message::GetInterface() {
315  const char* interface = dbus_message_get_interface(raw_message_);
316  return interface ? interface : "";
317}
318
319std::string Message::GetMember() {
320  const char* member = dbus_message_get_member(raw_message_);
321  return member ? member : "";
322}
323
324std::string Message::GetErrorName() {
325  const char* error_name = dbus_message_get_error_name(raw_message_);
326  return error_name ? error_name : "";
327}
328
329std::string Message::GetSender() {
330  const char* sender = dbus_message_get_sender(raw_message_);
331  return sender ? sender : "";
332}
333
334std::string Message::GetSignature() {
335  const char* signature = dbus_message_get_signature(raw_message_);
336  return signature ? signature : "";
337}
338
339uint32_t Message::GetSerial() {
340  return dbus_message_get_serial(raw_message_);
341}
342
343uint32_t Message::GetReplySerial() {
344  return dbus_message_get_reply_serial(raw_message_);
345}
346
347//
348// MethodCall implementation.
349//
350
351MethodCall::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
360MethodCall::MethodCall() : Message() {
361}
362
363MethodCall* 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//
374Signal::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
383Signal::Signal() : Message() {
384}
385
386Signal* 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
398Response::Response() : Message() {
399}
400
401scoped_ptr<Response> Response::FromRawMessage(DBusMessage* raw_message) {
402  DCHECK_EQ(DBUS_MESSAGE_TYPE_METHOD_RETURN,
403            dbus_message_get_type(raw_message));
404
405  scoped_ptr<Response> response(new Response);
406  response->Init(raw_message);
407  return response;
408}
409
410scoped_ptr<Response> Response::FromMethodCall(MethodCall* method_call) {
411  scoped_ptr<Response> response(new Response);
412  response->Init(dbus_message_new_method_return(method_call->raw_message()));
413  return response;
414}
415
416scoped_ptr<Response> Response::CreateEmpty() {
417  scoped_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
426ErrorResponse::ErrorResponse() : Response() {
427}
428
429scoped_ptr<ErrorResponse> ErrorResponse::FromRawMessage(
430    DBusMessage* raw_message) {
431  DCHECK_EQ(DBUS_MESSAGE_TYPE_ERROR, dbus_message_get_type(raw_message));
432
433  scoped_ptr<ErrorResponse> response(new ErrorResponse);
434  response->Init(raw_message);
435  return response;
436}
437
438scoped_ptr<ErrorResponse> ErrorResponse::FromMethodCall(
439    MethodCall* method_call,
440    const std::string& error_name,
441    const std::string& error_message) {
442  scoped_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
453MessageWriter::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
461MessageWriter::~MessageWriter() {
462}
463
464void MessageWriter::AppendByte(uint8_t value) {
465  AppendBasic(DBUS_TYPE_BYTE, &value);
466}
467
468void 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
478void MessageWriter::AppendInt16(int16_t value) {
479  AppendBasic(DBUS_TYPE_INT16, &value);
480}
481
482void MessageWriter::AppendUint16(uint16_t value) {
483  AppendBasic(DBUS_TYPE_UINT16, &value);
484}
485
486void MessageWriter::AppendInt32(int32_t value) {
487  AppendBasic(DBUS_TYPE_INT32, &value);
488}
489
490void MessageWriter::AppendUint32(uint32_t value) {
491  AppendBasic(DBUS_TYPE_UINT32, &value);
492}
493
494void MessageWriter::AppendInt64(int64_t value) {
495  AppendBasic(DBUS_TYPE_INT64, &value);
496}
497
498void MessageWriter::AppendUint64(uint64_t value) {
499  AppendBasic(DBUS_TYPE_UINT64, &value);
500}
501
502void MessageWriter::AppendDouble(double value) {
503  AppendBasic(DBUS_TYPE_DOUBLE, &value);
504}
505
506void 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
516void 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.
530void 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
543void 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
556void 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
568void 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
580void 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
589void 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
602void MessageWriter::AppendArrayOfStrings(
603    const std::vector<std::string>& strings) {
604  DCHECK(!container_is_open_);
605  MessageWriter array_writer(message_);
606  OpenArray("s", &array_writer);
607  for (size_t i = 0; i < strings.size(); ++i) {
608    array_writer.AppendString(strings[i]);
609  }
610  CloseContainer(&array_writer);
611}
612
613void MessageWriter::AppendArrayOfObjectPaths(
614    const std::vector<ObjectPath>& object_paths) {
615  DCHECK(!container_is_open_);
616  MessageWriter array_writer(message_);
617  OpenArray("o", &array_writer);
618  for (size_t i = 0; i < object_paths.size(); ++i) {
619    array_writer.AppendObjectPath(object_paths[i]);
620  }
621  CloseContainer(&array_writer);
622}
623
624bool MessageWriter::AppendProtoAsArrayOfBytes(
625    const google::protobuf::MessageLite& protobuf) {
626  std::string serialized_proto;
627  if (!protobuf.SerializeToString(&serialized_proto)) {
628    LOG(ERROR) << "Unable to serialize supplied protocol buffer";
629    return false;
630  }
631  AppendArrayOfBytes(reinterpret_cast<const uint8_t*>(serialized_proto.data()),
632                     serialized_proto.size());
633  return true;
634}
635
636void MessageWriter::AppendVariantOfByte(uint8_t value) {
637  AppendVariantOfBasic(DBUS_TYPE_BYTE, &value);
638}
639
640void MessageWriter::AppendVariantOfBool(bool value) {
641  // See the comment at MessageWriter::AppendBool().
642  dbus_bool_t dbus_value = value;
643  AppendVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
644}
645
646void MessageWriter::AppendVariantOfInt16(int16_t value) {
647  AppendVariantOfBasic(DBUS_TYPE_INT16, &value);
648}
649
650void MessageWriter::AppendVariantOfUint16(uint16_t value) {
651  AppendVariantOfBasic(DBUS_TYPE_UINT16, &value);
652}
653
654void MessageWriter::AppendVariantOfInt32(int32_t value) {
655  AppendVariantOfBasic(DBUS_TYPE_INT32, &value);
656}
657
658void MessageWriter::AppendVariantOfUint32(uint32_t value) {
659  AppendVariantOfBasic(DBUS_TYPE_UINT32, &value);
660}
661
662void MessageWriter::AppendVariantOfInt64(int64_t value) {
663  AppendVariantOfBasic(DBUS_TYPE_INT64, &value);
664}
665
666void MessageWriter::AppendVariantOfUint64(uint64_t value) {
667  AppendVariantOfBasic(DBUS_TYPE_UINT64, &value);
668}
669
670void MessageWriter::AppendVariantOfDouble(double value) {
671  AppendVariantOfBasic(DBUS_TYPE_DOUBLE, &value);
672}
673
674void MessageWriter::AppendVariantOfString(const std::string& value) {
675  const char* pointer = value.c_str();
676  AppendVariantOfBasic(DBUS_TYPE_STRING, &pointer);
677}
678
679void MessageWriter::AppendVariantOfObjectPath(const ObjectPath& value) {
680  const char* pointer = value.value().c_str();
681  AppendVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &pointer);
682}
683
684void MessageWriter::AppendBasic(int dbus_type, const void* value) {
685  DCHECK(!container_is_open_);
686
687  const bool success = dbus_message_iter_append_basic(
688      &raw_message_iter_, dbus_type, value);
689  // dbus_message_iter_append_basic() fails only when there is not enough
690  // memory. We don't return this error as there is nothing we can do when
691  // it fails to allocate memory for a byte etc.
692  CHECK(success) << "Unable to allocate memory";
693}
694
695void MessageWriter::AppendVariantOfBasic(int dbus_type, const void* value) {
696  const std::string signature(1u,  // length
697                              base::checked_cast<char>(dbus_type));
698  MessageWriter variant_writer(message_);
699  OpenVariant(signature, &variant_writer);
700  variant_writer.AppendBasic(dbus_type, value);
701  CloseContainer(&variant_writer);
702}
703
704void MessageWriter::AppendFileDescriptor(const FileDescriptor& value) {
705  CHECK(IsDBusTypeUnixFdSupported());
706
707  if (!value.is_valid()) {
708    // NB: sending a directory potentially enables sandbox escape
709    LOG(FATAL) << "Attempt to pass invalid file descriptor";
710  }
711  int fd = value.value();
712  AppendBasic(DBUS_TYPE_UNIX_FD, &fd);
713}
714
715//
716// MessageReader implementation.
717//
718
719MessageReader::MessageReader(Message* message)
720    : message_(message) {
721  memset(&raw_message_iter_, 0, sizeof(raw_message_iter_));
722  if (message)
723    dbus_message_iter_init(message_->raw_message(), &raw_message_iter_);
724}
725
726
727MessageReader::~MessageReader() {
728}
729
730bool MessageReader::HasMoreData() {
731  const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
732  return dbus_type != DBUS_TYPE_INVALID;
733}
734
735bool MessageReader::PopByte(uint8_t* value) {
736  return PopBasic(DBUS_TYPE_BYTE, value);
737}
738
739bool MessageReader::PopBool(bool* value) {
740  // Like MessageWriter::AppendBool(), we should copy |value| to
741  // dbus_bool_t, as dbus_message_iter_get_basic() used in PopBasic()
742  // expects four bytes for DBUS_TYPE_BOOLEAN.
743  dbus_bool_t dbus_value = FALSE;
744  const bool success = PopBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
745  *value = static_cast<bool>(dbus_value);
746  return success;
747}
748
749bool MessageReader::PopInt16(int16_t* value) {
750  return PopBasic(DBUS_TYPE_INT16, value);
751}
752
753bool MessageReader::PopUint16(uint16_t* value) {
754  return PopBasic(DBUS_TYPE_UINT16, value);
755}
756
757bool MessageReader::PopInt32(int32_t* value) {
758  return PopBasic(DBUS_TYPE_INT32, value);
759}
760
761bool MessageReader::PopUint32(uint32_t* value) {
762  return PopBasic(DBUS_TYPE_UINT32, value);
763}
764
765bool MessageReader::PopInt64(int64_t* value) {
766  return PopBasic(DBUS_TYPE_INT64, value);
767}
768
769bool MessageReader::PopUint64(uint64_t* value) {
770  return PopBasic(DBUS_TYPE_UINT64, value);
771}
772
773bool MessageReader::PopDouble(double* value) {
774  return PopBasic(DBUS_TYPE_DOUBLE, value);
775}
776
777bool MessageReader::PopString(std::string* value) {
778  char* tmp_value = NULL;
779  const bool success = PopBasic(DBUS_TYPE_STRING, &tmp_value);
780  if (success)
781    value->assign(tmp_value);
782  return success;
783}
784
785bool MessageReader::PopObjectPath(ObjectPath* value) {
786  char* tmp_value = NULL;
787  const bool success = PopBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
788  if (success)
789    *value = ObjectPath(tmp_value);
790  return success;
791}
792
793bool MessageReader::PopArray(MessageReader* sub_reader) {
794  return PopContainer(DBUS_TYPE_ARRAY, sub_reader);
795}
796
797bool MessageReader::PopStruct(MessageReader* sub_reader) {
798  return PopContainer(DBUS_TYPE_STRUCT, sub_reader);
799}
800
801bool MessageReader::PopDictEntry(MessageReader* sub_reader) {
802  return PopContainer(DBUS_TYPE_DICT_ENTRY, sub_reader);
803}
804
805bool MessageReader::PopVariant(MessageReader* sub_reader) {
806  return PopContainer(DBUS_TYPE_VARIANT, sub_reader);
807}
808
809bool MessageReader::PopArrayOfBytes(const uint8_t** bytes, size_t* length) {
810  MessageReader array_reader(message_);
811  if (!PopArray(&array_reader))
812      return false;
813  // An empty array is allowed.
814  if (!array_reader.HasMoreData()) {
815    *length = 0;
816    *bytes = NULL;
817    return true;
818  }
819  if (!array_reader.CheckDataType(DBUS_TYPE_BYTE))
820    return false;
821  int int_length = 0;
822  dbus_message_iter_get_fixed_array(&array_reader.raw_message_iter_,
823                                    bytes,
824                                    &int_length);
825  *length = static_cast<int>(int_length);
826  return true;
827}
828
829bool MessageReader::PopArrayOfStrings(
830    std::vector<std::string> *strings) {
831  strings->clear();
832  MessageReader array_reader(message_);
833  if (!PopArray(&array_reader))
834    return false;
835  while (array_reader.HasMoreData()) {
836    std::string string;
837    if (!array_reader.PopString(&string))
838      return false;
839    strings->push_back(string);
840  }
841  return true;
842}
843
844bool MessageReader::PopArrayOfObjectPaths(
845    std::vector<ObjectPath> *object_paths) {
846  object_paths->clear();
847  MessageReader array_reader(message_);
848  if (!PopArray(&array_reader))
849    return false;
850  while (array_reader.HasMoreData()) {
851    ObjectPath object_path;
852    if (!array_reader.PopObjectPath(&object_path))
853      return false;
854    object_paths->push_back(object_path);
855  }
856  return true;
857}
858
859bool MessageReader::PopArrayOfBytesAsProto(
860    google::protobuf::MessageLite* protobuf) {
861  DCHECK(protobuf != NULL);
862  const char* serialized_buf = NULL;
863  size_t buf_size = 0;
864  if (!PopArrayOfBytes(reinterpret_cast<const uint8_t**>(&serialized_buf),
865                       &buf_size)) {
866    LOG(ERROR) << "Error reading array of bytes";
867    return false;
868  }
869  if (!protobuf->ParseFromArray(serialized_buf, buf_size)) {
870    LOG(ERROR) << "Failed to parse protocol buffer from array";
871    return false;
872  }
873  return true;
874}
875
876bool MessageReader::PopVariantOfByte(uint8_t* value) {
877  return PopVariantOfBasic(DBUS_TYPE_BYTE, value);
878}
879
880bool MessageReader::PopVariantOfBool(bool* value) {
881  // See the comment at MessageReader::PopBool().
882  dbus_bool_t dbus_value = FALSE;
883  const bool success = PopVariantOfBasic(DBUS_TYPE_BOOLEAN, &dbus_value);
884  *value = static_cast<bool>(dbus_value);
885  return success;
886}
887
888bool MessageReader::PopVariantOfInt16(int16_t* value) {
889  return PopVariantOfBasic(DBUS_TYPE_INT16, value);
890}
891
892bool MessageReader::PopVariantOfUint16(uint16_t* value) {
893  return PopVariantOfBasic(DBUS_TYPE_UINT16, value);
894}
895
896bool MessageReader::PopVariantOfInt32(int32_t* value) {
897  return PopVariantOfBasic(DBUS_TYPE_INT32, value);
898}
899
900bool MessageReader::PopVariantOfUint32(uint32_t* value) {
901  return PopVariantOfBasic(DBUS_TYPE_UINT32, value);
902}
903
904bool MessageReader::PopVariantOfInt64(int64_t* value) {
905  return PopVariantOfBasic(DBUS_TYPE_INT64, value);
906}
907
908bool MessageReader::PopVariantOfUint64(uint64_t* value) {
909  return PopVariantOfBasic(DBUS_TYPE_UINT64, value);
910}
911
912bool MessageReader::PopVariantOfDouble(double* value) {
913  return PopVariantOfBasic(DBUS_TYPE_DOUBLE, value);
914}
915
916bool MessageReader::PopVariantOfString(std::string* value) {
917  char* tmp_value = NULL;
918  const bool success = PopVariantOfBasic(DBUS_TYPE_STRING, &tmp_value);
919  if (success)
920    value->assign(tmp_value);
921  return success;
922}
923
924bool MessageReader::PopVariantOfObjectPath(ObjectPath* value) {
925  char* tmp_value = NULL;
926  const bool success = PopVariantOfBasic(DBUS_TYPE_OBJECT_PATH, &tmp_value);
927  if (success)
928    *value = ObjectPath(tmp_value);
929  return success;
930}
931
932Message::DataType MessageReader::GetDataType() {
933  const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
934  return static_cast<Message::DataType>(dbus_type);
935}
936
937std::string MessageReader::GetDataSignature() {
938  std::string signature;
939  char* raw_signature = dbus_message_iter_get_signature(&raw_message_iter_);
940  if (raw_signature) {
941    signature = raw_signature;
942    dbus_free(raw_signature);
943  }
944  return signature;
945}
946
947bool MessageReader::CheckDataType(int dbus_type) {
948  const int actual_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
949  if (actual_type != dbus_type) {
950    VLOG(1) << "Type " << dbus_type  << " is expected but got "
951            << actual_type;
952    return false;
953  }
954  return true;
955}
956
957bool MessageReader::PopBasic(int dbus_type, void* value) {
958  if (!CheckDataType(dbus_type))
959    return false;
960  // dbus_message_iter_get_basic() here should always work, as we have
961  // already checked the next item's data type in CheckDataType(). Note
962  // that dbus_message_iter_get_basic() is a void function.
963  dbus_message_iter_get_basic(&raw_message_iter_, value);
964  DCHECK(value);
965  dbus_message_iter_next(&raw_message_iter_);
966  return true;
967}
968
969bool MessageReader::PopContainer(int dbus_type, MessageReader* sub_reader) {
970  DCHECK_NE(this, sub_reader);
971
972  if (!CheckDataType(dbus_type))
973    return false;
974  dbus_message_iter_recurse(&raw_message_iter_,
975                            &sub_reader->raw_message_iter_);
976  dbus_message_iter_next(&raw_message_iter_);
977  return true;
978}
979
980bool MessageReader::PopVariantOfBasic(int dbus_type, void* value) {
981  MessageReader variant_reader(message_);
982  if (!PopVariant(&variant_reader))
983    return false;
984  return variant_reader.PopBasic(dbus_type, value);
985}
986
987bool MessageReader::PopFileDescriptor(FileDescriptor* value) {
988  CHECK(IsDBusTypeUnixFdSupported());
989
990  int fd = -1;
991  const bool success = PopBasic(DBUS_TYPE_UNIX_FD, &fd);
992  if (!success)
993    return false;
994
995  value->PutValue(fd);
996  // NB: the caller must check validity before using the value
997  return true;
998}
999
1000}  // namespace dbus
1001