gdbusmessage.c 104 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
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
32 33 34
#ifdef HAVE_SYS_MKDEV_H
#include <sys/mkdev.h>
#endif
Matthias Clasen's avatar
Matthias Clasen committed
35 36 37
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
38 39 40 41 42 43 44 45 46 47 48 49 50

#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"
51
#include "gdbusprivate.h"
52 53

#ifdef G_OS_UNIX
54
#include "gunixfdlist.h"
55 56
#endif

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

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
typedef struct _GMemoryBuffer GMemoryBuffer;
struct _GMemoryBuffer
{
  gsize len;
  gsize valid_len;
  gsize pos;
  gchar *data;
  GDataStreamByteOrder byte_order;
};

static guchar
g_memory_buffer_read_byte (GMemoryBuffer  *mbuf,
			   GError            **error)
{
  if (mbuf->pos >= mbuf->valid_len)
    return 0;
  return mbuf->data [mbuf->pos++];
}

static gint16
g_memory_buffer_read_int16 (GMemoryBuffer  *mbuf,
			    GError            **error)
{
  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;
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      v = GINT16_FROM_BE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      v = GINT16_FROM_LE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  return v;
}

static guint16
g_memory_buffer_read_uint16 (GMemoryBuffer  *mbuf,
			     GError            **error)
{
  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;
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      v = GINT16_FROM_BE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      v = GINT16_FROM_LE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  return v;
}

static gint32
g_memory_buffer_read_int32 (GMemoryBuffer  *mbuf,
			    GError            **error)
{
  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;
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      v = GINT32_FROM_BE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      v = GINT32_FROM_LE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  return v;
}

static guint32
g_memory_buffer_read_uint32 (GMemoryBuffer  *mbuf,
			     GError            **error)
{
  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;
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      v = GUINT32_FROM_BE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      v = GUINT32_FROM_LE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  return v;
}

static gint64
g_memory_buffer_read_int64 (GMemoryBuffer  *mbuf,
			    GError            **error)
{
  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;
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      v = GINT64_FROM_BE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      v = GINT64_FROM_LE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
    default:
      break;
    }
  return v;
}

static guint64
g_memory_buffer_read_uint64 (GMemoryBuffer  *mbuf,
			     GError            **error)
{
  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;
  switch (mbuf->byte_order)
    {
    case G_DATA_STREAM_BYTE_ORDER_BIG_ENDIAN:
      v = GUINT64_FROM_BE (v);
      break;
    case G_DATA_STREAM_BYTE_ORDER_LITTLE_ENDIAN:
      v = GUINT64_FROM_LE (v);
      break;
	case G_DATA_STREAM_BYTE_ORDER_HOST_ENDIAN:
	default:
	  break;
	}
      return v;
}

#define MIN_ARRAY_SIZE  128

static gint
g_nearest_pow (gint num)
{
  gint n = 1;

  while (n < num)
    n <<= 1;

  return n;
}

static void
array_resize (GMemoryBuffer *mbuf,
              gsize                 size)
{
  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,
                              const void     *buffer,
                              gsize           count)
{
  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);
      /* Check for overflow again. We have only checked if
         pos + count > G_MAXSIZE, but it only catches the case of writing
         more than 4GiB total on a 32-bit system. There's still the problem
         of g_nearest_pow overflowing above 0x7fffffff, so we're
         effectively limited to 2GiB. */
      if (new_size < mbuf->len)
        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));
}


470 471 472
/**
 * SECTION:gdbusmessage
 * @short_description: D-Bus Message
David Zeuthen's avatar
David Zeuthen committed
473
 * @include: gio/gio.h
474 475 476 477 478
 *
 * A type for representing D-Bus messages that can be sent or received
 * on a #GDBusConnection.
 */

479
typedef struct _GDBusMessageClass GDBusMessageClass;
480 481 482 483 484 485 486 487 488 489 490 491 492 493

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

494 495 496 497 498 499 500 501 502
/**
 * GDBusMessage:
 *
 * The #GDBusMessage structure contains only private data and should
 * only be accessed using the provided API.
 *
 * Since: 2.26
 */
