gdbusmessage.c 105 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7
 *
 * 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
8
 * version 2.1 of the License, or (at your option) any later version.
9 10 11 12 13 14 15
 *
 * 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
16
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 18 19 20
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

21 22 23
/* Uncomment to debug serializer code */
/* #define DEBUG_SERIALIZER */

24 25
#include "config.h"

David Zeuthen's avatar
David Zeuthen committed
26
#include <string.h>
Matthias Clasen's avatar
Matthias Clasen committed
27 28 29
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
30

31 32 33 34
#if MAJOR_IN_MKDEV
#include <sys/mkdev.h>
#elif MAJOR_IN_SYSMACROS
#include <sys/sysmacros.h>
35 36
#elif MAJOR_IN_TYPES
#include <sys/types.h>
37 38
#else
#define MAJOR_MINOR_NOT_FOUND 1
39 40
#endif

41 42 43 44 45 46 47 48 49 50 51 52
#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"
53
#include "gdbusprivate.h"
54 55

#ifdef G_OS_UNIX
56
#include "gunixfdlist.h"
57 58
#endif

David Zeuthen's avatar
David Zeuthen committed
59
#include "glibintl.h"
60

61 62 63 64 65 66 67 68 69 70
typedef struct _GMemoryBuffer GMemoryBuffer;
struct _GMemoryBuffer
{
  gsize len;
  gsize valid_len;
  gsize pos;
  gchar *data;
  GDataStreamByteOrder byte_order;
};

71 72 73 74 75 76 77 78 79 80
static gboolean
g_memory_buffer_is_byteswapped (GMemoryBuffer *mbuf)
{
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
  return mbuf->byte_order == G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN;
#else
  return mbuf->byte_order == G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN;
#endif
}

81
static guchar
82
g_memory_buffer_read_byte (GMemoryBuffer  *mbuf)
83 84 85 86 87 88 89
{
  if (mbuf->pos >= mbuf->valid_len)
    return 0;
  return mbuf->data [mbuf->pos++];
}

static gint16
90
g_memory_buffer_read_int16 (GMemoryBuffer  *mbuf)
91 92 93 94 95 96 97 98 99 100 101
{
  gint16 v;
  
  if (mbuf->pos > mbuf->valid_len - 2)
    {
      mbuf->pos = mbuf->valid_len;
      return 0;
    }

  memcpy (&v, mbuf->data + mbuf->pos, 2);
  mbuf->pos += 2;
102 103 104 105

  if (g_memory_buffer_is_byteswapped (mbuf))
    v = GUINT16_SWAP_LE_BE (v);

106 107 108 109
  return v;
}

static guint16
110
g_memory_buffer_read_uint16 (GMemoryBuffer  *mbuf)
111 112 113 114 115 116 117 118 119 120 121
{
  guint16 v;
  
  if (mbuf->pos > mbuf->valid_len - 2)
    {
      mbuf->pos = mbuf->valid_len;
      return 0;
    }

  memcpy (&v, mbuf->data + mbuf->pos, 2);
  mbuf->pos += 2;
122 123 124 125

  if (g_memory_buffer_is_byteswapped (mbuf))
    v = GUINT16_SWAP_LE_BE (v);

126 127 128 129
  return v;
}

static gint32
130
g_memory_buffer_read_int32 (GMemoryBuffer  *mbuf)
131 132 133 134 135 136 137 138 139 140 141
{
  gint32 v;
  
  if (mbuf->pos > mbuf->valid_len - 4)
    {
      mbuf->pos = mbuf->valid_len;
      return 0;
    }

  memcpy (&v, mbuf->data + mbuf->pos, 4);
  mbuf->pos += 4;
142 143 144 145

  if (g_memory_buffer_is_byteswapped (mbuf))
    v = GUINT32_SWAP_LE_BE (v);

146 147 148 149
  return v;
}

static guint32
150
g_memory_buffer_read_uint32 (GMemoryBuffer  *mbuf)
151 152 153 154 155 156 157 158 159 160 161
{
  guint32 v;
  
  if (mbuf->pos > mbuf->valid_len - 4)
    {
      mbuf->pos = mbuf->valid_len;
      return 0;
    }

  memcpy (&v, mbuf->data + mbuf->pos, 4);
  mbuf->pos += 4;
162 163 164 165

  if (g_memory_buffer_is_byteswapped (mbuf))
    v = GUINT32_SWAP_LE_BE (v);

166 167 168 169
  return v;
}

static gint64
170
g_memory_buffer_read_int64 (GMemoryBuffer  *mbuf)
171 172 173 174 175 176 177 178 179 180 181
{
  gint64 v;
  
  if (mbuf->pos > mbuf->valid_len - 8)
    {
      mbuf->pos = mbuf->valid_len;
      return 0;
    }

  memcpy (&v, mbuf->data + mbuf->pos, 8);
  mbuf->pos += 8;
182 183 184 185

  if (g_memory_buffer_is_byteswapped (mbuf))
    v = GUINT64_SWAP_LE_BE (v);

186 187 188 189
  return v;
}

