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