gdbusmessage.c 91.6 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

23 24 25
/* Uncomment to debug serializer code */
/* #define DEBUG_SERIALIZER */

26 27
#include "config.h"

David Zeuthen's avatar
David Zeuthen committed
28
#include <string.h>
Matthias Clasen's avatar
Matthias Clasen committed
29 30 31 32 33 34
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
35 36 37 38 39 40 41 42 43 44 45 46 47

#include "gdbusutils.h"
#include "gdbusmessage.h"
#include "gdbuserror.h"
#include "gioenumtypes.h"
#include "ginputstream.h"
#include "gdatainputstream.h"
#include "gmemoryinputstream.h"
#include "goutputstream.h"
#include "gdataoutputstream.h"
#include "gmemoryoutputstream.h"
#include "gseekable.h"
#include "gioerror.h"
48
#include "gdbusprivate.h"
49 50

#ifdef G_OS_UNIX
51
#include "gunixfdlist.h"
52 53
#endif

David Zeuthen's avatar
David Zeuthen committed
54
#include "glibintl.h"
55 56 57 58

/**
 * SECTION:gdbusmessage
 * @short_description: D-Bus Message
David Zeuthen's avatar
David Zeuthen committed
59
 * @include: gio/gio.h
60 61 62 63 64
 *
 * A type for representing D-Bus messages that can be sent or received
 * on a #GDBusConnection.
 */

65
typedef struct _GDBusMessageClass GDBusMessageClass;
66 67 68 69 70 71 72 73 74 75 76 77 78 79

/**
 * GDBusMessageClass:
 *
 * Class structure for #GDBusMessage.
 *
 * Since: 2.26
 */
struct _GDBusMessageClass
{
  /*< private >*/
  GObjectClass parent_class;
};

80 81 82 83 84 85 86 87 88
/**
 * GDBusMessage:
 *
 * The #GDBusMessage structure contains only private data and should
 * only be accessed using the provided API.
 *
 * Since: 2.26
 */
struct _GDBusMessage
89
{
90 91 92
  /*< private >*/
  GObject parent_instance;

93 94 95 96 97 98 99 100 101
  GDBusMessageType type;
  GDBusMessageFlags flags;
  guchar major_protocol_version;
  guint32 serial;
  GHashTable *headers;
  GVariant *body;
#ifdef G_OS_UNIX
  GUnixFDList *fd_list;
#endif
102
  GDBusMessageByteOrder byte_order;
103 104 105 106 107 108 109 110 111
};

G_DEFINE_TYPE (GDBusMessage, g_dbus_message, G_TYPE_OBJECT);

static void
g_dbus_message_finalize (GObject *object)
{
  GDBusMessage *message = G_DBUS_MESSAGE (object);

112 113 114 115
  if (message->headers != NULL)
    g_hash_table_unref (message->headers);
  if (message->body != NULL)
    g_variant_unref (message->body);
116
#ifdef G_OS_UNIX
117 118
  if (message->fd_list != NULL)
    g_object_unref (message->fd_list);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
#endif

  if (G_OBJECT_CLASS (g_dbus_message_parent_class)->finalize != NULL)
    G_OBJECT_CLASS (g_dbus_message_parent_class)->finalize (object);
}

static void
g_dbus_message_class_init (GDBusMessageClass *klass)
{
  GObjectClass *gobject_class;

  gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->finalize     = g_dbus_message_finalize;
}

static void
g_dbus_message_init (GDBusMessage *message)
{
138 139 140 141 142 143 144 145 146 147 148 149
  /* Any D-Bus implementation is supposed to handle both Big and
   * Little Endian encodings and the Endianness is part of the D-Bus
   * message - we prefer to use Big Endian (since it's Network Byte
   * Order and just easier to read for humans) but if the machine is
   * Little Endian we use that for performance reasons.
   */
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
  message->byte_order = G_DBUS_MESSAGE_BYTE_ORDER_LITTLE_ENDIAN;
#else
  /* this could also be G_PDP_ENDIAN */
  message->byte_order = G_DBUS_MESSAGE_BYTE_ORDER_BIG_ENDIAN;
#endif
150 151 152 153
  message->headers = g_hash_table_new_full (g_direct_hash,
                                            g_direct_equal,
                                            NULL,
                                            (GDestroyNotify) g_variant_unref);
154 155 156 157 158 159 160 161
}

/**
 * g_dbus_message_new:
 *
 * Creates a new empty #GDBusMessage.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
162 163
 *
 * Since: 2.26
164 165 166 167 168 169 170 171 172 173 174
 */
GDBusMessage *
g_dbus_message_new (void)
{
  return g_object_new (G_TYPE_DBUS_MESSAGE, NULL);
}

/**
 * g_dbus_message_new_method_call:
 * @name: A valid D-Bus name or %NULL.
 * @path: A valid object path.
175
 * @interface_: A valid D-Bus interface name or %NULL.
176 177 178 179 180
 * @method: A valid method name.
 *
 * Creates a new #GDBusMessage for a method call.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
181 182
 *
 * Since: 2.26
183 184 185 186
 */
GDBusMessage *
g_dbus_message_new_method_call (const gchar *name,
                                const gchar *path,
187
                                const gchar *interface_,
188 189 190 191 192 193 194
                                const gchar *method)
{
  GDBusMessage *message;

  g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
  g_return_val_if_fail (g_variant_is_object_path (path), NULL);
  g_return_val_if_fail (g_dbus_is_member_name (method), NULL);
195
  g_return_val_if_fail (interface_ == NULL || g_dbus_is_interface_name (interface_), NULL);
196 197

  message = g_dbus_message_new ();
198
  message->type = G_DBUS_MESSAGE_TYPE_METHOD_CALL;
199 200 201 202 203

  if (name != NULL)
    g_dbus_message_set_destination (message, name);
  g_dbus_message_set_path (message, path);
  g_dbus_message_set_member (message, method);
204 205
  if (interface_ != NULL)
    g_dbus_message_set_interface (message, interface_);
206 207 208 209 210 211 212

  return message;
}

/**
 * g_dbus_message_new_signal:
 * @path: A valid object path.
213
 * @interface_: A valid D-Bus interface name.
214 215 216 217 218
 * @signal: A valid signal name.
 *
 * Creates a new #GDBusMessage for a signal emission.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
219 220
 *
 * Since: 2.26
221 222 223
 */
GDBusMessage *
g_dbus_message_new_signal (const gchar  *path,
224
                           const gchar  *interface_,
225 226 227 228 229 230
                           const gchar  *signal)
{
  GDBusMessage *message;

  g_return_val_if_fail (g_variant_is_object_path (path), NULL);
  g_return_val_if_fail (g_dbus_is_member_name (signal), NULL);
231
  g_return_val_if_fail (g_dbus_is_interface_name (interface_), NULL);
232 233

  message = g_dbus_message_new ();
234 235
  message->type = G_DBUS_MESSAGE_TYPE_SIGNAL;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
236 237 238

  g_dbus_message_set_path (message, path);
  g_dbus_message_set_member (message, signal);
239
  g_dbus_message_set_interface (message, interface_);
240 241 242 243 244 245 246 247 248 249 250 251 252

  return message;
}


