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