dbus-message.c 147 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 3
/* dbus-message.c  DBusMessage object
 *
4
 * Copyright (C) 2002, 2003, 2004, 2005  Red Hat Inc.
5
 * Copyright (C) 2002, 2003  CodeFactory AB
6
 *
7
 * Licensed under the Academic Free License version 2.1
8
 *
9 10 11 12 13 14 15 16 17
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
18
 *
19 20
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22 23 24
 *
 */

25
#include <config.h>
26
#include "dbus-internals.h"
27 28
#include "dbus-marshal-recursive.h"
#include "dbus-marshal-validate.h"
29
#include "dbus-marshal-byteswap.h"
30
#include "dbus-marshal-header.h"
31
#include "dbus-signature.h"
32
#include "dbus-message-private.h"
33
#include "dbus-object-tree.h"
34 35
#include "dbus-memory.h"
#include "dbus-list.h"
36
#include "dbus-threads-internal.h"
37
#ifdef HAVE_UNIX_FD_PASSING
38
#include "dbus-sysdeps.h"
39 40 41
#include "dbus-sysdeps-unix.h"
#endif

42
#include <string.h>
43

44 45 46 47
#define _DBUS_TYPE_IS_STRINGLIKE(type) \
  (type == DBUS_TYPE_STRING || type == DBUS_TYPE_SIGNATURE || \
   type == DBUS_TYPE_OBJECT_PATH)

48 49
static void dbus_message_finalize (DBusMessage *message);

50
/**
51 52 53
 * @defgroup DBusMessageInternals DBusMessage implementation details
 * @ingroup DBusInternals
 * @brief DBusMessage private implementation details.
54
 *
55
 * The guts of DBusMessage and its methods.
56 57 58 59
 *
 * @{
 */

60
#ifdef DBUS_ENABLE_EMBEDDED_TESTS
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
static dbus_bool_t
_dbus_enable_message_cache (void)
{
  static int enabled = -1;

  if (enabled < 0)
    {
      const char *s = _dbus_getenv ("DBUS_MESSAGE_CACHE");

      enabled = TRUE;

      if (s && *s)
        {
          if (*s == '0')
            enabled = FALSE;
          else if (*s == '1')
            enabled = TRUE;
          else
            _dbus_warn ("DBUS_MESSAGE_CACHE should be 0 or 1 if set, not '%s'",
                s);
        }
    }

  return enabled;
}
#else
    /* constant expression, should be optimized away */
#   define _dbus_enable_message_cache() (TRUE)
#endif

91 92 93 94 95 96 97 98 99 100 101 102 103 104
#ifndef _dbus_message_trace_ref
void
_dbus_message_trace_ref (DBusMessage *message,
                         int          old_refcount,
                         int          new_refcount,
                         const char  *why)
{
  static int enabled = -1;

  _dbus_trace_ref ("DBusMessage", message, old_refcount, new_refcount, why,
      "DBUS_MESSAGE_TRACE", &enabled);
}
#endif

105
/* Not thread locked, but strictly const/read-only so should be OK
106
 */
107
/** An static string representing an empty signature */
108
_DBUS_STRING_DEFINE_STATIC(_dbus_empty_signature_str,  "");
109

110 111 112
/* these have wacky values to help trap uninitialized iterators;
 * but has to fit in 3 bits
 */
113
enum {
114 115
  DBUS_MESSAGE_ITER_TYPE_READER = 3,
  DBUS_MESSAGE_ITER_TYPE_WRITER = 7
116 117
};

118
/** typedef for internals of message iterator */
119 120
typedef struct DBusMessageRealIter DBusMessageRealIter;

121 122
/**
 * @brief Internals of DBusMessageIter
123
 *
124 125
 * Object representing a position in a message. All fields are internal.
 */