/**
 * g_dbus_message_new_method_reply:
 * @method_call_message: A message of type %G_DBUS_MESSAGE_TYPE_METHOD_CALL to
 * create a reply message to.
 *
 * Creates a new #GDBusMessage that is a reply to @method_call_message.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
253 254
 *
 * Since: 2.26
255 256 257 258 259 260 261 262
 */
GDBusMessage *
g_dbus_message_new_method_reply (GDBusMessage *method_call_message)
{
  GDBusMessage *message;
  const gchar *sender;

  g_return_val_if_fail (G_IS_DBUS_MESSAGE (method_call_message), NULL);
263
  g_return_val_if_fail (g_dbus_message_get_message_type (method_call_message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL, NULL);
264 265 266
  g_return_val_if_fail (g_dbus_message_get_serial (method_call_message) != 0, NULL);

  message = g_dbus_message_new ();
267 268
  message->type = G_DBUS_MESSAGE_TYPE_METHOD_RETURN;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
269 270
  /* reply with same endianness */
  message->byte_order = method_call_message->byte_order;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

  g_dbus_message_set_reply_serial (message, g_dbus_message_get_serial (method_call_message));
  sender = g_dbus_message_get_sender (method_call_message);
  if (sender != NULL)
    g_dbus_message_set_destination (message, sender);

  return message;
}

/**
 * g_dbus_message_new_method_error:
 * @method_call_message: A message of type %G_DBUS_MESSAGE_TYPE_METHOD_CALL to
 * create a reply message to.
 * @error_name: A valid D-Bus error name.
 * @error_message_format: The D-Bus error message in a printf() format.
 * @...: Arguments for @error_message_format.
 *
 * Creates a new #GDBusMessage that is an error reply to @method_call_message.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
291 292
 *
 * Since: 2.26
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
 */
GDBusMessage *
g_dbus_message_new_method_error (GDBusMessage             *method_call_message,
                                 const gchar              *error_name,
                                 const gchar              *error_message_format,
                                 ...)
{
  GDBusMessage *ret;
  va_list var_args;

  va_start (var_args, error_message_format);
  ret = g_dbus_message_new_method_error_valist (method_call_message,
                                                error_name,
                                                error_message_format,
                                                var_args);
  va_end (var_args);

  return ret;
}

/**
 * g_dbus_message_new_method_error_literal:
 * @method_call_message: A message of type %G_DBUS_MESSAGE_TYPE_METHOD_CALL to
 * create a reply message to.
 * @error_name: A valid D-Bus error name.
 * @error_message: The D-Bus error message.
 *
 * Creates a new #GDBusMessage that is an error reply to @method_call_message.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
323 324
 *
 * Since: 2.26
325 326 327 328 329 330 331 332 333 334
 */
GDBusMessage *
g_dbus_message_new_method_error_literal (GDBusMessage  *method_call_message,
                                         const gchar   *error_name,
                                         const gchar   *error_message)
{
  GDBusMessage *message;
  const gchar *sender;

  g_return_val_if_fail (G_IS_DBUS_MESSAGE (method_call_message), NULL);
335
  g_return_val_if_fail (g_dbus_message_get_message_type (method_call_message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL, NULL);
336 337 338 339 340
  g_return_val_if_fail (g_dbus_message_get_serial (method_call_message) != 0, NULL);
  g_return_val_if_fail (g_dbus_is_name (error_name), NULL);
  g_return_val_if_fail (error_message != NULL, NULL);

  message = g_dbus_message_new ();
341 342
  message->type = G_DBUS_MESSAGE_TYPE_ERROR;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
343 344
  /* reply with same endianness */
  message->byte_order = method_call_message->byte_order;
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367

  g_dbus_message_set_reply_serial (message, g_dbus_message_get_serial (method_call_message));
  g_dbus_message_set_error_name (message, error_name);
  g_dbus_message_set_body (message, g_variant_new ("(s)", error_message));

  sender = g_dbus_message_get_sender (method_call_message);
  if (sender != NULL)
    g_dbus_message_set_destination (message, sender);

  return message;
}

/**
 * g_dbus_message_new_method_error_valist:
 * @method_call_message: A message of type %G_DBUS_MESSAGE_TYPE_METHOD_CALL to
 * create a reply message to.
 * @error_name: A valid D-Bus error name.
 * @error_message_format: The D-Bus error message in a printf() format.
 * @var_args: Arguments for @error_message_format.
 *
 * Like g_dbus_message_new_method_error() but intended for language bindings.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
368 369
 *
 * Since: 2.26
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
 */
GDBusMessage *
g_dbus_message_new_method_error_valist (GDBusMessage             *method_call_message,
                                        const gchar              *error_name,
                                        const gchar              *error_message_format,
                                        va_list                   var_args)
{
  GDBusMessage *ret;
  gchar *error_message;
  error_message = g_strdup_vprintf (error_message_format, var_args);
  ret = g_dbus_message_new_method_error_literal (method_call_message,
                                                 error_name,
                                                 error_message);
  g_free (error_message);
  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
/**
 * g_dbus_message_get_byte_order:
 * @message: A #GDBusMessage.
 *
 * Gets the byte order of @message.
 *
 * Returns: The byte order.
 */
GDBusMessageByteOrder
g_dbus_message_get_byte_order (GDBusMessage *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), (GDBusMessageByteOrder) 0);
  return message->byte_order;
}

/**
 * g_dbus_message_set_byte_order:
 * @message: A #GDBusMessage.
 * @byte_order: The byte order.
 *
 * Sets the byte order of @message.
 */
void
g_dbus_message_set_byte_order (GDBusMessage          *message,
                               GDBusMessageByteOrder  byte_order)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  message->byte_order = byte_order;
}

/* ---------------------------------------------------------------------------------------------------- */

421 422 423
/* TODO: need GI annotations to specify that any guchar value goes for the type */

/**
424
 * g_dbus_message_get_message_type:
425 426 427 428 429
 * @message: A #GDBusMessage.
 *
 * Gets the type of @message.
 *
 * Returns: A 8-bit unsigned integer (typically a value from the #GDBusMessageType enumeration).
430 431
 *
 * Since: 2.26
432 433
 */
GDBusMessageType
434
g_dbus_message_get_message_type (GDBusMessage  *message)
435 436
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), G_DBUS_MESSAGE_TYPE_INVALID);
437
  return message->type;
438 439 440
}

/**
441
 * g_dbus_message_set_message_type:
442 443 444 445
 * @message: A #GDBusMessage.
 * @type: A 8-bit unsigned integer (typically a value from the #GDBusMessageType enumeration).
 *
 * Sets @message to be of @type.
446 447
 *
 * Since: 2.26
448 449
 */
void
450 451
g_dbus_message_set_message_type (GDBusMessage      *message,
                                 GDBusMessageType   type)
452 453 454
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail (type >=0 && type < 256);
455
  message->type = type;
456 457 458 459 460 461 462 463 464 465 466 467 468
}

/* ---------------------------------------------------------------------------------------------------- */

