[daemon-fix] Fixed sending daemon match rules for kdbus broadcasts
[platform/upstream/dbus.git] / dbus / dbus-message.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-message.c  DBusMessage object
3  *
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  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * 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 #include "dbus-marshal-recursive.h"
28 #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 #include "dbus-memory.h"
35 #include "dbus-list.h"
36 #include "dbus-threads-internal.h"
37
38 #ifdef HAVE_UNIX_FD_PASSING
39 #include "dbus-sysdeps-unix.h"
40 #endif
41
42 #include <string.h>
43
44 #define _DBUS_TYPE_IS_STRINGLIKE(type) \
45   (type == DBUS_TYPE_STRING || type == DBUS_TYPE_SIGNATURE || \
46    type == DBUS_TYPE_OBJECT_PATH)
47
48 static void dbus_message_finalize (DBusMessage *message);
49
50 /**
51  * @defgroup DBusMessageInternals DBusMessage implementation details
52  * @ingroup DBusInternals
53  * @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 static dbus_bool_t
62 _dbus_enable_message_cache (void)
63 {
64   static int enabled = -1;
65
66   if (enabled < 0)
67     {
68       const char *s = _dbus_getenv ("DBUS_MESSAGE_CACHE");
69
70       enabled = TRUE;
71
72       if (s && *s)
73         {
74           if (*s == '0')
75             enabled = FALSE;
76           else if (*s == '1')
77             enabled = TRUE;
78           else
79             _dbus_warn ("DBUS_MESSAGE_CACHE should be 0 or 1 if set, not '%s'",
80                 s);
81         }
82     }
83
84   return enabled;
85 }
86 #else
87     /* constant expression, should be optimized away */
88 #   define _dbus_enable_message_cache() (TRUE)
89 #endif
90
91 #ifndef _dbus_message_trace_ref
92 void
93 _dbus_message_trace_ref (DBusMessage *message,
94                          int          old_refcount,
95                          int          new_refcount,
96                          const char  *why)
97 {
98   static int enabled = -1;
99
100   _dbus_trace_ref ("DBusMessage", message, old_refcount, new_refcount, why,
101       "DBUS_MESSAGE_TRACE", &enabled);
102 }
103 #endif
104
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 /* these have wacky values to help trap uninitialized iterators;
111  * but has to fit in 3 bits
112  */
113 enum {
114   DBUS_MESSAGE_ITER_TYPE_READER = 3,
115   DBUS_MESSAGE_ITER_TYPE_WRITER = 7
116 };
117
118 /** typedef for internals of message iterator */
119 typedef struct DBusMessageRealIter DBusMessageRealIter;
120
121 /**
122  * @brief Internals of DBusMessageIter
123  *
124  * Object representing a position in a message. All fields are internal.
125  */
126 struct DBusMessageRealIter
127 {
128   DBusMessage *message; /**< Message used */
129   dbus_uint32_t changed_stamp : CHANGED_STAMP_BITS; /**< stamp to detect invalid iters */
130   dbus_uint32_t iter_type : 3;      /**< whether this is a reader or writer iter */
131   dbus_uint32_t sig_refcount : 8;   /**< depth of open_signature() */
132   union
133   {
134     DBusTypeWriter writer; /**< writer */
135     DBusTypeReader reader; /**< reader */
136   } u; /**< the type writer or reader that does all the work */
137 };
138
139 static void
140 get_const_signature (DBusHeader        *header,
141                      const DBusString **type_str_p,
142                      int               *type_pos_p)
143 {
144   if (_dbus_header_get_field_raw (header,
145                                   DBUS_HEADER_FIELD_SIGNATURE,
146                                   type_str_p,
147                                   type_pos_p))
148     {
149       *type_pos_p += 1; /* skip the signature length which is 1 byte */
150     }
151   else
152     {
153       *type_str_p = &_dbus_empty_signature_str;
154       *type_pos_p = 0;
155     }
156 }
157
158 /**
159  * Swaps the message to compiler byte order if required
160  *
161  * @param message the message
162  */
163 static void
164 _dbus_message_byteswap (DBusMessage *message)
165 {
166   const DBusString *type_str;
167   int type_pos;
168   char byte_order;
169
170   byte_order = _dbus_header_get_byte_order (&message->header);
171
172   if (byte_order == DBUS_COMPILER_BYTE_ORDER)
173     return;
174
175   _dbus_verbose ("Swapping message into compiler byte order\n");
176   
177   get_const_signature (&message->header, &type_str, &type_pos);
178   
179   _dbus_marshal_byteswap (type_str, type_pos,
180                           byte_order,
181                           DBUS_COMPILER_BYTE_ORDER,
182                           &message->body, 0);
183
184   _dbus_header_byteswap (&message->header, DBUS_COMPILER_BYTE_ORDER);
185   _dbus_assert (_dbus_header_get_byte_order (&message->header) ==
186                 DBUS_COMPILER_BYTE_ORDER);
187 }
188
189 /** byte-swap the message if it doesn't match our byte order.
190  *  Called only when we need the message in our own byte order,
191  *  normally when reading arrays of integers or doubles.
192  *  Otherwise should not be called since it would do needless
193  *  work.
194  */
195 #define ensure_byte_order(message) _dbus_message_byteswap (message)
196
197 /**
198  * Gets the data to be sent over the network for this message.
199  * The header and then the body should be written out.
200  * This function is guaranteed to always return the same
201  * data once a message is locked (with dbus_message_lock()).
202  *
203  * @param message the message.
204  * @param header return location for message header data.
205  * @param body return location for message body data.
206  */
207 void
208 _dbus_message_get_network_data (DBusMessage          *message,
209                                 const DBusString    **header,
210                                 const DBusString    **body)
211 {
212   _dbus_assert (message->locked);
213
214   *header = &message->header.data;
215   *body = &message->body;
216 }
217
218 /**
219  * Gets the unix fds to be sent over the network for this message.
220  * This function is guaranteed to always return the same data once a
221  * message is locked (with dbus_message_lock()).
222  *
223  * @param message the message.
224  * @param fds return location of unix fd array
225  * @param n_fds return number of entries in array
226  */
227 void _dbus_message_get_unix_fds(DBusMessage *message,
228                                 const int  **fds,
229                                 unsigned    *n_fds)
230 {
231   _dbus_assert (message->locked);
232
233 #ifdef HAVE_UNIX_FD_PASSING
234   *fds = message->unix_fds;
235   *n_fds = message->n_unix_fds;
236 #else
237   *fds = NULL;
238   *n_fds = 0;
239 #endif
240 }
241
242 /**
243  * Sets the serial number of a message.
244  * This can only be done once on a message.
245  *
246  * DBusConnection will automatically set the serial to an appropriate value 
247  * when the message is sent; this function is only needed when encapsulating 
248  * messages in another protocol, or otherwise bypassing DBusConnection.
249  *
250  * @param message the message
251  * @param serial the serial
252  */
253 void 
254 dbus_message_set_serial (DBusMessage   *message,
255                          dbus_uint32_t  serial)
256 {
257   _dbus_return_if_fail (message != NULL);
258   _dbus_return_if_fail (!message->locked);
259
260   _dbus_header_set_serial (&message->header, serial);
261 }
262
263 /**
264  * Adds a counter to be incremented immediately with the size/unix fds
265  * of this message, and decremented by the size/unix fds of this
266  * message when this message if finalized.  The link contains a
267  * counter with its refcount already incremented, but the counter
268  * itself not incremented.  Ownership of link and counter refcount is
269  * passed to the message.
270  *
271  * This function may be called with locks held. As a result, the counter's
272  * notify function is not called; the caller is expected to either call
273  * _dbus_counter_notify() on the counter when they are no longer holding
274  * locks, or take the same action that would be taken by the notify function.
275  *
276  * @param message the message
277  * @param link link with counter as data
278  */
279 void
280 _dbus_message_add_counter_link (DBusMessage  *message,
281                                 DBusList     *link)
282 {
283   /* right now we don't recompute the delta when message
284    * size changes, and that's OK for current purposes
285    * I think, but could be important to change later.
286    * Do recompute it whenever there are no outstanding counters,
287    * since it's basically free.
288    */
289   if (message->counters == NULL)
290     {
291       message->size_counter_delta =
292         _dbus_string_get_length (&message->header.data) +
293         _dbus_string_get_length (&message->body);
294
295 #ifdef HAVE_UNIX_FD_PASSING
296       message->unix_fd_counter_delta = message->n_unix_fds;
297 #endif
298
299 #if 0
300       _dbus_verbose ("message has size %ld\n",
301                      message->size_counter_delta);
302 #endif
303     }
304
305   _dbus_list_append_link (&message->counters, link);
306
307   _dbus_counter_adjust_size (link->data, message->size_counter_delta);
308
309 #ifdef HAVE_UNIX_FD_PASSING
310   _dbus_counter_adjust_unix_fd (link->data, message->unix_fd_counter_delta);
311 #endif
312 }
313
314 /**
315  * Adds a counter to be incremented immediately with the size/unix fds
316  * of this message, and decremented by the size/unix fds of this
317  * message when this message if finalized.
318  *
319  * This function may be called with locks held. As a result, the counter's
320  * notify function is not called; the caller is expected to either call
321  * _dbus_counter_notify() on the counter when they are no longer holding
322  * locks, or take the same action that would be taken by the notify function.
323  *
324  * @param message the message
325  * @param counter the counter
326  * @returns #FALSE if no memory
327  */
328 dbus_bool_t
329 _dbus_message_add_counter (DBusMessage *message,
330                            DBusCounter *counter)
331 {
332   DBusList *link;
333
334   link = _dbus_list_alloc_link (counter);
335   if (link == NULL)
336     return FALSE;
337
338   _dbus_counter_ref (counter);
339   _dbus_message_add_counter_link (message, link);
340
341   return TRUE;
342 }
343
344 /**
345  * Removes a counter tracking the size/unix fds of this message, and
346  * decrements the counter by the size/unix fds of this message.
347  *
348  * @param message the message
349  * @param counter the counter
350  */
351 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                                counter);
359   _dbus_assert (link != NULL);
360
361   _dbus_list_remove_link (&message->counters, link);
362
363   _dbus_counter_adjust_size (counter, - message->size_counter_delta);
364
365 #ifdef HAVE_UNIX_FD_PASSING
366   _dbus_counter_adjust_unix_fd (counter, - message->unix_fd_counter_delta);
367 #endif
368
369   _dbus_counter_notify (counter);
370   _dbus_counter_unref (counter);
371 }
372
373 /**
374  * Locks a message. Allows checking that applications don't keep a
375  * reference to a message in the outgoing queue and change it
376  * underneath us. Messages are locked when they enter the outgoing
377  * queue (dbus_connection_send_message()), and the library complains
378  * if the message is modified while locked. This function may also 
379  * called externally, for applications wrapping D-Bus in another protocol.
380  *
381  * @param message the message to lock.
382  */
383 void
384 dbus_message_lock (DBusMessage  *message)
385 {
386   if (!message->locked)
387     {
388       _dbus_header_update_lengths (&message->header,
389                                    _dbus_string_get_length (&message->body));
390
391       /* must have a signature if you have a body */
392       _dbus_assert (_dbus_string_get_length (&message->body) == 0 ||
393                     dbus_message_get_signature (message) != NULL);
394
395       message->locked = TRUE;
396     }
397 }
398
399 #ifdef ENABLE_KDBUS_TRANSPORT
400 void
401 dbus_message_unlock (DBusMessage  *message)
402 {
403         message->locked = FALSE;
404 }
405 #endif
406
407 static dbus_bool_t
408 set_or_delete_string_field (DBusMessage *message,
409                             int          field,
410                             int          typecode,
411                             const char  *value)
412 {
413   if (value == NULL)
414     return _dbus_header_delete_field (&message->header, field);
415   else
416     return _dbus_header_set_field_basic (&message->header,
417                                          field,
418                                          typecode,
419                                          &value);
420 }
421
422 #if 0
423 /* Probably we don't need to use this */
424 /**
425  * Sets the signature of the message, i.e. the arguments in the
426  * message payload. The signature includes only "in" arguments for
427  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
428  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
429  * what you might expect (it does not include the signature of the
430  * entire C++-style method).
431  *
432  * The signature is a string made up of type codes such as
433  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
434  * the value of #DBUS_TYPE_INVALID). The macros such as
435  * #DBUS_TYPE_INT32 evaluate to integers; to assemble a signature you
436  * may find it useful to use the string forms, such as
437  * #DBUS_TYPE_INT32_AS_STRING.
438  *
439  * An "unset" or #NULL signature is considered the same as an empty
440  * signature. In fact dbus_message_get_signature() will never return
441  * #NULL.
442  *
443  * @param message the message
444  * @param signature the type signature or #NULL to unset
445  * @returns #FALSE if no memory
446  */
447 static dbus_bool_t
448 _dbus_message_set_signature (DBusMessage *message,
449                              const char  *signature)
450 {
451   _dbus_return_val_if_fail (message != NULL, FALSE);
452   _dbus_return_val_if_fail (!message->locked, FALSE);
453   _dbus_return_val_if_fail (signature == NULL ||
454                             _dbus_check_is_valid_signature (signature));
455   /* can't delete the signature if you have a message body */
456   _dbus_return_val_if_fail (_dbus_string_get_length (&message->body) == 0 ||
457                             signature != NULL);
458
459   return set_or_delete_string_field (message,
460                                      DBUS_HEADER_FIELD_SIGNATURE,
461                                      DBUS_TYPE_SIGNATURE,
462                                      signature);
463 }
464 #endif
465
466 /* Message Cache
467  *
468  * We cache some DBusMessage to reduce the overhead of allocating
469  * them.  In my profiling this consistently made about an 8%
470  * difference.  It avoids the malloc for the message, the malloc for
471  * the slot list, the malloc for the header string and body string,
472  * and the associated free() calls. It does introduce another global
473  * lock which could be a performance issue in certain cases.
474  *
475  * For the echo client/server the round trip time goes from around
476  * .000077 to .000069 with the message cache on my laptop. The sysprof
477  * change is as follows (numbers are cumulative percentage):
478  *
479  *  with message cache implemented as array as it is now (0.000069 per):
480  *    new_empty_header           1.46
481  *      mutex_lock               0.56    # i.e. _DBUS_LOCK(message_cache)
482  *      mutex_unlock             0.25
483  *      self                     0.41
484  *    unref                      2.24
485  *      self                     0.68
486  *      list_clear               0.43
487  *      mutex_lock               0.33    # i.e. _DBUS_LOCK(message_cache)
488  *      mutex_unlock             0.25
489  *
490  *  with message cache implemented as list (0.000070 per roundtrip):
491  *    new_empty_header           2.72
492  *      list_pop_first           1.88
493  *    unref                      3.3
494  *      list_prepend             1.63
495  *
496  * without cache (0.000077 per roundtrip):
497  *    new_empty_header           6.7
498  *      string_init_preallocated 3.43
499  *        dbus_malloc            2.43
500  *      dbus_malloc0             2.59
501  *
502  *    unref                      4.02
503  *      string_free              1.82
504  *        dbus_free              1.63
505  *      dbus_free                0.71
506  *
507  * If you implement the message_cache with a list, the primary reason
508  * it's slower is that you add another thread lock (on the DBusList
509  * mempool).
510  */
511
512 /** Avoid caching huge messages */
513 #define MAX_MESSAGE_SIZE_TO_CACHE 10 * _DBUS_ONE_KILOBYTE
514
515 /** Avoid caching too many messages */
516 #define MAX_MESSAGE_CACHE_SIZE    5
517
518 /* Protected by _DBUS_LOCK (message_cache) */
519 static DBusMessage *message_cache[MAX_MESSAGE_CACHE_SIZE];
520 static int message_cache_count = 0;
521 static dbus_bool_t message_cache_shutdown_registered = FALSE;
522
523 static void
524 dbus_message_cache_shutdown (void *data)
525 {
526   int i;
527
528   if (!_DBUS_LOCK (message_cache))
529     _dbus_assert_not_reached ("we would have initialized global locks "
530         "before registering a shutdown function");
531
532   i = 0;
533   while (i < MAX_MESSAGE_CACHE_SIZE)
534     {
535       if (message_cache[i])
536         dbus_message_finalize (message_cache[i]);
537
538       ++i;
539     }
540
541   message_cache_count = 0;
542   message_cache_shutdown_registered = FALSE;
543
544   _DBUS_UNLOCK (message_cache);
545 }
546
547 /**
548  * Tries to get a message from the message cache.  The retrieved
549  * message will have junk in it, so it still needs to be cleared out
550  * in dbus_message_new_empty_header()
551  *
552  * @returns the message, or #NULL if none cached
553  */
554 static DBusMessage*
555 dbus_message_get_cached (void)
556 {
557   DBusMessage *message;
558   int i;
559
560   message = NULL;
561
562   if (!_DBUS_LOCK (message_cache))
563     {
564       /* we'd have initialized global locks before caching anything,
565        * so there can't be anything in the cache */
566       return NULL;
567     }
568
569   _dbus_assert (message_cache_count >= 0);
570
571   if (message_cache_count == 0)
572     {
573       _DBUS_UNLOCK (message_cache);
574       return NULL;
575     }
576
577   /* This is not necessarily true unless count > 0, and
578    * message_cache is uninitialized until the shutdown is
579    * registered
580    */
581   _dbus_assert (message_cache_shutdown_registered);
582
583   i = 0;
584   while (i < MAX_MESSAGE_CACHE_SIZE)
585     {
586       if (message_cache[i])
587         {
588           message = message_cache[i];
589           message_cache[i] = NULL;
590           message_cache_count -= 1;
591           break;
592         }
593       ++i;
594     }
595   _dbus_assert (message_cache_count >= 0);
596   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
597   _dbus_assert (message != NULL);
598
599   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
600
601   _dbus_assert (message->counters == NULL);
602   
603   _DBUS_UNLOCK (message_cache);
604
605   return message;
606 }
607
608 #ifdef HAVE_UNIX_FD_PASSING
609 static void
610 close_unix_fds(int *fds, unsigned *n_fds)
611 {
612   DBusError e;
613   int i;
614
615   if (*n_fds <= 0)
616     return;
617
618   dbus_error_init(&e);
619
620   for (i = 0; i < *n_fds; i++)
621     {
622       if (!_dbus_close(fds[i], &e))
623         {
624           _dbus_warn("Failed to close file descriptor: %s\n", e.message);
625           dbus_error_free(&e);
626         }
627     }
628
629   *n_fds = 0;
630
631   /* We don't free the array here, in case we can recycle it later */
632 }
633 #endif
634
635 static void
636 free_counter (void *element,
637               void *data)
638 {
639   DBusCounter *counter = element;
640   DBusMessage *message = data;
641
642   _dbus_counter_adjust_size (counter, - message->size_counter_delta);
643 #ifdef HAVE_UNIX_FD_PASSING
644   _dbus_counter_adjust_unix_fd (counter, - message->unix_fd_counter_delta);
645 #endif
646
647   _dbus_counter_notify (counter);
648   _dbus_counter_unref (counter);
649 }
650
651 /**
652  * Tries to cache a message, otherwise finalize it.
653  *
654  * @param message the message
655  */
656 static void
657 dbus_message_cache_or_finalize (DBusMessage *message)
658 {
659   dbus_bool_t was_cached;
660   int i;
661
662   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
663
664   /* This calls application code and has to be done first thing
665    * without holding the lock
666    */
667   _dbus_data_slot_list_clear (&message->slot_list);
668
669   _dbus_list_foreach (&message->counters,
670                       free_counter, message);
671   _dbus_list_clear (&message->counters);
672
673 #ifdef HAVE_UNIX_FD_PASSING
674   close_unix_fds(message->unix_fds, &message->n_unix_fds);
675 #endif
676
677   was_cached = FALSE;
678
679   if (!_DBUS_LOCK (message_cache))
680     {
681       /* The only way to get a non-null message goes through
682        * dbus_message_get_cached() which takes the lock. */
683       _dbus_assert_not_reached ("we would have initialized global locks "
684           "the first time we constructed a message");
685     }
686
687   if (!message_cache_shutdown_registered)
688     {
689       _dbus_assert (message_cache_count == 0);
690
691       if (!_dbus_register_shutdown_func (dbus_message_cache_shutdown, NULL))
692         goto out;
693
694       i = 0;
695       while (i < MAX_MESSAGE_CACHE_SIZE)
696         {
697           message_cache[i] = NULL;
698           ++i;
699         }
700
701       message_cache_shutdown_registered = TRUE;
702     }
703
704   _dbus_assert (message_cache_count >= 0);
705
706   if (!_dbus_enable_message_cache ())
707     goto out;
708
709   if ((_dbus_string_get_length (&message->header.data) +
710        _dbus_string_get_length (&message->body)) >
711       MAX_MESSAGE_SIZE_TO_CACHE)
712     goto out;
713
714   if (message_cache_count >= MAX_MESSAGE_CACHE_SIZE)
715     goto out;
716
717   /* Find empty slot */
718   i = 0;
719   while (message_cache[i] != NULL)
720     ++i;
721
722   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
723
724   _dbus_assert (message_cache[i] == NULL);
725   message_cache[i] = message;
726   message_cache_count += 1;
727   was_cached = TRUE;
728 #ifndef DBUS_DISABLE_CHECKS
729   message->in_cache = TRUE;
730 #endif
731
732  out:
733   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
734
735   _DBUS_UNLOCK (message_cache);
736   
737   if (!was_cached)
738     dbus_message_finalize (message);
739 }
740
741 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
742 static dbus_bool_t
743 _dbus_message_iter_check (DBusMessageRealIter *iter)
744 {
745   char byte_order;
746
747   if (iter == NULL)
748     {
749       _dbus_warn_check_failed ("dbus message iterator is NULL\n");
750       return FALSE;
751     }
752
753   byte_order = _dbus_header_get_byte_order (&iter->message->header);
754
755   if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_READER)
756     {
757       if (iter->u.reader.byte_order != byte_order)
758         {
759           _dbus_warn_check_failed ("dbus message changed byte order since iterator was created\n");
760           return FALSE;
761         }
762       /* because we swap the message into compiler order when you init an iter */
763       _dbus_assert (iter->u.reader.byte_order == DBUS_COMPILER_BYTE_ORDER);
764     }
765   else if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER)
766     {
767       if (iter->u.writer.byte_order != byte_order)
768         {
769           _dbus_warn_check_failed ("dbus message changed byte order since append iterator was created\n");
770           return FALSE;
771         }
772       /* because we swap the message into compiler order when you init an iter */
773       _dbus_assert (iter->u.writer.byte_order == DBUS_COMPILER_BYTE_ORDER);
774     }
775   else
776     {
777       _dbus_warn_check_failed ("dbus message iterator looks uninitialized or corrupted\n");
778       return FALSE;
779     }
780
781   if (iter->changed_stamp != iter->message->changed_stamp)
782     {
783       _dbus_warn_check_failed ("dbus message iterator invalid because the message has been modified (or perhaps the iterator is just uninitialized)\n");
784       return FALSE;
785     }
786
787   return TRUE;
788 }
789 #endif /* DBUS_ENABLE_CHECKS || DBUS_ENABLE_ASSERT */
790
791 /**
792  * Implementation of the varargs arg-getting functions.
793  * dbus_message_get_args() is the place to go for complete
794  * documentation.
795  *
796  * @todo This may leak memory and file descriptors if parsing fails. See #21259
797  *
798  * @see dbus_message_get_args
799  * @param iter the message iter
800  * @param error error to be filled in
801  * @param first_arg_type type of the first argument
802  * @param var_args return location for first argument, followed by list of type/location pairs
803  * @returns #FALSE if error was set
804  */
805 dbus_bool_t
806 _dbus_message_iter_get_args_valist (DBusMessageIter *iter,
807                                     DBusError       *error,
808                                     int              first_arg_type,
809                                     va_list          var_args)
810 {
811   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
812   int spec_type, msg_type, i;
813   dbus_bool_t retval;
814
815   _dbus_assert (_dbus_message_iter_check (real));
816
817   retval = FALSE;
818
819   spec_type = first_arg_type;
820   i = 0;
821
822   while (spec_type != DBUS_TYPE_INVALID)
823     {
824       msg_type = dbus_message_iter_get_arg_type (iter);
825
826       if (msg_type != spec_type)
827         {
828           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
829                           "Argument %d is specified to be of type \"%s\", but "
830                           "is actually of type \"%s\"\n", i,
831                           _dbus_type_to_string (spec_type),
832                           _dbus_type_to_string (msg_type));
833
834           goto out;
835         }
836
837       if (spec_type == DBUS_TYPE_UNIX_FD)
838         {
839 #ifdef HAVE_UNIX_FD_PASSING
840           DBusBasicValue idx;
841           int *pfd, nfd;
842
843           pfd = va_arg (var_args, int*);
844           _dbus_assert(pfd);
845
846           _dbus_type_reader_read_basic(&real->u.reader, &idx);
847
848           if (idx.u32 >= real->message->n_unix_fds)
849             {
850               dbus_set_error (error, DBUS_ERROR_INCONSISTENT_MESSAGE,
851                               "Message refers to file descriptor at index %i,"
852                               "but has only %i descriptors attached.\n",
853                               idx.u32,
854                               real->message->n_unix_fds);
855               goto out;
856             }
857
858           if ((nfd = _dbus_dup(real->message->unix_fds[idx.u32], error)) < 0)
859             goto out;
860
861           *pfd = nfd;
862 #else
863           dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
864                           "Platform does not support file desciptor passing.\n");
865           goto out;
866 #endif
867         }
868       else if (dbus_type_is_basic (spec_type))
869         {
870           DBusBasicValue *ptr;
871
872           ptr = va_arg (var_args, DBusBasicValue*);
873
874           _dbus_assert (ptr != NULL);
875
876           _dbus_type_reader_read_basic (&real->u.reader,
877                                         ptr);
878         }
879       else if (spec_type == DBUS_TYPE_ARRAY)
880         {
881           int element_type;
882           int spec_element_type;
883           const DBusBasicValue **ptr;
884           int *n_elements_p;
885           DBusTypeReader array;
886
887           spec_element_type = va_arg (var_args, int);
888           element_type = _dbus_type_reader_get_element_type (&real->u.reader);
889
890           if (spec_element_type != element_type)
891             {
892               dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
893                               "Argument %d is specified to be an array of \"%s\", but "
894                               "is actually an array of \"%s\"\n",
895                               i,
896                               _dbus_type_to_string (spec_element_type),
897                               _dbus_type_to_string (element_type));
898
899               goto out;
900             }
901
902           if (dbus_type_is_fixed (spec_element_type) &&
903               element_type != DBUS_TYPE_UNIX_FD)
904             {
905               ptr = va_arg (var_args, const DBusBasicValue**);
906               n_elements_p = va_arg (var_args, int*);
907
908               _dbus_assert (ptr != NULL);
909               _dbus_assert (n_elements_p != NULL);
910
911               _dbus_type_reader_recurse (&real->u.reader, &array);
912
913               _dbus_type_reader_read_fixed_multi (&array,
914                                                   (void *) ptr, n_elements_p);
915             }
916           else if (_DBUS_TYPE_IS_STRINGLIKE (spec_element_type))
917             {
918               char ***str_array_p;
919               int n_elements;
920               char **str_array;
921
922               str_array_p = va_arg (var_args, char***);
923               n_elements_p = va_arg (var_args, int*);
924
925               _dbus_assert (str_array_p != NULL);
926               _dbus_assert (n_elements_p != NULL);
927
928               /* Count elements in the array */
929               _dbus_type_reader_recurse (&real->u.reader, &array);
930
931               n_elements = 0;
932               while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
933                 {
934                   ++n_elements;
935                   _dbus_type_reader_next (&array);
936                 }
937
938               str_array = dbus_new0 (char*, n_elements + 1);
939               if (str_array == NULL)
940                 {
941                   _DBUS_SET_OOM (error);
942                   goto out;
943                 }
944
945               /* Now go through and dup each string */
946               _dbus_type_reader_recurse (&real->u.reader, &array);
947
948               i = 0;
949               while (i < n_elements)
950                 {
951                   const char *s;
952                   _dbus_type_reader_read_basic (&array,
953                                                 (void *) &s);
954                   
955                   str_array[i] = _dbus_strdup (s);
956                   if (str_array[i] == NULL)
957                     {
958                       dbus_free_string_array (str_array);
959                       _DBUS_SET_OOM (error);
960                       goto out;
961                     }
962                   
963                   ++i;
964                   
965                   if (!_dbus_type_reader_next (&array))
966                     _dbus_assert (i == n_elements);
967                 }
968
969               _dbus_assert (_dbus_type_reader_get_current_type (&array) == DBUS_TYPE_INVALID);
970               _dbus_assert (i == n_elements);
971               _dbus_assert (str_array[i] == NULL);
972
973               *str_array_p = str_array;
974               *n_elements_p = n_elements;
975             }
976 #ifndef DBUS_DISABLE_CHECKS
977           else
978             {
979               _dbus_warn ("you can't read arrays of container types (struct, variant, array) with %s for now\n",
980                           _DBUS_FUNCTION_NAME);
981               goto out;
982             }
983 #endif
984         }
985 #ifndef DBUS_DISABLE_CHECKS
986       else
987         {
988           _dbus_warn ("you can only read arrays and basic types with %s for now\n",
989                       _DBUS_FUNCTION_NAME);
990           goto out;
991         }
992 #endif
993
994       spec_type = va_arg (var_args, int);
995       if (!_dbus_type_reader_next (&real->u.reader) && spec_type != DBUS_TYPE_INVALID)
996         {
997           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
998                           "Message has only %d arguments, but more were expected", i);
999           goto out;
1000         }
1001
1002       i++;
1003     }
1004
1005   retval = TRUE;
1006
1007  out:
1008
1009   return retval;
1010 }
1011
1012 /** @} */
1013
1014 /**
1015  * @defgroup DBusMessage DBusMessage
1016  * @ingroup  DBus
1017  * @brief Message to be sent or received over a #DBusConnection.
1018  *
1019  * A DBusMessage is the most basic unit of communication over a
1020  * DBusConnection. A DBusConnection represents a stream of messages
1021  * received from a remote application, and a stream of messages
1022  * sent to a remote application.
1023  *
1024  * A message has a message type, returned from
1025  * dbus_message_get_type().  This indicates whether the message is a
1026  * method call, a reply to a method call, a signal, or an error reply.
1027  *
1028  * A message has header fields such as the sender, destination, method
1029  * or signal name, and so forth. DBusMessage has accessor functions for
1030  * these, such as dbus_message_get_member().
1031  *
1032  * Convenience functions dbus_message_is_method_call(), dbus_message_is_signal(),
1033  * and dbus_message_is_error() check several header fields at once and are
1034  * slightly more efficient than checking the header fields with individual
1035  * accessor functions.
1036  *
1037  * Finally, a message has arguments. The number and types of arguments
1038  * are in the message's signature header field (accessed with
1039  * dbus_message_get_signature()).  Simple argument values are usually
1040  * retrieved with dbus_message_get_args() but more complex values such
1041  * as structs may require the use of #DBusMessageIter.
1042  *
1043  * The D-Bus specification goes into some more detail about header fields and
1044  * message types.
1045  * 
1046  * @{
1047  */
1048
1049 /**
1050  * @typedef DBusMessage
1051  *
1052  * Opaque data type representing a message received from or to be
1053  * sent to another application.
1054  */
1055
1056 /**
1057  * Returns the serial of a message or 0 if none has been specified.
1058  * The message's serial number is provided by the application sending
1059  * the message and is used to identify replies to this message.
1060  *
1061  * All messages received on a connection will have a serial provided
1062  * by the remote application.
1063  *
1064  * For messages you're sending, dbus_connection_send() will assign a
1065  * serial and return it to you.
1066  *
1067  * @param message the message
1068  * @returns the serial
1069  */
1070 dbus_uint32_t
1071 dbus_message_get_serial (DBusMessage *message)
1072 {
1073   _dbus_return_val_if_fail (message != NULL, 0);
1074
1075   return _dbus_header_get_serial (&message->header);
1076 }
1077
1078 /**
1079  * Sets the reply serial of a message (the serial of the message this
1080  * is a reply to).
1081  *
1082  * @param message the message
1083  * @param reply_serial the serial we're replying to
1084  * @returns #FALSE if not enough memory
1085  */
1086 dbus_bool_t
1087 dbus_message_set_reply_serial (DBusMessage   *message,
1088                                dbus_uint32_t  reply_serial)
1089 {
1090   _dbus_return_val_if_fail (message != NULL, FALSE);
1091   _dbus_return_val_if_fail (!message->locked, FALSE);
1092   _dbus_return_val_if_fail (reply_serial != 0, FALSE); /* 0 is invalid */
1093
1094   return _dbus_header_set_field_basic (&message->header,
1095                                        DBUS_HEADER_FIELD_REPLY_SERIAL,
1096                                        DBUS_TYPE_UINT32,
1097                                        &reply_serial);
1098 }
1099
1100 /**
1101  * Returns the serial that the message is a reply to or 0 if none.
1102  *
1103  * @param message the message
1104  * @returns the reply serial
1105  */
1106 dbus_uint32_t
1107 dbus_message_get_reply_serial  (DBusMessage *message)
1108 {
1109   dbus_uint32_t v_UINT32;
1110
1111   _dbus_return_val_if_fail (message != NULL, 0);
1112
1113   if (_dbus_header_get_field_basic (&message->header,
1114                                     DBUS_HEADER_FIELD_REPLY_SERIAL,
1115                                     DBUS_TYPE_UINT32,
1116                                     &v_UINT32))
1117     return v_UINT32;
1118   else
1119     return 0;
1120 }
1121
1122 static void
1123 dbus_message_finalize (DBusMessage *message)
1124 {
1125   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
1126
1127   /* This calls application callbacks! */
1128   _dbus_data_slot_list_free (&message->slot_list);
1129
1130   _dbus_list_foreach (&message->counters,
1131                       free_counter, message);
1132   _dbus_list_clear (&message->counters);
1133
1134   _dbus_header_free (&message->header);
1135   _dbus_string_free (&message->body);
1136
1137 #ifdef HAVE_UNIX_FD_PASSING
1138   close_unix_fds(message->unix_fds, &message->n_unix_fds);
1139   dbus_free(message->unix_fds);
1140 #endif
1141
1142   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
1143
1144   dbus_free (message);
1145 }
1146
1147 static DBusMessage*
1148 dbus_message_new_empty_header (void)
1149 {
1150   DBusMessage *message;
1151   dbus_bool_t from_cache;
1152
1153   message = dbus_message_get_cached ();
1154
1155   if (message != NULL)
1156     {
1157       from_cache = TRUE;
1158     }
1159   else
1160     {
1161       from_cache = FALSE;
1162       message = dbus_new0 (DBusMessage, 1);
1163       if (message == NULL)
1164         return NULL;
1165 #ifndef DBUS_DISABLE_CHECKS
1166       message->generation = _dbus_current_generation;
1167 #endif
1168
1169 #ifdef HAVE_UNIX_FD_PASSING
1170       message->unix_fds = NULL;
1171       message->n_unix_fds_allocated = 0;
1172 #endif
1173     }
1174
1175   _dbus_atomic_inc (&message->refcount);
1176
1177   _dbus_message_trace_ref (message, 0, 1, "new_empty_header");
1178
1179   message->locked = FALSE;
1180 #ifndef DBUS_DISABLE_CHECKS
1181   message->in_cache = FALSE;
1182 #endif
1183   message->counters = NULL;
1184   message->size_counter_delta = 0;
1185   message->changed_stamp = 0;
1186
1187 #ifdef HAVE_UNIX_FD_PASSING
1188   message->n_unix_fds = 0;
1189   message->n_unix_fds_allocated = 0;
1190   message->unix_fd_counter_delta = 0;
1191 #endif
1192
1193   if (!from_cache)
1194     _dbus_data_slot_list_init (&message->slot_list);
1195
1196   if (from_cache)
1197     {
1198       _dbus_header_reinit (&message->header);
1199       _dbus_string_set_length (&message->body, 0);
1200     }
1201   else
1202     {
1203       if (!_dbus_header_init (&message->header))
1204         {
1205           dbus_free (message);
1206           return NULL;
1207         }
1208
1209       if (!_dbus_string_init_preallocated (&message->body, 32))
1210         {
1211           _dbus_header_free (&message->header);
1212           dbus_free (message);
1213           return NULL;
1214         }
1215     }
1216
1217   return message;
1218 }
1219
1220 /**
1221  * Constructs a new message of the given message type.
1222  * Types include #DBUS_MESSAGE_TYPE_METHOD_CALL,
1223  * #DBUS_MESSAGE_TYPE_SIGNAL, and so forth.
1224  *
1225  * Usually you want to use dbus_message_new_method_call(),
1226  * dbus_message_new_method_return(), dbus_message_new_signal(),
1227  * or dbus_message_new_error() instead.
1228  * 
1229  * @param message_type type of message
1230  * @returns new message or #NULL if no memory
1231  */
1232 DBusMessage*
1233 dbus_message_new (int message_type)
1234 {
1235   DBusMessage *message;
1236
1237   _dbus_return_val_if_fail (message_type != DBUS_MESSAGE_TYPE_INVALID, NULL);
1238
1239   message = dbus_message_new_empty_header ();
1240   if (message == NULL)
1241     return NULL;
1242
1243   if (!_dbus_header_create (&message->header,
1244                             DBUS_COMPILER_BYTE_ORDER,
1245                             message_type,
1246                             NULL, NULL, NULL, NULL, NULL))
1247     {
1248       dbus_message_unref (message);
1249       return NULL;
1250     }
1251
1252   return message;
1253 }
1254
1255 /**
1256  * Constructs a new message to invoke a method on a remote
1257  * object. Returns #NULL if memory can't be allocated for the
1258  * message. The destination may be #NULL in which case no destination
1259  * is set; this is appropriate when using D-Bus in a peer-to-peer
1260  * context (no message bus). The interface may be #NULL, which means
1261  * that if multiple methods with the given name exist it is undefined
1262  * which one will be invoked.
1263  *
1264  * The path and method names may not be #NULL.
1265  *
1266  * Destination, path, interface, and method name can't contain
1267  * any invalid characters (see the D-Bus specification).
1268  * 
1269  * @param destination name that the message should be sent to or #NULL
1270  * @param path object path the message should be sent to
1271  * @param iface interface to invoke method on, or #NULL
1272  * @param method method to invoke
1273  *
1274  * @returns a new DBusMessage, free with dbus_message_unref()
1275  */
1276 DBusMessage*
1277 dbus_message_new_method_call (const char *destination,
1278                               const char *path,
1279                               const char *iface,
1280                               const char *method)
1281 {
1282   DBusMessage *message;
1283
1284   _dbus_return_val_if_fail (path != NULL, NULL);
1285   _dbus_return_val_if_fail (method != NULL, NULL);
1286   _dbus_return_val_if_fail (destination == NULL ||
1287                             _dbus_check_is_valid_bus_name (destination), NULL);
1288   _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
1289   _dbus_return_val_if_fail (iface == NULL ||
1290                             _dbus_check_is_valid_interface (iface), NULL);
1291   _dbus_return_val_if_fail (_dbus_check_is_valid_member (method), NULL);
1292
1293   message = dbus_message_new_empty_header ();
1294   if (message == NULL)
1295     return NULL;
1296
1297   if (!_dbus_header_create (&message->header,
1298                             DBUS_COMPILER_BYTE_ORDER,
1299                             DBUS_MESSAGE_TYPE_METHOD_CALL,
1300                             destination, path, iface, method, NULL))
1301     {
1302       dbus_message_unref (message);
1303       return NULL;
1304     }
1305
1306   return message;
1307 }
1308
1309 /**
1310  * Constructs a message that is a reply to a method call. Returns
1311  * #NULL if memory can't be allocated for the message.
1312  *
1313  * @param method_call the message being replied to
1314  * @returns a new DBusMessage, free with dbus_message_unref()
1315  */
1316 DBusMessage*
1317 dbus_message_new_method_return (DBusMessage *method_call)
1318 {
1319   DBusMessage *message;
1320   const char *sender;
1321
1322   _dbus_return_val_if_fail (method_call != NULL, NULL);
1323
1324   sender = dbus_message_get_sender (method_call);
1325
1326   /* sender is allowed to be null here in peer-to-peer case */
1327
1328   message = dbus_message_new_empty_header ();
1329   if (message == NULL)
1330     return NULL;
1331
1332   if (!_dbus_header_create (&message->header,
1333                             DBUS_COMPILER_BYTE_ORDER,
1334                             DBUS_MESSAGE_TYPE_METHOD_RETURN,
1335                             sender, NULL, NULL, NULL, NULL))
1336     {
1337       dbus_message_unref (message);
1338       return NULL;
1339     }
1340
1341   dbus_message_set_no_reply (message, TRUE);
1342
1343   if (!dbus_message_set_reply_serial (message,
1344                                       dbus_message_get_serial (method_call)))
1345     {
1346       dbus_message_unref (message);
1347       return NULL;
1348     }
1349
1350   return message;
1351 }
1352
1353 /**
1354  * Constructs a new message representing a signal emission. Returns
1355  * #NULL if memory can't be allocated for the message.  A signal is
1356  * identified by its originating object path, interface, and the name
1357  * of the signal.
1358  *
1359  * Path, interface, and signal name must all be valid (the D-Bus
1360  * specification defines the syntax of these fields).
1361  * 
1362  * @param path the path to the object emitting the signal
1363  * @param iface the interface the signal is emitted from
1364  * @param name name of the signal
1365  * @returns a new DBusMessage, free with dbus_message_unref()
1366  */
1367 DBusMessage*
1368 dbus_message_new_signal (const char *path,
1369                          const char *iface,
1370                          const char *name)
1371 {
1372   DBusMessage *message;
1373
1374   _dbus_return_val_if_fail (path != NULL, NULL);
1375   _dbus_return_val_if_fail (iface != NULL, NULL);
1376   _dbus_return_val_if_fail (name != NULL, NULL);
1377   _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
1378   _dbus_return_val_if_fail (_dbus_check_is_valid_interface (iface), NULL);
1379   _dbus_return_val_if_fail (_dbus_check_is_valid_member (name), NULL);
1380
1381   message = dbus_message_new_empty_header ();
1382   if (message == NULL)
1383     return NULL;
1384
1385   if (!_dbus_header_create (&message->header,
1386                             DBUS_COMPILER_BYTE_ORDER,
1387                             DBUS_MESSAGE_TYPE_SIGNAL,
1388                             NULL, path, iface, name, NULL))
1389     {
1390       dbus_message_unref (message);
1391       return NULL;
1392     }
1393
1394   dbus_message_set_no_reply (message, TRUE);
1395
1396   return message;
1397 }
1398
1399 /**
1400  * Creates a new message that is an error reply to another message.
1401  * Error replies are most common in response to method calls, but
1402  * can be returned in reply to any message.
1403  *
1404  * The error name must be a valid error name according to the syntax
1405  * given in the D-Bus specification. If you don't want to make
1406  * up an error name just use #DBUS_ERROR_FAILED.
1407  *
1408  * @param reply_to the message we're replying to
1409  * @param error_name the error name
1410  * @param error_message the error message string (or #NULL for none, but please give a message)
1411  * @returns a new error message object, free with dbus_message_unref()
1412  */
1413 DBusMessage*
1414 dbus_message_new_error (DBusMessage *reply_to,
1415                         const char  *error_name,
1416                         const char  *error_message)
1417 {
1418   DBusMessage *message;
1419   const char *sender;
1420   DBusMessageIter iter;
1421
1422   _dbus_return_val_if_fail (reply_to != NULL, NULL);
1423   _dbus_return_val_if_fail (error_name != NULL, NULL);
1424   _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
1425
1426   sender = dbus_message_get_sender (reply_to);
1427
1428   /* sender may be NULL for non-message-bus case or
1429    * when the message bus is dealing with an unregistered
1430    * connection.
1431    */
1432   message = dbus_message_new_empty_header ();
1433   if (message == NULL)
1434     return NULL;
1435
1436   if (!_dbus_header_create (&message->header,
1437                             DBUS_COMPILER_BYTE_ORDER,
1438                             DBUS_MESSAGE_TYPE_ERROR,
1439                             sender, NULL, NULL, NULL, error_name))
1440     {
1441       dbus_message_unref (message);
1442       return NULL;
1443     }
1444
1445   dbus_message_set_no_reply (message, TRUE);
1446
1447   if (!dbus_message_set_reply_serial (message,
1448                                       dbus_message_get_serial (reply_to)))
1449     {
1450       dbus_message_unref (message);
1451       return NULL;
1452     }
1453
1454   if (error_message != NULL)
1455     {
1456       dbus_message_iter_init_append (message, &iter);
1457       if (!dbus_message_iter_append_basic (&iter,
1458                                            DBUS_TYPE_STRING,
1459                                            &error_message))
1460         {
1461           dbus_message_unref (message);
1462           return NULL;
1463         }
1464     }
1465
1466   return message;
1467 }
1468
1469 /**
1470  * Creates a new message that is an error reply to another message, allowing
1471  * you to use printf formatting.
1472  *
1473  * See dbus_message_new_error() for details - this function is the same
1474  * aside from the printf formatting.
1475  *
1476  * @todo add _DBUS_GNUC_PRINTF to this (requires moving _DBUS_GNUC_PRINTF to
1477  * public header, see DBUS_DEPRECATED for an example)
1478  * 
1479  * @param reply_to the original message
1480  * @param error_name the error name
1481  * @param error_format the error message format as with printf
1482  * @param ... format string arguments
1483  * @returns a new error message
1484  */
1485 DBusMessage*
1486 dbus_message_new_error_printf (DBusMessage *reply_to,
1487                                const char  *error_name,
1488                                const char  *error_format,
1489                                ...)
1490 {
1491   va_list args;
1492   DBusString str;
1493   DBusMessage *message;
1494
1495   _dbus_return_val_if_fail (reply_to != NULL, NULL);
1496   _dbus_return_val_if_fail (error_name != NULL, NULL);
1497   _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
1498
1499   if (!_dbus_string_init (&str))
1500     return NULL;
1501
1502   va_start (args, error_format);
1503
1504   if (_dbus_string_append_printf_valist (&str, error_format, args))
1505     message = dbus_message_new_error (reply_to, error_name,
1506                                       _dbus_string_get_const_data (&str));
1507   else
1508     message = NULL;
1509
1510   _dbus_string_free (&str);
1511
1512   va_end (args);
1513
1514   return message;
1515 }
1516
1517
1518 /**
1519  * Creates a new message that is an exact replica of the message
1520  * specified, except that its refcount is set to 1, its message serial
1521  * is reset to 0, and if the original message was "locked" (in the
1522  * outgoing message queue and thus not modifiable) the new message
1523  * will not be locked.
1524  *
1525  * @todo This function can't be used in programs that try to recover from OOM errors.
1526  *
1527  * @param message the message
1528  * @returns the new message.or #NULL if not enough memory or Unix file descriptors (in case the message to copy includes Unix file descriptors) can be allocated.
1529  */
1530 DBusMessage *
1531 dbus_message_copy (const DBusMessage *message)
1532 {
1533   DBusMessage *retval;
1534
1535   _dbus_return_val_if_fail (message != NULL, NULL);
1536
1537   retval = dbus_new0 (DBusMessage, 1);
1538   if (retval == NULL)
1539     return NULL;
1540
1541   _dbus_atomic_inc (&retval->refcount);
1542
1543   retval->locked = FALSE;
1544 #ifndef DBUS_DISABLE_CHECKS
1545   retval->generation = message->generation;
1546 #endif
1547
1548   if (!_dbus_header_copy (&message->header, &retval->header))
1549     {
1550       dbus_free (retval);
1551       return NULL;
1552     }
1553
1554   if (!_dbus_string_init_preallocated (&retval->body,
1555                                        _dbus_string_get_length (&message->body)))
1556     {
1557       _dbus_header_free (&retval->header);
1558       dbus_free (retval);
1559       return NULL;
1560     }
1561
1562   if (!_dbus_string_copy (&message->body, 0,
1563                           &retval->body, 0))
1564     goto failed_copy;
1565
1566 #ifdef HAVE_UNIX_FD_PASSING
1567   retval->unix_fds = dbus_new(int, message->n_unix_fds);
1568   if (retval->unix_fds == NULL && message->n_unix_fds > 0)
1569     goto failed_copy;
1570
1571   retval->n_unix_fds_allocated = message->n_unix_fds;
1572
1573   for (retval->n_unix_fds = 0;
1574        retval->n_unix_fds < message->n_unix_fds;
1575        retval->n_unix_fds++)
1576     {
1577       retval->unix_fds[retval->n_unix_fds] = _dbus_dup(message->unix_fds[retval->n_unix_fds], NULL);
1578
1579       if (retval->unix_fds[retval->n_unix_fds] < 0)
1580         goto failed_copy;
1581     }
1582
1583 #endif
1584
1585   _dbus_message_trace_ref (retval, 0, 1, "copy");
1586   return retval;
1587
1588  failed_copy:
1589   _dbus_header_free (&retval->header);
1590   _dbus_string_free (&retval->body);
1591
1592 #ifdef HAVE_UNIX_FD_PASSING
1593   close_unix_fds(retval->unix_fds, &retval->n_unix_fds);
1594   dbus_free(retval->unix_fds);
1595 #endif
1596
1597   dbus_free (retval);
1598
1599   return NULL;
1600 }
1601
1602
1603 /**
1604  * Increments the reference count of a DBusMessage.
1605  *
1606  * @param message the message
1607  * @returns the message
1608  * @see dbus_message_unref
1609  */
1610 DBusMessage *
1611 dbus_message_ref (DBusMessage *message)
1612 {
1613   dbus_int32_t old_refcount;
1614
1615   _dbus_return_val_if_fail (message != NULL, NULL);
1616   _dbus_return_val_if_fail (message->generation == _dbus_current_generation, NULL);
1617   _dbus_return_val_if_fail (!message->in_cache, NULL);
1618
1619   old_refcount = _dbus_atomic_inc (&message->refcount);
1620   _dbus_assert (old_refcount >= 1);
1621   _dbus_message_trace_ref (message, old_refcount, old_refcount + 1, "ref");
1622
1623   return message;
1624 }
1625
1626 /**
1627  * Decrements the reference count of a DBusMessage, freeing the
1628  * message if the count reaches 0.
1629  *
1630  * @param message the message
1631  * @see dbus_message_ref
1632  */
1633 void
1634 dbus_message_unref (DBusMessage *message)
1635 {
1636  dbus_int32_t old_refcount;
1637
1638   _dbus_return_if_fail (message != NULL);
1639   _dbus_return_if_fail (message->generation == _dbus_current_generation);
1640   _dbus_return_if_fail (!message->in_cache);
1641
1642   old_refcount = _dbus_atomic_dec (&message->refcount);
1643
1644   _dbus_assert (old_refcount >= 1);
1645
1646   _dbus_message_trace_ref (message, old_refcount, old_refcount - 1, "unref");
1647
1648   if (old_refcount == 1)
1649     {
1650       /* Calls application callbacks! */
1651       dbus_message_cache_or_finalize (message);
1652     }
1653 }
1654
1655 /**
1656  * Gets the type of a message. Types include
1657  * #DBUS_MESSAGE_TYPE_METHOD_CALL, #DBUS_MESSAGE_TYPE_METHOD_RETURN,
1658  * #DBUS_MESSAGE_TYPE_ERROR, #DBUS_MESSAGE_TYPE_SIGNAL, but other
1659  * types are allowed and all code must silently ignore messages of
1660  * unknown type. #DBUS_MESSAGE_TYPE_INVALID will never be returned.
1661  *
1662  * @param message the message
1663  * @returns the type of the message
1664  */
1665 int
1666 dbus_message_get_type (DBusMessage *message)
1667 {
1668   _dbus_return_val_if_fail (message != NULL, DBUS_MESSAGE_TYPE_INVALID);
1669
1670   return _dbus_header_get_message_type (&message->header);
1671 }
1672
1673 /**
1674  * Appends fields to a message given a variable argument list. The
1675  * variable argument list should contain the type of each argument
1676  * followed by the value to append. Appendable types are basic types,
1677  * and arrays of fixed-length basic types (except arrays of Unix file
1678  * descriptors). To append variable-length basic types, or any more
1679  * complex value, you have to use an iterator rather than this
1680  * function.
1681  *
1682  * To append a basic type, specify its type code followed by the
1683  * address of the value. For example:
1684  *
1685  * @code
1686  *
1687  * dbus_int32_t v_INT32 = 42;
1688  * const char *v_STRING = "Hello World";
1689  * dbus_message_append_args (message,
1690  *                           DBUS_TYPE_INT32, &v_INT32,
1691  *                           DBUS_TYPE_STRING, &v_STRING,
1692  *                           DBUS_TYPE_INVALID);
1693  * @endcode
1694  *
1695  * To append an array of fixed-length basic types (except Unix file
1696  * descriptors), pass in the DBUS_TYPE_ARRAY typecode, the element
1697  * typecode, the address of the array pointer, and a 32-bit integer
1698  * giving the number of elements in the array. So for example: @code
1699  * const dbus_int32_t array[] = { 1, 2, 3 }; const dbus_int32_t
1700  * *v_ARRAY = array; dbus_message_append_args (message,
1701  * DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY, 3, DBUS_TYPE_INVALID);
1702  * @endcode
1703  *
1704  * This function does not support arrays of Unix file descriptors. If
1705  * you need those you need to manually recurse into the array.
1706  *
1707  * For Unix file descriptors this function will internally duplicate
1708  * the descriptor you passed in. Hence you may close the descriptor
1709  * immediately after this call.
1710  *
1711  * @warning in C, given "int array[]", "&array == array" (the
1712  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
1713  * So if you're using an array instead of a pointer you have to create
1714  * a pointer variable, assign the array to it, then take the address
1715  * of the pointer variable. For strings it works to write
1716  * const char *array = "Hello" and then use &array though.
1717  *
1718  * The last argument to this function must be #DBUS_TYPE_INVALID,
1719  * marking the end of the argument list. If you don't do this
1720  * then libdbus won't know to stop and will read invalid memory.
1721  *
1722  * String/signature/path arrays should be passed in as "const char***
1723  * address_of_array" and "int n_elements"
1724  *
1725  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1726  *
1727  * @todo If this fails due to lack of memory, the message is hosed and
1728  * you have to start over building the whole message.
1729  *
1730  * @param message the message
1731  * @param first_arg_type type of the first argument
1732  * @param ... value of first argument, list of additional type-value pairs
1733  * @returns #TRUE on success
1734  */
1735 dbus_bool_t
1736 dbus_message_append_args (DBusMessage *message,
1737                           int          first_arg_type,
1738                           ...)
1739 {
1740   dbus_bool_t retval;
1741   va_list var_args;
1742
1743   _dbus_return_val_if_fail (message != NULL, FALSE);
1744
1745   va_start (var_args, first_arg_type);
1746   retval = dbus_message_append_args_valist (message,
1747                                             first_arg_type,
1748                                             var_args);
1749   va_end (var_args);
1750
1751   return retval;
1752 }
1753
1754 /**
1755  * Like dbus_message_append_args() but takes a va_list for use by language bindings.
1756  *
1757  * @todo for now, if this function fails due to OOM it will leave
1758  * the message half-written and you have to discard the message
1759  * and start over.
1760  *
1761  * @see dbus_message_append_args.
1762  * @param message the message
1763  * @param first_arg_type type of first argument
1764  * @param var_args value of first argument, then list of type/value pairs
1765  * @returns #TRUE on success
1766  */
1767 dbus_bool_t
1768 dbus_message_append_args_valist (DBusMessage *message,
1769                                  int          first_arg_type,
1770                                  va_list      var_args)
1771 {
1772   int type;
1773   DBusMessageIter iter;
1774
1775   _dbus_return_val_if_fail (message != NULL, FALSE);
1776
1777   type = first_arg_type;
1778
1779   dbus_message_iter_init_append (message, &iter);
1780
1781   while (type != DBUS_TYPE_INVALID)
1782     {
1783       if (dbus_type_is_basic (type))
1784         {
1785           const DBusBasicValue *value;
1786           value = va_arg (var_args, const DBusBasicValue*);
1787
1788           if (!dbus_message_iter_append_basic (&iter,
1789                                                type,
1790                                                value))
1791             goto failed;
1792         }
1793       else if (type == DBUS_TYPE_ARRAY)
1794         {
1795           int element_type;
1796           DBusMessageIter array;
1797           char buf[2];
1798
1799           element_type = va_arg (var_args, int);
1800               
1801           buf[0] = element_type;
1802           buf[1] = '\0';
1803           if (!dbus_message_iter_open_container (&iter,
1804                                                  DBUS_TYPE_ARRAY,
1805                                                  buf,
1806                                                  &array))
1807             goto failed;
1808
1809           if (dbus_type_is_fixed (element_type) &&
1810               element_type != DBUS_TYPE_UNIX_FD)
1811             {
1812               const DBusBasicValue **value;
1813               int n_elements;
1814
1815               value = va_arg (var_args, const DBusBasicValue**);
1816               n_elements = va_arg (var_args, int);
1817               
1818               if (!dbus_message_iter_append_fixed_array (&array,
1819                                                          element_type,
1820                                                          value,
1821                                                          n_elements)) {
1822                 dbus_message_iter_abandon_container (&iter, &array);
1823                 goto failed;
1824               }
1825             }
1826           else if (_DBUS_TYPE_IS_STRINGLIKE (element_type))
1827             {
1828               const char ***value_p;
1829               const char **value;
1830               int n_elements;
1831               int i;
1832               
1833               value_p = va_arg (var_args, const char***);
1834               n_elements = va_arg (var_args, int);
1835
1836               value = *value_p;
1837               
1838               i = 0;
1839               while (i < n_elements)
1840                 {
1841                   if (!dbus_message_iter_append_basic (&array,
1842                                                        element_type,
1843                                                        &value[i])) {
1844                     dbus_message_iter_abandon_container (&iter, &array);
1845                     goto failed;
1846                   }
1847                   ++i;
1848                 }
1849             }
1850           else
1851             {
1852               _dbus_warn ("arrays of %s can't be appended with %s for now\n",
1853                           _dbus_type_to_string (element_type),
1854                           _DBUS_FUNCTION_NAME);
1855               goto failed;
1856             }
1857
1858           if (!dbus_message_iter_close_container (&iter, &array))
1859             goto failed;
1860         }
1861 #ifndef DBUS_DISABLE_CHECKS
1862       else
1863         {
1864           _dbus_warn ("type %s isn't supported yet in %s\n",
1865                       _dbus_type_to_string (type), _DBUS_FUNCTION_NAME);
1866           goto failed;
1867         }
1868 #endif
1869
1870       type = va_arg (var_args, int);
1871     }
1872
1873   return TRUE;
1874
1875  failed:
1876   return FALSE;
1877 }
1878
1879 /**
1880  * Gets arguments from a message given a variable argument list.  The
1881  * supported types include those supported by
1882  * dbus_message_append_args(); that is, basic types and arrays of
1883  * fixed-length basic types.  The arguments are the same as they would
1884  * be for dbus_message_iter_get_basic() or
1885  * dbus_message_iter_get_fixed_array().
1886  *
1887  * In addition to those types, arrays of string, object path, and
1888  * signature are supported; but these are returned as allocated memory
1889  * and must be freed with dbus_free_string_array(), while the other
1890  * types are returned as const references. To get a string array
1891  * pass in "char ***array_location" and "int *n_elements".
1892  *
1893  * Similar to dbus_message_get_fixed_array() this function does not
1894  * support arrays of type DBUS_TYPE_UNIX_FD. If you need to parse
1895  * messages with arrays of Unix file descriptors you need to recurse
1896  * into the array manually.
1897  *
1898  * Unix file descriptors that are read with this function will have
1899  * the FD_CLOEXEC flag set. If you need them without this flag set,
1900  * make sure to unset it with fcntl().
1901  *
1902  * The variable argument list should contain the type of the argument
1903  * followed by a pointer to where the value should be stored. The list
1904  * is terminated with #DBUS_TYPE_INVALID.
1905  *
1906  * Except for string arrays, the returned values are constant; do not
1907  * free them. They point into the #DBusMessage.
1908  *
1909  * If the requested arguments are not present, or do not have the
1910  * requested types, then an error will be set.
1911  *
1912  * If more arguments than requested are present, the requested
1913  * arguments are returned and the extra arguments are ignored.
1914  * 
1915  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1916  *
1917  * @param message the message
1918  * @param error error to be filled in on failure
1919  * @param first_arg_type the first argument type
1920  * @param ... location for first argument value, then list of type-location pairs
1921  * @returns #FALSE if the error was set
1922  */
1923 dbus_bool_t
1924 dbus_message_get_args (DBusMessage     *message,
1925                        DBusError       *error,
1926                        int              first_arg_type,
1927                        ...)
1928 {
1929   dbus_bool_t retval;
1930   va_list var_args;
1931
1932   _dbus_return_val_if_fail (message != NULL, FALSE);
1933   _dbus_return_val_if_error_is_set (error, FALSE);
1934
1935   va_start (var_args, first_arg_type);
1936   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
1937   va_end (var_args);
1938
1939   return retval;
1940 }
1941
1942 /**
1943  * Like dbus_message_get_args but takes a va_list for use by language bindings.
1944  *
1945  * @see dbus_message_get_args
1946  * @param message the message
1947  * @param error error to be filled in
1948  * @param first_arg_type type of the first argument
1949  * @param var_args return location for first argument, followed by list of type/location pairs
1950  * @returns #FALSE if error was set
1951  */
1952 dbus_bool_t
1953 dbus_message_get_args_valist (DBusMessage     *message,
1954                               DBusError       *error,
1955                               int              first_arg_type,
1956                               va_list          var_args)
1957 {
1958   DBusMessageIter iter;
1959
1960   _dbus_return_val_if_fail (message != NULL, FALSE);
1961   _dbus_return_val_if_error_is_set (error, FALSE);
1962
1963   dbus_message_iter_init (message, &iter);
1964   return _dbus_message_iter_get_args_valist (&iter, error, first_arg_type, var_args);
1965 }
1966
1967 static void
1968 _dbus_message_iter_init_common (DBusMessage         *message,
1969                                 DBusMessageRealIter *real,
1970                                 int                  iter_type)
1971 {
1972   _dbus_assert (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
1973
1974   /* Since the iterator will read or write who-knows-what from the
1975    * message, we need to get in the right byte order
1976    */
1977   ensure_byte_order (message);
1978   
1979   real->message = message;
1980   real->changed_stamp = message->changed_stamp;
1981   real->iter_type = iter_type;
1982   real->sig_refcount = 0;
1983 }
1984
1985 /**
1986  * Initializes a #DBusMessageIter for reading the arguments of the
1987  * message passed in.
1988  *
1989  * When possible, dbus_message_get_args() is much more convenient.
1990  * Some types of argument can only be read with #DBusMessageIter
1991  * however.
1992  *
1993  * The easiest way to iterate is like this: 
1994  * @code
1995  * dbus_message_iter_init (message, &iter);
1996  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
1997  *   dbus_message_iter_next (&iter);
1998  * @endcode
1999  *
2000  * #DBusMessageIter contains no allocated memory; it need not be
2001  * freed, and can be copied by assignment or memcpy().
2002  * 
2003  * @param message the message
2004  * @param iter pointer to an iterator to initialize
2005  * @returns #FALSE if the message has no arguments
2006  */
2007 dbus_bool_t
2008 dbus_message_iter_init (DBusMessage     *message,
2009                         DBusMessageIter *iter)
2010 {
2011   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2012   const DBusString *type_str;
2013   int type_pos;
2014
2015   _dbus_return_val_if_fail (message != NULL, FALSE);
2016   _dbus_return_val_if_fail (iter != NULL, FALSE);
2017
2018   get_const_signature (&message->header, &type_str, &type_pos);
2019
2020   _dbus_message_iter_init_common (message, real,
2021                                   DBUS_MESSAGE_ITER_TYPE_READER);
2022
2023   _dbus_type_reader_init (&real->u.reader,
2024                           _dbus_header_get_byte_order (&message->header),
2025                           type_str, type_pos,
2026                           &message->body,
2027                           0);
2028
2029   return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
2030 }
2031
2032 /**
2033  * Checks if an iterator has any more fields.
2034  *
2035  * @param iter the message iter
2036  * @returns #TRUE if there are more fields following
2037  */
2038 dbus_bool_t
2039 dbus_message_iter_has_next (DBusMessageIter *iter)
2040 {
2041   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2042
2043   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
2044   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2045
2046   return _dbus_type_reader_has_next (&real->u.reader);
2047 }
2048
2049 /**
2050  * Moves the iterator to the next field, if any. If there's no next
2051  * field, returns #FALSE. If the iterator moves forward, returns
2052  * #TRUE.
2053  *
2054  * @param iter the message iter
2055  * @returns #TRUE if the iterator was moved to the next field
2056  */
2057 dbus_bool_t
2058 dbus_message_iter_next (DBusMessageIter *iter)
2059 {
2060   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2061
2062   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
2063   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2064
2065   return _dbus_type_reader_next (&real->u.reader);
2066 }
2067
2068 /**
2069  * Returns the argument type of the argument that the message iterator
2070  * points to. If the iterator is at the end of the message, returns
2071  * #DBUS_TYPE_INVALID. You can thus write a loop as follows:
2072  *
2073  * @code
2074  * dbus_message_iter_init (message, &iter);
2075  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
2076  *   dbus_message_iter_next (&iter);
2077  * @endcode
2078  *
2079  * @param iter the message iter
2080  * @returns the argument type
2081  */
2082 int
2083 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
2084 {
2085   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2086
2087   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2088   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2089
2090   return _dbus_type_reader_get_current_type (&real->u.reader);
2091 }
2092
2093 /**
2094  * Returns the element type of the array that the message iterator
2095  * points to. Note that you need to check that the iterator points to
2096  * an array prior to using this function.
2097  *
2098  * @param iter the message iter
2099  * @returns the array element type
2100  */
2101 int
2102 dbus_message_iter_get_element_type (DBusMessageIter *iter)
2103 {
2104   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2105
2106   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2107   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, DBUS_TYPE_INVALID);
2108   _dbus_return_val_if_fail (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY, DBUS_TYPE_INVALID);
2109
2110   return _dbus_type_reader_get_element_type (&real->u.reader);
2111 }
2112
2113 /**
2114  * Recurses into a container value when reading values from a message,
2115  * initializing a sub-iterator to use for traversing the child values
2116  * of the container.
2117  *
2118  * Note that this recurses into a value, not a type, so you can only
2119  * recurse if the value exists. The main implication of this is that
2120  * if you have for example an empty array of array of int32, you can
2121  * recurse into the outermost array, but it will have no values, so
2122  * you won't be able to recurse further. There's no array of int32 to
2123  * recurse into.
2124  *
2125  * If a container is an array of fixed-length types (except Unix file
2126  * descriptors), it is much more efficient to use
2127  * dbus_message_iter_get_fixed_array() to get the whole array in one
2128  * shot, rather than individually walking over the array elements.
2129  *
2130  * Be sure you have somehow checked that
2131  * dbus_message_iter_get_arg_type() matches the type you are expecting
2132  * to recurse into. Results of this function are undefined if there is
2133  * no container to recurse into at the current iterator position.
2134  *
2135  * @param iter the message iterator
2136  * @param sub the sub-iterator to initialize
2137  */
2138 void
2139 dbus_message_iter_recurse (DBusMessageIter  *iter,
2140                            DBusMessageIter  *sub)
2141 {
2142   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2143   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2144
2145   _dbus_return_if_fail (_dbus_message_iter_check (real));
2146   _dbus_return_if_fail (sub != NULL);
2147
2148   *real_sub = *real;
2149   _dbus_type_reader_recurse (&real->u.reader, &real_sub->u.reader);
2150 }
2151
2152 /**
2153  * Returns the current signature of a message iterator.  This
2154  * is useful primarily for dealing with variants; one can
2155  * recurse into a variant and determine the signature of
2156  * the variant's value.
2157  *
2158  * The returned string must be freed with dbus_free().
2159  * 
2160  * @param iter the message iterator
2161  * @returns the contained signature, or NULL if out of memory
2162  */
2163 char *
2164 dbus_message_iter_get_signature (DBusMessageIter *iter)
2165 {
2166   const DBusString *sig;
2167   DBusString retstr;
2168   char *ret;
2169   int start, len;
2170   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2171
2172   _dbus_return_val_if_fail (_dbus_message_iter_check (real), NULL);
2173
2174   if (!_dbus_string_init (&retstr))
2175     return NULL;
2176
2177   _dbus_type_reader_get_signature (&real->u.reader, &sig,
2178                                    &start, &len);
2179   if (!_dbus_string_append_len (&retstr,
2180                                 _dbus_string_get_const_data (sig) + start,
2181                                 len))
2182     return NULL;
2183   if (!_dbus_string_steal_data (&retstr, &ret))
2184     return NULL;
2185   _dbus_string_free (&retstr);
2186   return ret;
2187 }
2188
2189 /**
2190  * Reads a basic-typed value from the message iterator.
2191  * Basic types are the non-containers such as integer and string.
2192  *
2193  * The value argument should be the address of a location to store
2194  * the returned value. So for int32 it should be a "dbus_int32_t*"
2195  * and for string a "const char**". The returned value is
2196  * by reference and should not be freed.
2197  *
2198  * This call duplicates Unix file descriptors when reading them. It is
2199  * your job to close them when you don't need them anymore.
2200  *
2201  * Unix file descriptors that are read with this function will have
2202  * the FD_CLOEXEC flag set. If you need them without this flag set,
2203  * make sure to unset it with fcntl().
2204  *
2205  * Be sure you have somehow checked that
2206  * dbus_message_iter_get_arg_type() matches the type you are
2207  * expecting, or you'll crash when you try to use an integer as a
2208  * string or something.
2209  *
2210  * To read any container type (array, struct, dict) you will need to
2211  * recurse into the container with dbus_message_iter_recurse().  If
2212  * the container is an array of fixed-length values (except Unix file
2213  * descriptors), you can get all the array elements at once with
2214  * dbus_message_iter_get_fixed_array(). Otherwise, you have to iterate
2215  * over the container's contents one value at a time.
2216  *
2217  * All basic-typed values are guaranteed to fit in a #DBusBasicValue,
2218  * so in versions of libdbus that have that type, you can write code like this:
2219  *
2220  * @code
2221  * DBusBasicValue value;
2222  * int type;
2223  * dbus_message_iter_get_basic (&read_iter, &value);
2224  * type = dbus_message_iter_get_arg_type (&read_iter);
2225  * dbus_message_iter_append_basic (&write_iter, type, &value);
2226  * @endcode
2227  *
2228  * (All D-Bus basic types are either numeric and 8 bytes or smaller, or
2229  * behave like a string; so in older versions of libdbus, DBusBasicValue
2230  * can be replaced with union { char *string; unsigned char bytes[8]; },
2231  * for instance.)
2232  *
2233  * @param iter the iterator
2234  * @param value location to store the value
2235  */
2236 void
2237 dbus_message_iter_get_basic (DBusMessageIter  *iter,
2238                              void             *value)
2239 {
2240   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2241
2242   _dbus_return_if_fail (_dbus_message_iter_check (real));
2243   _dbus_return_if_fail (value != NULL);
2244
2245   if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UNIX_FD)
2246     {
2247 #ifdef HAVE_UNIX_FD_PASSING
2248       DBusBasicValue idx;
2249
2250       _dbus_type_reader_read_basic(&real->u.reader, &idx);
2251
2252       if (idx.u32 >= real->message->n_unix_fds) {
2253         /* Hmm, we cannot really signal an error here, so let's make
2254            sure to return an invalid fd. */
2255         *((int*) value) = -1;
2256         return;
2257       }
2258
2259       *((int*) value) = _dbus_dup(real->message->unix_fds[idx.u32], NULL);
2260 #else
2261       *((int*) value) = -1;
2262 #endif
2263     }
2264   else
2265     {
2266       _dbus_type_reader_read_basic (&real->u.reader,
2267                                     value);
2268     }
2269 }
2270
2271 /**
2272  * Returns the number of bytes in the array as marshaled in the wire
2273  * protocol. The iterator must currently be inside an array-typed
2274  * value.
2275  *
2276  * This function is deprecated on the grounds that it is stupid.  Why
2277  * would you want to know how many bytes are in the array as marshaled
2278  * in the wire protocol?  For now, use the n_elements returned from
2279  * dbus_message_iter_get_fixed_array() instead, or iterate over the
2280  * array values and count them.
2281  *
2282  * @todo introduce a variant of this get_n_elements that returns
2283  * the number of elements, though with a non-fixed array it will not
2284  * be very efficient, so maybe it's not good.
2285  * 
2286  * @param iter the iterator
2287  * @returns the number of bytes in the array
2288  */
2289 int
2290 dbus_message_iter_get_array_len (DBusMessageIter *iter)
2291 {
2292   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2293
2294   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2295
2296   return _dbus_type_reader_get_array_length (&real->u.reader);
2297 }
2298
2299 /**
2300  * Reads a block of fixed-length values from the message iterator.
2301  * Fixed-length values are those basic types that are not string-like,
2302  * such as integers, bool, double. The returned block will be from the
2303  * current position in the array until the end of the array.
2304  *
2305  * There is one exception here: although DBUS_TYPE_UNIX_FD is
2306  * considered a 'fixed' type arrays of this type may not be read with
2307  * this function.
2308  *
2309  * The message iter should be "in" the array (that is, you recurse into the
2310  * array, and then you call dbus_message_iter_get_fixed_array() on the
2311  * "sub-iterator" created by dbus_message_iter_recurse()).
2312  *
2313  * The value argument should be the address of a location to store the
2314  * returned array. So for int32 it should be a "const dbus_int32_t**"
2315  * The returned value is by reference and should not be freed.
2316  * 
2317  * This function should only be used if dbus_type_is_fixed() returns
2318  * #TRUE for the element type.
2319  *
2320  * If an array's elements are not fixed in size, you have to recurse
2321  * into the array with dbus_message_iter_recurse() and read the
2322  * elements one by one.
2323  * 
2324  * Because the array is not copied, this function runs in constant
2325  * time and is fast; it's much preferred over walking the entire array
2326  * with an iterator. (However, you can always use
2327  * dbus_message_iter_recurse(), even for fixed-length types;
2328  * dbus_message_iter_get_fixed_array() is just an optimization.)
2329  * 
2330  * @param iter the iterator
2331  * @param value location to store the block
2332  * @param n_elements number of elements in the block
2333  */
2334 void
2335 dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
2336                                    void             *value,
2337                                    int              *n_elements)
2338 {
2339   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2340 #ifndef DBUS_DISABLE_CHECKS
2341   int subtype = _dbus_type_reader_get_current_type(&real->u.reader);
2342
2343   _dbus_return_if_fail (_dbus_message_iter_check (real));
2344   _dbus_return_if_fail (value != NULL);
2345   _dbus_return_if_fail ((subtype == DBUS_TYPE_INVALID) ||
2346                         (dbus_type_is_fixed (subtype) && subtype != DBUS_TYPE_UNIX_FD));
2347 #endif
2348
2349   _dbus_type_reader_read_fixed_multi (&real->u.reader,
2350                                       value, n_elements);
2351 }
2352
2353 /**
2354  * Initializes a #DBusMessageIter for appending arguments to the end
2355  * of a message.
2356  *
2357  * @todo If appending any of the arguments fails due to lack of
2358  * memory, the message is hosed and you have to start over building
2359  * the whole message.
2360  *
2361  * @param message the message
2362  * @param iter pointer to an iterator to initialize
2363  */
2364 void
2365 dbus_message_iter_init_append (DBusMessage     *message,
2366                                DBusMessageIter *iter)
2367 {
2368   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2369
2370   _dbus_return_if_fail (message != NULL);
2371   _dbus_return_if_fail (iter != NULL);
2372
2373   _dbus_message_iter_init_common (message, real,
2374                                   DBUS_MESSAGE_ITER_TYPE_WRITER);
2375
2376   /* We create the signature string and point iterators at it "on demand"
2377    * when a value is actually appended. That means that init() never fails
2378    * due to OOM.
2379    */
2380   _dbus_type_writer_init_types_delayed (&real->u.writer,
2381                                         _dbus_header_get_byte_order (&message->header),
2382                                         &message->body,
2383                                         _dbus_string_get_length (&message->body));
2384 }
2385
2386 /**
2387  * Creates a temporary signature string containing the current
2388  * signature, stores it in the iterator, and points the iterator to
2389  * the end of it. Used any time we write to the message.
2390  *
2391  * @param real an iterator without a type_str
2392  * @returns #FALSE if no memory
2393  */
2394 static dbus_bool_t
2395 _dbus_message_iter_open_signature (DBusMessageRealIter *real)
2396 {
2397   DBusString *str;
2398   const DBusString *current_sig;
2399   int current_sig_pos;
2400
2401   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2402
2403   if (real->u.writer.type_str != NULL)
2404     {
2405       _dbus_assert (real->sig_refcount > 0);
2406       real->sig_refcount += 1;
2407       return TRUE;
2408     }
2409
2410   str = dbus_new (DBusString, 1);
2411   if (str == NULL)
2412     return FALSE;
2413
2414   if (!_dbus_header_get_field_raw (&real->message->header,
2415                                    DBUS_HEADER_FIELD_SIGNATURE,
2416                                    &current_sig, &current_sig_pos))
2417     current_sig = NULL;
2418
2419   if (current_sig)
2420     {
2421       int current_len;
2422
2423       current_len = _dbus_string_get_byte (current_sig, current_sig_pos);
2424       current_sig_pos += 1; /* move on to sig data */
2425
2426       if (!_dbus_string_init_preallocated (str, current_len + 4))
2427         {
2428           dbus_free (str);
2429           return FALSE;
2430         }
2431
2432       if (!_dbus_string_copy_len (current_sig, current_sig_pos, current_len,
2433                                   str, 0))
2434         {
2435           _dbus_string_free (str);
2436           dbus_free (str);
2437           return FALSE;
2438         }
2439     }
2440   else
2441     {
2442       if (!_dbus_string_init_preallocated (str, 4))
2443         {
2444           dbus_free (str);
2445           return FALSE;
2446         }
2447     }
2448
2449   real->sig_refcount = 1;
2450
2451   _dbus_type_writer_add_types (&real->u.writer,
2452                                str, _dbus_string_get_length (str));
2453   return TRUE;
2454 }
2455
2456 /**
2457  * Sets the new signature as the message signature, frees the
2458  * signature string, and marks the iterator as not having a type_str
2459  * anymore. Frees the signature even if it fails, so you can't
2460  * really recover from failure. Kinda busted.
2461  *
2462  * @param real an iterator without a type_str
2463  * @returns #FALSE if no memory
2464  */
2465 static dbus_bool_t
2466 _dbus_message_iter_close_signature (DBusMessageRealIter *real)
2467 {
2468   DBusString *str;
2469   const char *v_STRING;
2470   dbus_bool_t retval;
2471
2472   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2473   _dbus_assert (real->u.writer.type_str != NULL);
2474   _dbus_assert (real->sig_refcount > 0);
2475
2476   real->sig_refcount -= 1;
2477
2478   if (real->sig_refcount > 0)
2479     return TRUE;
2480   _dbus_assert (real->sig_refcount == 0);
2481
2482   retval = TRUE;
2483
2484   str = real->u.writer.type_str;
2485
2486   v_STRING = _dbus_string_get_const_data (str);
2487   if (!_dbus_header_set_field_basic (&real->message->header,
2488                                      DBUS_HEADER_FIELD_SIGNATURE,
2489                                      DBUS_TYPE_SIGNATURE,
2490                                      &v_STRING))
2491     retval = FALSE;
2492
2493   _dbus_type_writer_remove_types (&real->u.writer);
2494   _dbus_string_free (str);
2495   dbus_free (str);
2496
2497   return retval;
2498 }
2499
2500 /**
2501  * Frees the signature string and marks the iterator as not having a
2502  * type_str anymore.  Since the new signature is not set, the message
2503  * will generally be hosed after this is called.
2504  *
2505  * @param real an iterator without a type_str
2506  */
2507 static void
2508 _dbus_message_iter_abandon_signature (DBusMessageRealIter *real)
2509 {
2510   DBusString *str;
2511
2512   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2513   _dbus_assert (real->u.writer.type_str != NULL);
2514   _dbus_assert (real->sig_refcount > 0);
2515
2516   real->sig_refcount -= 1;
2517
2518   if (real->sig_refcount > 0)
2519     return;
2520   _dbus_assert (real->sig_refcount == 0);
2521
2522   str = real->u.writer.type_str;
2523
2524   _dbus_type_writer_remove_types (&real->u.writer);
2525   _dbus_string_free (str);
2526   dbus_free (str);
2527 }
2528
2529 #ifndef DBUS_DISABLE_CHECKS
2530 static dbus_bool_t
2531 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
2532 {
2533   if (!_dbus_message_iter_check (iter))
2534     return FALSE;
2535
2536   if (iter->message->locked)
2537     {
2538       _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)\n");
2539       return FALSE;
2540     }
2541
2542   return TRUE;
2543 }
2544 #endif /* DBUS_DISABLE_CHECKS */
2545
2546 #ifdef HAVE_UNIX_FD_PASSING
2547 static int *
2548 expand_fd_array(DBusMessage *m,
2549                 unsigned     n)
2550 {
2551   _dbus_assert(m);
2552
2553   /* This makes space for adding n new fds to the array and returns a
2554      pointer to the place were the first fd should be put. */
2555
2556   if (m->n_unix_fds + n > m->n_unix_fds_allocated)
2557     {
2558       unsigned k;
2559       int *p;
2560
2561       /* Make twice as much space as necessary */
2562       k = (m->n_unix_fds + n) * 2;
2563
2564       /* Allocate at least four */
2565       if (k < 4)
2566         k = 4;
2567
2568       p = dbus_realloc(m->unix_fds, k * sizeof(int));
2569       if (p == NULL)
2570         return NULL;
2571
2572       m->unix_fds = p;
2573       m->n_unix_fds_allocated = k;
2574     }
2575
2576   return m->unix_fds + m->n_unix_fds;
2577 }
2578 #endif
2579
2580 /**
2581  * Appends a basic-typed value to the message. The basic types are the
2582  * non-container types such as integer and string.
2583  *
2584  * The "value" argument should be the address of a basic-typed value.
2585  * So for string, const char**. For integer, dbus_int32_t*.
2586  *
2587  * For Unix file descriptors this function will internally duplicate
2588  * the descriptor you passed in. Hence you may close the descriptor
2589  * immediately after this call.
2590  *
2591  * @todo If this fails due to lack of memory, the message is hosed and
2592  * you have to start over building the whole message.
2593  *
2594  * @param iter the append iterator
2595  * @param type the type of the value
2596  * @param value the address of the value
2597  * @returns #FALSE if not enough memory
2598  */
2599 dbus_bool_t
2600 dbus_message_iter_append_basic (DBusMessageIter *iter,
2601                                 int              type,
2602                                 const void      *value)
2603 {
2604   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2605   dbus_bool_t ret;
2606
2607   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2608   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2609   _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
2610   _dbus_return_val_if_fail (value != NULL, FALSE);
2611
2612 #ifndef DBUS_DISABLE_CHECKS
2613   switch (type)
2614     {
2615       const char * const *string_p;
2616       const dbus_bool_t *bool_p;
2617
2618       case DBUS_TYPE_STRING:
2619         string_p = value;
2620         _dbus_return_val_if_fail (_dbus_check_is_valid_utf8 (*string_p), FALSE);
2621         break;
2622
2623       case DBUS_TYPE_OBJECT_PATH:
2624         string_p = value;
2625         _dbus_return_val_if_fail (_dbus_check_is_valid_path (*string_p), FALSE);
2626         break;
2627
2628       case DBUS_TYPE_SIGNATURE:
2629         string_p = value;
2630         _dbus_return_val_if_fail (_dbus_check_is_valid_signature (*string_p), FALSE);
2631         break;
2632
2633       case DBUS_TYPE_BOOLEAN:
2634         bool_p = value;
2635         _dbus_return_val_if_fail (*bool_p == 0 || *bool_p == 1, FALSE);
2636         break;
2637
2638       default:
2639           {
2640             /* nothing to check, all possible values are allowed */
2641           }
2642     }
2643 #endif
2644
2645   if (!_dbus_message_iter_open_signature (real))
2646     return FALSE;
2647
2648   if (type == DBUS_TYPE_UNIX_FD)
2649     {
2650 #ifdef HAVE_UNIX_FD_PASSING
2651       int *fds;
2652       dbus_uint32_t u;
2653
2654       /* First step, include the fd in the fd list of this message */
2655       if (!(fds = expand_fd_array(real->message, 1)))
2656         return FALSE;
2657
2658       *fds = _dbus_dup(*(int*) value, NULL);
2659       if (*fds < 0)
2660         return FALSE;
2661
2662       u = real->message->n_unix_fds;
2663
2664       /* Second step, write the index to the fd */
2665       if (!(ret = _dbus_type_writer_write_basic (&real->u.writer, DBUS_TYPE_UNIX_FD, &u))) {
2666         _dbus_close(*fds, NULL);
2667         return FALSE;
2668       }
2669
2670       real->message->n_unix_fds += 1;
2671       u += 1;
2672
2673       /* Final step, update the header accordingly */
2674       ret = _dbus_header_set_field_basic (&real->message->header,
2675                                           DBUS_HEADER_FIELD_UNIX_FDS,
2676                                           DBUS_TYPE_UINT32,
2677                                           &u);
2678
2679       /* If any of these operations fail the message is
2680          hosed. However, no memory or fds should be leaked since what
2681          has been added to message has been added to the message, and
2682          can hence be accounted for when the message is being
2683          freed. */
2684 #else
2685       ret = FALSE;
2686 #endif
2687     }
2688   else
2689     {
2690       ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
2691     }
2692
2693   if (!_dbus_message_iter_close_signature (real))
2694     ret = FALSE;
2695
2696   return ret;
2697 }
2698
2699 /**
2700  * Appends a block of fixed-length values to an array. The
2701  * fixed-length types are all basic types that are not string-like. So
2702  * int32, double, bool, etc. (Unix file descriptors however are not
2703  * supported.) You must call dbus_message_iter_open_container() to
2704  * open an array of values before calling this function. You may call
2705  * this function multiple times (and intermixed with calls to
2706  * dbus_message_iter_append_basic()) for the same array.
2707  *
2708  * The "value" argument should be the address of the array.  So for
2709  * integer, "dbus_int32_t**" is expected for example.
2710  *
2711  * @warning in C, given "int array[]", "&array == array" (the
2712  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
2713  * So if you're using an array instead of a pointer you have to create
2714  * a pointer variable, assign the array to it, then take the address
2715  * of the pointer variable.
2716  * @code
2717  * const dbus_int32_t array[] = { 1, 2, 3 };
2718  * const dbus_int32_t *v_ARRAY = array;
2719  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
2720  *   fprintf (stderr, "No memory!\n");
2721  * @endcode
2722  * For strings it works to write const char *array = "Hello" and then
2723  * use &array though.
2724  *
2725  * @todo If this fails due to lack of memory, the message is hosed and
2726  * you have to start over building the whole message.
2727  *
2728  * @param iter the append iterator
2729  * @param element_type the type of the array elements
2730  * @param value the address of the array
2731  * @param n_elements the number of elements to append
2732  * @returns #FALSE if not enough memory
2733  */
2734 dbus_bool_t
2735 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
2736                                       int              element_type,
2737                                       const void      *value,
2738                                       int              n_elements)
2739 {
2740   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2741   dbus_bool_t ret;
2742
2743   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2744   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2745   _dbus_return_val_if_fail (dbus_type_is_fixed (element_type) && element_type != DBUS_TYPE_UNIX_FD, FALSE);
2746   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
2747   _dbus_return_val_if_fail (value != NULL, FALSE);
2748   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
2749   _dbus_return_val_if_fail (n_elements <=
2750                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
2751                             FALSE);
2752
2753 #ifndef DBUS_DISABLE_CHECKS
2754   if (element_type == DBUS_TYPE_BOOLEAN)
2755     {
2756       const dbus_bool_t * const *bools = value;
2757       int i;
2758
2759       for (i = 0; i < n_elements; i++)
2760         {
2761           _dbus_return_val_if_fail ((*bools)[i] == 0 || (*bools)[i] == 1, FALSE);
2762         }
2763     }
2764 #endif
2765
2766   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
2767
2768   return ret;
2769 }
2770
2771 /**
2772  * Appends a container-typed value to the message; you are required to
2773  * append the contents of the container using the returned
2774  * sub-iterator, and then call
2775  * dbus_message_iter_close_container(). Container types are for
2776  * example struct, variant, and array. For variants, the
2777  * contained_signature should be the type of the single value inside
2778  * the variant. For structs and dict entries, contained_signature
2779  * should be #NULL; it will be set to whatever types you write into
2780  * the struct.  For arrays, contained_signature should be the type of
2781  * the array elements.
2782  *
2783  * @todo If this fails due to lack of memory, the message is hosed and
2784  * you have to start over building the whole message.
2785  *
2786  * @param iter the append iterator
2787  * @param type the type of the value
2788  * @param contained_signature the type of container contents
2789  * @param sub sub-iterator to initialize
2790  * @returns #FALSE if not enough memory
2791  */
2792 dbus_bool_t
2793 dbus_message_iter_open_container (DBusMessageIter *iter,
2794                                   int              type,
2795                                   const char      *contained_signature,
2796                                   DBusMessageIter *sub)
2797 {
2798   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2799   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2800   DBusString contained_str;
2801
2802   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2803   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2804   _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
2805   _dbus_return_val_if_fail (sub != NULL, FALSE);
2806   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
2807                              contained_signature == NULL) ||
2808                             (type == DBUS_TYPE_DICT_ENTRY &&
2809                              contained_signature == NULL) ||
2810                             (type == DBUS_TYPE_VARIANT &&
2811                              contained_signature != NULL) ||
2812                             (type == DBUS_TYPE_ARRAY &&
2813                              contained_signature != NULL), FALSE);
2814   
2815   /* this would fail if the contained_signature is a dict entry, since
2816    * dict entries are invalid signatures standalone (they must be in
2817    * an array)
2818    */
2819   _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
2820                             (contained_signature == NULL ||
2821                              _dbus_check_is_valid_signature (contained_signature)),
2822                             FALSE);
2823
2824   if (!_dbus_message_iter_open_signature (real))
2825     return FALSE;
2826
2827   *real_sub = *real;
2828
2829   if (contained_signature != NULL)
2830     {
2831       _dbus_string_init_const (&contained_str, contained_signature);
2832
2833       return _dbus_type_writer_recurse (&real->u.writer,
2834                                         type,
2835                                         &contained_str, 0,
2836                                         &real_sub->u.writer);
2837     }
2838   else
2839     {
2840       return _dbus_type_writer_recurse (&real->u.writer,
2841                                         type,
2842                                         NULL, 0,
2843                                         &real_sub->u.writer);
2844     } 
2845 }
2846
2847
2848 /**
2849  * Closes a container-typed value appended to the message; may write
2850  * out more information to the message known only after the entire
2851  * container is written, and may free resources created by
2852  * dbus_message_iter_open_container().
2853  *
2854  * @todo If this fails due to lack of memory, the message is hosed and
2855  * you have to start over building the whole message.
2856  *
2857  * @param iter the append iterator
2858  * @param sub sub-iterator to close
2859  * @returns #FALSE if not enough memory
2860  */
2861 dbus_bool_t
2862 dbus_message_iter_close_container (DBusMessageIter *iter,
2863                                    DBusMessageIter *sub)
2864 {
2865   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2866   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2867   dbus_bool_t ret;
2868
2869   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2870   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2871   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
2872   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2873
2874   ret = _dbus_type_writer_unrecurse (&real->u.writer,
2875                                      &real_sub->u.writer);
2876
2877   if (!_dbus_message_iter_close_signature (real))
2878     ret = FALSE;
2879
2880   return ret;
2881 }
2882
2883 /**
2884  * Abandons creation of a contained-typed value and frees resources created
2885  * by dbus_message_iter_open_container().  Once this returns, the message
2886  * is hosed and you have to start over building the whole message.
2887  *
2888  * This should only be used to abandon creation of a message when you have
2889  * open containers.
2890  *
2891  * @param iter the append iterator
2892  * @param sub sub-iterator to close
2893  */
2894 void
2895 dbus_message_iter_abandon_container (DBusMessageIter *iter,
2896                                      DBusMessageIter *sub)
2897 {
2898   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2899 #ifndef DBUS_DISABLE_CHECKS
2900   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2901
2902   _dbus_return_if_fail (_dbus_message_iter_append_check (real));
2903   _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2904   _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
2905   _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2906 #endif
2907
2908   _dbus_message_iter_abandon_signature (real);
2909 }
2910
2911 /**
2912  * Sets a flag indicating that the message does not want a reply; if
2913  * this flag is set, the other end of the connection may (but is not
2914  * required to) optimize by not sending method return or error
2915  * replies. If this flag is set, there is no way to know whether the
2916  * message successfully arrived at the remote end. Normally you know a
2917  * message was received when you receive the reply to it.
2918  *
2919  * The flag is #FALSE by default, that is by default the other end is
2920  * required to reply.
2921  *
2922  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
2923  * 
2924  * @param message the message
2925  * @param no_reply #TRUE if no reply is desired
2926  */
2927 void
2928 dbus_message_set_no_reply (DBusMessage *message,
2929                            dbus_bool_t  no_reply)
2930 {
2931   _dbus_return_if_fail (message != NULL);
2932   _dbus_return_if_fail (!message->locked);
2933
2934   _dbus_header_toggle_flag (&message->header,
2935                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
2936                             no_reply);
2937 }
2938
2939 /**
2940  * Returns #TRUE if the message does not expect
2941  * a reply.
2942  *
2943  * @param message the message
2944  * @returns #TRUE if the message sender isn't waiting for a reply
2945  */
2946 dbus_bool_t
2947 dbus_message_get_no_reply (DBusMessage *message)
2948 {
2949   _dbus_return_val_if_fail (message != NULL, FALSE);
2950
2951   return _dbus_header_get_flag (&message->header,
2952                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
2953 }
2954
2955 /**
2956  * Sets a flag indicating that an owner for the destination name will
2957  * be automatically started before the message is delivered. When this
2958  * flag is set, the message is held until a name owner finishes
2959  * starting up, or fails to start up. In case of failure, the reply
2960  * will be an error.
2961  *
2962  * The flag is set to #TRUE by default, i.e. auto starting is the default.
2963  *
2964  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
2965  * 
2966  * @param message the message
2967  * @param auto_start #TRUE if auto-starting is desired
2968  */
2969 void
2970 dbus_message_set_auto_start (DBusMessage *message,
2971                              dbus_bool_t  auto_start)
2972 {
2973   _dbus_return_if_fail (message != NULL);
2974   _dbus_return_if_fail (!message->locked);
2975
2976   _dbus_header_toggle_flag (&message->header,
2977                             DBUS_HEADER_FLAG_NO_AUTO_START,
2978                             !auto_start);
2979 }
2980
2981 /**
2982  * Returns #TRUE if the message will cause an owner for
2983  * destination name to be auto-started.
2984  *
2985  * @param message the message
2986  * @returns #TRUE if the message will use auto-start
2987  */
2988 dbus_bool_t
2989 dbus_message_get_auto_start (DBusMessage *message)
2990 {
2991   _dbus_return_val_if_fail (message != NULL, FALSE);
2992
2993   return !_dbus_header_get_flag (&message->header,
2994                                  DBUS_HEADER_FLAG_NO_AUTO_START);
2995 }
2996
2997
2998 /**
2999  * Sets the object path this message is being sent to (for
3000  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
3001  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
3002  *
3003  * The path must contain only valid characters as defined
3004  * in the D-Bus specification.
3005  *
3006  * @param message the message
3007  * @param object_path the path or #NULL to unset
3008  * @returns #FALSE if not enough memory
3009  */
3010 dbus_bool_t
3011 dbus_message_set_path (DBusMessage   *message,
3012                        const char    *object_path)
3013 {
3014   _dbus_return_val_if_fail (message != NULL, FALSE);
3015   _dbus_return_val_if_fail (!message->locked, FALSE);
3016   _dbus_return_val_if_fail (object_path == NULL ||
3017                             _dbus_check_is_valid_path (object_path),
3018                             FALSE);
3019
3020   return set_or_delete_string_field (message,
3021                                      DBUS_HEADER_FIELD_PATH,
3022                                      DBUS_TYPE_OBJECT_PATH,
3023                                      object_path);
3024 }
3025
3026 /**
3027  * Gets the object path this message is being sent to (for
3028  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
3029  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3030  *
3031  * See also dbus_message_get_path_decomposed().
3032  *
3033  * The returned string becomes invalid if the message is
3034  * modified, since it points into the wire-marshaled message data.
3035  * 
3036  * @param message the message
3037  * @returns the path (should not be freed) or #NULL
3038  */
3039 const char*
3040 dbus_message_get_path (DBusMessage   *message)
3041 {
3042   const char *v;
3043
3044   _dbus_return_val_if_fail (message != NULL, NULL);
3045
3046   v = NULL; /* in case field doesn't exist */
3047   _dbus_header_get_field_basic (&message->header,
3048                                 DBUS_HEADER_FIELD_PATH,
3049                                 DBUS_TYPE_OBJECT_PATH,
3050                                 (void *) &v);
3051   return v;
3052 }
3053
3054 /**
3055  * Checks if the message has a particular object path.  The object
3056  * path is the destination object for a method call or the emitting
3057  * object for a signal.
3058  *
3059  * @param message the message
3060  * @param path the path name
3061  * @returns #TRUE if there is a path field in the header
3062  */
3063 dbus_bool_t
3064 dbus_message_has_path (DBusMessage   *message,
3065                        const char    *path)
3066 {
3067   const char *msg_path;
3068   msg_path = dbus_message_get_path (message);
3069   
3070   if (msg_path == NULL)
3071     {
3072       if (path == NULL)
3073         return TRUE;
3074       else
3075         return FALSE;
3076     }
3077
3078   if (path == NULL)
3079     return FALSE;
3080    
3081   if (strcmp (msg_path, path) == 0)
3082     return TRUE;
3083
3084   return FALSE;
3085 }
3086
3087 /**
3088  * Gets the object path this message is being sent to
3089  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
3090  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
3091  * format (one array element per path component).
3092  * Free the returned array with dbus_free_string_array().
3093  *
3094  * An empty but non-NULL path array means the path "/".
3095  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
3096  * and the path "/" becomes { NULL }.
3097  *
3098  * See also dbus_message_get_path().
3099  * 
3100  * @todo this could be optimized by using the len from the message
3101  * instead of calling strlen() again
3102  *
3103  * @param message the message
3104  * @param path place to store allocated array of path components; #NULL set here if no path field exists
3105  * @returns #FALSE if no memory to allocate the array
3106  */
3107 dbus_bool_t
3108 dbus_message_get_path_decomposed (DBusMessage   *message,
3109                                   char        ***path)
3110 {
3111   const char *v;
3112
3113   _dbus_return_val_if_fail (message != NULL, FALSE);
3114   _dbus_return_val_if_fail (path != NULL, FALSE);
3115
3116   *path = NULL;
3117
3118   v = dbus_message_get_path (message);
3119   if (v != NULL)
3120     {
3121       if (!_dbus_decompose_path (v, strlen (v),
3122                                  path, NULL))
3123         return FALSE;
3124     }
3125   return TRUE;
3126 }
3127
3128 /**
3129  * Sets the interface this message is being sent to
3130  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
3131  * the interface a signal is being emitted from
3132  * (for DBUS_MESSAGE_TYPE_SIGNAL).
3133  *
3134  * The interface name must contain only valid characters as defined
3135  * in the D-Bus specification.
3136  * 
3137  * @param message the message
3138  * @param iface the interface or #NULL to unset
3139  * @returns #FALSE if not enough memory
3140  */
3141 dbus_bool_t
3142 dbus_message_set_interface (DBusMessage  *message,
3143                             const char   *iface)
3144 {
3145   _dbus_return_val_if_fail (message != NULL, FALSE);
3146   _dbus_return_val_if_fail (!message->locked, FALSE);
3147   _dbus_return_val_if_fail (iface == NULL ||
3148                             _dbus_check_is_valid_interface (iface),
3149                             FALSE);
3150
3151   return set_or_delete_string_field (message,
3152                                      DBUS_HEADER_FIELD_INTERFACE,
3153                                      DBUS_TYPE_STRING,
3154                                      iface);
3155 }
3156
3157 /**
3158  * Gets the interface this message is being sent to
3159  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
3160  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
3161  * The interface name is fully-qualified (namespaced).
3162  * Returns #NULL if none.
3163  *
3164  * The returned string becomes invalid if the message is
3165  * modified, since it points into the wire-marshaled message data.
3166  *
3167  * @param message the message
3168  * @returns the message interface (should not be freed) or #NULL
3169  */
3170 const char*
3171 dbus_message_get_interface (DBusMessage *message)
3172 {
3173   const char *v;
3174
3175   _dbus_return_val_if_fail (message != NULL, NULL);
3176
3177   v = NULL; /* in case field doesn't exist */
3178   _dbus_header_get_field_basic (&message->header,
3179                                 DBUS_HEADER_FIELD_INTERFACE,
3180                                 DBUS_TYPE_STRING,
3181                                 (void *) &v);
3182   return v;
3183 }
3184
3185 /**
3186  * Checks if the message has an interface
3187  *
3188  * @param message the message
3189  * @param iface the interface name
3190  * @returns #TRUE if the interface field in the header matches
3191  */
3192 dbus_bool_t
3193 dbus_message_has_interface (DBusMessage   *message,
3194                             const char    *iface)
3195 {
3196   const char *msg_interface;
3197   msg_interface = dbus_message_get_interface (message);
3198    
3199   if (msg_interface == NULL)
3200     {
3201       if (iface == NULL)
3202         return TRUE;
3203       else
3204         return FALSE;
3205     }
3206
3207   if (iface == NULL)
3208     return FALSE;
3209      
3210   if (strcmp (msg_interface, iface) == 0)
3211     return TRUE;
3212
3213   return FALSE;
3214
3215 }
3216
3217 /**
3218  * Sets the interface member being invoked
3219  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3220  * (DBUS_MESSAGE_TYPE_SIGNAL).
3221  *
3222  * The member name must contain only valid characters as defined
3223  * in the D-Bus specification.
3224  *
3225  * @param message the message
3226  * @param member the member or #NULL to unset
3227  * @returns #FALSE if not enough memory
3228  */
3229 dbus_bool_t
3230 dbus_message_set_member (DBusMessage  *message,
3231                          const char   *member)
3232 {
3233   _dbus_return_val_if_fail (message != NULL, FALSE);
3234   _dbus_return_val_if_fail (!message->locked, FALSE);
3235   _dbus_return_val_if_fail (member == NULL ||
3236                             _dbus_check_is_valid_member (member),
3237                             FALSE);
3238
3239   return set_or_delete_string_field (message,
3240                                      DBUS_HEADER_FIELD_MEMBER,
3241                                      DBUS_TYPE_STRING,
3242                                      member);
3243 }
3244
3245 /**
3246  * Gets the interface member being invoked
3247  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3248  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3249  *
3250  * The returned string becomes invalid if the message is
3251  * modified, since it points into the wire-marshaled message data.
3252  * 
3253  * @param message the message
3254  * @returns the member name (should not be freed) or #NULL
3255  */
3256 const char*
3257 dbus_message_get_member (DBusMessage *message)
3258 {
3259   const char *v;
3260
3261   _dbus_return_val_if_fail (message != NULL, NULL);
3262
3263   v = NULL; /* in case field doesn't exist */
3264   _dbus_header_get_field_basic (&message->header,
3265                                 DBUS_HEADER_FIELD_MEMBER,
3266                                 DBUS_TYPE_STRING,
3267                                 (void *) &v);
3268   return v;
3269 }
3270
3271 /**
3272  * Checks if the message has an interface member
3273  *
3274  * @param message the message
3275  * @param member the member name
3276  * @returns #TRUE if there is a member field in the header
3277  */
3278 dbus_bool_t
3279 dbus_message_has_member (DBusMessage   *message,
3280                          const char    *member)
3281 {
3282   const char *msg_member;
3283   msg_member = dbus_message_get_member (message);
3284  
3285   if (msg_member == NULL)
3286     {
3287       if (member == NULL)
3288         return TRUE;
3289       else
3290         return FALSE;
3291     }
3292
3293   if (member == NULL)
3294     return FALSE;
3295     
3296   if (strcmp (msg_member, member) == 0)
3297     return TRUE;
3298
3299   return FALSE;
3300
3301 }
3302
3303 /**
3304  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
3305  * The name is fully-qualified (namespaced).
3306  *
3307  * The error name must contain only valid characters as defined
3308  * in the D-Bus specification.
3309  *
3310  * @param message the message
3311  * @param error_name the name or #NULL to unset
3312  * @returns #FALSE if not enough memory
3313  */
3314 dbus_bool_t
3315 dbus_message_set_error_name (DBusMessage  *message,
3316                              const char   *error_name)
3317 {
3318   _dbus_return_val_if_fail (message != NULL, FALSE);
3319   _dbus_return_val_if_fail (!message->locked, FALSE);
3320   _dbus_return_val_if_fail (error_name == NULL ||
3321                             _dbus_check_is_valid_error_name (error_name),
3322                             FALSE);
3323
3324   return set_or_delete_string_field (message,
3325                                      DBUS_HEADER_FIELD_ERROR_NAME,
3326                                      DBUS_TYPE_STRING,
3327                                      error_name);
3328 }
3329
3330 /**
3331  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
3332  * or #NULL if none.
3333  *
3334  * The returned string becomes invalid if the message is
3335  * modified, since it points into the wire-marshaled message data.
3336  * 
3337  * @param message the message
3338  * @returns the error name (should not be freed) or #NULL
3339  */
3340 const char*
3341 dbus_message_get_error_name (DBusMessage *message)
3342 {
3343   const char *v;
3344
3345   _dbus_return_val_if_fail (message != NULL, NULL);
3346
3347   v = NULL; /* in case field doesn't exist */
3348   _dbus_header_get_field_basic (&message->header,
3349                                 DBUS_HEADER_FIELD_ERROR_NAME,
3350                                 DBUS_TYPE_STRING,
3351                                 (void *) &v);
3352   return v;
3353 }
3354
3355 /**
3356  * Sets the message's destination. The destination is the name of
3357  * another connection on the bus and may be either the unique name
3358  * assigned by the bus to each connection, or a well-known name
3359  * specified in advance.
3360  *
3361  * The destination name must contain only valid characters as defined
3362  * in the D-Bus specification.
3363  * 
3364  * @param message the message
3365  * @param destination the destination name or #NULL to unset
3366  * @returns #FALSE if not enough memory
3367  */
3368 dbus_bool_t
3369 dbus_message_set_destination (DBusMessage  *message,
3370                               const char   *destination)
3371 {
3372   _dbus_return_val_if_fail (message != NULL, FALSE);
3373   _dbus_return_val_if_fail (!message->locked, FALSE);
3374   _dbus_return_val_if_fail (destination == NULL ||
3375                             _dbus_check_is_valid_bus_name (destination),
3376                             FALSE);
3377
3378   return set_or_delete_string_field (message,
3379                                      DBUS_HEADER_FIELD_DESTINATION,
3380                                      DBUS_TYPE_STRING,
3381                                      destination);
3382 }
3383
3384 /**
3385  * Gets the destination of a message or #NULL if there is none set.
3386  *
3387  * The returned string becomes invalid if the message is
3388  * modified, since it points into the wire-marshaled message data.
3389  *
3390  * @param message the message
3391  * @returns the message destination (should not be freed) or #NULL
3392  */
3393 const char*
3394 dbus_message_get_destination (DBusMessage *message)
3395 {
3396   const char *v;
3397
3398   _dbus_return_val_if_fail (message != NULL, NULL);
3399
3400   v = NULL; /* in case field doesn't exist */
3401   _dbus_header_get_field_basic (&message->header,
3402                                 DBUS_HEADER_FIELD_DESTINATION,
3403                                 DBUS_TYPE_STRING,
3404                                 (void *) &v);
3405   return v;
3406 }
3407
3408 /**
3409  * Sets the message sender.
3410  *
3411  * The sender must be a valid bus name as defined in the D-Bus
3412  * specification.
3413  *
3414  * Usually you don't want to call this. The message bus daemon will
3415  * call it to set the origin of each message. If you aren't implementing
3416  * a message bus daemon you shouldn't need to set the sender.
3417  *
3418  * @param message the message
3419  * @param sender the sender or #NULL to unset
3420  * @returns #FALSE if not enough memory
3421  */
3422 dbus_bool_t
3423 dbus_message_set_sender (DBusMessage  *message,
3424                          const char   *sender)
3425 {
3426   _dbus_return_val_if_fail (message != NULL, FALSE);
3427   _dbus_return_val_if_fail (!message->locked, FALSE);
3428   _dbus_return_val_if_fail (sender == NULL ||
3429                             _dbus_check_is_valid_bus_name (sender),
3430                             FALSE);
3431
3432   return set_or_delete_string_field (message,
3433                                      DBUS_HEADER_FIELD_SENDER,
3434                                      DBUS_TYPE_STRING,
3435                                      sender);
3436 }
3437
3438 /**
3439  * Gets the unique name of the connection which originated this
3440  * message, or #NULL if unknown or inapplicable. The sender is filled
3441  * in by the message bus.
3442  *
3443  * Note, the returned sender is always the unique bus name.
3444  * Connections may own multiple other bus names, but those
3445  * are not found in the sender field.
3446  * 
3447  * The returned string becomes invalid if the message is
3448  * modified, since it points into the wire-marshaled message data.
3449  *
3450  * @param message the message
3451  * @returns the unique name of the sender or #NULL
3452  */
3453 const char*
3454 dbus_message_get_sender (DBusMessage *message)
3455 {
3456   const char *v;
3457
3458   _dbus_return_val_if_fail (message != NULL, NULL);
3459
3460   v = NULL; /* in case field doesn't exist */
3461   _dbus_header_get_field_basic (&message->header,
3462                                 DBUS_HEADER_FIELD_SENDER,
3463                                 DBUS_TYPE_STRING,
3464                                 (void *) &v);
3465   return v;
3466 }
3467
3468 /**
3469  * Gets the type signature of the message, i.e. the arguments in the
3470  * message payload. The signature includes only "in" arguments for
3471  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
3472  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
3473  * what you might expect (that is, it does not include the signature of the
3474  * entire C++-style method).
3475  *
3476  * The signature is a string made up of type codes such as
3477  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
3478  * the value of #DBUS_TYPE_INVALID).
3479  *
3480  * The returned string becomes invalid if the message is
3481  * modified, since it points into the wire-marshaled message data.
3482  *
3483  * @param message the message
3484  * @returns the type signature
3485  */
3486 const char*
3487 dbus_message_get_signature (DBusMessage *message)
3488 {
3489   const DBusString *type_str;
3490   int type_pos;
3491
3492   _dbus_return_val_if_fail (message != NULL, NULL);
3493
3494   get_const_signature (&message->header, &type_str, &type_pos);
3495
3496   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
3497 }
3498
3499 static dbus_bool_t
3500 _dbus_message_has_type_interface_member (DBusMessage *message,
3501                                          int          type,
3502                                          const char  *iface,
3503                                          const char  *member)
3504 {
3505   const char *n;
3506
3507   _dbus_assert (message != NULL);
3508   _dbus_assert (iface != NULL);
3509   _dbus_assert (member != NULL);
3510
3511   if (dbus_message_get_type (message) != type)
3512     return FALSE;
3513
3514   /* Optimize by checking the short member name first
3515    * instead of the longer interface name
3516    */
3517
3518   n = dbus_message_get_member (message);
3519
3520   if (n && strcmp (n, member) == 0)
3521     {
3522       n = dbus_message_get_interface (message);
3523
3524       if (n == NULL || strcmp (n, iface) == 0)
3525         return TRUE;
3526     }
3527
3528   return FALSE;
3529 }
3530
3531 /**
3532  * Checks whether the message is a method call with the given
3533  * interface and member fields.  If the message is not
3534  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
3535  * member field, returns #FALSE. If the interface field is missing,
3536  * then it will be assumed equal to the provided interface.  The D-Bus
3537  * protocol allows method callers to leave out the interface name.
3538  *
3539  * @param message the message
3540  * @param iface the name to check (must not be #NULL)
3541  * @param method the name to check (must not be #NULL)
3542  *
3543  * @returns #TRUE if the message is the specified method call
3544  */
3545 dbus_bool_t
3546 dbus_message_is_method_call (DBusMessage *message,
3547                              const char  *iface,
3548                              const char  *method)
3549 {
3550   _dbus_return_val_if_fail (message != NULL, FALSE);
3551   _dbus_return_val_if_fail (iface != NULL, FALSE);
3552   _dbus_return_val_if_fail (method != NULL, FALSE);
3553   /* don't check that interface/method are valid since it would be
3554    * expensive, and not catch many common errors
3555    */
3556
3557   return _dbus_message_has_type_interface_member (message,
3558                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
3559                                                   iface, method);
3560 }
3561
3562 /**
3563  * Checks whether the message is a signal with the given interface and
3564  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
3565  * has a different interface or member field, returns #FALSE.
3566  *
3567  * @param message the message
3568  * @param iface the name to check (must not be #NULL)
3569  * @param signal_name the name to check (must not be #NULL)
3570  *
3571  * @returns #TRUE if the message is the specified signal
3572  */
3573 dbus_bool_t
3574 dbus_message_is_signal (DBusMessage *message,
3575                         const char  *iface,
3576                         const char  *signal_name)
3577 {
3578   _dbus_return_val_if_fail (message != NULL, FALSE);
3579   _dbus_return_val_if_fail (iface != NULL, FALSE);
3580   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
3581   /* don't check that interface/name are valid since it would be
3582    * expensive, and not catch many common errors
3583    */
3584
3585   return _dbus_message_has_type_interface_member (message,
3586                                                   DBUS_MESSAGE_TYPE_SIGNAL,
3587                                                   iface, signal_name);
3588 }
3589
3590 /**
3591  * Checks whether the message is an error reply with the given error
3592  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
3593  * different name, returns #FALSE.
3594  *
3595  * @param message the message
3596  * @param error_name the name to check (must not be #NULL)
3597  *
3598  * @returns #TRUE if the message is the specified error
3599  */
3600 dbus_bool_t
3601 dbus_message_is_error (DBusMessage *message,
3602                        const char  *error_name)
3603 {
3604   const char *n;
3605
3606   _dbus_return_val_if_fail (message != NULL, FALSE);
3607   _dbus_return_val_if_fail (error_name != NULL, FALSE);
3608   /* don't check that error_name is valid since it would be expensive,
3609    * and not catch many common errors
3610    */
3611
3612   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3613     return FALSE;
3614
3615   n = dbus_message_get_error_name (message);
3616
3617   if (n && strcmp (n, error_name) == 0)
3618     return TRUE;
3619   else
3620     return FALSE;
3621 }
3622
3623 /**
3624  * Checks whether the message was sent to the given name.  If the
3625  * message has no destination specified or has a different
3626  * destination, returns #FALSE.
3627  *
3628  * @param message the message
3629  * @param name the name to check (must not be #NULL)
3630  *
3631  * @returns #TRUE if the message has the given destination name
3632  */
3633 dbus_bool_t
3634 dbus_message_has_destination (DBusMessage  *message,
3635                               const char   *name)
3636 {
3637   const char *s;
3638
3639   _dbus_return_val_if_fail (message != NULL, FALSE);
3640   _dbus_return_val_if_fail (name != NULL, FALSE);
3641   /* don't check that name is valid since it would be expensive, and
3642    * not catch many common errors
3643    */
3644
3645   s = dbus_message_get_destination (message);
3646
3647   if (s && strcmp (s, name) == 0)
3648     return TRUE;
3649   else
3650     return FALSE;
3651 }
3652
3653 /**
3654  * Checks whether the message has the given unique name as its sender.
3655  * If the message has no sender specified or has a different sender,
3656  * returns #FALSE. Note that a peer application will always have the
3657  * unique name of the connection as the sender. So you can't use this
3658  * function to see whether a sender owned a well-known name.
3659  *
3660  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
3661  * as the sender.
3662  *
3663  * @param message the message
3664  * @param name the name to check (must not be #NULL)
3665  *
3666  * @returns #TRUE if the message has the given sender
3667  */
3668 dbus_bool_t
3669 dbus_message_has_sender (DBusMessage  *message,
3670                          const char   *name)
3671 {
3672   const char *s;
3673
3674   _dbus_return_val_if_fail (message != NULL, FALSE);
3675   _dbus_return_val_if_fail (name != NULL, FALSE);
3676   /* don't check that name is valid since it would be expensive, and
3677    * not catch many common errors
3678    */
3679
3680   s = dbus_message_get_sender (message);
3681
3682   if (s && strcmp (s, name) == 0)
3683     return TRUE;
3684   else
3685     return FALSE;
3686 }
3687
3688 /**
3689  * Checks whether the message has the given signature; see
3690  * dbus_message_get_signature() for more details on what the signature
3691  * looks like.
3692  *
3693  * @param message the message
3694  * @param signature typecode array
3695  * @returns #TRUE if message has the given signature
3696 */
3697 dbus_bool_t
3698 dbus_message_has_signature (DBusMessage   *message,
3699                             const char    *signature)
3700 {
3701   const char *s;
3702
3703   _dbus_return_val_if_fail (message != NULL, FALSE);
3704   _dbus_return_val_if_fail (signature != NULL, FALSE);
3705   /* don't check that signature is valid since it would be expensive,
3706    * and not catch many common errors
3707    */
3708
3709   s = dbus_message_get_signature (message);
3710
3711   if (s && strcmp (s, signature) == 0)
3712     return TRUE;
3713   else
3714     return FALSE;
3715 }
3716
3717 /**
3718  * Sets a #DBusError based on the contents of the given
3719  * message. The error is only set if the message
3720  * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
3721  * The name of the error is set to the name of the message,
3722  * and the error message is set to the first argument
3723  * if the argument exists and is a string.
3724  *
3725  * The return value indicates whether the error was set (the error is
3726  * set if and only if the message is an error message).  So you can
3727  * check for an error reply and convert it to DBusError in one go:
3728  * @code
3729  *  if (dbus_set_error_from_message (error, reply))
3730  *    return error;
3731  *  else
3732  *    process reply;
3733  * @endcode
3734  *
3735  * @param error the error to set
3736  * @param message the message to set it from
3737  * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
3738  */
3739 dbus_bool_t
3740 dbus_set_error_from_message (DBusError   *error,
3741                              DBusMessage *message)
3742 {
3743   const char *str;
3744
3745   _dbus_return_val_if_fail (message != NULL, FALSE);
3746   _dbus_return_val_if_error_is_set (error, FALSE);
3747
3748   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3749     return FALSE;
3750
3751   str = NULL;
3752   dbus_message_get_args (message, NULL,
3753                          DBUS_TYPE_STRING, &str,
3754                          DBUS_TYPE_INVALID);
3755
3756   dbus_set_error (error, dbus_message_get_error_name (message),
3757                   str ? "%s" : NULL, str);
3758
3759   return TRUE;
3760 }
3761
3762 /**
3763  * Checks whether a message contains unix fds
3764  *
3765  * @param message the message
3766  * @returns #TRUE if the message contains unix fds
3767  */
3768 dbus_bool_t
3769 dbus_message_contains_unix_fds(DBusMessage *message)
3770 {
3771 #ifdef HAVE_UNIX_FD_PASSING
3772   _dbus_assert(message);
3773
3774   return message->n_unix_fds > 0;
3775 #else
3776   return FALSE;
3777 #endif
3778 }
3779
3780 /** @} */
3781
3782 /**
3783  * @addtogroup DBusMessageInternals
3784  *
3785  * @{
3786  */
3787
3788 /**
3789  * The initial buffer size of the message loader.
3790  *
3791  * @todo this should be based on min header size plus some average
3792  * body size, or something. Or rather, the min header size only, if we
3793  * want to try to read only the header, store that in a DBusMessage,
3794  * then read only the body and store that, etc., depends on
3795  * how we optimize _dbus_message_loader_get_buffer() and what
3796  * the exact message format is.
3797  */
3798 #define INITIAL_LOADER_DATA_LEN 32
3799
3800 /**
3801  * Creates a new message loader. Returns #NULL if memory can't
3802  * be allocated.
3803  *
3804  * @returns new loader, or #NULL.
3805  */
3806 DBusMessageLoader*
3807 _dbus_message_loader_new (void)
3808 {
3809   DBusMessageLoader *loader;
3810
3811   loader = dbus_new0 (DBusMessageLoader, 1);
3812   if (loader == NULL)
3813     return NULL;
3814   
3815   loader->refcount = 1;
3816
3817   loader->corrupted = FALSE;
3818   loader->corruption_reason = DBUS_VALID;
3819
3820   /* this can be configured by the app, but defaults to the protocol max */
3821   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3822
3823   /* We set a very relatively conservative default here since due to how
3824   SCM_RIGHTS works we need to preallocate an fd array of the maximum
3825   number of unix fds we want to receive in advance. A
3826   try-and-reallocate loop is not possible. */
3827   loader->max_message_unix_fds = DBUS_DEFAULT_MESSAGE_UNIX_FDS;
3828
3829   if (!_dbus_string_init (&loader->data))
3830     {
3831       dbus_free (loader);
3832       return NULL;
3833     }
3834
3835   /* preallocate the buffer for speed, ignore failure */
3836   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
3837   _dbus_string_set_length (&loader->data, 0);
3838
3839 #ifdef HAVE_UNIX_FD_PASSING
3840   loader->unix_fds = NULL;
3841   loader->n_unix_fds = loader->n_unix_fds_allocated = 0;
3842   loader->unix_fds_outstanding = FALSE;
3843 #endif
3844
3845   return loader;
3846 }
3847
3848 /**
3849  * Increments the reference count of the loader.
3850  *
3851  * @param loader the loader.
3852  * @returns the loader
3853  */
3854 DBusMessageLoader *
3855 _dbus_message_loader_ref (DBusMessageLoader *loader)
3856 {
3857   loader->refcount += 1;
3858
3859   return loader;
3860 }
3861
3862 /**
3863  * Decrements the reference count of the loader and finalizes the
3864  * loader when the count reaches zero.
3865  *
3866  * @param loader the loader.
3867  */
3868 void
3869 _dbus_message_loader_unref (DBusMessageLoader *loader)
3870 {
3871   loader->refcount -= 1;
3872   if (loader->refcount == 0)
3873     {
3874 #ifdef HAVE_UNIX_FD_PASSING
3875       close_unix_fds(loader->unix_fds, &loader->n_unix_fds);
3876       dbus_free(loader->unix_fds);
3877 #endif
3878       _dbus_list_foreach (&loader->messages,
3879                           (DBusForeachFunction) dbus_message_unref,
3880                           NULL);
3881       _dbus_list_clear (&loader->messages);
3882       _dbus_string_free (&loader->data);
3883       dbus_free (loader);
3884     }
3885 }
3886
3887 /**
3888  * Gets the buffer to use for reading data from the network.  Network
3889  * data is read directly into an allocated buffer, which is then used
3890  * in the DBusMessage, to avoid as many extra memcpy's as possible.
3891  * The buffer must always be returned immediately using
3892  * _dbus_message_loader_return_buffer(), even if no bytes are
3893  * successfully read.
3894  *
3895  * @todo this function can be a lot more clever. For example
3896  * it can probably always return a buffer size to read exactly
3897  * the body of the next message, thus avoiding any memory wastage
3898  * or reallocs.
3899  *
3900  * @todo we need to enforce a max length on strings in header fields.
3901  *
3902  * @param loader the message loader.
3903  * @param buffer the buffer
3904  */
3905 void
3906 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
3907                                  DBusString        **buffer)
3908 {
3909   _dbus_assert (!loader->buffer_outstanding);
3910
3911   *buffer = &loader->data;
3912
3913   loader->buffer_outstanding = TRUE;
3914 }
3915
3916 /**
3917  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
3918  * indicating to the loader how many bytes of the buffer were filled
3919  * in. This function must always be called, even if no bytes were
3920  * successfully read.
3921  *
3922  * @param loader the loader.
3923  * @param buffer the buffer.
3924  * @param bytes_read number of bytes that were read into the buffer.
3925  */
3926 void
3927 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
3928                                     DBusString         *buffer,
3929                                     int                 bytes_read)
3930 {
3931   _dbus_assert (loader->buffer_outstanding);
3932   _dbus_assert (buffer == &loader->data);
3933
3934   loader->buffer_outstanding = FALSE;
3935 }
3936
3937 /**
3938  * Gets the buffer to use for reading unix fds from the network.
3939  *
3940  * This works similar to _dbus_message_loader_get_buffer()
3941  *
3942  * @param loader the message loader.
3943  * @param fds the array to read fds into
3944  * @param max_n_fds how many fds to read at most
3945  * @return TRUE on success, FALSE on OOM
3946  */
3947 dbus_bool_t
3948 _dbus_message_loader_get_unix_fds(DBusMessageLoader  *loader,
3949                                   int               **fds,
3950                                   unsigned           *max_n_fds)
3951 {
3952 #ifdef HAVE_UNIX_FD_PASSING
3953   _dbus_assert (!loader->unix_fds_outstanding);
3954
3955   /* Allocate space where we can put the fds we read. We allocate
3956      space for max_message_unix_fds since this is an
3957      upper limit how many fds can be received within a single
3958      message. Since SCM_RIGHTS doesn't allow a reallocate+retry logic
3959      we are allocating the maximum possible array size right from the
3960      beginning. This sucks a bit, however unless SCM_RIGHTS is fixed
3961      there is no better way. */
3962
3963   if (loader->n_unix_fds_allocated < loader->max_message_unix_fds)
3964     {
3965       int *a = dbus_realloc(loader->unix_fds,
3966                             loader->max_message_unix_fds * sizeof(loader->unix_fds[0]));
3967
3968       if (!a)
3969         return FALSE;
3970
3971       loader->unix_fds = a;
3972       loader->n_unix_fds_allocated = loader->max_message_unix_fds;
3973     }
3974
3975   *fds = loader->unix_fds + loader->n_unix_fds;
3976   *max_n_fds = loader->n_unix_fds_allocated - loader->n_unix_fds;
3977
3978   loader->unix_fds_outstanding = TRUE;
3979   return TRUE;
3980 #else
3981   _dbus_assert_not_reached("Platform doesn't support unix fd passing");
3982   return FALSE;
3983 #endif
3984 }
3985
3986 /**
3987  * Returns a buffer obtained from _dbus_message_loader_get_unix_fds().
3988  *
3989  * This works similar to _dbus_message_loader_return_buffer()
3990  *
3991  * @param loader the message loader.
3992  * @param fds the array fds were read into
3993  * @param n_fds how many fds were read
3994  */
3995
3996 void
3997 _dbus_message_loader_return_unix_fds(DBusMessageLoader  *loader,
3998                                      int                *fds,
3999                                      unsigned            n_fds)
4000 {
4001 #ifdef HAVE_UNIX_FD_PASSING
4002   _dbus_assert(loader->unix_fds_outstanding);
4003   _dbus_assert(loader->unix_fds + loader->n_unix_fds == fds);
4004   _dbus_assert(loader->n_unix_fds + n_fds <= loader->n_unix_fds_allocated);
4005
4006   loader->n_unix_fds += n_fds;
4007   loader->unix_fds_outstanding = FALSE;
4008 #else
4009   _dbus_assert_not_reached("Platform doesn't support unix fd passing");
4010 #endif
4011 }
4012
4013 /*
4014  * FIXME when we move the header out of the buffer, that memmoves all
4015  * buffered messages. Kind of crappy.
4016  *
4017  * Also we copy the header and body, which is kind of crappy.  To
4018  * avoid this, we have to allow header and body to be in a single
4019  * memory block, which is good for messages we read and bad for
4020  * messages we are creating. But we could move_len() the buffer into
4021  * this single memory block, and move_len() will just swap the buffers
4022  * if you're moving the entire buffer replacing the dest string.
4023  *
4024  * We could also have the message loader tell the transport how many
4025  * bytes to read; so it would first ask for some arbitrary number like
4026  * 256, then if the message was incomplete it would use the
4027  * header/body len to ask for exactly the size of the message (or
4028  * blocks the size of a typical kernel buffer for the socket). That
4029  * way we don't get trailing bytes in the buffer that have to be
4030  * memmoved. Though I suppose we also don't have a chance of reading a
4031  * bunch of small messages at once, so the optimization may be stupid.
4032  *
4033  * Another approach would be to keep a "start" index into
4034  * loader->data and only delete it occasionally, instead of after
4035  * each message is loaded.
4036  *
4037  * load_message() returns FALSE if not enough memory OR the loader was corrupted
4038  */
4039 static dbus_bool_t
4040 load_message (DBusMessageLoader *loader,
4041               DBusMessage       *message,
4042               int                byte_order,
4043               int                fields_array_len,
4044               int                header_len,
4045               int                body_len)
4046 {
4047   dbus_bool_t oom;
4048   DBusValidity validity;
4049   const DBusString *type_str;
4050   int type_pos;
4051   DBusValidationMode mode;
4052   dbus_uint32_t n_unix_fds = 0;
4053
4054   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
4055   
4056   oom = FALSE;
4057
4058 #if 0
4059   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
4060 #endif
4061
4062   /* 1. VALIDATE AND COPY OVER HEADER */
4063   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
4064   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
4065
4066   if (!_dbus_header_load (&message->header,
4067                           mode,
4068                           &validity,
4069                           byte_order,
4070                           fields_array_len,
4071                           header_len,
4072                           body_len,
4073                           &loader->data, 0,
4074                           _dbus_string_get_length (&loader->data)))
4075     {
4076       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
4077
4078       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
4079          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
4080       _dbus_assert (validity != DBUS_VALID);
4081
4082       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
4083         oom = TRUE;
4084       else
4085         {
4086           loader->corrupted = TRUE;
4087           loader->corruption_reason = validity;
4088         }
4089       goto failed;
4090     }
4091
4092   _dbus_assert (validity == DBUS_VALID);
4093
4094   /* 2. VALIDATE BODY */
4095   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
4096     {
4097       get_const_signature (&message->header, &type_str, &type_pos);
4098       
4099       /* Because the bytes_remaining arg is NULL, this validates that the
4100        * body is the right length
4101        */
4102       validity = _dbus_validate_body_with_reason (type_str,
4103                                                   type_pos,
4104                                                   byte_order,
4105                                                   NULL,
4106                                                   &loader->data,
4107                                                   header_len,
4108                                                   body_len);
4109       if (validity != DBUS_VALID)
4110         {
4111           _dbus_verbose ("Failed to validate message body code %d\n", validity);
4112
4113           loader->corrupted = TRUE;
4114           loader->corruption_reason = validity;
4115           
4116           goto failed;
4117         }
4118     }
4119
4120   /* 3. COPY OVER UNIX FDS */
4121   _dbus_header_get_field_basic(&message->header,
4122                                DBUS_HEADER_FIELD_UNIX_FDS,
4123                                DBUS_TYPE_UINT32,
4124                                &n_unix_fds);
4125
4126 #ifdef HAVE_UNIX_FD_PASSING
4127
4128   if (n_unix_fds > loader->n_unix_fds)
4129     {
4130       _dbus_verbose("Message contains references to more unix fds than were sent %u != %u\n",
4131                     n_unix_fds, loader->n_unix_fds);
4132
4133       loader->corrupted = TRUE;
4134       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
4135       goto failed;
4136     }
4137
4138   /* If this was a recycled message there might still be
4139      some memory allocated for the fds */
4140   dbus_free(message->unix_fds);
4141
4142   if (n_unix_fds > 0)
4143     {
4144       message->unix_fds = _dbus_memdup(loader->unix_fds, n_unix_fds * sizeof(message->unix_fds[0]));
4145       if (message->unix_fds == NULL)
4146         {
4147           _dbus_verbose ("Failed to allocate file descriptor array\n");
4148           oom = TRUE;
4149           goto failed;
4150         }
4151
4152       message->n_unix_fds_allocated = message->n_unix_fds = n_unix_fds;
4153       loader->n_unix_fds -= n_unix_fds;
4154       memmove(loader->unix_fds + n_unix_fds, loader->unix_fds, loader->n_unix_fds);
4155     }
4156   else
4157     message->unix_fds = NULL;
4158
4159 #else
4160
4161   if (n_unix_fds > 0)
4162     {
4163       _dbus_verbose ("Hmm, message claims to come with file descriptors "
4164                      "but that's not supported on our platform, disconnecting.\n");
4165
4166       loader->corrupted = TRUE;
4167       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
4168       goto failed;
4169     }
4170
4171 #endif
4172
4173   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
4174
4175   if (!_dbus_list_append (&loader->messages, message))
4176     {
4177       _dbus_verbose ("Failed to append new message to loader queue\n");
4178       oom = TRUE;
4179       goto failed;
4180     }
4181
4182   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
4183   _dbus_assert (_dbus_string_get_length (&loader->data) >=
4184                 (header_len + body_len));
4185
4186   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
4187     {
4188       _dbus_verbose ("Failed to move body into new message\n");
4189       oom = TRUE;
4190       goto failed;
4191     }
4192
4193   _dbus_string_delete (&loader->data, 0, header_len + body_len);
4194
4195   /* don't waste more than 2k of memory */
4196   _dbus_string_compact (&loader->data, 2048);
4197
4198   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
4199   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
4200
4201   _dbus_verbose ("Loaded message %p\n", message);
4202
4203   _dbus_assert (!oom);
4204   _dbus_assert (!loader->corrupted);
4205   _dbus_assert (loader->messages != NULL);
4206   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4207
4208   return TRUE;
4209
4210  failed:
4211
4212   /* Clean up */
4213
4214   /* does nothing if the message isn't in the list */
4215   _dbus_list_remove_last (&loader->messages, message);
4216   
4217   if (oom)
4218     _dbus_assert (!loader->corrupted);
4219   else
4220     _dbus_assert (loader->corrupted);
4221
4222   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
4223
4224   return FALSE;
4225 }
4226
4227 /**
4228  * Converts buffered data into messages, if we have enough data.  If
4229  * we don't have enough data, does nothing.
4230  *
4231  * @todo we need to check that the proper named header fields exist
4232  * for each message type.
4233  *
4234  * @todo If a message has unknown type, we should probably eat it
4235  * right here rather than passing it out to applications.  However
4236  * it's not an error to see messages of unknown type.
4237  *
4238  * @param loader the loader.
4239  * @returns #TRUE if we had enough memory to finish.
4240  */
4241 dbus_bool_t
4242 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
4243 {
4244   while (!loader->corrupted &&
4245          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
4246     {
4247       DBusValidity validity;
4248       int byte_order, fields_array_len, header_len, body_len;
4249
4250       if (_dbus_header_have_message_untrusted (loader->max_message_size,
4251                                                &validity,
4252                                                &byte_order,
4253                                                &fields_array_len,
4254                                                &header_len,
4255                                                &body_len,
4256                                                &loader->data, 0,
4257                                                _dbus_string_get_length (&loader->data)))
4258         {
4259           DBusMessage *message;
4260
4261           _dbus_assert (validity == DBUS_VALID);
4262
4263           message = dbus_message_new_empty_header ();
4264           if (message == NULL)
4265             return FALSE;
4266
4267           if (!load_message (loader, message,
4268                              byte_order, fields_array_len,
4269                              header_len, body_len))
4270             {
4271               dbus_message_unref (message);
4272               /* load_message() returns false if corrupted or OOM; if
4273                * corrupted then return TRUE for not OOM
4274                */
4275               return loader->corrupted;
4276             }
4277
4278           _dbus_assert (loader->messages != NULL);
4279           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4280         }
4281       else
4282         {
4283           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
4284                          validity);
4285           if (validity != DBUS_VALID)
4286             {
4287               loader->corrupted = TRUE;
4288               loader->corruption_reason = validity;
4289             }
4290           return TRUE;
4291         }
4292     }
4293
4294   return TRUE;
4295 }
4296
4297 /**
4298  * Peeks at first loaded message, returns #NULL if no messages have
4299  * been queued.
4300  *
4301  * @param loader the loader.
4302  * @returns the next message, or #NULL if none.
4303  */
4304 DBusMessage*
4305 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
4306 {
4307   if (loader->messages)
4308     return loader->messages->data;
4309   else
4310     return NULL;
4311 }
4312
4313 /**
4314  * Pops a loaded message (passing ownership of the message
4315  * to the caller). Returns #NULL if no messages have been
4316  * queued.
4317  *
4318  * @param loader the loader.
4319  * @returns the next message, or #NULL if none.
4320  */
4321 DBusMessage*
4322 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
4323 {
4324   return _dbus_list_pop_first (&loader->messages);
4325 }
4326
4327 /**
4328  * Pops a loaded message inside a list link (passing ownership of the
4329  * message and link to the caller). Returns #NULL if no messages have
4330  * been loaded.
4331  *
4332  * @param loader the loader.
4333  * @returns the next message link, or #NULL if none.
4334  */
4335 DBusList*
4336 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
4337 {
4338   return _dbus_list_pop_first_link (&loader->messages);
4339 }
4340
4341 /**
4342  * Returns a popped message link, used to undo a pop.
4343  *
4344  * @param loader the loader
4345  * @param link the link with a message in it
4346  */
4347 void
4348 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
4349                                            DBusList           *link)
4350 {
4351   _dbus_list_prepend_link (&loader->messages, link);
4352 }
4353
4354 /**
4355  * Checks whether the loader is confused due to bad data.
4356  * If messages are received that are invalid, the
4357  * loader gets confused and gives up permanently.
4358  * This state is called "corrupted."
4359  *
4360  * @param loader the loader
4361  * @returns #TRUE if the loader is hosed.
4362  */
4363 dbus_bool_t
4364 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
4365 {
4366   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
4367                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
4368   return loader->corrupted;
4369 }
4370
4371 /**
4372  * Checks what kind of bad data confused the loader.
4373  *
4374  * @param loader the loader
4375  * @returns why the loader is hosed, or DBUS_VALID if it isn't.
4376  */
4377 DBusValidity
4378 _dbus_message_loader_get_corruption_reason (DBusMessageLoader *loader)
4379 {
4380   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
4381                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
4382
4383   return loader->corruption_reason;
4384 }
4385
4386 /**
4387  * Sets the maximum size message we allow.
4388  *
4389  * @param loader the loader
4390  * @param size the max message size in bytes
4391  */
4392 void
4393 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
4394                                            long                size)
4395 {
4396   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
4397     {
4398       _dbus_verbose ("clamping requested max message size %ld to %d\n",
4399                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
4400       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
4401     }
4402   loader->max_message_size = size;
4403 }
4404
4405 /**
4406  * Gets the maximum allowed message size in bytes.
4407  *
4408  * @param loader the loader
4409  * @returns max size in bytes
4410  */
4411 long
4412 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
4413 {
4414   return loader->max_message_size;
4415 }
4416
4417 /**
4418  * Sets the maximum unix fds per message we allow.
4419  *
4420  * @param loader the loader
4421  * @param n the max number of unix fds in a message
4422  */
4423 void
4424 _dbus_message_loader_set_max_message_unix_fds (DBusMessageLoader  *loader,
4425                                                long                n)
4426 {
4427   if (n > DBUS_MAXIMUM_MESSAGE_UNIX_FDS)
4428     {
4429       _dbus_verbose ("clamping requested max message unix_fds %ld to %d\n",
4430                      n, DBUS_MAXIMUM_MESSAGE_UNIX_FDS);
4431       n = DBUS_MAXIMUM_MESSAGE_UNIX_FDS;
4432     }
4433   loader->max_message_unix_fds = n;
4434 }
4435
4436 /**
4437  * Gets the maximum allowed number of unix fds per message
4438  *
4439  * @param loader the loader
4440  * @returns max unix fds
4441  */
4442 long
4443 _dbus_message_loader_get_max_message_unix_fds (DBusMessageLoader  *loader)
4444 {
4445   return loader->max_message_unix_fds;
4446 }
4447
4448 static DBusDataSlotAllocator slot_allocator =
4449   _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (message_slots));
4450
4451 /**
4452  * Allocates an integer ID to be used for storing application-specific
4453  * data on any DBusMessage. The allocated ID may then be used
4454  * with dbus_message_set_data() and dbus_message_get_data().
4455  * The passed-in slot must be initialized to -1, and is filled in
4456  * with the slot ID. If the passed-in slot is not -1, it's assumed
4457  * to be already allocated, and its refcount is incremented.
4458  *
4459  * The allocated slot is global, i.e. all DBusMessage objects will
4460  * have a slot with the given integer ID reserved.
4461  *
4462  * @param slot_p address of a global variable storing the slot
4463  * @returns #FALSE on failure (no memory)
4464  */
4465 dbus_bool_t
4466 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
4467 {
4468   return _dbus_data_slot_allocator_alloc (&slot_allocator,
4469                                           slot_p);
4470 }
4471
4472 /**
4473  * Deallocates a global ID for message data slots.
4474  * dbus_message_get_data() and dbus_message_set_data() may no
4475  * longer be used with this slot.  Existing data stored on existing
4476  * DBusMessage objects will be freed when the message is
4477  * finalized, but may not be retrieved (and may only be replaced if
4478  * someone else reallocates the slot).  When the refcount on the
4479  * passed-in slot reaches 0, it is set to -1.
4480  *
4481  * @param slot_p address storing the slot to deallocate
4482  */
4483 void
4484 dbus_message_free_data_slot (dbus_int32_t *slot_p)
4485 {
4486   _dbus_return_if_fail (*slot_p >= 0);
4487
4488   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
4489 }
4490
4491 /**
4492  * Stores a pointer on a DBusMessage, along
4493  * with an optional function to be used for freeing
4494  * the data when the data is set again, or when
4495  * the message is finalized. The slot number
4496  * must have been allocated with dbus_message_allocate_data_slot().
4497  *
4498  * @param message the message
4499  * @param slot the slot number
4500  * @param data the data to store
4501  * @param free_data_func finalizer function for the data
4502  * @returns #TRUE if there was enough memory to store the data
4503  */
4504 dbus_bool_t
4505 dbus_message_set_data (DBusMessage     *message,
4506                        dbus_int32_t     slot,
4507                        void            *data,
4508                        DBusFreeFunction free_data_func)
4509 {
4510   DBusFreeFunction old_free_func;
4511   void *old_data;
4512   dbus_bool_t retval;
4513
4514   _dbus_return_val_if_fail (message != NULL, FALSE);
4515   _dbus_return_val_if_fail (slot >= 0, FALSE);
4516
4517   retval = _dbus_data_slot_list_set (&slot_allocator,
4518                                      &message->slot_list,
4519                                      slot, data, free_data_func,
4520                                      &old_free_func, &old_data);
4521
4522   if (retval)
4523     {
4524       /* Do the actual free outside the message lock */
4525       if (old_free_func)
4526         (* old_free_func) (old_data);
4527     }
4528
4529   return retval;
4530 }
4531
4532 /**
4533  * Retrieves data previously set with dbus_message_set_data().
4534  * The slot must still be allocated (must not have been freed).
4535  *
4536  * @param message the message
4537  * @param slot the slot to get data from
4538  * @returns the data, or #NULL if not found
4539  */
4540 void*
4541 dbus_message_get_data (DBusMessage   *message,
4542                        dbus_int32_t   slot)
4543 {
4544   void *res;
4545
4546   _dbus_return_val_if_fail (message != NULL, NULL);
4547
4548   res = _dbus_data_slot_list_get (&slot_allocator,
4549                                   &message->slot_list,
4550                                   slot);
4551
4552   return res;
4553 }
4554
4555 /**
4556  * Utility function to convert a machine-readable (not translated)
4557  * string into a D-Bus message type.
4558  *
4559  * @code
4560  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
4561  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
4562  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
4563  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
4564  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
4565  * @endcode
4566  *
4567  */
4568 int
4569 dbus_message_type_from_string (const char *type_str)
4570 {
4571   if (strcmp (type_str, "method_call") == 0)
4572     return DBUS_MESSAGE_TYPE_METHOD_CALL;
4573   if (strcmp (type_str, "method_return") == 0)
4574     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
4575   else if (strcmp (type_str, "signal") == 0)
4576     return DBUS_MESSAGE_TYPE_SIGNAL;
4577   else if (strcmp (type_str, "error") == 0)
4578     return DBUS_MESSAGE_TYPE_ERROR;
4579   else
4580     return DBUS_MESSAGE_TYPE_INVALID;
4581 }
4582
4583 /**
4584  * Utility function to convert a D-Bus message type into a
4585  * machine-readable string (not translated).
4586  *
4587  * @code
4588  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
4589  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
4590  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
4591  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
4592  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
4593  * @endcode
4594  *
4595  */
4596 const char *
4597 dbus_message_type_to_string (int type)
4598 {
4599   switch (type)
4600     {
4601     case DBUS_MESSAGE_TYPE_METHOD_CALL:
4602       return "method_call";
4603     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
4604       return "method_return";
4605     case DBUS_MESSAGE_TYPE_SIGNAL:
4606       return "signal";
4607     case DBUS_MESSAGE_TYPE_ERROR:
4608       return "error";
4609     default:
4610       return "invalid";
4611     }
4612 }
4613
4614 /**
4615  * Turn a DBusMessage into the marshalled form as described in the D-Bus
4616  * specification.
4617  *
4618  * Generally, this function is only useful for encapsulating D-Bus messages in
4619  * a different protocol.
4620  *
4621  * @param msg the DBusMessage
4622  * @param marshalled_data_p the location to save the marshalled form to
4623  * @param len_p the location to save the length of the marshalled form to
4624  * @returns #FALSE if there was not enough memory
4625  */
4626 dbus_bool_t
4627 dbus_message_marshal (DBusMessage  *msg,
4628                       char        **marshalled_data_p,
4629                       int          *len_p)
4630 {
4631   DBusString tmp;
4632   dbus_bool_t was_locked;
4633
4634   _dbus_return_val_if_fail (msg != NULL, FALSE);
4635   _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
4636   _dbus_return_val_if_fail (len_p != NULL, FALSE);
4637   
4638   if (!_dbus_string_init (&tmp))
4639     return FALSE;
4640
4641   /* Ensure the message is locked, to ensure the length header is filled in. */
4642   was_locked = msg->locked;
4643
4644   if (!was_locked)
4645     dbus_message_lock (msg);
4646
4647   if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
4648     goto fail;
4649
4650   *len_p = _dbus_string_get_length (&tmp);
4651
4652   if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
4653     goto fail;
4654
4655   *len_p = _dbus_string_get_length (&tmp);
4656
4657   if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
4658     goto fail;
4659
4660   _dbus_string_free (&tmp);
4661
4662   if (!was_locked)
4663     msg->locked = FALSE;
4664
4665   return TRUE;
4666
4667  fail:
4668   _dbus_string_free (&tmp);
4669
4670   if (!was_locked)
4671     msg->locked = FALSE;
4672
4673   return FALSE;
4674 }
4675
4676 /**
4677  * Demarshal a D-Bus message from the format described in the D-Bus
4678  * specification.
4679  *
4680  * Generally, this function is only useful for encapsulating D-Bus messages in
4681  * a different protocol.
4682  *
4683  * @param str the marshalled DBusMessage
4684  * @param len the length of str
4685  * @param error the location to save errors to
4686  * @returns #NULL if there was an error
4687  */
4688 DBusMessage *
4689 dbus_message_demarshal (const char *str,
4690                         int         len,
4691                         DBusError  *error)
4692 {
4693   DBusMessageLoader *loader;
4694   DBusString *buffer;
4695   DBusMessage *msg;
4696
4697   _dbus_return_val_if_fail (str != NULL, NULL);
4698
4699   loader = _dbus_message_loader_new ();
4700
4701   if (loader == NULL)
4702     return NULL;
4703
4704   _dbus_message_loader_get_buffer (loader, &buffer);
4705   _dbus_string_append_len (buffer, str, len);
4706   _dbus_message_loader_return_buffer (loader, buffer, len);
4707
4708   if (!_dbus_message_loader_queue_messages (loader))
4709     goto fail_oom;
4710
4711   if (_dbus_message_loader_get_is_corrupted (loader))
4712     goto fail_corrupt;
4713
4714   msg = _dbus_message_loader_pop_message (loader);
4715
4716   if (!msg)
4717     goto fail_oom;
4718
4719   _dbus_message_loader_unref (loader);
4720   return msg;
4721
4722  fail_corrupt:
4723   dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted (%s)",
4724                   _dbus_validity_to_error_message (loader->corruption_reason));
4725   _dbus_message_loader_unref (loader);
4726   return NULL;
4727
4728  fail_oom:
4729   _DBUS_SET_OOM (error);
4730   _dbus_message_loader_unref (loader);
4731   return NULL;
4732 }
4733
4734 /**
4735  * Returns the number of bytes required to be in the buffer to demarshal a
4736  * D-Bus message.
4737  *
4738  * Generally, this function is only useful for encapsulating D-Bus messages in
4739  * a different protocol.
4740  *
4741  * @param buf data to be marshalled
4742  * @param len the length of @p buf
4743  * @returns -1 if there was no valid data to be demarshalled, 0 if there wasn't enough data to determine how much should be demarshalled. Otherwise returns the number of bytes to be demarshalled
4744  * 
4745  */
4746 int 
4747 dbus_message_demarshal_bytes_needed(const char *buf, 
4748                                     int         len)
4749 {
4750   DBusString str;
4751   int byte_order, fields_array_len, header_len, body_len;
4752   DBusValidity validity = DBUS_VALID;
4753   int have_message;
4754
4755   if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
4756     return 0;
4757
4758   if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
4759     len = DBUS_MAXIMUM_MESSAGE_LENGTH;
4760   _dbus_string_init_const_len (&str, buf, len);
4761   
4762   validity = DBUS_VALID;
4763   have_message
4764     = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
4765                                           &validity, &byte_order,
4766                                           &fields_array_len,
4767                                           &header_len,
4768                                           &body_len,
4769                                           &str, 0,
4770                                           len);
4771   _dbus_string_free (&str);
4772
4773   if (validity == DBUS_VALID)
4774     {
4775       _dbus_assert (have_message || (header_len + body_len) > len);
4776       (void) have_message; /* unused unless asserting */
4777       return header_len + body_len;
4778     }
4779   else
4780     {
4781       return -1; /* broken! */
4782     }
4783 }
4784
4785 /** @} */
4786
4787 /* tests in dbus-message-util.c */