126
struct DBusMessageRealIter
127 128
{
  DBusMessage *message; /**< Message used */
129 130 131 132 133
  dbus_uint32_t changed_stamp : CHANGED_STAMP_BITS; /**< stamp to detect invalid iters */
  dbus_uint32_t iter_type : 3;      /**< whether this is a reader or writer iter */
  dbus_uint32_t sig_refcount : 8;   /**< depth of open_signature() */
  union
  {
134 135 136
    DBusTypeWriter writer; /**< writer */
    DBusTypeReader reader; /**< reader */
  } u; /**< the type writer or reader that does all the work */
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
static void
get_const_signature (DBusHeader        *header,
                     const DBusString **type_str_p,
                     int               *type_pos_p)
{
  if (_dbus_header_get_field_raw (header,
                                  DBUS_HEADER_FIELD_SIGNATURE,
                                  type_str_p,
                                  type_pos_p))
    {
      *type_pos_p += 1; /* skip the signature length which is 1 byte */
    }
  else
    {
      *type_str_p = &_dbus_empty_signature_str;
      *type_pos_p = 0;
    }
}

/**
 * Swaps the message to compiler byte order if required
 *
 * @param message the message
 */
static void
_dbus_message_byteswap (DBusMessage *message)
{
  const DBusString *type_str;
  int type_pos;
168 169 170 171 172
  char byte_order;

  byte_order = _dbus_header_get_byte_order (&message->header);

  if (byte_order == DBUS_COMPILER_BYTE_ORDER)
173 174 175 176 177 178 179
    return;

  _dbus_verbose ("Swapping message into compiler byte order\n");
  
  get_const_signature (&message->header, &type_str, &type_pos);
  
  _dbus_marshal_byteswap (type_str, type_pos,
180
                          byte_order,
181 182 183 184
                          DBUS_COMPILER_BYTE_ORDER,
                          &message->body, 0);

  _dbus_header_byteswap (&message->header, DBUS_COMPILER_BYTE_ORDER);
185 186
  _dbus_assert (_dbus_header_get_byte_order (&message->header) ==
                DBUS_COMPILER_BYTE_ORDER);
187 188
}

189 190 191 192 193 194
/** byte-swap the message if it doesn't match our byte order.
 *  Called only when we need the message in our own byte order,
 *  normally when reading arrays of integers or doubles.
 *  Otherwise should not be called since it would do needless
 *  work.
 */
195
#define ensure_byte_order(message) _dbus_message_byteswap (message)
196

197 198 199 200
/**
 * Gets the data to be sent over the network for this message.
 * The header and then the body should be written out.
 * This function is guaranteed to always return the same
201
 * data once a message is locked (with dbus_message_lock()).
202 203 204 205 206 207 208
 *
 * @param message the message.
 * @param header return location for message header data.
 * @param body return location for message body data.
 */
void
_dbus_message_get_network_data (DBusMessage          *message,
209 210
                                const DBusString    **header,
                                const DBusString    **body)
211 212
{
  _dbus_assert (message->locked);
213 214

  *header = &message->header.data;
215
  *body = &message->body;
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
/**
 * Gets the unix fds to be sent over the network for this message.
 * This function is guaranteed to always return the same data once a
 * message is locked (with dbus_message_lock()).
 *
 * @param message the message.
 * @param fds return location of unix fd array
 * @param n_fds return number of entries in array
 */
void _dbus_message_get_unix_fds(DBusMessage *message,
                                const int  **fds,
                                unsigned    *n_fds)
{
  _dbus_assert (message->locked);

#ifdef HAVE_UNIX_FD_PASSING
  *fds = message->unix_fds;
  *n_fds = message->n_unix_fds;
#else
  *fds = NULL;
  *n_fds = 0;
#endif
}

242 243 244 245
/**
 * Sets the serial number of a message.
 * This can only be done once on a message.
 *
246 247 248 249
 * DBusConnection will automatically set the serial to an appropriate value 
 * when the message is sent; this function is only needed when encapsulating 
 * messages in another protocol, or otherwise bypassing DBusConnection.
 *
250 251 252
 * @param message the message
 * @param serial the serial
 */
253 254 255
void 
dbus_message_set_serial (DBusMessage   *message,
                         dbus_uint32_t  serial)
256
{
257 258
  _dbus_return_if_fail (message != NULL);
  _dbus_return_if_fail (!message->locked);
259

260
  _dbus_header_set_serial (&message->header, serial);
261 262
}

263
/**
264 265 266 267 268 269
 * Adds a counter to be incremented immediately with the size/unix fds
 * of this message, and decremented by the size/unix fds of this
 * message when this message if finalized.  The link contains a
 * counter with its refcount already incremented, but the counter
 * itself not incremented.  Ownership of link and counter refcount is
 * passed to the message.
270
 *
271 272 273 274 275
 * This function may be called with locks held. As a result, the counter's
 * notify function is not called; the caller is expected to either call
 * _dbus_counter_notify() on the counter when they are no longer holding
 * locks, or take the same action that would be taken by the notify function.
 *
276 277 278 279
 * @param message the message
 * @param link link with counter as data
 */
void
280 281
_dbus_message_add_counter_link (DBusMessage  *message,
                                DBusList     *link)
282
{
283 284 285 286 287 288
  /* right now we don't recompute the delta when message
   * size changes, and that's OK for current purposes
   * I think, but could be important to change later.
   * Do recompute it whenever there are no outstanding counters,
   * since it's basically free.
   */
289
  if (message->counters == NULL)
290 291 292 293
    {
      message->size_counter_delta =
        _dbus_string_get_length (&message->header.data) +
        _dbus_string_get_length (&message->body);
294

295 296 297 298
#ifdef HAVE_UNIX_FD_PASSING
      message->unix_fd_counter_delta = message->n_unix_fds;
#endif

299 300 301 302 303
#if 0
      _dbus_verbose ("message has size %ld\n",
                     message->size_counter_delta);
#endif
    }
304

305
  _dbus_list_append_link (&message->counters, link);
306

307
  _dbus_counter_adjust_size (link->data, message->size_counter_delta);
308

309 310 311
#ifdef HAVE_UNIX_FD_PASSING
  _dbus_counter_adjust_unix_fd (link->data, message->unix_fd_counter_delta);
#endif
312 313
}

314
/**
315 316 317
 * Adds a counter to be incremented immediately with the size/unix fds
 * of this message, and decremented by the size/unix fds of this
 * message when this message if finalized.
318
 *
319 320 321 322 323
 * This function may be called with locks held. As a result, the counter's
 * notify function is not called; the caller is expected to either call
 * _dbus_counter_notify() on the counter when they are no longer holding
 * locks, or take the same action that would be taken by the notify function.
 *
324 325 326 327 328
 * @param message the message
 * @param counter the counter
 * @returns #FALSE if no memory
 */
dbus_bool_t
329 330
_dbus_message_add_counter (DBusMessage *message,
                           DBusCounter *counter)
331
{
332 333 334 335 336 337 338
  DBusList *link;

  link = _dbus_list_alloc_link (counter);
  if (link == NULL)
    return FALSE;

  _dbus_counter_ref (counter);
339
  _dbus_message_add_counter_link (message, link);
340 341

  return TRUE;
342 343
}

344
/**
345 346
 * Removes a counter tracking the size/unix fds of this message, and
 * decrements the counter by the size/unix fds of this message.
347 348 349 350 351
 *
 * @param message the message
 * @param counter the counter
 */
void
352
_dbus_message_remove_counter (DBusMessage  *message,
353
                              DBusCounter  *counter)
354
{
355
  DBusList *link;
356

357
  link = _dbus_list_find_last (&message->counters,
358 359
                               counter);
  _dbus_assert (link != NULL);
360

361
  _dbus_list_remove_link (&message->counters, link);
362

363 364 365 366 367
  _dbus_counter_adjust_size (counter, - message->size_counter_delta);

#ifdef HAVE_UNIX_FD_PASSING
  _dbus_counter_adjust_unix_fd (counter, - message->unix_fd_counter_delta);
#endif
368

369
  _dbus_counter_notify (counter);
370
  _dbus_counter_unref (counter);
371 372
}

373 374 375 376 377
/**
 * Locks a message. Allows checking that applications don't keep a
 * reference to a message in the outgoing queue and change it
 * underneath us. Messages are locked when they enter the outgoing
 * queue (dbus_connection_send_message()), and the library complains
378 379
 * if the message is modified while locked. This function may also 
 * called externally, for applications wrapping D-Bus in another protocol.
380 381 382 383
 *
 * @param message the message to lock.
 */
void
384
dbus_message_lock (DBusMessage  *message)
385
{
386 387 388 389
  if (!message->locked)
    {
      _dbus_header_update_lengths (&message->header,
                                   _dbus_string_get_length (&message->body));
390

391 392 393
      /* must have a signature if you have a body */
      _dbus_assert (_dbus_string_get_length (&message->body) == 0 ||
                    dbus_message_get_signature (message) != NULL);
394

395
      message->locked = TRUE;
396 397 398
    }
}

399
static dbus_bool_t
400 401 402 403
set_or_delete_string_field (DBusMessage *message,
                            int          field,
                            int          typecode,
                            const char  *value)
404
{
405 406 407 408 409 410 411 412
  if (value == NULL)
    return _dbus_header_delete_field (&message->header, field);
  else
    return _dbus_header_set_field_basic (&message->header,
                                         field,
                                         typecode,
                                         &value);
}
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
#if 0
/* Probably we don't need to use this */
/**
 * Sets the signature of the message, i.e. the arguments in the
 * message payload. The signature includes only "in" arguments for
 * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
 * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
 * what you might expect (it does not include the signature of the
 * entire C++-style method).
 *
 * The signature is a string made up of type codes such as
 * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
 * the value of #DBUS_TYPE_INVALID). The macros such as
 * #DBUS_TYPE_INT32 evaluate to integers; to assemble a signature you
 * may find it useful to use the string forms, such as
 * #DBUS_TYPE_INT32_AS_STRING.
 *
 * An "unset" or #NULL signature is considered the same as an empty
 * signature. In fact dbus_message_get_signature() will never return
 * #NULL.
 *
 * @param message the message
 * @param signature the type signature or #NULL to unset
 * @returns #FALSE if no memory
 */
439
static dbus_bool_t
440 441
_dbus_message_set_signature (DBusMessage *message,
                             const char  *signature)
442
{
443 444 445 446 447 448 449
  _dbus_return_val_if_fail (message != NULL, FALSE);
  _dbus_return_val_if_fail (!message->locked, FALSE);
  _dbus_return_val_if_fail (signature == NULL ||
                            _dbus_check_is_valid_signature (signature));
  /* can't delete the signature if you have a message body */
  _dbus_return_val_if_fail (_dbus_string_get_length (&message->body) == 0 ||
                            signature != NULL);
450

451 452 453 454 455 456
  return set_or_delete_string_field (message,
                                     DBUS_HEADER_FIELD_SIGNATURE,
                                     DBUS_TYPE_SIGNATURE,
                                     signature);
}
#endif
457

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
/* Message Cache
 *
 * We cache some DBusMessage to reduce the overhead of allocating
 * them.  In my profiling this consistently made about an 8%
 * difference.  It avoids the malloc for the message, the malloc for
 * the slot list, the malloc for the header string and body string,
 * and the associated free() calls. It does introduce another global
 * lock which could be a performance issue in certain cases.
 *
 * For the echo client/server the round trip time goes from around
 * .000077 to .000069 with the message cache on my laptop. The sysprof
 * change is as follows (numbers are cumulative percentage):
 *
 *  with message cache implemented as array as it is now (0.000069 per):
 *    new_empty_header           1.46
 *      mutex_lock               0.56    # i.e. _DBUS_LOCK(message_cache)
 *      mutex_unlock             0.25
 *      self                     0.41
 *    unref                      2.24
 *      self                     0.68
 *      list_clear               0.43
 *      mutex_lock               0.33    # i.e. _DBUS_LOCK(message_cache)
 *      mutex_unlock             0.25
 *
 *  with message cache implemented as list (0.000070 per roundtrip):
 *    new_empty_header           2.72
 *      list_pop_first           1.88
 *    unref                      3.3
 *      list_prepend             1.63
 *
 * without cache (0.000077 per roundtrip):
 *    new_empty_header           6.7
 *      string_init_preallocated 3.43
 *        dbus_malloc            2.43
 *      dbus_malloc0             2.59
 *
 *    unref                      4.02
 *      string_free              1.82
 *        dbus_free              1.63
 *      dbus_free                0.71
 *
 * If you implement the message_cache with a list, the primary reason
 * it's slower is that you add another thread lock (on the DBusList
 * mempool).
 */

504
/** Avoid caching huge messages */
505
#define MAX_MESSAGE_SIZE_TO_CACHE 10 * _DBUS_ONE_KILOBYTE
506 507

/** Avoid caching too many messages */
508 509
#define MAX_MESSAGE_CACHE_SIZE    5

510
/* Protected by _DBUS_LOCK (message_cache) */
511 512 513 514
static DBusMessage *message_cache[MAX_MESSAGE_CACHE_SIZE];
static int message_cache_count = 0;
static dbus_bool_t message_cache_shutdown_registered = FALSE;

515
static void
516
dbus_message_cache_shutdown (void *data)
517 518
{
  int i;
519

520 521 522
  if (!_DBUS_LOCK (message_cache))
    _dbus_assert_not_reached ("we would have initialized global locks "
        "before registering a shutdown function");
523

524
  i = 0;
525
  while (i < MAX_MESSAGE_CACHE_SIZE)
526
    {
527 528 529
      if (message_cache[i])
        dbus_message_finalize (message_cache[i]);

530
      ++i;
531
    }
532 533 534 535 536

  message_cache_count = 0;
  message_cache_shutdown_registered = FALSE;

  _DBUS_UNLOCK (message_cache);
537 538
}

539 540 541 542 543 544
/**
 * Tries to get a message from the message cache.  The retrieved
 * message will have junk in it, so it still needs to be cleared out
 * in dbus_message_new_empty_header()
 *
 * @returns the message, or #NULL if none cached
545
 */
546 547
static DBusMessage*
dbus_message_get_cached (void)
548
{
549 550 551 552 553
  DBusMessage *message;
  int i;

  message = NULL;

554 555 556 557 558 559
  if (!_DBUS_LOCK (message_cache))
    {
      /* we'd have initialized global locks before caching anything,
       * so there can't be anything in the cache */
      return NULL;
    }
560 561

  _dbus_assert (message_cache_count >= 0);
562

563
  if (message_cache_count == 0)
564
    {
565 566
      _DBUS_UNLOCK (message_cache);
      return NULL;
567
    }
568 569 570 571

  /* This is not necessarily true unless count > 0, and
   * message_cache is uninitialized until the shutdown is
   * registered
572
   */
573
  _dbus_assert (message_cache_shutdown_registered);
574

575 576
  i = 0;
  while (i < MAX_MESSAGE_CACHE_SIZE)
577
    {
578
      if (message_cache[i])
579
        {
580 581 582 583
          message = message_cache[i];
          message_cache[i] = NULL;
          message_cache_count -= 1;
          break;
584
        }
585
      ++i;
586
    }
587 588 589
  _dbus_assert (message_cache_count >= 0);
  _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
  _dbus_assert (message != NULL);
590

591 592
  _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);

593
  _dbus_assert (message->counters == NULL);
594 595
  
  _DBUS_UNLOCK (message_cache);
596 597

  return message;
598
}
599

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
#ifdef HAVE_UNIX_FD_PASSING
static void
close_unix_fds(int *fds, unsigned *n_fds)
{
  DBusError e;
  int i;

  if (*n_fds <= 0)
    return;

  dbus_error_init(&e);

  for (i = 0; i < *n_fds; i++)
    {
      if (!_dbus_close(fds[i], &e))
        {
          _dbus_warn("Failed to close file descriptor: %s\n", e.message);
          dbus_error_free(&e);
        }
    }

  *n_fds = 0;

  /* We don't free the array here, in case we can recycle it later */
}
#endif

627
static void
628 629
free_counter (void *element,
              void *data)
630 631 632 633
{
  DBusCounter *counter = element;
  DBusMessage *message = data;

634 635 636 637
  _dbus_counter_adjust_size (counter, - message->size_counter_delta);
#ifdef HAVE_UNIX_FD_PASSING
  _dbus_counter_adjust_unix_fd (counter, - message->unix_fd_counter_delta);
#endif
638

639
  _dbus_counter_notify (counter);
640 641 642
  _dbus_counter_unref (counter);
}

643 644 645 646 647 648 649
/**
 * Tries to cache a message, otherwise finalize it.
 *
 * @param message the message
 */
static void
dbus_message_cache_or_finalize (DBusMessage *message)
650
{
651 652
  dbus_bool_t was_cached;
  int i;
653 654

  _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
655

656 657 658 659
  /* This calls application code and has to be done first thing
   * without holding the lock
   */
  _dbus_data_slot_list_clear (&message->slot_list);
660

661 662 663
  _dbus_list_foreach (&message->counters,
                      free_counter, message);
  _dbus_list_clear (&message->counters);
664

665 666 667
#ifdef HAVE_UNIX_FD_PASSING
  close_unix_fds(message->unix_fds, &message->n_unix_fds);
#endif
668 669 670

  was_cached = FALSE;

671 672 673 674 675 676 677
  if (!_DBUS_LOCK (message_cache))
    {
      /* The only way to get a non-null message goes through
       * dbus_message_get_cached() which takes the lock. */
      _dbus_assert_not_reached ("we would have initialized global locks "
          "the first time we constructed a message");
    }
678 679

  if (!message_cache_shutdown_registered)
680
    {
681 682 683 684 685 686 687 688 689 690 691 692 693
      _dbus_assert (message_cache_count == 0);

      if (!_dbus_register_shutdown_func (dbus_message_cache_shutdown, NULL))
        goto out;

      i = 0;
      while (i < MAX_MESSAGE_CACHE_SIZE)
        {
          message_cache[i] = NULL;
          ++i;
        }

      message_cache_shutdown_registered = TRUE;
694 695
    }

696 697
  _dbus_assert (message_cache_count >= 0);

698 699 700
  if (!_dbus_enable_message_cache ())
    goto out;

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
  if ((_dbus_string_get_length (&message->header.data) +
       _dbus_string_get_length (&message->body)) >
      MAX_MESSAGE_SIZE_TO_CACHE)
    goto out;

  if (message_cache_count >= MAX_MESSAGE_CACHE_SIZE)
    goto out;

  /* Find empty slot */
  i = 0;
  while (message_cache[i] != NULL)
    ++i;

  _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);

  _dbus_assert (message_cache[i] == NULL);
  message_cache[i] = message;
  message_cache_count += 1;
  was_cached = TRUE;
720 721 722
#ifndef DBUS_DISABLE_CHECKS
  message->in_cache = TRUE;
#endif
723 724

 out:
725 726
  _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);