/* TODO: need GI annotations to specify that any guchar value goes for flags */

/**
 * g_dbus_message_get_flags:
 * @message: A #GDBusMessage.
 *
 * Gets the flags for @message.
 *
 * Returns: Flags that are set (typically values from the #GDBusMessageFlags enumeration bitwise ORed together).
469 470
 *
 * Since: 2.26
471 472 473 474 475
 */
GDBusMessageFlags
g_dbus_message_get_flags (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), G_DBUS_MESSAGE_FLAGS_NONE);
476
  return message->flags;
477 478 479 480 481 482 483 484 485
}

/**
 * g_dbus_message_set_flags:
 * @message: A #GDBusMessage.
 * @flags: Flags for @message that are set (typically values from the #GDBusMessageFlags
 * enumeration bitwise ORed together).
 *
 * Sets the flags to set on @message.
486 487
 *
 * Since: 2.26
488 489 490 491 492 493 494
 */
void
g_dbus_message_set_flags (GDBusMessage       *message,
                          GDBusMessageFlags   flags)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail (flags >=0 && flags < 256);
495
  message->flags = flags;
496 497 498 499 500 501 502 503 504 505 506
}

/* ---------------------------------------------------------------------------------------------------- */

/**
 * g_dbus_message_get_serial:
 * @message: A #GDBusMessage.
 *
 * Gets the serial for @message.
 *
 * Returns: A #guint32.
507 508
 *
 * Since: 2.26
509 510 511 512 513
 */
guint32
g_dbus_message_get_serial (GDBusMessage *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), 0);
514
  return message->serial;
515 516 517 518 519 520 521 522
}

/**
 * g_dbus_message_set_serial:
 * @message: A #GDBusMessage.
 * @serial: A #guint32.
 *
 * Sets the serial for @message.
523 524
 *
 * Since: 2.26
525 526 527 528 529 530
 */
void
g_dbus_message_set_serial (GDBusMessage  *message,
                           guint32        serial)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
531
  message->serial = serial;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
}

/* ---------------------------------------------------------------------------------------------------- */

/* TODO: need GI annotations to specify that any guchar value goes for header_field */

/**
 * g_dbus_message_get_header:
 * @message: A #GDBusMessage.
 * @header_field: A 8-bit unsigned integer (typically a value from the #GDBusMessageHeaderField enumeration)
 *
 * Gets a header field on @message.
 *
 * Returns: A #GVariant with the value if the header was found, %NULL
 * otherwise. Do not free, it is owned by @message.
547 548
 *
 * Since: 2.26
549 550 551 552 553 554 555
 */
GVariant *
g_dbus_message_get_header (GDBusMessage             *message,
                           GDBusMessageHeaderField   header_field)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
  g_return_val_if_fail (header_field >=0 && header_field < 256, NULL);
556
  return g_hash_table_lookup (message->headers, GUINT_TO_POINTER (header_field));
557 558 559 560 561 562 563 564 565 566 567
}

/**
 * g_dbus_message_set_header:
 * @message: A #GDBusMessage.
 * @header_field: A 8-bit unsigned integer (typically a value from the #GDBusMessageHeaderField enumeration)
 * @value: A #GVariant to set the header field or %NULL to clear the header field.
 *
 * Sets a header field on @message.
 *
 * If @value is floating, @message assumes ownership of @value.
568 569
 *
 * Since: 2.26
570 571 572 573 574 575 576 577 578 579
 */
void
g_dbus_message_set_header (GDBusMessage             *message,
                           GDBusMessageHeaderField   header_field,
                           GVariant                 *value)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail (header_field >=0 && header_field < 256);
  if (value == NULL)
    {
580
      g_hash_table_remove (message->headers, GUINT_TO_POINTER (header_field));
581 582 583
    }
  else
    {
584
      g_hash_table_insert (message->headers, GUINT_TO_POINTER (header_field), g_variant_ref_sink (value));
585 586 587 588 589 590 591 592 593 594 595 596
    }
}

/**
 * g_dbus_message_get_header_fields:
 * @message: A #GDBusMessage.
 *
 * Gets an array of all header fields on @message that are set.
 *
 * Returns: An array of header fields terminated by
 * %G_DBUS_MESSAGE_HEADER_FIELD_INVALID.  Each element is a
 * #guchar. Free with g_free().
597 598
 *
 * Since: 2.26
599 600 601 602 603 604 605 606 607 608 609 610
 */
guchar *
g_dbus_message_get_header_fields (GDBusMessage  *message)
{
  GList *keys;
  guchar *ret;
  guint num_keys;
  GList *l;
  guint n;

  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);

611
  keys = g_hash_table_get_keys (message->headers);
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  num_keys = g_list_length (keys);
  ret = g_new (guchar, num_keys + 1);
  for (l = keys, n = 0; l != NULL; l = l->next, n++)
    ret[n] = GPOINTER_TO_UINT (l->data);
  g_assert (n == num_keys);
  ret[n] = G_DBUS_MESSAGE_HEADER_FIELD_INVALID;
  g_list_free (keys);

  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

/**
 * g_dbus_message_get_body:
 * @message: A #GDBusMessage.
 *
 * Gets the body of a message.
 *
 * Returns: A #GVariant or %NULL if the body is empty. Do not free, it is owned by @message.
632 633
 *
 * Since: 2.26
634 635 636 637 638
 */
GVariant *
g_dbus_message_get_body (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
639
  return message->body;
640 641 642 643 644 645 646 647 648 649 650 651
}

/**
 * g_dbus_message_set_body:
 * @message: A #GDBusMessage.
 * @body: Either %NULL or a #GVariant that is a tuple.
 *
 * Sets the body @message. As a side-effect the
 * %G_DBUS_MESSAGE_HEADER_FIELD_SIGNATURE header field is set to the
 * type string of @body (or cleared if @body is %NULL).
 *
 * If @body is floating, @message assumes ownership of @body.
652 653
 *
 * Since: 2.26
654 655 656 657 658 659 660 661
 */
void
g_dbus_message_set_body (GDBusMessage  *message,
                         GVariant      *body)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail ((body == NULL) || g_variant_is_of_type (body, G_VARIANT_TYPE_TUPLE));

662 663
  if (message->body != NULL)
    g_variant_unref (message->body);
664 665
  if (body == NULL)
    {
666
      message->body = NULL;
667 668 669 670 671 672 673 674
      g_dbus_message_set_signature (message, NULL);
    }
  else
    {
      const gchar *type_string;
      gsize type_string_len;
      gchar *signature;

675
      message->body = g_variant_ref_sink (body);
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698

      type_string = g_variant_get_type_string (body);
      type_string_len = strlen (type_string);
      g_assert (type_string_len >= 2);
      signature = g_strndup (type_string + 1, type_string_len - 2);
      g_dbus_message_set_signature (message, signature);
      g_free (signature);
    }
}

/* ---------------------------------------------------------------------------------------------------- */

