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