727 728
  _DBUS_UNLOCK (message_cache);
  
729 730
  if (!was_cached)
    dbus_message_finalize (message);
731 732
}

733
#if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
734 735 736
static dbus_bool_t
_dbus_message_iter_check (DBusMessageRealIter *iter)
{
737 738
  char byte_order;

739 740 741 742 743 744
  if (iter == NULL)
    {
      _dbus_warn_check_failed ("dbus message iterator is NULL\n");
      return FALSE;
    }

745 746
  byte_order = _dbus_header_get_byte_order (&iter->message->header);

747 748
  if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_READER)
    {
749
      if (iter->u.reader.byte_order != byte_order)
750 751 752 753 754 755 756 757 758
        {
          _dbus_warn_check_failed ("dbus message changed byte order since iterator was created\n");
          return FALSE;
        }
      /* because we swap the message into compiler order when you init an iter */
      _dbus_assert (iter->u.reader.byte_order == DBUS_COMPILER_BYTE_ORDER);
    }
  else if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER)
    {
759
      if (iter->u.writer.byte_order != byte_order)
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
        {
          _dbus_warn_check_failed ("dbus message changed byte order since append iterator was created\n");
          return FALSE;
        }
      /* because we swap the message into compiler order when you init an iter */
      _dbus_assert (iter->u.writer.byte_order == DBUS_COMPILER_BYTE_ORDER);
    }
  else
    {
      _dbus_warn_check_failed ("dbus message iterator looks uninitialized or corrupted\n");
      return FALSE;
    }

  if (iter->changed_stamp != iter->message->changed_stamp)
    {
      _dbus_warn_check_failed ("dbus message iterator invalid because the message has been modified (or perhaps the iterator is just uninitialized)\n");
      return FALSE;
    }

  return TRUE;
}
781
#endif /* DBUS_ENABLE_CHECKS || DBUS_ENABLE_ASSERT */
782

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
/**
 * Implementation of the varargs arg-getting functions.
 * dbus_message_get_args() is the place to go for complete
 * documentation.
 *
 * @see dbus_message_get_args
 * @param iter the message iter
 * @param error error to be filled in
 * @param first_arg_type type of the first argument
 * @param var_args return location for first argument, followed by list of type/location pairs
 * @returns #FALSE if error was set
 */