#ifdef G_OS_UNIX
/**
 * g_dbus_message_get_unix_fd_list:
 * @message: A #GDBusMessage.
 *
 * Gets the UNIX file descriptors associated with @message, if any.
 *
 * This method is only available on UNIX.
 *
 * Returns: A #GUnixFDList or %NULL if no file descriptors are
 * associated. Do not free, this object is owned by @message.
699 700
 *
 * Since: 2.26
701 702 703 704 705
 */
GUnixFDList *
g_dbus_message_get_unix_fd_list (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
706
  return message->fd_list;
707 708 709 710 711 712 713 714 715 716 717 718 719
}

/**
 * g_dbus_message_set_unix_fd_list:
 * @message: A #GDBusMessage.
 * @fd_list: A #GUnixFDList or %NULL.
 *
 * Sets the UNIX file descriptors associated with @message. As a
 * side-effect the %G_DBUS_MESSAGE_HEADER_FIELD_NUM_UNIX_FDS header
 * field is set to the number of fds in @fd_list (or cleared if
 * @fd_list is %NULL).
 *
 * This method is only available on UNIX.
720 721
 *
 * Since: 2.26
722 723 724 725 726 727 728
 */
void
g_dbus_message_set_unix_fd_list (GDBusMessage  *message,
                                 GUnixFDList   *fd_list)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
729 730
  if (message->fd_list != NULL)
    g_object_unref (message->fd_list);
731 732
  if (fd_list != NULL)
    {
733
      message->fd_list = g_object_ref (fd_list);
734 735 736 737
      g_dbus_message_set_num_unix_fds (message, g_unix_fd_list_get_length (fd_list));
    }
  else
    {
738
      message->fd_list = NULL;
739 740 741 742 743 744 745
      g_dbus_message_set_num_unix_fds (message, 0);
    }
}
#endif

/* ---------------------------------------------------------------------------------------------------- */

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
static gboolean
validate_headers (GDBusMessage  *message,
                  GError       **error)
{
  gboolean ret;

  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  ret = FALSE;

  switch (message->type)
    {
    case G_DBUS_MESSAGE_TYPE_INVALID:
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("type is INVALID"));
      goto out;
      break;

    case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
      if (g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_PATH) == NULL ||
          g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_MEMBER) == NULL)
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("METHOD_CALL message: PATH or MEMBER header field is missing"));
          goto out;
        }
      break;

    case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
      if (g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_REPLY_SERIAL) == NULL)
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("METHOD_RETURN message: REPLY_SERIAL header field is missing"));
          goto out;
        }
      break;

    case G_DBUS_MESSAGE_TYPE_ERROR:
      if (g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_ERROR_NAME) == NULL ||
          g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_REPLY_SERIAL) == NULL)
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("ERROR message: REPLY_SERIAL or ERROR_NAME header field is missing"));
          goto out;
        }
      break;

    case G_DBUS_MESSAGE_TYPE_SIGNAL:
      if (g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_PATH) == NULL ||
          g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_INTERFACE) == NULL ||
          g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_MEMBER) == NULL)
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("SIGNAL message: PATH, INTERFACE or MEMBER header field is missing"));
          goto out;
        }
      if (g_strcmp0 (g_dbus_message_get_path (message), "/org/freedesktop/DBus/Local") == 0)
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("SIGNAL message: The PATH header field is using the reserved value /org/freedesktop/DBus/Local"));
          goto out;
        }
      if (g_strcmp0 (g_dbus_message_get_interface (message), "org.freedesktop.DBus.Local") == 0)
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
                               _("SIGNAL message: The INTERFACE header field is using the reserved value org.freedesktop.DBus.Local"));
          goto out;
        }
      break;

    default:
      /* hitherto unknown type - nothing to check */
      break;
    }

  ret = TRUE;

 out:
  g_assert (ret || (error == NULL || *error != NULL));
  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

845 846 847 848 849 850 851 852 853 854 855
static gboolean
ensure_input_padding (GMemoryInputStream   *mis,
                      gsize                 padding_size,
                      GError              **error)
{
  gsize offset;
  gsize wanted_offset;

  offset = g_seekable_tell (G_SEEKABLE (mis));
  wanted_offset = ((offset + padding_size - 1) / padding_size) * padding_size;

856 857 858 859 860 861 862 863
  if (offset != wanted_offset)
    {
      return g_seekable_seek (G_SEEKABLE (mis), wanted_offset, G_SEEK_SET, NULL, error);
    }
  else
    {
      return TRUE;
    }
864 865 866 867 868 869 870 871 872 873 874 875 876
}

static gchar *
read_string (GMemoryInputStream    *mis,
             GDataInputStream      *dis,
             gsize                  len,
             GError               **error)
{
  GString *s;
  gchar buf[256];
  gsize remaining;
  guchar nul;
  GError *local_error;
877
  const gchar *end_valid;
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896

  s = g_string_new (NULL);

  remaining = len;
  while (remaining > 0)
    {
      gsize to_read;
      gssize num_read;

      to_read = MIN (remaining, sizeof (buf));
      num_read = g_input_stream_read (G_INPUT_STREAM (mis),
                                      buf,
                                      to_read,
                                      NULL,
                                      error);
      if (num_read < 0)
        goto fail;
      if (num_read == 0)
        {
897
          /* G_GSIZE_FORMAT doesn't work with gettext, so we use %lu */
898 899 900
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_ARGUMENT,
901
                       _("Wanted to read %lu bytes but got EOF"),
902
                       (gulong)to_read);
903 904 905 906 907 908 909 910 911 912 913 914 915 916
          goto fail;
        }

      remaining -= num_read;
      g_string_append_len (s, buf, num_read);
    }

  local_error = NULL;
  nul = g_data_input_stream_read_byte (dis, NULL, &local_error);
  if (local_error != NULL)
    {
      g_propagate_error (error, local_error);
      goto fail;
    }
917 918 919 920 921 922 923 924 925 926
  if (!g_utf8_validate (s->str, -1, &end_valid))
    {
      gint offset;
      gchar *valid_str;
      offset = (gint) (end_valid - s->str);
      valid_str = g_strndup (s->str, offset);
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   _("Expected valid UTF-8 string but found invalid bytes at byte offset %d (length of string is %d). "
Matthias Clasen's avatar
Matthias Clasen committed
927
                     "The valid UTF-8 string up until that point was `%s'"),
928 929 930 931 932 933
                   offset,
                   (gint) s->len,
                   valid_str);
      g_free (valid_str);
      goto fail;
    }
934 935 936 937 938
  if (nul != '\0')
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
939 940
                   _("Expected NUL byte after the string `%s' but found byte %d"),
                   s->str, nul);
941 942 943 944 945 946 947 948 949 950
      goto fail;
    }

  return g_string_free (s, FALSE);

 fail:
  g_string_free (s, TRUE);
  return NULL;
}

951
/* if just_align==TRUE, don't read a value, just align the input stream wrt padding */
952 953