struct _GDBusMessage
503
{
504 505 506
  /*< private >*/
  GObject parent_instance;

507 508
  GDBusMessageType type;
  GDBusMessageFlags flags;
509 510
  gboolean locked;
  GDBusMessageByteOrder byte_order;
511 512 513 514 515 516 517
  guchar major_protocol_version;
  guint32 serial;
  GHashTable *headers;
  GVariant *body;
#ifdef G_OS_UNIX
  GUnixFDList *fd_list;
#endif
518 519 520 521 522 523
};

enum
{
  PROP_0,
  PROP_LOCKED
524 525 526 527 528 529 530 531 532
};

G_DEFINE_TYPE (GDBusMessage, g_dbus_message, G_TYPE_OBJECT);

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

533 534 535 536
  if (message->headers != NULL)
    g_hash_table_unref (message->headers);
  if (message->body != NULL)
    g_variant_unref (message->body);
537
#ifdef G_OS_UNIX
538 539
  if (message->fd_list != NULL)
    g_object_unref (message->fd_list);
540 541 542 543 544 545
#endif

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

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
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;
    }
}

566 567 568 569 570 571 572
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;
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  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));
592 593 594 595 596
}

static void
g_dbus_message_init (GDBusMessage *message)
{
597 598 599 600 601 602 603 604 605 606 607 608
  /* 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
609 610 611 612
  message->headers = g_hash_table_new_full (g_direct_hash,
                                            g_direct_equal,
                                            NULL,
                                            (GDestroyNotify) g_variant_unref);
613 614 615 616 617 618 619 620
}

/**
 * g_dbus_message_new:
 *
 * Creates a new empty #GDBusMessage.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
621 622
 *
 * Since: 2.26
623 624 625 626 627 628 629 630 631
 */
GDBusMessage *
g_dbus_message_new (void)
{
  return g_object_new (G_TYPE_DBUS_MESSAGE, NULL);
}

/**
 * g_dbus_message_new_method_call:
632
 * @name: (allow-none): A valid D-Bus name or %NULL.
633
 * @path: A valid object path.
634
 * @interface_: (allow-none): A valid D-Bus interface name or %NULL.
635 636 637 638 639
 * @method: A valid method name.
 *
 * Creates a new #GDBusMessage for a method call.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
640 641
 *
 * Since: 2.26
642 643 644 645
 */
GDBusMessage *
g_dbus_message_new_method_call (const gchar *name,
                                const gchar *path,
646
                                const gchar *interface_,
647 648 649 650 651 652 653
                                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);
654
  g_return_val_if_fail (interface_ == NULL || g_dbus_is_interface_name (interface_), NULL);
655 656

  message = g_dbus_message_new ();
657
  message->type = G_DBUS_MESSAGE_TYPE_METHOD_CALL;
658 659 660 661 662

  if (name != NULL)
    g_dbus_message_set_destination (message, name);
  g_dbus_message_set_path (message, path);
  g_dbus_message_set_member (message, method);
663 664
  if (interface_ != NULL)
    g_dbus_message_set_interface (message, interface_);
665 666 667 668 669 670 671

  return message;
}

/**
 * g_dbus_message_new_signal:
 * @path: A valid object path.
672
 * @interface_: A valid D-Bus interface name.
673 674 675 676 677
 * @signal: A valid signal name.
 *
 * Creates a new #GDBusMessage for a signal emission.
 *
 * Returns: A #GDBusMessage. Free with g_object_unref().
678 679
 *
 * Since: 2.26
680 681 682
 */
GDBusMessage *
g_dbus_message_new_signal (const gchar  *path,
683
                           const gchar  *interface_,
684 685 686 687 688 689
                           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);
690
  g_return_val_if_fail (g_dbus_is_interface_name (interface_), NULL);
691 692

  message = g_dbus_message_new ();
693 694
  message->type = G_DBUS_MESSAGE_TYPE_SIGNAL;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
695 696 697

  g_dbus_message_set_path (message, path);
  g_dbus_message_set_member (message, signal);
698
  g_dbus_message_set_interface (message, interface_);
699 700 701 702 703 704 705 706 707 708 709 710

  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.
 *
711
 * Returns: (transfer full):  #GDBusMessage. Free with g_object_unref().
712 713
 *
 * Since: 2.26