dbus_bool_t
_dbus_message_iter_get_args_valist (DBusMessageIter *iter,
                                    DBusError       *error,
                                    int              first_arg_type,
                                    va_list          var_args)
{
  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
802
  int spec_type, msg_type, i, j;
803
  dbus_bool_t retval;
804
  va_list copy_args;
805 806 807 808 809 810 811 812

  _dbus_assert (_dbus_message_iter_check (real));

  retval = FALSE;

  spec_type = first_arg_type;
  i = 0;

813 814 815
  /* copy var_args first, then we can do another iteration over it to
   * free memory and close unix fds if parse failed at some point.
   */
816
  DBUS_VA_COPY (copy_args, var_args);
817

818 819 820 821 822
  while (spec_type != DBUS_TYPE_INVALID)
    {
      msg_type = dbus_message_iter_get_arg_type (iter);

      if (msg_type != spec_type)
823
        {
824 825 826 827 828 829 830
          dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                          "Argument %d is specified to be of type \"%s\", but "
                          "is actually of type \"%s\"\n", i,
                          _dbus_type_to_string (spec_type),
                          _dbus_type_to_string (msg_type));

          goto out;
831
        }
832

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
      if (spec_type == DBUS_TYPE_UNIX_FD)
        {
#ifdef HAVE_UNIX_FD_PASSING
          DBusBasicValue idx;
          int *pfd, nfd;

          pfd = va_arg (var_args, int*);
          _dbus_assert(pfd);

          _dbus_type_reader_read_basic(&real->u.reader, &idx);

          if (idx.u32 >= real->message->n_unix_fds)
            {
              dbus_set_error (error, DBUS_ERROR_INCONSISTENT_MESSAGE,
                              "Message refers to file descriptor at index %i,"
                              "but has only %i descriptors attached.\n",
                              idx.u32,
                              real->message->n_unix_fds);
              goto out;
            }

          if ((nfd = _dbus_dup(real->message->unix_fds[idx.u32], error)) < 0)
            goto out;

          *pfd = nfd;
#else
          dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
                          "Platform does not support file desciptor passing.\n");
          goto out;
#endif
        }
      else if (dbus_type_is_basic (spec_type))
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
        {
          DBusBasicValue *ptr;

          ptr = va_arg (var_args, DBusBasicValue*);

          _dbus_assert (ptr != NULL);

          _dbus_type_reader_read_basic (&real->u.reader,
                                        ptr);
        }
      else if (spec_type == DBUS_TYPE_ARRAY)
        {
          int element_type;
          int spec_element_type;
          const DBusBasicValue **ptr;
          int *n_elements_p;
          DBusTypeReader array;

          spec_element_type = va_arg (var_args, int);
          element_type = _dbus_type_reader_get_element_type (&real->u.reader);

          if (spec_element_type != element_type)
            {
              dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                              "Argument %d is specified to be an array of \"%s\", but "
                              "is actually an array of \"%s\"\n",
                              i,
                              _dbus_type_to_string (spec_element_type),
                              _dbus_type_to_string (element_type));

              goto out;
            }