static guint64
190
g_memory_buffer_read_uint64 (GMemoryBuffer  *mbuf)
191 192 193 194 195 196 197 198 199 200 201
{
  guint64 v;
  
  if (mbuf->pos > mbuf->valid_len - 8)
    {
      mbuf->pos = mbuf->valid_len;
      return 0;
    }

  memcpy (&v, mbuf->data + mbuf->pos, 8);
  mbuf->pos += 8;
202 203 204 205 206

  if (g_memory_buffer_is_byteswapped (mbuf))
    v = GUINT64_SWAP_LE_BE (v);

  return v;
207 208 209 210
}

#define MIN_ARRAY_SIZE  128

211 212
static gsize
g_nearest_pow (gsize num)
213
{
214
  gsize n = 1;
215

216
  while (n < num && n > 0)
217 218 219 220 221 222
    n <<= 1;

  return n;
}

static void
223 224
array_resize (GMemoryBuffer  *mbuf,
              gsize           size)
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
{
  gpointer data;
  gsize len;

  if (mbuf->len == size)
    return;

  len = mbuf->len;
  data = g_realloc (mbuf->data, size);

  if (size > len)
    memset ((guint8 *)data + len, 0, size - len);

  mbuf->data = data;
  mbuf->len = size;

  if (mbuf->len < mbuf->valid_len)
    mbuf->valid_len = mbuf->len;
}

static gboolean
g_memory_buffer_write (GMemoryBuffer  *mbuf,
247 248
                       const void     *buffer,
                       gsize           count)
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
{
  guint8   *dest;
  gsize new_size;

  if (count == 0)
    return TRUE;

  /* Check for address space overflow, but only if the buffer is resizable.
     Otherwise we just do a short write and don't worry. */
  if (mbuf->pos + count < mbuf->pos)
    return FALSE;

  if (mbuf->pos + count > mbuf->len)
    {
      /* At least enought to fit the write, rounded up
	     for greater than linear growth.
         TODO: This wastes a lot of memory at large buffer sizes.
               Figure out a more rational allocation strategy. */
      new_size = g_nearest_pow (mbuf->pos + count);
268 269 270 271
      /* Check for overflow again. We have checked if
         pos + count > G_MAXSIZE, but now check if g_nearest_pow () has
         overflowed */
      if (new_size == 0)
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 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 421 422 423 424
        return FALSE;

      new_size = MAX (new_size, MIN_ARRAY_SIZE);
      array_resize (mbuf, new_size);
    }

  dest = (guint8 *)mbuf->data + mbuf->pos;
  memcpy (dest, buffer, count);
  mbuf->pos += count;

  if (mbuf->pos > mbuf->valid_len)
    mbuf->valid_len = mbuf->pos;

  return TRUE;
}

static gboolean
g_memory_buffer_put_byte (GMemoryBuffer  *mbuf,
			  guchar          data)
{
  return g_memory_buffer_write (mbuf, &data, 1);
}

static gboolean
g_memory_buffer_put_int16 (GMemoryBuffer  *mbuf,
			   gint16          data)
{
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      data = GINT16_TO_BE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      data = GINT16_TO_LE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  
  return g_memory_buffer_write (mbuf, &data, 2);
}

static gboolean
g_memory_buffer_put_uint16 (GMemoryBuffer  *mbuf,
			    guint16         data)
{
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      data = GUINT16_TO_BE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      data = GUINT16_TO_LE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  
  return g_memory_buffer_write (mbuf, &data, 2);
}

static gboolean
g_memory_buffer_put_int32 (GMemoryBuffer  *mbuf,
			   gint32          data)
{
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      data = GINT32_TO_BE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      data = GINT32_TO_LE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  
  return g_memory_buffer_write (mbuf, &data, 4);
}

static gboolean
g_memory_buffer_put_uint32 (GMemoryBuffer  *mbuf,
			    guint32         data)
{
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      data = GUINT32_TO_BE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      data = GUINT32_TO_LE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  
  return g_memory_buffer_write (mbuf, &data, 4);
}

static gboolean
g_memory_buffer_put_int64 (GMemoryBuffer  *mbuf,
			   gint64          data)
{
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      data = GINT64_TO_BE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      data = GINT64_TO_LE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  
  return g_memory_buffer_write (mbuf, &data, 8);
}

static gboolean
g_memory_buffer_put_uint64 (GMemoryBuffer  *mbuf,
			    guint64         data)
{
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      data = GUINT64_TO_BE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      data = GUINT64_TO_LE (data);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  
  return g_memory_buffer_write (mbuf, &data, 8);
}

static gboolean
g_memory_buffer_put_string (GMemoryBuffer  *mbuf,
			    const char     *str)
{
  g_return_val_if_fail (str != NULL, FALSE);

  return g_memory_buffer_write (mbuf, str, strlen (str));
}