/* returns a non-floating GVariant! */
954 955 956 957
static GVariant *
parse_value_from_blob (GMemoryInputStream    *mis,
                       GDataInputStream      *dis,
                       const GVariantType    *type,
958
                       gboolean               just_align,
959
                       guint                  indent,
960 961 962 963
                       GError               **error)
{
  GVariant *ret;
  GError *local_error;
964
  gboolean is_leaf;
965

966 967 968 969 970 971 972 973 974 975 976 977
#ifdef DEBUG_SERIALIZER
  if (!just_align)
    {
      gchar *s;
      s = g_variant_type_dup_string (type);
      g_print ("%*sReading type %s from offset 0x%04x",
               indent, "",
               s,
               (gint) g_seekable_tell (G_SEEKABLE (mis)));
      g_free (s);
    }
#endif /* DEBUG_SERIALIZER */
978 979 980

  ret = NULL;

981
  is_leaf = TRUE;
982 983 984 985 986
  local_error = NULL;
  if (g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
    {
      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;
987 988 989 990 991 992 993 994
      if (!just_align)
        {
          gboolean v;
          v = g_data_input_stream_read_uint32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_boolean (v);
        }
995 996 997
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_BYTE))
    {
998 999 1000 1001 1002 1003 1004 1005
      if (!just_align)
        {
          guchar v;
          v = g_data_input_stream_read_byte (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_byte (v);
        }
1006 1007 1008 1009 1010
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_INT16))
    {
      if (!ensure_input_padding (mis, 2, &local_error))
        goto fail;
1011 1012 1013 1014 1015 1016 1017 1018
      if (!just_align)
        {
          gint16 v;
          v = g_data_input_stream_read_int16 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_int16 (v);
        }
1019 1020 1021 1022 1023
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_UINT16))
    {
      if (!ensure_input_padding (mis, 2, &local_error))
        goto fail;
1024 1025 1026 1027 1028 1029 1030 1031
      if (!just_align)
        {
          guint16 v;
          v = g_data_input_stream_read_uint16 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_uint16 (v);
        }
1032 1033 1034 1035 1036
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_INT32))
    {
      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;
1037 1038 1039 1040 1041 1042 1043 1044
      if (!just_align)
        {
          gint32 v;
          v = g_data_input_stream_read_int32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_int32 (v);
        }
1045 1046 1047 1048 1049
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_UINT32))
    {
      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;
1050 1051 1052 1053 1054 1055 1056 1057
      if (!just_align)
        {
          guint32 v;
          v = g_data_input_stream_read_uint32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_uint32 (v);
        }
1058 1059 1060 1061 1062
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_INT64))
    {
      if (!ensure_input_padding (mis, 8, &local_error))
        goto fail;
1063 1064 1065 1066 1067 1068 1069 1070
      if (!just_align)
        {
          gint64 v;
          v = g_data_input_stream_read_int64 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_int64 (v);
        }
1071 1072 1073 1074 1075
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_UINT64))
    {
      if (!ensure_input_padding (mis, 8, &local_error))
        goto fail;
1076 1077 1078 1079 1080 1081 1082 1083
      if (!just_align)
        {
          guint64 v;
          v = g_data_input_stream_read_uint64 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_uint64 (v);
        }
1084 1085 1086 1087 1088
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
    {
      if (!ensure_input_padding (mis, 8, &local_error))
        goto fail;
1089 1090 1091 1092 1093 1094 1095
      if (!just_align)
        {
          guint64 v;
          gdouble *encoded;
          v = g_data_input_stream_read_uint64 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
1096
          G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
1097 1098 1099
          encoded = (gdouble *) &v;
          ret = g_variant_new_double (*encoded);
        }
1100 1101 1102 1103 1104
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
    {
      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
      if (!just_align)
        {
          guint32 len;
          gchar *v;
          len = g_data_input_stream_read_uint32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          v = read_string (mis, dis, (gsize) len, &local_error);
          if (v == NULL)
            goto fail;
          ret = g_variant_new_string (v);
1116
          g_free (v);
1117
        }
1118 1119 1120 1121 1122
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
    {
      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;
1123
      if (!just_align)
1124
        {
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
          guint32 len;
          gchar *v;
          len = g_data_input_stream_read_uint32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          v = read_string (mis, dis, (gsize) len, &local_error);
          if (v == NULL)
            goto fail;
          if (!g_variant_is_object_path (v))
            {
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("Parsed value `%s' is not a valid D-Bus object path"),
                           v);
1140
              g_free (v);
1141 1142 1143
              goto fail;
            }
          ret = g_variant_new_object_path (v);
1144
          g_free (v);
1145 1146 1147 1148
        }
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
    {
1149
      if (!just_align)
1150
        {
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
          guchar len;
          gchar *v;
          len = g_data_input_stream_read_byte (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          v = read_string (mis, dis, (gsize) len, &local_error);
          if (v == NULL)
            goto fail;
          if (!g_variant_is_signature (v))
            {
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("Parsed value `%s' is not a valid D-Bus signature"),
1165
                       v);
1166
              g_free (v);
1167 1168 1169
              goto fail;
            }
          ret = g_variant_new_signature (v);
1170
          g_free (v);
1171 1172
        }
    }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_HANDLE))
    {
      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;
      if (!just_align)
        {
          gint32 v;
          v = g_data_input_stream_read_int32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_handle (v);
        }
    }
1186 1187 1188 1189 1190 1191
  else if (g_variant_type_is_array (type))
    {
      guint32 array_len;
      goffset offset;
      goffset target;
      const GVariantType *element_type;
1192
      GVariantBuilder builder;
1193 1194 1195 1196

      if (!ensure_input_padding (mis, 4, &local_error))
        goto fail;

1197
      if (just_align)
1198
        {
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
          array_len = 0;
        }
      else
        {
          array_len = g_data_input_stream_read_uint32 (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;

          is_leaf = FALSE;
#ifdef DEBUG_SERIALIZER
          g_print (": array spans 0x%04x bytes\n", array_len);
#endif /* DEBUG_SERIALIZER */

          if (array_len > (2<<26))
            {
1214
              /* G_GUINT32_FORMAT doesn't work with gettext, so use u */
1215 1216 1217
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
1218
                           _("Encountered array of length %u bytes. Maximum length is 2<<26 bytes (64 MiB)."),
1219 1220 1221
                           array_len);
              goto fail;
            }
1222 1223
        }

1224
      g_variant_builder_init (&builder, type);
1225 1226
      element_type = g_variant_type_element (type);

1227
      if (array_len == 0)
1228 1229
        {
          GVariant *item;
1230 1231 1232 1233
          item = parse_value_from_blob (mis,
                                        dis,
                                        element_type,
                                        TRUE,
1234
                                        indent + 2,
1235 1236 1237 1238 1239 1240 1241 1242 1243
                                        &local_error);
          g_assert (item == NULL);
        }
      else
        {
          /* TODO: optimize array of primitive types */
          offset = g_seekable_tell (G_SEEKABLE (mis));
          target = offset + array_len;
          while (offset < target)
1244
            {
1245 1246 1247 1248 1249
              GVariant *item;
              item = parse_value_from_blob (mis,
                                            dis,
                                            element_type,
                                            FALSE,
1250
                                            indent + 2,
1251 1252 1253
                                            &local_error);
              if (item == NULL)
                {
1254
                  g_variant_builder_clear (&builder);
1255 1256
                  goto fail;
                }
1257
              g_variant_builder_add_value (&builder, item);
1258
              g_variant_unref (item);
1259
              offset = g_seekable_tell (G_SEEKABLE (mis));
1260 1261 1262
            }
        }

1263 1264
      if (!just_align)
        {
1265
          ret = g_variant_builder_end (&builder);
1266 1267 1268
        }
      else
        {
1269
          g_variant_builder_clear (&builder);
1270
        }
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    }
  else if (g_variant_type_is_dict_entry (type))
    {
      const GVariantType *key_type;
      const GVariantType *value_type;
      GVariant *key;
      GVariant *value;

      if (!ensure_input_padding (mis, 8, &local_error))
        goto fail;

1282 1283 1284 1285 1286
      is_leaf = FALSE;
#ifdef DEBUG_SERIALIZER
      g_print ("\n");
#endif /* DEBUG_SERIALIZER */

1287
      if (!just_align)
1288
        {
1289 1290 1291 1292 1293
          key_type = g_variant_type_key (type);
          key = parse_value_from_blob (mis,
                                       dis,
                                       key_type,
                                       FALSE,
1294
                                       indent + 2,
1295 1296 1297 1298 1299 1300 1301 1302
                                       &local_error);
          if (key == NULL)
            goto fail;
          value_type = g_variant_type_value (type);
          value = parse_value_from_blob (mis,
                                         dis,
                                         value_type,
                                         FALSE,
1303
                                         indent + 2,
1304 1305 1306 1307 1308 1309 1310
                                         &local_error);
          if (value == NULL)
            {
              g_variant_unref (key);
              goto fail;
            }
          ret = g_variant_new_dict_entry (key, value);
1311 1312
          g_variant_unref (key);
          g_variant_unref (value);
1313 1314 1315 1316 1317 1318 1319
        }
    }
  else if (g_variant_type_is_tuple (type))
    {
      if (!ensure_input_padding (mis, 8, &local_error))
        goto fail;

1320 1321 1322 1323 1324
      is_leaf = FALSE;
#ifdef DEBUG_SERIALIZER
      g_print ("\n");
#endif /* DEBUG_SERIALIZER */

1325
      if (!just_align)
1326
        {
1327
          const GVariantType *element_type;
1328
          GVariantBuilder builder;
1329

1330
          g_variant_builder_init (&builder, type);
1331 1332
          element_type = g_variant_type_first (type);
          while (element_type != NULL)
1333
            {
1334 1335 1336 1337 1338
              GVariant *item;
              item = parse_value_from_blob (mis,
                                            dis,
                                            element_type,
                                            FALSE,
1339
                                            indent + 2,
1340 1341 1342
                                            &local_error);
              if (item == NULL)
                {
1343
                  g_variant_builder_clear (&builder);
1344 1345
                  goto fail;
                }
1346
              g_variant_builder_add_value (&builder, item);
1347
              g_variant_unref (item);
1348 1349

              element_type = g_variant_type_next (element_type);
1350
            }
1351
          ret = g_variant_builder_end (&builder);
1352 1353 1354 1355
        }
    }
  else if (g_variant_type_is_variant (type))
    {
1356 1357 1358 1359 1360
      is_leaf = FALSE;
#ifdef DEBUG_SERIALIZER
      g_print ("\n");
#endif /* DEBUG_SERIALIZER */

1361
      if (!just_align)
1362
        {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
          guchar siglen;
          gchar *sig;
          GVariantType *variant_type;
          GVariant *value;

          siglen = g_data_input_stream_read_byte (dis, NULL, &local_error);
          if (local_error != NULL)
            goto fail;
          sig = read_string (mis, dis, (gsize) siglen, &local_error);
          if (sig == NULL)
            goto fail;
          if (!g_variant_is_signature (sig))
            {
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("Parsed value `%s' for variant is not a valid D-Bus signature"),
                           sig);
1381
              g_free (sig);
1382 1383 1384
              goto fail;
            }
          variant_type = g_variant_type_new (sig);
1385
          g_free (sig);
1386 1387 1388 1389
          value = parse_value_from_blob (mis,
                                         dis,
                                         variant_type,
                                         FALSE,
1390
                                         indent + 2,
1391 1392 1393 1394 1395
                                         &local_error);
          g_variant_type_free (variant_type);
          if (value == NULL)
            goto fail;
          ret = g_variant_new_variant (value);
1396
          g_variant_unref (value);
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
        }
    }
  else
    {
      gchar *s;
      s = g_variant_type_dup_string (type);
      g_set_error (&local_error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   _("Error deserializing GVariant with type-string `%s' from the D-Bus wire format"),
                   s);
      g_free (s);
      goto fail;
    }