898 899
          if (dbus_type_is_fixed (spec_element_type) &&
              element_type != DBUS_TYPE_UNIX_FD)
900 901 902 903 904 905 906 907 908 909
            {
              ptr = va_arg (var_args, const DBusBasicValue**);
              n_elements_p = va_arg (var_args, int*);

              _dbus_assert (ptr != NULL);
              _dbus_assert (n_elements_p != NULL);

              _dbus_type_reader_recurse (&real->u.reader, &array);

              _dbus_type_reader_read_fixed_multi (&array,
910
                                                  (void *) ptr, n_elements_p);
911
            }
912
          else if (_DBUS_TYPE_IS_STRINGLIKE (spec_element_type))
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
            {
              char ***str_array_p;
              int n_elements;
              char **str_array;

              str_array_p = va_arg (var_args, char***);
              n_elements_p = va_arg (var_args, int*);

              _dbus_assert (str_array_p != NULL);
              _dbus_assert (n_elements_p != NULL);

              /* Count elements in the array */
              _dbus_type_reader_recurse (&real->u.reader, &array);

              n_elements = 0;
              while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
                {
                  ++n_elements;
                  _dbus_type_reader_next (&array);
                }

              str_array = dbus_new0 (char*, n_elements + 1);
              if (str_array == NULL)
                {
                  _DBUS_SET_OOM (error);
                  goto out;
                }

              /* Now go through and dup each string */
              _dbus_type_reader_recurse (&real->u.reader, &array);

944 945
              j = 0;
              while (j < n_elements)
946 947 948
                {
                  const char *s;
                  _dbus_type_reader_read_basic (&array,
949
                                                (void *) &s);
950
                  
951 952
                  str_array[j] = _dbus_strdup (s);
                  if (str_array[j] == NULL)
953 954 955 956 957 958
                    {
                      dbus_free_string_array (str_array);
                      _DBUS_SET_OOM (error);
                      goto out;
                    }
                  
959
                  ++j;
960 961
                  
                  if (!_dbus_type_reader_next (&array))
962
                    _dbus_assert (j == n_elements);
963 964 965
                }

              _dbus_assert (_dbus_type_reader_get_current_type (&array) == DBUS_TYPE_INVALID);
966 967
              _dbus_assert (j == n_elements);
              _dbus_assert (str_array[j] == NULL);
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

              *str_array_p = str_array;
              *n_elements_p = n_elements;
            }