425 426 427
/**
 * SECTION:gdbusmessage
 * @short_description: D-Bus Message
David Zeuthen's avatar
David Zeuthen committed
428
 * @include: gio/gio.h
429 430 431 432 433
 *
 * A type for representing D-Bus messages that can be sent or received
 * on a #GDBusConnection.
 */

434
typedef struct _GDBusMessageClass GDBusMessageClass;
435 436 437 438 439 440 441 442 443 444 445 446 447 448

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

449 450 451 452 453 454 455 456 457
/**
 * GDBusMessage:
 *
 * The #GDBusMessage structure contains only private data and should
 * only be accessed using the provided API.
 *
 * Since: 2.26
 */
struct _GDBusMessage
458
{
459 460 461
  /*< private >*/
  GObject parent_instance;

462 463
  GDBusMessageType type;
  GDBusMessageFlags flags;
464 465
  gboolean locked;
  GDBusMessageByteOrder byte_order;
466 467 468 469 470 471 472
  guchar major_protocol_version;
  guint32 serial;
  GHashTable *headers;
  GVariant *body;
#ifdef G_OS_UNIX
  GUnixFDList *fd_list;
#endif
473 474 475 476 477 478
};

enum
{
  PROP_0,
  PROP_LOCKED
479 480
};

481
G_DEFINE_TYPE (GDBusMessage, g_dbus_message, G_TYPE_OBJECT)
482 483 484 485 486 487

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

488 489 490 491
  if (message->headers != NULL)
    g_hash_table_unref (message->headers);
  if (message->body != NULL)
    g_variant_unref (message->body);
492
#ifdef G_OS_UNIX
493 494
  if (message->fd_list != NULL)
    g_object_unref (message->fd_list);
495 496 497 498 499 500
#endif

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

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
static void
g_dbus_message_get_property (GObject    *object,
                             guint       prop_id,
                             GValue     *value,
                             GParamSpec *pspec)
{
  GDBusMessage *message = G_DBUS_MESSAGE (object);

  switch (prop_id)
    {
    case PROP_LOCKED:
      g_value_set_boolean (value, g_dbus_message_get_locked (message));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

521 522 523 524 525 526 527
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;
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
  gobject_class->get_property = g_dbus_message_get_property;

  /**
   * GDBusConnection:locked:
   *
   * A boolean specifying whether the message is locked.
   *
   * Since: 2.26
   */
  g_object_class_install_property (gobject_class,
                                   PROP_LOCKED,
                                   g_param_spec_boolean ("locked",
                                                         P_("Locked"),
                                                         P_("Whether the message is locked"),
                                                         FALSE,
                                                         G_PARAM_READABLE |
                                                         G_PARAM_STATIC_NAME |
                                                         G_PARAM_STATIC_BLURB |
                                                         G_PARAM_STATIC_NICK));
547 548 549 550 551
}

static void
g_dbus_message_init (GDBusMessage *message)
{
552 553 554 555 556 557 558 559 560 561 562 563
  /* 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
564 565 566 567
  message->headers = g_hash_table_new_full (g_direct_hash,
                                            g_direct_equal,
                                            NULL,
                                            (GDestroyNotify) g_variant_unref);
568 569 570 571 572 573 574 575
}

/**
 * g_dbus_message_new:
 *
 * Creates a new empty #GDBusMessage.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
576 577
 *
 * Since: 2.26
578 579 580 581 582 583 584 585 586
 */
GDBusMessage *
g_dbus_message_new (void)
{
  return g_object_new (G_TYPE_DBUS_MESSAGE, NULL);
}

/**
 * g_dbus_message_new_method_call:
587
 * @name: (nullable): A valid D-Bus name or %NULL.
588
 * @path: A valid object path.
589
 * @interface_: (nullable): A valid D-Bus interface name or %NULL.
590 591 592 593 594
 * @method: A valid method name.
 *
 * Creates a new #GDBusMessage for a method call.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
595 596
 *
 * Since: 2.26
597 598 599 600
 */
GDBusMessage *
g_dbus_message_new_method_call (const gchar *name,
                                const gchar *path,
601
                                const gchar *interface_,
602 603 604 605 606 607 608
                                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);
609
  g_return_val_if_fail (interface_ == NULL || g_dbus_is_interface_name (interface_), NULL);
610 611

  message = g_dbus_message_new ();
612
  message->type = G_DBUS_MESSAGE_TYPE_METHOD_CALL;
613 614 615 616 617

  if (name != NULL)
    g_dbus_message_set_destination (message, name);
  g_dbus_message_set_path (message, path);
  g_dbus_message_set_member (message, method);
618 619
  if (interface_ != NULL)
    g_dbus_message_set_interface (message, interface_);
620 621 622 623 624 625 626

  return message;
}

/**
 * g_dbus_message_new_signal:
 * @path: A valid object path.
627
 * @interface_: A valid D-Bus interface name.
628 629 630 631 632
 * @signal: A valid signal name.
 *
 * Creates a new #GDBusMessage for a signal emission.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
633 634
 *
 * Since: 2.26
635 636 637
 */
GDBusMessage *
g_dbus_message_new_signal (const gchar  *path,
638
                           const gchar  *interface_,
639 640 641 642 643 644
                           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);
645
  g_return_val_if_fail (g_dbus_is_interface_name (interface_), NULL);
646 647

  message = g_dbus_message_new ();
648 649
  message->type = G_DBUS_MESSAGE_TYPE_SIGNAL;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
650 651 652

  g_dbus_message_set_path (message, path);
  g_dbus_message_set_member (message, signal);
653
  g_dbus_message_set_interface (message, interface_);
654 655 656 657 658 659 660 661 662 663 664 665

  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.
 *
666
 * Returns: (transfer full):  #GDBusMessage. Free with g_object_unref().
667 668
 *
 * Since: 2.26
669 670 671 672 673 674 675 676
 */
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);
677
  g_return_val_if_fail (g_dbus_message_get_message_type (method_call_message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL, NULL);
678 679 680
  g_return_val_if_fail (g_dbus_message_get_serial (method_call_message) != 0, NULL);

  message = g_dbus_message_new ();
681 682
  message->type = G_DBUS_MESSAGE_TYPE_METHOD_RETURN;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
683 684
  /* reply with same endianness */
  message->byte_order = method_call_message->byte_order;
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

  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.
 *
704
 * Returns: (transfer full): A #GDBusMessage. Free with g_object_unref().
705 706
 *
 * Since: 2.26
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
 */
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.
 *
736
 * Returns: (transfer full): A #GDBusMessage. Free with g_object_unref().
737 738
 *
 * Since: 2.26
739 740 741 742 743 744 745 746 747 748
 */
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);
749
  g_return_val_if_fail (g_dbus_message_get_message_type (method_call_message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL, NULL);
750 751 752 753 754
  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 ();
755 756
  message->type = G_DBUS_MESSAGE_TYPE_ERROR;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
757 758
  /* reply with same endianness */
  message->byte_order = method_call_message->byte_order;
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

  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.
 *
781
 * Returns: (transfer full): A #GDBusMessage. Free with g_object_unref().
782 783
 *
 * Since: 2.26
784
 */
785
G_GNUC_PRINTF(3, 0)
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
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;
}

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

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
/**
 * 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));
831 832 833 834 835 836 837

  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

838 839 840 841 842
  message->byte_order = byte_order;
}

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

843 844 845
/* TODO: need GI annotations to specify that any guchar value goes for the type */