714 715 716 717 718 719 720 721
 */
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);
722
  g_return_val_if_fail (g_dbus_message_get_message_type (method_call_message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL, NULL);
723 724 725
  g_return_val_if_fail (g_dbus_message_get_serial (method_call_message) != 0, NULL);

  message = g_dbus_message_new ();
726 727
  message->type = G_DBUS_MESSAGE_TYPE_METHOD_RETURN;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
728 729
  /* reply with same endianness */
  message->byte_order = method_call_message->byte_order;
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

  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.
 *
749
 * Returns: (transfer full): A #GDBusMessage. Free with g_object_unref().
750 751
 *
 * Since: 2.26
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
 */
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.
 *
781
 * Returns: (transfer full): A #GDBusMessage. Free with g_object_unref().
782 783
 *
 * Since: 2.26
784 785 786 787 788 789 790 791 792 793
 */
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);
794
  g_return_val_if_fail (g_dbus_message_get_message_type (method_call_message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL, NULL);
795 796 797 798 799
  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 ();
800 801
  message->type = G_DBUS_MESSAGE_TYPE_ERROR;
  message->flags = G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
802 803
  /* reply with same endianness */
  message->byte_order = method_call_message->byte_order;
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825

  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.
 *
826
 * Returns: (transfer full): A #GDBusMessage. Free with g_object_unref().
827 828
 *
 * Since: 2.26
829
 */
830
G_GNUC_PRINTF(3, 0)
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
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;
}

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

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
/**
 * 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));
876 877 878 879 880 881 882

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

883 884 885 886 887
  message->byte_order = byte_order;
}

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

888 889 890
/* TODO: need GI annotations to specify that any guchar value goes for the type */

/**
891
 * g_dbus_message_get_message_type:
892 893 894 895 896
 * @message: A #GDBusMessage.
 *
 * Gets the type of @message.
 *
 * Returns: A 8-bit unsigned integer (typically a value from the #GDBusMessageType enumeration).
897 898
 *
 * Since: 2.26
899 900
 */
GDBusMessageType
901
g_dbus_message_get_message_type (GDBusMessage  *message)
902 903
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), G_DBUS_MESSAGE_TYPE_INVALID);
904
  return message->type;
905 906 907
}

/**
908
 * g_dbus_message_set_message_type:
909 910 911 912
 * @message: A #GDBusMessage.
 * @type: A 8-bit unsigned integer (typically a value from the #GDBusMessageType enumeration).
 *
 * Sets @message to be of @type.
913 914
 *
 * Since: 2.26
915 916
 */
void
917 918
g_dbus_message_set_message_type (GDBusMessage      *message,
                                 GDBusMessageType   type)
919 920 921
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
  g_return_if_fail (type >=0 && type < 256);
922 923 924 925 926 927 928

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

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

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

/* 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).
943 944
 *
 * Since: 2.26
945 946 947 948 949
 */
GDBusMessageFlags
g_dbus_message_get_flags (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), G_DBUS_MESSAGE_FLAGS_NONE);
950
  return message->flags;
951 952 953 954 955 956 957 958 959
}

/**
 * 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.
960 961
 *
 * Since: 2.26
962 963 964 965 966 967 968
 */
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);
969 970 971 972 973 974 975

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

976
  message->flags = flags;
977 978 979 980 981 982 983 984 985 986 987
}

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

/**
 * g_dbus_message_get_serial:
 * @message: A #GDBusMessage.
 *
 * Gets the serial for @message.
 *
 * Returns: A #guint32.
988 989
 *
 * Since: 2.26
990 991 992 993 994
 */
guint32
g_dbus_message_get_serial (GDBusMessage *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), 0);
995
  return message->serial;
996 997 998 999 1000 1001 1002 1003
}

/**
 * g_dbus_message_set_serial:
 * @message: A #GDBusMessage.
 * @serial: A #guint32.
 *
 * Sets the serial for @message.
1004 1005
 *
 * Since: 2.26
1006 1007 1008 1009 1010 1011
 */
void
g_dbus_message_set_serial (GDBusMessage  *message,
                           guint32        serial)
{
  g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1012 1013 1014 1015 1016 1017 1018

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

1019
  message->serial = serial;
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
}

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

/* 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.
1035 1036
 *
 * Since: 2.26
1037 1038 1039 1040 1041 1042 1043
 */
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);
1044
  return g_hash_table_lookup (message->headers, GUINT_TO_POINTER (header_field));
1045 1046 1047 1048 1049 1050
}