1412
  g_assert ((just_align && ret == NULL) || (!just_align && ret != NULL));
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433

#ifdef DEBUG_SERIALIZER
  if (ret != NULL)
    {
      if (is_leaf)
        {
          gchar *s;
          if (g_variant_type_equal (type, G_VARIANT_TYPE_BYTE))
            {
              s = g_strdup_printf ("0x%02x '%c'", g_variant_get_byte (ret), g_variant_get_byte (ret));
            }
          else
            {
              s = g_variant_print (ret, FALSE);
            }
          g_print (": %s\n", s);
          g_free (s);
        }
    }
#endif /* DEBUG_SERIALIZER */

1434 1435 1436 1437 1438 1439
  /* sink the reference */
  if (ret != NULL)
    {
      g_assert (g_variant_is_floating (ret));
      g_variant_ref_sink (ret);
    }
1440 1441 1442
  return ret;

 fail:
1443 1444 1445 1446 1447 1448 1449 1450
#ifdef DEBUG_SERIALIZER
  g_print ("\n"
           "%*sFAILURE: %s (%s, %d)\n",
           indent, "",
           local_error->message,
           g_quark_to_string (local_error->domain),
           local_error->code);
#endif /* DEBUG_SERIALIZER */
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
  g_propagate_error (error, local_error);
  return NULL;
}

/* ---------------------------------------------------------------------------------------------------- */

/* message_header must be at least 16 bytes */

/**
 * g_dbus_message_bytes_needed:
 * @blob: A blob represent a binary D-Bus message.
 * @blob_len: The length of @blob (must be at least 16).
 * @error: Return location for error or %NULL.
 *
 * Utility function to calculate how many bytes are needed to
 * completely deserialize the D-Bus message stored at @blob.
 *
 * Returns: Number of bytes needed or -1 if @error is set (e.g. if
 * @blob contains invalid data or not enough data is available to
 * determine the size).
1471 1472
 *
 * Since: 2.26
1473 1474
 */