/**
846
 * g_dbus_message_get_message_type:
847 848 849 850 851
 * @message: A #GDBusMessage.
 *
 * Gets the type of @message.
 *
 * Returns: A 8-bit unsigned integer (typically a value from the #GDBusMessageType enumeration).
852 853
 *
 * Since: 2.26
854 855
 */
GDBusMessageType
856
g_dbus_message_get_message_type (GDBusMessage  *message)
857 858
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), G_DBUS_MESSAGE_TYPE_INVALID);
859
  return message->type;
860 861 862
}

/**
863
 * g_dbus_message_set_message_type:
864 865 866 867
 * @message: A #GDBusMessage.
 * @type: A 8-bit unsigned integer (typically a value from the #GDBusMessageType enumeration).
 *
 * Sets @message to be of @type.
868 869
 *
 * Since: 2.26
870 871
 */
void
872 873
g_dbus_message_set_message_type (GDBusMessage      *message,
                                 GDBusMessageType   type)
874 875 876
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail (type >=0 && type < 256);
877 878 879 880 881 882 883

  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

884
  message->type = type;
885 886 887 888 889 890 891 892 893 894 895 896 897
}

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

/* 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).
898 899
 *
 * Since: 2.26
900 901 902 903 904
 */
GDBusMessageFlags
g_dbus_message_get_flags (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), G_DBUS_MESSAGE_FLAGS_NONE);
905
  return message->flags;
906 907 908 909 910 911 912 913 914
}

/**
 * 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.
915 916
 *
 * Since: 2.26
917 918 919 920 921 922 923
 */
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);
924 925 926 927 928 929 930

  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

931
  message->flags = flags;
932 933 934 935 936 937 938 939 940 941 942
}

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

/**
 * g_dbus_message_get_serial:
 * @message: A #GDBusMessage.
 *
 * Gets the serial for @message.
 *
 * Returns: A #guint32.
943 944
 *
 * Since: 2.26
945 946 947 948 949
 */
guint32
g_dbus_message_get_serial (GDBusMessage *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), 0);
950
  return message->serial;
951 952 953 954 955 956 957 958
}

/**
 * g_dbus_message_set_serial:
 * @message: A #GDBusMessage.
 * @serial: A #guint32.
 *
 * Sets the serial for @message.
959 960
 *
 * Since: 2.26
961 962 963 964 965 966
 */
void
g_dbus_message_set_serial (GDBusMessage  *message,
                           guint32        serial)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