/**
 * g_dbus_message_set_header:
 * @message: A #GDBusMessage.
 * @header_field: A 8-bit unsigned integer (typically a value from the #GDBusMessageHeaderField enumeration)
1051
 * @value: (allow-none): A #GVariant to set the header field or %NULL to clear the header field.
1052 1053 1054 1055
 *
 * Sets a header field on @message.
 *
 * If @value is floating, @message assumes ownership of @value.
1056 1057
 *
 * Since: 2.26
1058 1059 1060 1061 1062 1063 1064 1065
 */
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);
1066 1067 1068 1069 1070 1071 1072

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

1073 1074
  if (value == NULL)
    {
1075
      g_hash_table_remove (message->headers, GUINT_TO_POINTER (header_field));
1076 1077 1078
    }
  else
    {
1079
      g_hash_table_insert (message->headers, GUINT_TO_POINTER (header_field), g_variant_ref_sink (value));
1080 1081 1082 1083 1084 1085 1086 1087 1088
    }
}

/**
 * g_dbus_message_get_header_fields:
 * @message: A #GDBusMessage.
 *
 * Gets an array of all header fields on @message that are set.
 *
1089 1090 1091
 * 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().
1092 1093
 *
 * Since: 2.26
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
 */
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);

1106
  keys = g_hash_table_get_keys (message->headers);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  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.
1127 1128
 *
 * Since: 2.26
1129 1130 1131 1132 1133
 */
GVariant *
g_dbus_message_get_body (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1134
  return message->body;
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
}

/**
 * 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.
1147 1148
 *
 * Since: 2.26
1149 1150 1151 1152 1153 1154 1155 1156
 */
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));

1157 1158 1159 1160 1161 1162
  if (message->locked)
    {
      g_warning ("%s: Attempted to modify a locked message", G_STRFUNC);
      return;
    }

1163 1164
  if (message->body != NULL)
    g_variant_unref (message->body);
1165 1166
  if (body == NULL)
    {
1167
      message->body = NULL;
1168 1169 1170 1171 1172 1173 1174 1175
      g_dbus_message_set_signature (message, NULL);
    }
  else
    {
      const gchar *type_string;
      gsize type_string_len;
      gchar *signature;

1176
      message->body = g_variant_ref_sink (body);
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

      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.
 *
1198
 * Returns: (transfer none):A #GUnixFDList or %NULL if no file descriptors are
1199
 * associated. Do not free, this object is owned by @message.
1200 1201
 *
 * Since: 2.26
1202 1203 1204 1205 1206
 */
GUnixFDList *
g_dbus_message_get_unix_fd_list (GDBusMessage  *message)
{
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1207
  return message->fd_list;
1208 1209 1210 1211 1212
}

/**
 * g_dbus_message_set_unix_fd_list:
 * @message: A #GDBusMessage.
Matthias Clasen's avatar
Matthias Clasen committed
1213
 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
1214 1215 1216 1217 1218 1219 1220
 *
 * 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.
1221 1222
 *
 * Since: 2.26
1223 1224 1225 1226 1227 1228 1229
 */
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));
1230 1231 1232 1233 1234 1235 1236

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

1237 1238
  if (message->fd_list != NULL)
    g_object_unref (message->fd_list);
1239 1240
  if (fd_list != NULL)
    {
1241
      message->fd_list = g_object_ref (fd_list);
1242 1243 1244 1245
      g_dbus_message_set_num_unix_fds (message, g_unix_fd_list_get_length (fd_list));
    }
  else
    {
1246
      message->fd_list = NULL;
1247 1248 1249 1250 1251 1252 1253
      g_dbus_message_set_num_unix_fds (message, 0);
    }
}
#endif

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

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 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
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;
}

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

1353
static gboolean
1354
ensure_input_padding (GMemoryBuffer         *buf,
1355 1356 1357 1358 1359 1360
                      gsize                 padding_size,
                      GError              **error)
{
  gsize offset;
  gsize wanted_offset;

1361
  offset = buf->pos;
1362
  wanted_offset = ((offset + padding_size - 1) / padding_size) * padding_size;
1363 1364
  buf->pos = wanted_offset;
  return TRUE;
1365 1366
}

