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