967 968 969 970 971 972 973

  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

974
  message->serial = serial;
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
}

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

/* 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.
990 991
 *
 * Since: 2.26
992 993 994 995 996 997 998
 */
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);
999
  return g_hash_table_lookup (message->headers, GUINT_TO_POINTER (header_field));
1000 1001 1002 1003 1004 1005
}

/**
 * g_dbus_message_set_header:
 * @message: A #GDBusMessage.
 * @header_field: A 8-bit unsigned integer (typically a value from the #GDBusMessageHeaderField enumeration)
1006
 * @value: (nullable): A #GVariant to set the header field or %NULL to clear the header field.
1007 1008 1009 1010
 *
 * Sets a header field on @message.
 *
 * If @value is floating, @message assumes ownership of @value.
1011 1012
 *
 * Since: 2.26
1013 1014 1015 1016 1017 1018 1019 1020
 */
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);
1021 1022 1023 1024 1025 1026 1027

  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

1028 1029
  if (value == NULL)
    {
1030
      g_hash_table_remove (message->headers, GUINT_TO_POINTER (header_field));
1031 1032 1033
    }
  else
    {
1034
      g_hash_table_insert (message->headers, GUINT_TO_POINTER (header_field), g_variant_ref_sink (value));
1035 1036 1037 1038 1039 1040 1041 1042 1043
    }
}

/**
 * g_dbus_message_get_header_fields:
 * @message: A #GDBusMessage.
 *
 * Gets an array of all header fields on @message that are set.
 *
1044 1045 1046
 * Returns: (array zero-terminated=1): An array of header fields
 * terminated by %G_DBUS_MESSAGE_HEADER_FIELD_INVALID.  Each element
 * is a #guchar. Free with g_free().
1047 1048
 *
 * Since: 2.26
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
 */
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);

1061
  keys = g_hash_table_get_keys (message->headers);
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
  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.
 *
1081 1082
 * Returns: (transfer none): A #GVariant or %NULL if the body is
 * empty. Do not free, it is owned by @message.
1083 1084
 *
 * Since: 2.26
1085 1086 1087 1088 1089
 */
GVariant *
g_dbus_message_get_body (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1090
  return message->body;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
}

/**
 * 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.
1103 1104
 *
 * Since: 2.26
1105 1106 1107 1108 1109 1110 1111 1112
 */
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));

1113 1114 1115 1116 1117 1118
  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

1119 1120
  if (message->body != NULL)
    g_variant_unref (message->body);
1121 1122
  if (body == NULL)
    {
1123
      message->body = NULL;
1124 1125 1126 1127 1128 1129 1130 1131
      g_dbus_message_set_signature (message, NULL);
    }
  else
    {
      const gchar *type_string;
      gsize type_string_len;
      gchar *signature;

1132
      message->body = g_variant_ref_sink (body);
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

      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.
 *
1154
 * Returns: (transfer none):A #GUnixFDList or %NULL if no file descriptors are
1155
 * associated. Do not free, this object is owned by @message.
1156 1157
 *
 * Since: 2.26
1158 1159 1160 1161 1162
 */
GUnixFDList *
g_dbus_message_get_unix_fd_list (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1163
  return message->fd_list;
1164 1165 1166 1167 1168
}

/**
 * g_dbus_message_set_unix_fd_list:
 * @message: A #GDBusMessage.
1169
 * @fd_list: (nullable): A #GUnixFDList or %NULL.
1170 1171 1172 1173 1174 1175 1176
 *
 * 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.
1177 1178
 *
 * Since: 2.26
1179 1180 1181 1182 1183 1184 1185
 */
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));
1186 1187 1188 1189 1190 1191 1192

  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

1193 1194
  if (message->fd_list != NULL)
    g_object_unref (message->fd_list);
1195 1196
  if (fd_list != NULL)
    {
1197
      message->fd_list = g_object_ref (fd_list);
1198 1199 1200 1201
      g_dbus_message_set_num_unix_fds (message, g_unix_fd_list_get_length (fd_list));
    }
  else
    {
1202
      message->fd_list = NULL;
1203 1204 1205 1206 1207 1208 1209
      g_dbus_message_set_num_unix_fds (message, 0);
    }
}
#endif

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

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
static guint
get_type_fixed_size (const GVariantType *type)
{
  /* NB: we do not treat 'b' as fixed-size here because GVariant and
   * D-Bus disagree about the size.
   */
  switch (*g_variant_type_peek_string (type))
    {
    case 'y':
      return 1;
    case 'n': case 'q':
      return 2;
    case 'i': case 'u': case 'h':
      return 4;
1224
    case 'x': case 't': case 'd':
1225 1226 1227 1228 1229 1230
      return 8;
    default:
      return 0;
    }
}

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
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;
}

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

1330
static gboolean
1331 1332
ensure_input_padding (GMemoryBuffer  *buf,
                      gsize           padding_size)