#ifndef DBUS_DISABLE_CHECKS
          else
            {
              _dbus_warn ("you can't read arrays of container types (struct, variant, array) with %s for now\n",
                          _DBUS_FUNCTION_NAME);
              goto out;
            }
#endif
        }
#ifndef DBUS_DISABLE_CHECKS
      else
        {
          _dbus_warn ("you can only read arrays and basic types with %s for now\n",
                      _DBUS_FUNCTION_NAME);
          goto out;
        }
#endif

990 991 992
      /* how many arguments already handled */
      i++;

993 994 995 996
      spec_type = va_arg (var_args, int);
      if (!_dbus_type_reader_next (&real->u.reader) && spec_type != DBUS_TYPE_INVALID)
        {
          dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
997
                          "Message has only %d arguments, but more were expected", i);
998 999 1000 1001 1002 1003 1004
          goto out;
        }
    }

  retval = TRUE;

 out:
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  /* there may memory or unix fd leak in the above iteration if parse failed.
   * so we have another iteration over copy_args to free memory and close
   * unix fds.
   */
  if (!retval)
    {
      spec_type = first_arg_type;
      j = 0;

      while (j < i)
        {
          if (spec_type == DBUS_TYPE_UNIX_FD)
            {
#ifdef HAVE_UNIX_FD_PASSING
              int *pfd;

              pfd = va_arg (copy_args, int *);
              _dbus_assert(pfd);
              if (*pfd >= 0)
                {
                  _dbus_close (*pfd, NULL);
                  *pfd = -1;
                }
#endif
            }
          else if (dbus_type_is_basic (spec_type))
            {
              /* move the index forward */
              va_arg (copy_args, DBusBasicValue *);
            }
          else if (spec_type == DBUS_TYPE_ARRAY)
            {
              int spec_element_type;

              spec_element_type = va_arg (copy_args, int);
              if (dbus_type_is_fixed (spec_element_type))
                {
                  /* move the index forward */
                  va_arg (copy_args, const DBusBasicValue **);
                  va_arg (copy_args, int *);
                }
              else if (_DBUS_TYPE_IS_STRINGLIKE (spec_element_type))
                {
                  char ***str_array_p;

                  str_array_p = va_arg (copy_args, char ***);
                  /* move the index forward */
                  va_arg (copy_args, int *);
                  _dbus_assert (str_array_p != NULL);
                  dbus_free_string_array (*str_array_p);
                  *str_array_p = NULL;
                }
            }

          spec_type = va_arg (copy_args, int);
          j++;
        }
    }
1063

1064
  va_end (copy_args);
1065 1066 1067
  return retval;
}

1068 1069 1070 1071 1072
/** @} */

/**
 * @defgroup DBusMessage DBusMessage
 * @ingroup  DBus
1073
 * @brief Message to be sent or received over a #DBusConnection.
1074 1075 1076 1077 1078 1079
 *
 * A DBusMessage is the most basic unit of communication over a
 * DBusConnection. A DBusConnection represents a stream of messages
 * received from a remote application, and a stream of messages
 * sent to a remote application.
 *
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
 * A message has a message type, returned from
 * dbus_message_get_type().  This indicates whether the message is a
 * method call, a reply to a method call, a signal, or an error reply.
 *
 * A message has header fields such as the sender, destination, method
 * or signal name, and so forth. DBusMessage has accessor functions for
 * these, such as dbus_message_get_member().
 *
 * Convenience functions dbus_message_is_method_call(), dbus_message_is_signal(),
 * and dbus_message_is_error() check several header fields at once and are
 * slightly more efficient than checking the header fields with individual
 * accessor functions.
 *
 * Finally, a message has arguments. The number and types of arguments
 * are in the message's signature header field (accessed with
 * dbus_message_get_signature()).  Simple argument values are usually
 * retrieved with dbus_message_get_args() but more complex values such
 * as structs may require the use of #DBusMessageIter.
 *
 * The D-Bus specification goes into some more detail about header fields and
 * message types.
 * 
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
 * @{
 */

/**
 * @typedef DBusMessage
 *
 * Opaque data type representing a message received from or to be
 * sent to another application.
 */

/**
 * Returns the serial of a message or 0 if none has been specified.
 * The message's serial number is provided by the application sending
1115 1116 1117 1118 1119 1120 1121
 * the message and is used to identify replies to this message.
 *
 * All messages received on a connection will have a serial provided
 * by the remote application.
 *
 * For messages you're sending, dbus_connection_send() will assign a
 * serial and return it to you.
1122 1123
 *
 * @param message the message
1124
 * @returns the serial
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
 */
dbus_uint32_t
dbus_message_get_serial (DBusMessage *message)
{
  _dbus_return_val_if_fail (message != NULL, 0);

  return _dbus_header_get_serial (&message->header);
}

/**
1135 1136
 * Sets the reply serial of a message (the serial of the message this
 * is a reply to).
1137 1138
 *
 * @param message the message
1139
 * @param reply_serial the serial we're replying to
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
 * @returns #FALSE if not enough memory
 */
dbus_bool_t
dbus_message_set_reply_serial (DBusMessage   *message,
                               dbus_uint32_t  reply_serial)
{
  _dbus_return_val_if_fail (message != NULL, FALSE);
  _dbus_return_val_if_fail (!message->locked, FALSE);
  _dbus_return_val_if_fail (reply_serial != 0, FALSE); /* 0 is invalid */

  return _dbus_header_set_field_basic (&message->header,
                                       DBUS_HEADER_FIELD_REPLY_SERIAL,
                                       DBUS_TYPE_UINT32,
                                       &reply_serial);
}

/**
 * Returns the serial that the message is a reply to or 0 if none.
 *
 * @param message the message
 * @returns the reply serial
 */
dbus_uint32_t
dbus_message_get_reply_serial  (DBusMessage *message)
{
  dbus_uint32_t v_UINT32;

  _dbus_return_val_if_fail (message != NULL, 0);

  if (_dbus_header_get_field_basic (&message->header,
                                    DBUS_HEADER_FIELD_REPLY_SERIAL,
                                    DBUS_TYPE_UINT32,
                                    &v_UINT32))
    return v_UINT32;
  else
    return 0;
}