gssize
1475 1476 1477
g_dbus_message_bytes_needed (guchar                *blob,
                             gsize                  blob_len,
                             GError               **error)
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
{
  gssize ret;

  ret = -1;

  g_return_val_if_fail (blob != NULL, -1);
  g_return_val_if_fail (error == NULL || *error == NULL, -1);
  g_return_val_if_fail (blob_len >= 16, -1);

  if (blob[0] == 'l')
    {
      /* core header (12 bytes) + ARRAY of STRUCT of (BYTE,VARIANT) */
      ret = 12 + 4 + GUINT32_FROM_LE (((guint32 *) blob)[3]);
      /* round up so it's a multiple of 8 */
      ret = 8 * ((ret + 7)/8);
      /* finally add the body size */
      ret += GUINT32_FROM_LE (((guint32 *) blob)[1]);
    }
  else if (blob[0] == 'B')
    {
David Zeuthen's avatar
David Zeuthen committed
1498 1499 1500 1501 1502 1503
      /* core header (12 bytes) + ARRAY of STRUCT of (BYTE,VARIANT) */
      ret = 12 + 4 + GUINT32_FROM_BE (((guint32 *) blob)[3]);
      /* round up so it's a multiple of 8 */
      ret = 8 * ((ret + 7)/8);
      /* finally add the body size */
      ret += GUINT32_FROM_BE (((guint32 *) blob)[1]);
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    }
  else
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   "Unable to determine message blob length - given blob is malformed");
    }

  if (ret > (2<<27))
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   "Blob indicates that message exceeds maximum message length (128MiB)");
      ret = -1;
    }

  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

/**
 * g_dbus_message_new_from_blob:
 * @blob: A blob represent a binary D-Bus message.
 * @blob_len: The length of @blob.
1531
 * @capabilities: A #GDBusCapabilityFlags describing what protocol features are supported.
1532 1533
 * @error: Return location for error or %NULL.
 *
1534 1535 1536
 * Creates a new #GDBusMessage from the data stored at @blob. The byte
 * order that the message was in can be retrieved using
 * g_dbus_message_get_byte_order().
1537 1538 1539
 *
 * Returns: A new #GDBusMessage or %NULL if @error is set. Free with
 * g_object_unref().
1540 1541
 *
 * Since: 2.26
1542 1543
 */
GDBusMessage *
1544 1545 1546 1547
g_dbus_message_new_from_blob (guchar                *blob,
                              gsize                  blob_len,
                              GDBusCapabilityFlags   capabilities,
                              GError               **error)
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
{
  gboolean ret;
  GMemoryInputStream *mis;
  GDataInputStream *dis;
  GDBusMessage *message;
  guchar endianness;
  guchar major_protocol_version;
  GDataStreamByteOrder byte_order;
  guint32 message_body_len;
  GVariant *headers;
  GVariant *item;
  GVariantIter iter;
  GVariant *signature;

1562 1563
  /* TODO: check against @capabilities */

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
  ret = FALSE;

  g_return_val_if_fail (blob != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
  g_return_val_if_fail (blob_len >= 12, NULL);

  message = g_dbus_message_new ();

  mis = G_MEMORY_INPUT_STREAM (g_memory_input_stream_new_from_data (blob, blob_len, NULL));
  dis = g_data_input_stream_new (G_INPUT_STREAM (mis));

  endianness = g_data_input_stream_read_byte (dis, NULL, NULL);
  switch (endianness)
    {
    case 'l':
      byte_order = G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN;
1580
      message->byte_order = G_DBUS_MESSAGE_BYTE_ORDER_LITTLE_ENDIAN;
1581 1582 1583
      break;
    case 'B':
      byte_order = G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN;
1584
      message->byte_order = G_DBUS_MESSAGE_BYTE_ORDER_BIG_ENDIAN;
1585 1586 1587 1588 1589
      break;
    default:
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
1590 1591
                   _("Invalid endianness value. Expected 0x6c ('l') or 0x42 ('B') but found value 0x%02x"),
                   endianness);
1592 1593 1594 1595
      goto out;
    }
  g_data_input_stream_set_byte_order (dis, byte_order);

1596 1597
  message->type = g_data_input_stream_read_byte (dis, NULL, NULL);
  message->flags = g_data_input_stream_read_byte (dis, NULL, NULL);
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
  major_protocol_version = g_data_input_stream_read_byte (dis, NULL, NULL);
  if (major_protocol_version != 1)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   _("Invalid major protocol version. Expected 1 but found %d"),
                   major_protocol_version);
      goto out;
    }
  message_body_len = g_data_input_stream_read_uint32 (dis, NULL, NULL);
1609
  message->serial = g_data_input_stream_read_uint32 (dis, NULL, NULL);
1610

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
#ifdef DEBUG_SERIALIZER
  g_print ("Parsing blob (blob_len = 0x%04x bytes)\n", (gint) blob_len);
  {
    gchar *s;
    s = _g_dbus_hexdump ((const gchar *) blob, blob_len, 2);
    g_print ("%s\n", s);
    g_free (s);
  }
#endif /* DEBUG_SERIALIZER */

#ifdef DEBUG_SERIALIZER
  g_print ("Parsing headers (blob_len = 0x%04x bytes)\n", (gint) blob_len);
#endif /* DEBUG_SERIALIZER */
1624 1625 1626
  headers = parse_value_from_blob (mis,
                                   dis,
                                   G_VARIANT_TYPE ("a{yv}"),
1627
                                   FALSE,
1628
                                   2,
1629 1630 1631 1632
                                   error);
  if (headers == NULL)
    goto out;
  g_variant_iter_init (&iter, headers);
1633
  while ((item = g_variant_iter_next_value (&iter)) != NULL)
1634 1635 1636 1637 1638 1639 1640 1641
    {
      guchar header_field;
      GVariant *value;
      g_variant_get (item,
                     "{yv}",
                     &header_field,
                     &value);
      g_dbus_message_set_header (message, header_field, value);
1642 1643
      g_variant_unref (value);
      g_variant_unref (item);
1644 1645 1646 1647 1648 1649 1650 1651 1652
    }
  g_variant_unref (headers);

  signature = g_dbus_message_get_header (message, G_DBUS_MESSAGE_HEADER_FIELD_SIGNATURE);
  if (signature != NULL)
    {
      const gchar *signature_str;
      gsize signature_str_len;

1653
      signature_str = g_variant_get_string (signature, &signature_str_len);
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681

      /* signature but no body */
      if (message_body_len == 0 && signature_str_len > 0)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_ARGUMENT,
                       _("Signature header with signature `%s' found but message body is empty"),
                       signature_str);
          goto out;
        }
      else if (signature_str_len > 0)
        {
          GVariantType *variant_type;
          gchar *tupled_signature_str;

          if (!g_variant_is_signature (signature_str))
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("Parsed value `%s' is not a valid D-Bus signature (for body)"),
                           signature_str);
              goto out;
            }
          tupled_signature_str = g_strdup_printf ("(%s)", signature_str);
          variant_type = g_variant_type_new (tupled_signature_str);
          g_free (tupled_signature_str);
1682 1683 1684
#ifdef DEBUG_SERIALIZER
          g_print ("Parsing body (blob_len = 0x%04x bytes)\n", (gint) blob_len);
#endif /* DEBUG_SERIALIZER */
1685 1686 1687 1688 1689 1690
          message->body = parse_value_from_blob (mis,
                                                 dis,
                                                 variant_type,
                                                 FALSE,
                                                 2,
                                                 error);
1691
          g_variant_type_free (variant_type);
1692
          if (message->body == NULL)
1693
            goto out;