1367
static const gchar *
1368
read_string (GMemoryBuffer          *mbuf,
1369 1370 1371
             gsize                  len,
             GError               **error)
{
1372
  gchar *str;
1373
  const gchar *end_valid;
1374 1375

  if (mbuf->pos + len >= mbuf->valid_len || mbuf->pos + len < mbuf->pos)
1376
    {
1377
      mbuf->pos = mbuf->valid_len;
1378 1379 1380 1381 1382 1383
      /* 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",
1384
                                "Wanted to read %lu bytes but only got %lu",
1385 1386
                                (gulong)len),
                                (gulong)len,
1387
                   (gulong)(mbuf->valid_len - mbuf->pos));
1388 1389
      mbuf->pos = mbuf->valid_len;
      return NULL;
1390 1391
    }

1392
  if (mbuf->data[mbuf->pos + len] != '\0')
1393
    {
1394 1395 1396 1397
      str = g_strndup (mbuf->data + mbuf->pos, len);
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
1398
                   _("Expected NUL byte after the string '%s' but found byte %d"),
1399 1400 1401 1402
                   str, mbuf->data[mbuf->pos + len]);
      g_free (str);
      mbuf->pos += len + 1;
      return NULL;
1403
    }
1404 1405 1406 1407

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

1408
  if (!g_utf8_validate (str, -1, &end_valid))
1409 1410 1411
    {
      gint offset;
      gchar *valid_str;
1412 1413
      offset = (gint) (end_valid - str);
      valid_str = g_strndup (str, offset);
1414 1415 1416 1417
      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). "
1418
                     "The valid UTF-8 string up until that point was '%s'"),
1419
                   offset,
1420
                   (gint) len,
1421 1422
                   valid_str);
      g_free (valid_str);
1423
      return NULL;
1424 1425
    }

1426
  return str;
1427 1428
}

1429
/* if just_align==TRUE, don't read a value, just align the input stream wrt padding */
1430 1431

/* returns a non-floating GVariant! */
1432
static GVariant *
1433
parse_value_from_blob (GMemoryBuffer          *buf,
1434
                       const GVariantType    *type,
1435
                       gboolean               just_align,
1436
                       guint                  indent,
1437 1438 1439 1440
                       GError               **error)
{
  GVariant *ret;
  GError *local_error;
1441
  gboolean is_leaf;
1442 1443 1444
  const gchar *type_string;

  type_string = g_variant_type_peek_string (type);
1445

1446 1447 1448 1449
#ifdef DEBUG_SERIALIZER
    {
      gchar *s;
      s = g_variant_type_dup_string (type);
1450
      g_print ("%*s%s type %s from offset 0x%04x",
1451
               indent, "",
1452
               just_align ? "Aligning" : "Reading",
1453
               s,
1454
               (gint) g_seekable_tell (G_SEEKABLE (buf)));
1455 1456 1457
      g_free (s);
    }
#endif /* DEBUG_SERIALIZER */
1458 1459 1460

  ret = NULL;

1461
  is_leaf = TRUE;
1462
  local_error = NULL;
1463
  switch (type_string[0])
1464
    {
1465
    case 'b': /* G_VARIANT_TYPE_BOOLEAN */
1466
      if (!ensure_input_padding (buf, 4, &local_error))
1467
        goto fail;
1468 1469 1470
      if (!just_align)
        {
          gboolean v;
1471
          v = g_memory_buffer_read_uint32 (buf, &local_error);
1472 1473 1474 1475
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_boolean (v);
        }
1476 1477 1478
      break;

    case 'y': /* G_VARIANT_TYPE_BYTE */
1479 1480 1481
      if (!just_align)
        {
          guchar v;
1482
          v = g_memory_buffer_read_byte (buf, &local_error);
1483 1484 1485 1486
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_byte (v);
        }
1487 1488 1489
      break;

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

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

    case 'i': /* G_VARIANT_TYPE_INT32 */
1516
      if (!ensure_input_padding (buf, 4, &local_error))
1517
        goto fail;
1518 1519 1520
      if (!just_align)
        {
          gint32 v;
1521
          v = g_memory_buffer_read_int32 (buf, &local_error);
1522 1523 1524 1525
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_int32 (v);
        }
1526 1527 1528
      break;

    case 'u': /* G_VARIANT_TYPE_UINT32 */
1529
      if (!ensure_input_padding (buf, 4, &local_error))
1530
        goto fail;
1531 1532 1533
      if (!just_align)
        {
          guint32 v;
1534
          v = g_memory_buffer_read_uint32 (buf, &local_error);
1535 1536 1537 1538
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_uint32 (v);
        }
1539 1540 1541
      break;

    case 'x': /* G_VARIANT_TYPE_INT64 */
1542
      if (!ensure_input_padding (buf, 8, &local_error))
1543
        goto fail;
1544 1545 1546
      if (!just_align)
        {
          gint64 v;
1547
          v = g_memory_buffer_read_int64 (buf, &local_error);
1548 1549 1550 1551
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_int64 (v);
        }
1552 1553 1554
      break;

    case 't': /* G_VARIANT_TYPE_UINT64 */
1555
      if (!ensure_input_padding (buf, 8, &local_error))
1556
        goto fail;
1557 1558 1559
      if (!just_align)
        {
          guint64 v;
1560
          v = g_memory_buffer_read_uint64 (buf, &local_error);
1561 1562 1563 1564
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_uint64 (v);
        }
1565 1566 1567
      break;

    case 'd': /* G_VARIANT_TYPE_DOUBLE */
1568
      if (!ensure_input_padding (buf, 8, &local_error))
1569
        goto fail;
1570 1571
      if (!just_align)
        {
1572 1573 1574 1575
          union {
            guint64 v_uint64;
            gdouble v_double;
          } u;
1576
          G_STATIC_ASSERT (sizeof (gdouble) == sizeof (guint64));
1577
          u.v_uint64 = g_memory_buffer_read_uint64 (buf, &local_error);
1578 1579
          if (local_error != NULL)
            goto fail;
1580
          ret = g_variant_new_double (u.v_double);
1581
        }
1582 1583 1584
      break;

    case 's': /* G_VARIANT_TYPE_STRING */
1585
      if (!ensure_input_padding (buf, 4, &local_error))
1586
        goto fail;
1587 1588 1589
      if (!just_align)
        {
          guint32 len;
1590
          const gchar *v;
1591
          len = g_memory_buffer_read_uint32 (buf, &local_error);
1592 1593
          if (local_error != NULL)
            goto fail;
1594
          v = read_string (buf, (gsize) len, &local_error);
1595 1596 1597 1598
          if (v == NULL)
            goto fail;
          ret = g_variant_new_string (v);
        }
1599 1600 1601
      break;

    case 'o': /* G_VARIANT_TYPE_OBJECT_PATH */
1602
      if (!ensure_input_padding (buf, 4, &local_error))
1603
        goto fail;
1604
      if (!just_align)
1605
        {
1606
          guint32 len;
1607
          const gchar *v;
1608
          len = g_memory_buffer_read_uint32 (buf, &local_error);
1609 1610
          if (local_error != NULL)
            goto fail;
1611
          v = read_string (buf, (gsize) len, &local_error);
1612 1613 1614 1615 1616 1617 1618
          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,
1619
                           _("Parsed value '%s' is not a valid D-Bus object path"),
1620 1621 1622 1623
                           v);
              goto fail;
            }
          ret = g_variant_new_object_path (v);
1624
        }
1625 1626 1627
      break;

    case 'g': /* G_VARIANT_TYPE_SIGNATURE */
1628
      if (!just_align)
1629
        {
1630
          guchar len;
1631
          const gchar *v;
1632
          len = g_memory_buffer_read_byte (buf, &local_error);
1633 1634
          if (local_error != NULL)
            goto fail;
1635
          v = read_string (buf, (gsize) len, &local_error);
1636 1637 1638 1639 1640 1641 1642
          if (v == NULL)
            goto fail;
          if (!g_variant_is_signature (v))
            {
              g_set_error (&local_error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
1643
                           _("Parsed value '%s' is not a valid D-Bus signature"),
1644
                       v);
1645 1646 1647
              goto fail;
            }
          ret = g_variant_new_signature (v);
1648
        }
1649 1650 1651
      break;

    case 'h': /* G_VARIANT_TYPE_HANDLE */
1652
      if (!ensure_input_padding (buf, 4, &local_error))
1653 1654 1655 1656
        goto fail;
      if (!just_align)
        {
          gint32 v;
1657
          v = g_memory_buffer_read_int32 (buf, &local_error);
1658 1659 1660 1661
          if (local_error != NULL)
            goto fail;
          ret = g_variant_new_handle (v);
        }
1662
      break;
1663

1664
    case 'a': /* G_VARIANT_TYPE_ARRAY */
1665
      if (!ensure_input_padding (buf, 4, &local_error))
1666
        goto fail;
1667

1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
      /* 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;
          goffset offset;
          goffset target;
          const GVariantType *element_type;
          GVariantBuilder builder;
1681

1682
          array_len = g_memory_buffer_read_uint32 (buf, &local_error);
1683 1684 1685 1686
          if (local_error != NULL)
            goto fail;

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

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
          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;
            }

          g_variant_builder_init (&builder, type);
          element_type = g_variant_type_element (type);

          if (array_len == 0)
            {
              GVariant *item;
1711
              item = parse_value_from_blob (buf,
1712 1713 1714 1715 1716 1717 1718 1719 1720
                                            element_type,
                                            TRUE,
                                            indent + 2,
                                            NULL);
              g_assert (item == NULL);
            }
          else
            {
              /* TODO: optimize array of primitive types */
1721
              offset = buf->pos;
1722 1723 1724 1725
              target = offset + array_len;
              while (offset < target)
                {
                  GVariant *item;
1726
                  item = parse_value_from_blob (buf,
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
                                                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);
1738
                  offset = buf->pos;
1739 1740 1741 1742 1743
                }
            }

          ret = g_variant_builder_end (&builder);
        }