static void
dbus_message_finalize (DBusMessage *message)
{
1181
  _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
1182 1183 1184 1185

  /* This calls application callbacks! */
  _dbus_data_slot_list_free (&message->slot_list);

1186 1187 1188
  _dbus_list_foreach (&message->counters,
                      free_counter, message);
  _dbus_list_clear (&message->counters);
1189 1190 1191 1192

  _dbus_header_free (&message->header);
  _dbus_string_free (&message->body);

1193 1194 1195 1196 1197
#ifdef HAVE_UNIX_FD_PASSING
  close_unix_fds(message->unix_fds, &message->n_unix_fds);
  dbus_free(message->unix_fds);
#endif

1198 1199
  _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);

1200 1201 1202
  dbus_free (message);
}

1203 1204
static DBusMessage*
dbus_message_new_empty_header (void)
1205
{
1206 1207
  DBusMessage *message;
  dbus_bool_t from_cache;
1208

1209
  message = dbus_message_get_cached ();
1210

1211
  if (message != NULL)
1212
    {
1213
      from_cache = TRUE;
1214 1215 1216
    }
  else
    {
1217
      from_cache = FALSE;
1218
      message = dbus_new0 (DBusMessage, 1);
1219 1220 1221 1222
      if (message == NULL)
        return NULL;
#ifndef DBUS_DISABLE_CHECKS
      message->generation = _dbus_current_generation;
1223
#endif
1224 1225 1226 1227 1228

#ifdef HAVE_UNIX_FD_PASSING
      message->unix_fds = NULL;
      message->n_unix_fds_allocated = 0;
#endif
1229
    }
1230 1231 1232

  _dbus_atomic_inc (&message->refcount);

1233 1234
  _dbus_message_trace_ref (message, 0, 1, "new_empty_header");

1235
  message->locked = FALSE;
1236 1237 1238
#ifndef DBUS_DISABLE_CHECKS
  message->in_cache = FALSE;
#endif
1239
  message->counters = NULL;
1240 1241
  message->size_counter_delta = 0;
  message->changed_stamp = 0;
1242

1243 1244
#ifdef HAVE_UNIX_FD_PASSING
  message->n_unix_fds = 0;
1245
  message->n_unix_fds_allocated = 0;
1246
  message->unix_fd_counter_delta = 0;
1247 1248
#endif

1249 1250
  if (!from_cache)
    _dbus_data_slot_list_init (&message->slot_list);
1251

1252
  if (from_cache)
1253
    {
1254
      _dbus_header_reinit (&message->header);
1255
      _dbus_string_set_length (&message->body, 0);
1256 1257 1258
    }
  else
    {
1259
      if (!_dbus_header_init (&message->header))
1260 1261 1262 1263
        {
          dbus_free (message);
          return NULL;
        }
1264

1265 1266 1267 1268 1269 1270
      if (!_dbus_string_init_preallocated (&message->body, 32))
        {
          _dbus_header_free (&message->header);
          dbus_free (message);
          return NULL;
        }
1271
    }
1272

1273
  return message;
1274 1275
}

1276
/**
1277 1278 1279
 * Constructs a new message of the given message type.
 * Types include #DBUS_MESSAGE_TYPE_METHOD_CALL,
 * #DBUS_MESSAGE_TYPE_SIGNAL, and so forth.
1280
 *
1281 1282 1283 1284
 * Usually you want to use dbus_message_new_method_call(),
 * dbus_message_new_method_return(), dbus_message_new_signal(),
 * or dbus_message_new_error() instead.
 * 
1285
 * @param message_type type of message
1286
 * @returns new message or #NULL if no memory
1287
 */
1288 1289
DBusMessage*
dbus_message_new (int message_type)
1290
{
1291
  DBusMessage *message;
1292

1293
  _dbus_return_val_if_fail (message_type != DBUS_MESSAGE_TYPE_INVALID, NULL);
1294

1295 1296 1297
  message = dbus_message_new_empty_header ();
  if (message == NULL)
    return NULL;
1298

1299
  if (!_dbus_header_create (&message->header,
1300
                            DBUS_COMPILER_BYTE_ORDER,
1301 1302
                            message_type,
                            NULL, NULL, NULL, NULL, NULL))
1303
    {
1304 1305
      dbus_message_unref (message);
      return NULL;
1306 1307
    }

1308
  return message;
1309 1310
}

1311
/**
1312 1313 1314
 * Constructs a new message to invoke a method on a remote
 * object. Returns #NULL if memory can't be allocated for the
 * message. The destination may be #NULL in which case no destination
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1315
 * is set; this is appropriate when using D-Bus in a peer-to-peer
1316 1317 1318
 * context (no message bus). The interface may be #NULL, which means
 * that if multiple methods with the given name exist it is undefined
 * which one will be invoked.
1319 1320 1321 1322 1323 1324
 *
 * The path and method names may not be #NULL.
 *
 * Destination, path, interface, and method name can't contain
 * any invalid characters (see the D-Bus specification).
 * 
1325
 * @param destination name that the message should be sent to or #NULL
1326
 * @param path object path the message should be sent to
1327
 * @param iface interface to invoke method on, or #NULL
1328
 * @param method method to invoke
1329
 *
1330
 * @returns a new DBusMessage, free with dbus_message_unref()
1331
 */
1332 1333 1334
DBusMessage*
dbus_message_new_method_call (const char *destination,
                              const char *path,
1335
                              const char *iface,
1336
                              const char *method)
1337
{
1338
  DBusMessage *message;
1339

1340 1341 1342
  _dbus_return_val_if_fail (path != NULL, NULL);
  _dbus_return_val_if_fail (method != NULL, NULL);
  _dbus_return_val_if_fail (destination == NULL ||
1343
                            _dbus_check_is_valid_bus_name (destination), NULL);
1344
  _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
1345 1346
  _dbus_return_val_if_fail (iface == NULL ||
                            _dbus_check_is_valid_interface (iface), NULL);
1347
  _dbus_return_val_if_fail (_dbus_check_is_valid_member (method), NULL);
1348

1349 1350 1351
  message = dbus_message_new_empty_header ();
  if (message == NULL)
    return NULL;
1352

1353
  if (!_dbus_header_create (&message->header,
1354
                            DBUS_COMPILER_BYTE_ORDER,
1355
                            DBUS_MESSAGE_TYPE_METHOD_CALL,
1356
                            destination, path, iface, method, NULL))
1357 1358 1359 1360
    {
      dbus_message_unref (message);
      return NULL;
    }
1361

1362
  return message;
1363 1364
}

