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