1694 1695 1696 1697 1698 1699 1700
        }
    }
  else
    {
      /* no signature, this is only OK if the body is empty */
      if (message_body_len != 0)
        {
1701
          /* G_GUINT32_FORMAT doesn't work with gettext, just use %u */
1702 1703 1704
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_ARGUMENT,
1705
                       _("No signature header in message but the message body is %u bytes"),
1706 1707 1708 1709 1710
                       message_body_len);
          goto out;
        }
    }

1711 1712 1713 1714 1715
  if (!validate_headers (message, error))
    {
      g_prefix_error (error, _("Cannot deserialize message: "));
      goto out;
    }
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756

  ret = TRUE;

 out:
  g_object_unref (dis);
  g_object_unref (mis);

  if (ret)
    {
      return message;
    }
  else
    {
      if (message != NULL)
        g_object_unref (message);
      return NULL;
    }
}

/* ---------------------------------------------------------------------------------------------------- */

static gsize
ensure_output_padding (GMemoryOutputStream  *mos,
                       GDataOutputStream    *dos,
                       gsize                 padding_size)
{
  gsize offset;
  gsize wanted_offset;
  gsize padding_needed;
  guint n;

  offset = g_memory_output_stream_get_data_size (mos);
  wanted_offset = ((offset + padding_size - 1) / padding_size) * padding_size;
  padding_needed = wanted_offset - offset;

  for (n = 0; n < padding_needed; n++)
    g_data_output_stream_put_byte (dos, '\0', NULL, NULL);

  return padding_needed;
}

1757
/* note that value can be NULL for e.g. empty arrays - type is never NULL */
1758 1759
static gboolean
append_value_to_blob (GVariant             *value,
1760
                      const GVariantType   *type,
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
                      GMemoryOutputStream  *mos,
                      GDataOutputStream    *dos,
                      gsize                *out_padding_added,
                      GError              **error)
{
  gsize padding_added;

  padding_added = 0;

  if (g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
    {
      padding_added = ensure_output_padding (mos, dos, 4);
1773 1774 1775 1776 1777
      if (value != NULL)
        {
          gboolean v = g_variant_get_boolean (value);
          g_data_output_stream_put_uint32 (dos, v, NULL, NULL);
        }
1778 1779 1780
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_BYTE))
    {
1781 1782 1783 1784 1785
      if (value != NULL)
        {
          guint8 v = g_variant_get_byte (value);
          g_data_output_stream_put_byte (dos, v, NULL, NULL);
        }
1786 1787 1788 1789
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_INT16))
    {
      padding_added = ensure_output_padding (mos, dos, 2);
1790 1791 1792 1793 1794
      if (value != NULL)
        {
          gint16 v = g_variant_get_int16 (value);
          g_data_output_stream_put_int16 (dos, v, NULL, NULL);
        }
1795 1796 1797 1798
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_UINT16))
    {
      padding_added = ensure_output_padding (mos, dos, 2);
1799 1800 1801 1802 1803
      if (value != NULL)
        {
          guint16 v = g_variant_get_uint16 (value);
          g_data_output_stream_put_uint16 (dos, v, NULL, NULL);
        }
1804 1805 1806 1807
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_INT32))
    {
      padding_added = ensure_output_padding (mos, dos, 4);
1808 1809 1810 1811 1812
      if (value != NULL)
        {
          gint32 v = g_variant_get_int32 (value);
          g_data_output_stream_put_int32 (dos, v, NULL, NULL);
        }
1813 1814 1815 1816
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_UINT32))
    {
      padding_added = ensure_output_padding (mos, dos, 4);
1817 1818 1819 1820 1821
      if (value != NULL)
        {
          guint32 v = g_variant_get_uint32 (value);
          g_data_output_stream_put_uint32 (dos, v, NULL, NULL);
        }
1822 1823 1824 1825
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_INT64))
    {
      padding_added = ensure_output_padding (mos, dos, 8);
1826 1827 1828 1829 1830
      if (value != NULL)
        {
          gint64 v = g_variant_get_int64 (value);
          g_data_output_stream_put_int64 (dos, v, NULL, NULL);
        }
1831 1832 1833 1834
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_UINT64))
    {
      padding_added = ensure_output_padding (mos, dos, 8);
1835 1836 1837 1838 1839
      if (value != NULL)
        {
          guint64 v = g_variant_get_uint64 (value);
          g_data_output_stream_put_uint64 (dos, v, NULL, NULL);
        }
1840 1841 1842 1843
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_DOUBLE))
    {
      padding_added = ensure_output_padding (mos, dos, 8);
1844 1845 1846 1847
      if (value != NULL)
        {
          guint64 *encoded;
          gdouble v = g_variant_get_double (value);
1848
          G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
1849 1850 1851
          encoded = (guint64 *) &v;
          g_data_output_stream_put_uint64 (dos, *encoded, NULL, NULL);
        }
1852 1853 1854 1855
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
    {
      padding_added = ensure_output_padding (mos, dos, 4);
1856 1857 1858
      if (value != NULL)
        {
          gsize len;
1859 1860 1861 1862
          const gchar *v;
          const gchar *end;
          v = g_variant_get_string (value, &len);
          g_assert (g_utf8_validate (v, -1, &end) && (end == v + len));
1863 1864 1865 1866
          g_data_output_stream_put_uint32 (dos, len, NULL, NULL);
          g_data_output_stream_put_string (dos, v, NULL, NULL);
          g_data_output_stream_put_byte (dos, '\0', NULL, NULL);
        }
1867 1868 1869 1870
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
    {
      padding_added = ensure_output_padding (mos, dos, 4);
1871 1872 1873
      if (value != NULL)
        {
          gsize len;
1874
          const gchar *v = g_variant_get_string (value, &len);
1875
          g_assert (g_variant_is_object_path (v));
1876 1877 1878 1879
          g_data_output_stream_put_uint32 (dos, len, NULL, NULL);
          g_data_output_stream_put_string (dos, v, NULL, NULL);
          g_data_output_stream_put_byte (dos, '\0', NULL, NULL);
        }
1880 1881 1882
    }
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_SIGNATURE))
    {
1883 1884 1885
      if (value != NULL)
        {
          gsize len;
1886
          const gchar *v = g_variant_get_string (value, &len);
1887
          g_assert (g_variant_is_signature (v));
1888 1889 1890 1891
          g_data_output_stream_put_byte (dos, len, NULL, NULL);
          g_data_output_stream_put_string (dos, v, NULL, NULL);
          g_data_output_stream_put_byte (dos, '\0', NULL, NULL);
        }
1892
    }
1893 1894 1895 1896 1897 1898 1899 1900 1901
  else if (g_variant_type_equal (type, G_VARIANT_TYPE_HANDLE))
    {
      padding_added = ensure_output_padding (mos, dos, 4);
      if (value != NULL)
        {
          gint32 v = g_variant_get_handle (value);
          g_data_output_stream_put_int32 (dos, v, NULL, NULL);
        }
    }
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
  else if (g_variant_type_is_array (type))
    {
      GVariant *item;
      GVariantIter iter;
      goffset array_len_offset;
      goffset array_payload_begin_offset;
      goffset cur_offset;