1365
/**
1366 1367
 * Constructs a message that is a reply to a method call. Returns
 * #NULL if memory can't be allocated for the message.
1368
 *
1369
 * @param method_call the message being replied to
1370
 * @returns a new DBusMessage, free with dbus_message_unref()
1371
 */
1372 1373
DBusMessage*
dbus_message_new_method_return (DBusMessage *method_call)
1374
{
1375 1376
  DBusMessage *message;
  const char *sender;
1377

1378
  _dbus_return_val_if_fail (method_call != NULL, NULL);
1379

1380
  sender = dbus_message_get_sender (method_call);
1381

1382 1383 1384 1385 1386 1387 1388
  /* sender is allowed to be null here in peer-to-peer case */

  message = dbus_message_new_empty_header ();
  if (message == NULL)
    return NULL;

  if (!_dbus_header_create (&message->header,
1389
                            DBUS_COMPILER_BYTE_ORDER,
1390 1391 1392 1393 1394 1395
                            DBUS_MESSAGE_TYPE_METHOD_RETURN,
                            sender, NULL, NULL, NULL, NULL))
    {
      dbus_message_unref (message);
      return NULL;
    }
1396

1397
  dbus_message_set_no_reply (message, TRUE);
1398

1399 1400 1401 1402 1403 1404
  if (!dbus_message_set_reply_serial (message,
                                      dbus_message_get_serial (method_call)))
    {
      dbus_message_unref (message);
      return NULL;
    }
1405

1406
  return message;
1407 1408 1409
}

/**
1410 1411
 * Constructs a new message representing a signal emission. Returns
 * #NULL if memory can't be allocated for the message.  A signal is
1412 1413
 * identified by its originating object path, interface, and the name
 * of the signal.
1414
 *
1415 1416 1417
 * Path, interface, and signal name must all be valid (the D-Bus
 * specification defines the syntax of these fields).
 * 
1418
 * @param path the path to the object emitting the signal
1419
 * @param iface the interface the signal is emitted from
1420 1421
 * @param name name of the signal
 * @returns a new DBusMessage, free with dbus_message_unref()
1422
 */
1423 1424
DBusMessage*
dbus_message_new_signal (const char *path,
1425
                         const char *iface,
1426
                         const char *name)
1427
{
1428
  DBusMessage *message;
1429

1430
  _dbus_return_val_if_fail (path != NULL, NULL);
1431
  _dbus_return_val_if_fail (iface != NULL, NULL);
1432 1433
  _dbus_return_val_if_fail (name != NULL, NULL);
  _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
1434
  _dbus_return_val_if_fail (_dbus_check_is_valid_interface (iface), NULL);
1435
  _dbus_return_val_if_fail (_dbus_check_is_valid_member (name), NULL);
1436

1437 1438 1439
  message = dbus_message_new_empty_header ();
  if (message == NULL)
    return NULL;
1440

1441
  if (!_dbus_header_create (&message->header,
1442
                            DBUS_COMPILER_BYTE_ORDER,
1443
                            DBUS_MESSAGE_TYPE_SIGNAL,
1444
                            NULL, path, iface, name, NULL))
1445
    {
1446 1447
      dbus_message_unref (message);
      return NULL;
1448 1449
    }

1450
  dbus_message_set_no_reply (message, TRUE);
1451

1452
  return message;
1453 1454 1455
}

/**
1456 1457 1458
 * Creates a new message that is an error reply to another message.
 * Error replies are most common in response to method calls, but
 * can be returned in reply to any message.
1459
 *
1460 1461 1462 1463 1464
 * The error name must be a valid error name according to the syntax
 * given in the D-Bus specification. If you don't want to make
 * up an error name just use #DBUS_ERROR_FAILED.
 *
 * @param reply_to the message we're replying to
1465
 * @param error_name the error name
1466 1467
 * @param error_message the error message string (or #NULL for none, but please give a message)
 * @returns a new error message object, free with dbus_message_unref()
1468
 */
1469 1470 1471 1472
DBusMessage*
dbus_message_new_error (DBusMessage *reply_to,
                        const char  *error_name,
                        const char  *error_message)
1473
{
1474 1475 1476
  DBusMessage *message;
  const char *sender;
  DBusMessageIter iter;
1477

1478 1479 1480
  _dbus_return_val_if_fail (reply_to != NULL, NULL);
  _dbus_return_val_if_fail (error_name != NULL, NULL);
  _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
1481

1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  sender = dbus_message_get_sender (reply_to);

  /* sender may be NULL for non-message-bus case or
   * when the message bus is dealing with an unregistered
   * connection.
   */
  message = dbus_message_new_empty_header ();
  if (message == NULL)
    return NULL;

  if (!_dbus_header_create (&message->header,
1493
                            DBUS_COMPILER_BYTE_ORDER,
1494 1495
                            DBUS_MESSAGE_TYPE_ERROR,
                            sender, NULL, NULL, NULL, error_name))
1496
    {
1497 1498 1499
      dbus_message_unref (message);
      return NULL;
    }
1500

1501
  dbus_message_set_no_reply (message, TRUE);
1502

1503 1504 1505 1506 1507 1508
  if (!dbus_message_set_reply_serial (message,
                                      dbus_message_get_serial (reply_to)))
    {
      dbus_message_unref (message);
      return NULL;
    }
1509

1510 1511
  if (error_message != NULL)
    {
1512
      dbus_message_iter_init_append (message, &iter);
1513 1514 1515
      if (!dbus_message_iter_append_basic (&iter,
                                           DBUS_TYPE_STRING,
                                           &error_message))
1516
        {
1517 1518
          dbus_message_unref (message);
          return NULL;
1519 1520
        }
    }
1521 1522