1744 1745 1746 1747
      break;

    default:
      if (g_variant_type_is_dict_entry (type))
1748
        {
1749 1750 1751 1752 1753
          const GVariantType *key_type;
          const GVariantType *value_type;
          GVariant *key;
          GVariant *value;

1754
          if (!ensure_input_padding (buf, 8, &local_error))
1755 1756 1757 1758
            goto fail;

          is_leaf = FALSE;
#ifdef DEBUG_SERIALIZER
1759
          g_print ("\n");
1760 1761
#endif /* DEBUG_SERIALIZER */

1762
          if (!just_align)
1763
            {
1764
              key_type = g_variant_type_key (type);
1765
              key = parse_value_from_blob (buf,
1766 1767 1768 1769 1770 1771 1772
                                           key_type,
                                           FALSE,
                                           indent + 2,
                                           &local_error);
              if (key == NULL)
                goto fail;
              value_type = g_variant_type_value (type);
1773
              value = parse_value_from_blob (buf,
1774 1775 1776 1777 1778
                                             value_type,
                                             FALSE,
                                             indent + 2,
                                             &local_error);
              if (value == NULL)
1779
                {
1780
                  g_variant_unref (key);
1781 1782
                  goto fail;
                }
1783 1784 1785
              ret = g_variant_new_dict_entry (key, value);
              g_variant_unref (key);
              g_variant_unref (value);
1786 1787
            }
        }