1333 1334 1335 1336
{
  gsize offset;
  gsize wanted_offset;

1337
  offset = buf->pos;
1338
  wanted_offset = ((offset + padding_size - 1) / padding_size) * padding_size;
1339 1340
  buf->pos = wanted_offset;
  return TRUE;
1341 1342
}

1343
static const gchar *
1344 1345 1346
read_string (GMemoryBuffer  *mbuf,
             gsize           len,
             GError        **error)
1347
{
1348
  gchar *str;
1349
  const gchar *end_valid;
1350

1351
  if G_UNLIKELY (mbuf->pos + len >= mbuf->valid_len || mbuf->pos + len < mbuf->pos)
1352
    {
1353
      mbuf->pos = mbuf->valid_len;
1354 1355 1356 1357 1358 1359
      /* G_GSIZE_FORMAT doesn't work with gettext, so we use %lu */
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   g_dngettext (GETTEXT_PACKAGE,
                                "Wanted to read %lu byte but only got %lu",
1360
                                "Wanted to read %lu bytes but only got %lu",
1361 1362
                                (gulong)len),
                                (gulong)len,
1363
                   (gulong)(mbuf->valid_len - mbuf->pos));
1364
      return NULL;
1365 1366
    }

1367
  if G_UNLIKELY (mbuf->data[mbuf->pos + len] != '\0')
1368
    {
1369 1370 1371 1372
      str = g_strndup (mbuf->data + mbuf->pos, len);
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
1373
                   _("Expected NUL byte after the string “%s” but found byte %d"),
1374 1375 1376 1377
                   str, mbuf->data[mbuf->pos + len]);
      g_free (str);
      mbuf->pos += len + 1;
      return NULL;
1378
    }
1379 1380 1381 1382

  str = mbuf->data + mbuf->pos;
  mbuf->pos += len + 1;

1383
  if G_UNLIKELY (!g_utf8_validate (str, -1, &end_valid))
1384 1385 1386
    {
      gint offset;
      gchar *valid_str;
1387 1388
      offset = (gint) (end_valid - str);
      valid_str = g_strndup (str, offset);
1389 1390 1391 1392
      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). "
1393
                     "The valid UTF-8 string up until that point was “%s”"),
1394
                   offset,
1395
                   (gint) len,
1396 1397
                   valid_str);
      g_free (valid_str);
1398
      return NULL;
1399 1400
    }

1401
  return str;
1402 1403
}

1404 1405 1406 1407 1408 1409 1410
static gconstpointer
read_bytes (GMemoryBuffer  *mbuf,
            gsize           len,
            GError        **error)
{
  gconstpointer result;

1411
  if G_UNLIKELY (mbuf->pos + len > mbuf->valid_len || mbuf->pos + len < mbuf->pos)
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    {
      mbuf->pos = mbuf->valid_len;
      /* G_GSIZE_FORMAT doesn't work with gettext, so we use %lu */
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
                   g_dngettext (GETTEXT_PACKAGE,
                                "Wanted to read %lu byte but only got %lu",
                                "Wanted to read %lu bytes but only got %lu",
                                (gulong)len),
                                (gulong)len,
                   (gulong)(mbuf->valid_len - mbuf->pos));
      return NULL;
    }

  result = mbuf->data + mbuf->pos;
  mbuf->pos += len;

  return result;
}

1433
/* if just_align==TRUE, don't read a value, just align the input stream wrt padding */
1434 1435

/* returns a non-floating GVariant! */
1436
static GVariant *
1437 1438 1439 1440 1441
parse_value_from_blob (GMemoryBuffer       *buf,
                       const GVariantType  *type,
                       gboolean             just_align,
                       guint                indent,
                       GError             **error)
