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