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