1442 1443 1444
{
  GVariant *ret;
  GError *local_error;
1445
#ifdef DEBUG_SERIALIZER
1446
  gboolean is_leaf;
1447
#endif /* DEBUG_SERIALIZER */
1448 1449 1450
  const gchar *type_string;

  type_string = g_variant_type_peek_string (type);
1451

1452 1453 1454 1455
#ifdef DEBUG_SERIALIZER
    {
      gchar *s;
      s = g_variant_type_dup_string (type);
1456
      g_print ("%*s%s type %s from offset 0x%04x",
1457
               indent, "",
1458
               just_align ? "Aligning" : "Reading",
1459
               s,
1460
               (gint) buf->pos);
1461 1462 1463
      g_free (s);
    }
#endif /* DEBUG_SERIALIZER */
1464 1465 1466

  ret = NULL;

1467
#ifdef DEBUG_SERIALIZER
1468
  is_leaf = TRUE;
1469
#endif /* DEBUG_SERIALIZER */
1470
  local_error = NULL;
1471
  switch (type_string[0])
1472
    {
1473
    case 'b': /* G_VARIANT_TYPE_BOOLEAN */
1474
      ensure_input_padding (buf, 4);
1475 1476 1477
      if (!just_align)
        {
          gboolean v;
1478
          v = g_memory_buffer_read_uint32 (buf);
1479 1480
          ret = g_variant_new_boolean (v);
        }
1481 1482 1483
      break;

    case 'y': /* G_VARIANT_TYPE_BYTE */
1484 1485 1486
      if (!just_align)
        {
          guchar v;
1487
          v = g_memory_buffer_read_byte (buf);
1488 1489
          ret = g_variant_new_byte (v);
        }
1490 1491 1492
      break;

    case 'n': /* G_VARIANT_TYPE_INT16 */
1493
      ensure_input_padding (buf, 2);
1494 1495 1496
      if (!just_align)
        {
          gint16 v;
1497
          v = g_memory_buffer_read_int16 (buf);
1498 1499
          ret = g_variant_new_int16 (v);
        }
1500 1501 1502
      break;

    case 'q': /* G_VARIANT_TYPE_UINT16 */
1503
      ensure_input_padding (buf, 2);
1504 1505 1506
      if (!just_align)
        {
          guint16 v;
1507
          v = g_memory_buffer_read_uint16 (buf);
1508 1509
          ret = g_variant_new_uint16 (v);
        }
1510 1511 1512
      break;

    case 'i': /* G_VARIANT_TYPE_INT32 */
1513
      ensure_input_padding (buf, 4);
1514 1515 1516
      if (!just_align)
        {
          gint32 v;
1517
          v = g_memory_buffer_read_int32 (buf);
1518 1519
          ret = g_variant_new_int32 (v);
        }
1520 1521 1522
      break;

    case 'u': /* G_VARIANT_TYPE_UINT32 */
1523
      ensure_input_padding (buf, 4);
1524 1525 1526
      if (!just_align)
        {
          guint32 v;
1527
          v = g_memory_buffer_read_uint32 (buf);
1528 1529
          ret = g_variant_new_uint32 (v);
        }
1530 1531 1532
      break;

    case 'x': /* G_VARIANT_TYPE_INT64 */
1533
      ensure_input_padding (buf, 8);
1534 1535 1536
      if (!just_align)
        {
          gint64 v;
1537
          v = g_memory_buffer_read_int64 (buf);
1538 1539
          ret = g_variant_new_int64 (v);
        }
1540 1541 1542
      break;

    case 't': /* G_VARIANT_TYPE_UINT64 */
1543
      ensure_input_padding (buf, 8);
1544 1545 1546
      if (!just_align)
        {
          guint64 v;
1547
          v = g_memory_buffer_read_uint64 (buf);
1548 1549
          ret = g_variant_new_uint64 (v);
        }
1550 1551 1552
      break;

    case 'd': /* G_VARIANT_TYPE_DOUBLE */
1553
      ensure_input_padding (buf, 8);
1554 1555
      if (!just_align)
        {
1556 1557 1558 1559
          union {
            guint64 v_uint64;
            gdouble v_double;
          } u;
1560
          G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
1561
          u.v_uint64 = g_memory_buffer_read_uint64 (buf);
1562
          ret = g_variant_new_double (u.v_double);
1563
        }
1564 1565 1566
      break;

    case 's': /* G_VARIANT_TYPE_STRING */
1567
      ensure_input_padding (buf, 4);
1568 1569 1570
      if (!just_align)
        {
          guint32 len;
1571
          const gchar *v;
1572
          len = g_memory_buffer_read_uint32 (buf);
1573
          v = read_string (buf, (gsize) len, &local_error);
1574 1575 1576 1577
          if (v == NULL)
            goto fail;
          ret = g_variant_new_string (v);
        }
1578 1579 1580
      break;

    case 'o': /* G_VARIANT_TYPE_OBJECT_PATH */
1581
      ensure_input_padding (buf, 4);
1582
      if (!just_align)
1583
        {
1584
          guint32 len;
1585
          const gchar *v;
1586
          len = g_memory_buffer_read_uint32 (buf);
1587
          v = read_string (buf, (gsize) len, &local_error);
1588 1589 1590 1591 1592 1593 1594
          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,
1595
                           _("Parsed value “%s” is not a valid D-Bus object path"),
1596 1597 1598 1599
                           v);
              goto fail;
            }
          ret = g_variant_new_object_path (v);
1600
        }
1601 1602 1603
      break;

    case 'g': /* G_VARIANT_TYPE_SIGNATURE */
1604
      if (!just_align)
1605
        {
1606
          guchar len;
1607
          const gchar *v;
1608
          len = g_memory_buffer_read_byte (buf);
1609
          v = read_string (buf, (gsize) len, &local_error);
1610 1611 1612 1613 1614 1615 1616
          if (v == NULL)
            goto fail;
          if (!g_variant_is_signature (v))
            {
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
1617
                           _("Parsed value “%s” is not a valid D-Bus signature"),
1618
                       v);
1619 1620 1621
              goto fail;
            }
          ret = g_variant_new_signature (v);
1622
        }
1623 1624 1625
      break;

    case 'h': /* G_VARIANT_TYPE_HANDLE */