1788
      else if (g_variant_type_is_tuple (type))
1789
        {
1790
          if (!ensure_input_padding (buf, 8, &local_error))
1791
            goto fail;
1792

1793
          is_leaf = FALSE;
1794
#ifdef DEBUG_SERIALIZER
1795
          g_print ("\n");
1796 1797
#endif /* DEBUG_SERIALIZER */

1798
          if (!just_align)
1799
            {
1800 1801 1802 1803 1804 1805 1806 1807
              const GVariantType *element_type;
              GVariantBuilder builder;

              g_variant_builder_init (&builder, type);
              element_type = g_variant_type_first (type);
              while (element_type != NULL)
                {
                  GVariant *item;
1808
                  item = parse_value_from_blob (buf,
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
                                                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);

                  element_type = g_variant_type_next (element_type);
                }
              ret = g_variant_builder_end (&builder);
1824
            }
1825
        }
1826 1827 1828
      else if (g_variant_type_is_variant (type))
        {
          is_leaf = FALSE;
1829
#ifdef DEBUG_SERIALIZER
1830
          g_print ("\n");
1831 1832
#endif /* DEBUG_SERIALIZER */

1833
          if (!just_align)
1834
            {
1835
              guchar siglen;
1836
              const gchar *sig;
1837 1838 1839
              GVariantType *variant_type;
              GVariant *value;

1840
              siglen = g_memory_buffer_read_byte (buf, &local_error);
1841 1842
              if (local_error != NULL)
                goto fail;
1843
              sig = read_string (buf, (gsize) siglen, &local_error);
1844 1845 1846
              if (sig == NULL)
                goto fail;
              if (!g_variant_is_signature (sig))
1847
                {
1848 1849 1850
                  g_set_error