1626
      ensure_input_padding (buf, 4);
1627 1628 1629
      if (!just_align)
        {
          gint32 v;
1630
          v = g_memory_buffer_read_int32 (buf);
1631 1632
          ret = g_variant_new_handle (v);
        }
1633
      break;
1634

1635
    case 'a': /* G_VARIANT_TYPE_ARRAY */
1636
      ensure_input_padding (buf, 4);
1637

1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
      /* If we are only aligning for this array type, it is the child type of
       * another array, which is empty. So, we do not need to add padding for
       * this nonexistent array's elements: we only need to align for this
       * array itself (4 bytes). See
       * <https://bugzilla.gnome.org/show_bug.cgi?id=673612>.
       */
      if (!just_align)
        {
          guint32 array_len;
          const GVariantType *element_type;
1648
          guint fixed_size;
1649

1650
          array_len = g_memory_buffer_read_uint32 (buf);
1651

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

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
          if (array_len > (2<<26))
            {
              /* G_GUINT32_FORMAT doesn't work with gettext, so use u */
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           g_dngettext (GETTEXT_PACKAGE,
                                        "Encountered array of length %u byte. Maximum length is 2<<26 bytes (64 MiB).",
                                        "Encountered array of length %u bytes. Maximum length is 2<<26 bytes (64 MiB).",
                                        array_len),
                           array_len);
              goto fail;
            }

          element_type = g_variant_type_element (type);
1672
          fixed_size = get_type_fixed_size (element_type);
1673

1674 1675
          /* Fast-path the cases like 'ay', etc. */
          if (fixed_size != 0)
1676
            {
1677 1678 1679 1680 1681 1682 1683
              gconstpointer array_data;

              if (array_len % fixed_size != 0)
                {
                  g_set_error (&local_error,
                               G_IO_ERROR,
                               G_IO_ERROR_INVALID_ARGUMENT,
1684
                               _("Encountered array of type “a%c”, expected to have a length a multiple "
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
                                 "of %u bytes, but found to be %u bytes in length"),
                               g_variant_type_peek_string (element_type)[0], fixed_size, array_len);
                  goto fail;
                }

              ensure_input_padding (buf, fixed_size);
              array_data = read_bytes (buf, array_len, &local_error);
              if (array_data == NULL)
                goto fail;

              ret = g_variant_new_fixed_array (element_type, array_data, array_len / fixed_size, fixed_size);

              if (g_memory_buffer_is_byteswapped (buf))
                {
                  GVariant *tmp = g_variant_ref_sink (ret);
                  ret = g_variant_byteswap (tmp);
                  g_variant_unref (tmp);
                }
1703 1704 1705
            }
          else
            {
1706 1707 1708 1709 1710 1711 1712
              GVariantBuilder builder;
              goffset offset;
              goffset target;

              g_variant_builder_init (&builder, type);

              if (array_len == 0)
1713 1714
                {
                  GVariant *item;
1715
                  item = parse_value_from_blob (buf,
1716
                                                element_type,
1717
                                                TRUE,
1718
                                                indent + 2,
1719 1720 1721 1722 1723 1724 1725 1726
                                                NULL);
                  g_assert (item == NULL);
                }
              else
                {
                  offset = buf->pos;
                  target = offset + array_len;
                  while (offset < target)
1727
                    {
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
                      GVariant *item;
                      item = parse_value_from_blob (buf,
                                                    element_type,
                                                    FALSE,
                                                    indent + 2,
                                                    &local_error);
                      if (item == NULL)
                        {
                          g_variant_builder_clear (&builder);
                          goto fail;
                        }
                      g_variant_builder_add_value (&builder, item);
                      g_variant_unref (item);
                      offset = buf->pos;
1742 1743 1744
                    }
                }

1745 1746
              ret = g_variant_builder_end (&builder);
            }
1747
        }
1748 1749 1750 1751
      break;

    default:
      if (g_variant_type_is_dict_entry (type))
1752
        {
1753 1754 1755 1756 1757
          const GVariantType *key_type;
          const GVariantType *value_type;
          GVariant *key;
          GVariant *value;

1758
          ensure_input_padding (buf, 8);
1759 1760

#ifdef DEBUG_SERIALIZER
1761
          is_leaf = FALSE;
1762
          g_print ("\n");
1763 1764
#endif /* DEBUG_SERIALIZER */

1765
          if (!just_align)
1766
            {
1767
              key_type = g_variant_type_key (type);
1768
              key = parse_value_from_blob (buf,
1769 1770 1771 1772 1773 1774 1775
                                           key_type,
                                           FALSE,
                                           indent + 2,
                                           &local_error);
              if (key == NULL)
                goto fail;
              value_type = g_variant_type_value (type);
1776
              value = parse_value_from_blob (buf,
1777 1778 1779 1780 1781
                                             value_type,
                                             FALSE,
                                             indent + 2,
                                             &local_error);
              if (value == NULL)