30b5d6c0b436bf23843f1e49b6f7a4e3a540b539
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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                 goto failed;
1572             }
1573           else if (element_type == DBUS_TYPE_STRING ||
1574                    element_type == DBUS_TYPE_SIGNATURE ||
1575                    element_type == DBUS_TYPE_OBJECT_PATH)
1576             {
1577               const char ***value_p;
1578               const char **value;
1579               int n_elements;
1580               int i;
1581               
1582               value_p = va_arg (var_args, const char***);
1583               n_elements = va_arg (var_args, int);
1584
1585               value = *value_p;
1586               
1587               i = 0;
1588               while (i < n_elements)
1589                 {
1590                   if (!dbus_message_iter_append_basic (&array,
1591                                                        element_type,
1592                                                        &value[i]))
1593                     goto failed;
1594                   ++i;
1595                 }
1596             }
1597           else
1598             {
1599               _dbus_warn ("arrays of %s can't be appended with %s for now\n",
1600                           _dbus_type_to_string (element_type),
1601                           _DBUS_FUNCTION_NAME);
1602               goto failed;
1603             }
1604
1605           if (!dbus_message_iter_close_container (&iter, &array))
1606             goto failed;
1607         }
1608 #ifndef DBUS_DISABLE_CHECKS
1609       else
1610         {
1611           _dbus_warn ("type %s isn't supported yet in %s\n",
1612                       _dbus_type_to_string (type), _DBUS_FUNCTION_NAME);
1613           goto failed;
1614         }
1615 #endif
1616
1617       type = va_arg (var_args, int);
1618     }
1619
1620   return TRUE;
1621
1622  failed:
1623   return FALSE;
1624 }
1625
1626 /**
1627  * Gets arguments from a message given a variable argument list.  The
1628  * supported types include those supported by
1629  * dbus_message_append_args(); that is, basic types and arrays of
1630  * fixed-length basic types.  The arguments are the same as they would
1631  * be for dbus_message_iter_get_basic() or
1632  * dbus_message_iter_get_fixed_array().
1633  *
1634  * In addition to those types, arrays of string, object path, and
1635  * signature are supported; but these are returned as allocated memory
1636  * and must be freed with dbus_free_string_array(), while the other
1637  * types are returned as const references. To get a string array
1638  * pass in "char ***array_location" and "int *n_elements"
1639  *
1640  * The variable argument list should contain the type of the argument
1641  * followed by a pointer to where the value should be stored. The list
1642  * is terminated with #DBUS_TYPE_INVALID.
1643  *
1644  * Except for string arrays, the returned values are constant; do not
1645  * free them. They point into the #DBusMessage.
1646  *
1647  * If the requested arguments are not present, or do not have the
1648  * requested types, then an error will be set.
1649  *
1650  * If more arguments than requested are present, the requested
1651  * arguments are returned and the extra arguments are ignored.
1652  * 
1653  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1654  *
1655  * @param message the message
1656  * @param error error to be filled in on failure
1657  * @param first_arg_type the first argument type
1658  * @param ... location for first argument value, then list of type-location pairs
1659  * @returns #FALSE if the error was set
1660  */
1661 dbus_bool_t
1662 dbus_message_get_args (DBusMessage     *message,
1663                        DBusError       *error,
1664                        int              first_arg_type,
1665                        ...)
1666 {
1667   dbus_bool_t retval;
1668   va_list var_args;
1669
1670   _dbus_return_val_if_fail (message != NULL, FALSE);
1671   _dbus_return_val_if_error_is_set (error, FALSE);
1672
1673   va_start (var_args, first_arg_type);
1674   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
1675   va_end (var_args);
1676
1677   return retval;
1678 }
1679
1680 /**
1681  * Like dbus_message_get_args but takes a va_list for use by language bindings.
1682  *
1683  * @see dbus_message_get_args
1684  * @param message the message
1685  * @param error error to be filled in
1686  * @param first_arg_type type of the first argument
1687  * @param var_args return location for first argument, followed by list of type/location pairs
1688  * @returns #FALSE if error was set
1689  */
1690 dbus_bool_t
1691 dbus_message_get_args_valist (DBusMessage     *message,
1692                               DBusError       *error,
1693                               int              first_arg_type,
1694                               va_list          var_args)
1695 {
1696   DBusMessageIter iter;
1697
1698   _dbus_return_val_if_fail (message != NULL, FALSE);
1699   _dbus_return_val_if_error_is_set (error, FALSE);
1700
1701   dbus_message_iter_init (message, &iter);
1702   return _dbus_message_iter_get_args_valist (&iter, error, first_arg_type, var_args);
1703 }
1704
1705 static void
1706 _dbus_message_iter_init_common (DBusMessage         *message,
1707                                 DBusMessageRealIter *real,
1708                                 int                  iter_type)
1709 {
1710   _dbus_assert (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
1711
1712   /* Since the iterator will read or write who-knows-what from the
1713    * message, we need to get in the right byte order
1714    */
1715   ensure_byte_order (message);
1716   
1717   real->message = message;
1718   real->changed_stamp = message->changed_stamp;
1719   real->iter_type = iter_type;
1720   real->sig_refcount = 0;
1721 }
1722
1723 /**
1724  * Initializes a #DBusMessageIter for reading the arguments of the
1725  * message passed in.
1726  *
1727  * When possible, dbus_message_get_args() is much more convenient.
1728  * Some types of argument can only be read with #DBusMessageIter
1729  * however.
1730  *
1731  * The easiest way to iterate is like this: 
1732  * @code
1733  * dbus_message_iter_init (message, &iter);
1734  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
1735  *   dbus_message_iter_next (&iter);
1736  * @endcode
1737  *
1738  * #DBusMessageIter contains no allocated memory; it need not be
1739  * freed, and can be copied by assignment or memcpy().
1740  * 
1741  * @param message the message
1742  * @param iter pointer to an iterator to initialize
1743  * @returns #FALSE if the message has no arguments
1744  */
1745 dbus_bool_t
1746 dbus_message_iter_init (DBusMessage     *message,
1747                         DBusMessageIter *iter)
1748 {
1749   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1750   const DBusString *type_str;
1751   int type_pos;
1752
1753   _dbus_return_val_if_fail (message != NULL, FALSE);
1754   _dbus_return_val_if_fail (iter != NULL, FALSE);
1755
1756   get_const_signature (&message->header, &type_str, &type_pos);
1757
1758   _dbus_message_iter_init_common (message, real,
1759                                   DBUS_MESSAGE_ITER_TYPE_READER);
1760
1761   _dbus_type_reader_init (&real->u.reader,
1762                           message->byte_order,
1763                           type_str, type_pos,
1764                           &message->body,
1765                           0);
1766
1767   return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
1768 }
1769
1770 /**
1771  * Checks if an iterator has any more fields.
1772  *
1773  * @param iter the message iter
1774  * @returns #TRUE if there are more fields following
1775  */
1776 dbus_bool_t
1777 dbus_message_iter_has_next (DBusMessageIter *iter)
1778 {
1779   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1780
1781   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
1782   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1783
1784   return _dbus_type_reader_has_next (&real->u.reader);
1785 }
1786
1787 /**
1788  * Moves the iterator to the next field, if any. If there's no next
1789  * field, returns #FALSE. If the iterator moves forward, returns
1790  * #TRUE.
1791  *
1792  * @param iter the message iter
1793  * @returns #TRUE if the iterator was moved to the next field
1794  */
1795 dbus_bool_t
1796 dbus_message_iter_next (DBusMessageIter *iter)
1797 {
1798   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1799
1800   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
1801   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1802
1803   return _dbus_type_reader_next (&real->u.reader);
1804 }
1805
1806 /**
1807  * Returns the argument type of the argument that the message iterator
1808  * points to. If the iterator is at the end of the message, returns
1809  * #DBUS_TYPE_INVALID. You can thus write a loop as follows:
1810  *
1811  * @code
1812  * dbus_message_iter_init (&iter);
1813  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
1814  *   dbus_message_iter_next (&iter);
1815  * @endcode
1816  *
1817  * @param iter the message iter
1818  * @returns the argument type
1819  */
1820 int
1821 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
1822 {
1823   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1824
1825   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
1826   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1827
1828   return _dbus_type_reader_get_current_type (&real->u.reader);
1829 }
1830
1831 /**
1832  * Returns the element type of the array that the message iterator
1833  * points to. Note that you need to check that the iterator points to
1834  * an array prior to using this function.
1835  *
1836  * @param iter the message iter
1837  * @returns the array element type
1838  */
1839 int
1840 dbus_message_iter_get_element_type (DBusMessageIter *iter)
1841 {
1842   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1843
1844   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
1845   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, DBUS_TYPE_INVALID);
1846   _dbus_return_val_if_fail (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY, DBUS_TYPE_INVALID);
1847
1848   return _dbus_type_reader_get_element_type (&real->u.reader);
1849 }
1850
1851 /**
1852  * Recurses into a container value when reading values from a message,
1853  * initializing a sub-iterator to use for traversing the child values
1854  * of the container.
1855  *
1856  * Note that this recurses into a value, not a type, so you can only
1857  * recurse if the value exists. The main implication of this is that
1858  * if you have for example an empty array of array of int32, you can
1859  * recurse into the outermost array, but it will have no values, so
1860  * you won't be able to recurse further. There's no array of int32 to
1861  * recurse into.
1862  *
1863  * If a container is an array of fixed-length types, it is much more
1864  * efficient to use dbus_message_iter_get_fixed_array() to get the
1865  * whole array in one shot, rather than individually walking over the
1866  * array elements.
1867  *
1868  * Be sure you have somehow checked that
1869  * dbus_message_iter_get_arg_type() matches the type you are expecting
1870  * to recurse into. Results of this function are undefined if there is
1871  * no container to recurse into at the current iterator position.
1872  *
1873  * @param iter the message iterator
1874  * @param sub the sub-iterator to initialize
1875  */
1876 void
1877 dbus_message_iter_recurse (DBusMessageIter  *iter,
1878                            DBusMessageIter  *sub)
1879 {
1880   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1881   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
1882
1883   _dbus_return_if_fail (_dbus_message_iter_check (real));
1884   _dbus_return_if_fail (sub != NULL);
1885
1886   *real_sub = *real;
1887   _dbus_type_reader_recurse (&real->u.reader, &real_sub->u.reader);
1888 }
1889
1890 /**
1891  * Returns the current signature of a message iterator.  This
1892  * is useful primarily for dealing with variants; one can
1893  * recurse into a variant and determine the signature of
1894  * the variant's value.
1895  *
1896  * The returned string must be freed with dbus_free().
1897  * 
1898  * @param iter the message iterator
1899  * @returns the contained signature, or NULL if out of memory
1900  */
1901 char *
1902 dbus_message_iter_get_signature (DBusMessageIter *iter)
1903 {
1904   const DBusString *sig;
1905   DBusString retstr;
1906   char *ret;
1907   int start, len;
1908   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1909
1910   _dbus_return_val_if_fail (_dbus_message_iter_check (real), NULL);
1911
1912   if (!_dbus_string_init (&retstr))
1913     return NULL;
1914
1915   _dbus_type_reader_get_signature (&real->u.reader, &sig,
1916                                    &start, &len);
1917   if (!_dbus_string_append_len (&retstr,
1918                                 _dbus_string_get_const_data (sig) + start,
1919                                 len))
1920     return NULL;
1921   if (!_dbus_string_steal_data (&retstr, &ret))
1922     return NULL;
1923   _dbus_string_free (&retstr);
1924   return ret;
1925 }
1926
1927 /**
1928  * Reads a basic-typed value from the message iterator.
1929  * Basic types are the non-containers such as integer and string.
1930  *
1931  * The value argument should be the address of a location to store
1932  * the returned value. So for int32 it should be a "dbus_int32_t*"
1933  * and for string a "const char**". The returned value is
1934  * by reference and should not be freed.
1935  *
1936  * Be sure you have somehow checked that
1937  * dbus_message_iter_get_arg_type() matches the type you are
1938  * expecting, or you'll crash when you try to use an integer as a
1939  * string or something.
1940  *
1941  * To read any container type (array, struct, dict) you will need
1942  * to recurse into the container with dbus_message_iter_recurse().
1943  * If the container is an array of fixed-length values, you can
1944  * get all the array elements at once with
1945  * dbus_message_iter_get_fixed_array(). Otherwise, you have to
1946  * iterate over the container's contents one value at a time.
1947  * 
1948  * All basic-typed values are guaranteed to fit in 8 bytes. So you can
1949  * write code like this:
1950  *
1951  * @code
1952  * dbus_uint64_t value;
1953  * int type;
1954  * dbus_message_iter_get_basic (&read_iter, &value);
1955  * type = dbus_message_iter_get_arg_type (&read_iter);
1956  * dbus_message_iter_append_basic (&write_iter, type, &value);
1957  * @endcode
1958  *
1959  * On some really obscure platforms dbus_uint64_t might not exist, if
1960  * you need to worry about this you will know.  dbus_uint64_t is just
1961  * one example of a type that's large enough to hold any possible
1962  * value, you could use a struct or char[8] instead if you like.
1963  *
1964  * @param iter the iterator
1965  * @param value location to store the value
1966  */
1967 void
1968 dbus_message_iter_get_basic (DBusMessageIter  *iter,
1969                              void             *value)
1970 {
1971   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1972
1973   _dbus_return_if_fail (_dbus_message_iter_check (real));
1974   _dbus_return_if_fail (value != NULL);
1975
1976   _dbus_type_reader_read_basic (&real->u.reader,
1977                                 value);
1978 }
1979
1980 /**
1981  * Returns the number of bytes in the array as marshaled in the wire
1982  * protocol. The iterator must currently be inside an array-typed
1983  * value.
1984  *
1985  * This function is deprecated on the grounds that it is stupid.  Why
1986  * would you want to know how many bytes are in the array as marshaled
1987  * in the wire protocol?  For now, use the n_elements returned from
1988  * dbus_message_iter_get_fixed_array() instead, or iterate over the
1989  * array values and count them.
1990  *
1991  * @todo introduce a variant of this get_n_elements that returns
1992  * the number of elements, though with a non-fixed array it will not
1993  * be very efficient, so maybe it's not good.
1994  * 
1995  * @param iter the iterator
1996  * @returns the number of bytes in the array
1997  */
1998 int
1999 dbus_message_iter_get_array_len (DBusMessageIter *iter)
2000 {
2001   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2002
2003   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2004
2005   return _dbus_type_reader_get_array_length (&real->u.reader);
2006 }
2007
2008 /**
2009  * Reads a block of fixed-length values from the message iterator.
2010  * Fixed-length values are those basic types that are not string-like,
2011  * such as integers, bool, double. The returned block will be from the
2012  * current position in the array until the end of the array.
2013  *
2014  * The message iter should be "in" the array (that is, you recurse into the
2015  * array, and then you call dbus_message_iter_get_fixed_array() on the
2016  * "sub-iterator" created by dbus_message_iter_recurse()).
2017  *
2018  * The value argument should be the address of a location to store the
2019  * returned array. So for int32 it should be a "const dbus_int32_t**"
2020  * The returned value is by reference and should not be freed.
2021  * 
2022  * This function should only be used if dbus_type_is_fixed() returns
2023  * #TRUE for the element type.
2024  *
2025  * If an array's elements are not fixed in size, you have to recurse
2026  * into the array with dbus_message_iter_recurse() and read the
2027  * elements one by one.
2028  * 
2029  * Because the array is not copied, this function runs in constant
2030  * time and is fast; it's much preferred over walking the entire array
2031  * with an iterator. (However, you can always use
2032  * dbus_message_iter_recurse(), even for fixed-length types;
2033  * dbus_message_iter_get_fixed_array() is just an optimization.)
2034  * 
2035  * @param iter the iterator
2036  * @param value location to store the block
2037  * @param n_elements number of elements in the block
2038  */
2039 void
2040 dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
2041                                    void             *value,
2042                                    int              *n_elements)
2043 {
2044   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2045   int subtype = _dbus_type_reader_get_current_type(&real->u.reader);
2046
2047   _dbus_return_if_fail (_dbus_message_iter_check (real));
2048   _dbus_return_if_fail (value != NULL);
2049   _dbus_return_if_fail ((subtype == DBUS_TYPE_INVALID) ||
2050                          dbus_type_is_fixed (subtype));
2051
2052   _dbus_type_reader_read_fixed_multi (&real->u.reader,
2053                                       value, n_elements);
2054 }
2055
2056 /**
2057  * Initializes a #DBusMessageIter for appending arguments to the end
2058  * of a message.
2059  *
2060  * @todo If appending any of the arguments fails due to lack of
2061  * memory, the message is hosed and you have to start over building
2062  * the whole message.
2063  *
2064  * @param message the message
2065  * @param iter pointer to an iterator to initialize
2066  */
2067 void
2068 dbus_message_iter_init_append (DBusMessage     *message,
2069                                DBusMessageIter *iter)
2070 {
2071   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2072
2073   _dbus_return_if_fail (message != NULL);
2074   _dbus_return_if_fail (iter != NULL);
2075
2076   _dbus_message_iter_init_common (message, real,
2077                                   DBUS_MESSAGE_ITER_TYPE_WRITER);
2078
2079   /* We create the signature string and point iterators at it "on demand"
2080    * when a value is actually appended. That means that init() never fails
2081    * due to OOM.
2082    */
2083   _dbus_type_writer_init_types_delayed (&real->u.writer,
2084                                         message->byte_order,
2085                                         &message->body,
2086                                         _dbus_string_get_length (&message->body));
2087 }
2088
2089 /**
2090  * Creates a temporary signature string containing the current
2091  * signature, stores it in the iterator, and points the iterator to
2092  * the end of it. Used any time we write to the message.
2093  *
2094  * @param real an iterator without a type_str
2095  * @returns #FALSE if no memory
2096  */
2097 static dbus_bool_t
2098 _dbus_message_iter_open_signature (DBusMessageRealIter *real)
2099 {
2100   DBusString *str;
2101   const DBusString *current_sig;
2102   int current_sig_pos;
2103
2104   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2105
2106   if (real->u.writer.type_str != NULL)
2107     {
2108       _dbus_assert (real->sig_refcount > 0);
2109       real->sig_refcount += 1;
2110       return TRUE;
2111     }
2112
2113   str = dbus_new (DBusString, 1);
2114   if (str == NULL)
2115     return FALSE;
2116
2117   if (!_dbus_header_get_field_raw (&real->message->header,
2118                                    DBUS_HEADER_FIELD_SIGNATURE,
2119                                    &current_sig, &current_sig_pos))
2120     current_sig = NULL;
2121
2122   if (current_sig)
2123     {
2124       int current_len;
2125
2126       current_len = _dbus_string_get_byte (current_sig, current_sig_pos);
2127       current_sig_pos += 1; /* move on to sig data */
2128
2129       if (!_dbus_string_init_preallocated (str, current_len + 4))
2130         {
2131           dbus_free (str);
2132           return FALSE;
2133         }
2134
2135       if (!_dbus_string_copy_len (current_sig, current_sig_pos, current_len,
2136                                   str, 0))
2137         {
2138           _dbus_string_free (str);
2139           dbus_free (str);
2140           return FALSE;
2141         }
2142     }
2143   else
2144     {
2145       if (!_dbus_string_init_preallocated (str, 4))
2146         {
2147           dbus_free (str);
2148           return FALSE;
2149         }
2150     }
2151
2152   real->sig_refcount = 1;
2153
2154   _dbus_type_writer_add_types (&real->u.writer,
2155                                str, _dbus_string_get_length (str));
2156   return TRUE;
2157 }
2158
2159 /**
2160  * Sets the new signature as the message signature, frees the
2161  * signature string, and marks the iterator as not having a type_str
2162  * anymore. Frees the signature even if it fails, so you can't
2163  * really recover from failure. Kinda busted.
2164  *
2165  * @param real an iterator without a type_str
2166  * @returns #FALSE if no memory
2167  */
2168 static dbus_bool_t
2169 _dbus_message_iter_close_signature (DBusMessageRealIter *real)
2170 {
2171   DBusString *str;
2172   const char *v_STRING;
2173   dbus_bool_t retval;
2174
2175   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2176   _dbus_assert (real->u.writer.type_str != NULL);
2177   _dbus_assert (real->sig_refcount > 0);
2178
2179   real->sig_refcount -= 1;
2180
2181   if (real->sig_refcount > 0)
2182     return TRUE;
2183   _dbus_assert (real->sig_refcount == 0);
2184
2185   retval = TRUE;
2186
2187   str = real->u.writer.type_str;
2188
2189   v_STRING = _dbus_string_get_const_data (str);
2190   if (!_dbus_header_set_field_basic (&real->message->header,
2191                                      DBUS_HEADER_FIELD_SIGNATURE,
2192                                      DBUS_TYPE_SIGNATURE,
2193                                      &v_STRING))
2194     retval = FALSE;
2195
2196   _dbus_type_writer_remove_types (&real->u.writer);
2197   _dbus_string_free (str);
2198   dbus_free (str);
2199
2200   return retval;
2201 }
2202
2203 /**
2204  * Frees the signature string and marks the iterator as not having a
2205  * type_str anymore.  Since the new signature is not set, the message
2206  * will generally be hosed after this is called.
2207  *
2208  * @param real an iterator without a type_str
2209  */
2210 static void
2211 _dbus_message_iter_abandon_signature (DBusMessageRealIter *real)
2212 {
2213   DBusString *str;
2214
2215   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2216   _dbus_assert (real->u.writer.type_str != NULL);
2217   _dbus_assert (real->sig_refcount > 0);
2218
2219   real->sig_refcount -= 1;
2220
2221   if (real->sig_refcount > 0)
2222     return;
2223   _dbus_assert (real->sig_refcount == 0);
2224
2225   str = real->u.writer.type_str;
2226
2227   _dbus_type_writer_remove_types (&real->u.writer);
2228   _dbus_string_free (str);
2229   dbus_free (str);
2230 }
2231
2232 #ifndef DBUS_DISABLE_CHECKS
2233 static dbus_bool_t
2234 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
2235 {
2236   if (!_dbus_message_iter_check (iter))
2237     return FALSE;
2238
2239   if (iter->message->locked)
2240     {
2241       _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)\n");
2242       return FALSE;
2243     }
2244
2245   return TRUE;
2246 }
2247 #endif /* DBUS_DISABLE_CHECKS */
2248
2249 /**
2250  * Appends a basic-typed value to the message. The basic types are the
2251  * non-container types such as integer and string.
2252  *
2253  * The "value" argument should be the address of a basic-typed value.
2254  * So for string, const char**. For integer, dbus_int32_t*.
2255  *
2256  * @todo If this fails due to lack of memory, the message is hosed and
2257  * you have to start over building the whole message.
2258  *
2259  * @param iter the append iterator
2260  * @param type the type of the value
2261  * @param value the address of the value
2262  * @returns #FALSE if not enough memory
2263  */
2264 dbus_bool_t
2265 dbus_message_iter_append_basic (DBusMessageIter *iter,
2266                                 int              type,
2267                                 const void      *value)
2268 {
2269   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2270   dbus_bool_t ret;
2271
2272   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2273   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2274   _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
2275   _dbus_return_val_if_fail (value != NULL, FALSE);
2276
2277   if (!_dbus_message_iter_open_signature (real))
2278     return FALSE;
2279
2280   ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
2281
2282   if (!_dbus_message_iter_close_signature (real))
2283     ret = FALSE;
2284
2285   return ret;
2286 }
2287
2288 /**
2289  * Appends a block of fixed-length values to an array. The
2290  * fixed-length types are all basic types that are not string-like. So
2291  * int32, double, bool, etc. You must call
2292  * dbus_message_iter_open_container() to open an array of values
2293  * before calling this function. You may call this function multiple
2294  * times (and intermixed with calls to
2295  * dbus_message_iter_append_basic()) for the same array.
2296  *
2297  * The "value" argument should be the address of the array.  So for
2298  * integer, "dbus_int32_t**" is expected for example.
2299  *
2300  * @warning in C, given "int array[]", "&array == array" (the
2301  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
2302  * So if you're using an array instead of a pointer you have to create
2303  * a pointer variable, assign the array to it, then take the address
2304  * of the pointer variable.
2305  * @code
2306  * const dbus_int32_t array[] = { 1, 2, 3 };
2307  * const dbus_int32_t *v_ARRAY = array;
2308  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
2309  *   fprintf (stderr, "No memory!\n");
2310  * @endcode
2311  * For strings it works to write const char *array = "Hello" and then
2312  * use &array though.
2313  *
2314  * @todo If this fails due to lack of memory, the message is hosed and
2315  * you have to start over building the whole message.
2316  *
2317  * @param iter the append iterator
2318  * @param element_type the type of the array elements
2319  * @param value the address of the array
2320  * @param n_elements the number of elements to append
2321  * @returns #FALSE if not enough memory
2322  */
2323 dbus_bool_t
2324 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
2325                                       int              element_type,
2326                                       const void      *value,
2327                                       int              n_elements)
2328 {
2329   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2330   dbus_bool_t ret;
2331
2332   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2333   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2334   _dbus_return_val_if_fail (dbus_type_is_fixed (element_type), FALSE);
2335   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
2336   _dbus_return_val_if_fail (value != NULL, FALSE);
2337   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
2338   _dbus_return_val_if_fail (n_elements <=
2339                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
2340                             FALSE);
2341
2342   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
2343
2344   return ret;
2345 }
2346
2347 /**
2348  * Appends a container-typed value to the message; you are required to
2349  * append the contents of the container using the returned
2350  * sub-iterator, and then call
2351  * dbus_message_iter_close_container(). Container types are for
2352  * example struct, variant, and array. For variants, the
2353  * contained_signature should be the type of the single value inside
2354  * the variant. For structs and dict entries, contained_signature
2355  * should be #NULL; it will be set to whatever types you write into
2356  * the struct.  For arrays, contained_signature should be the type of
2357  * the array elements.
2358  *
2359  * @todo If this fails due to lack of memory, the message is hosed and
2360  * you have to start over building the whole message.
2361  *
2362  * @param iter the append iterator
2363  * @param type the type of the value
2364  * @param contained_signature the type of container contents
2365  * @param sub sub-iterator to initialize
2366  * @returns #FALSE if not enough memory
2367  */
2368 dbus_bool_t
2369 dbus_message_iter_open_container (DBusMessageIter *iter,
2370                                   int              type,
2371                                   const char      *contained_signature,
2372                                   DBusMessageIter *sub)
2373 {
2374   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2375   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2376   DBusString contained_str;
2377
2378   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2379   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2380   _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
2381   _dbus_return_val_if_fail (sub != NULL, FALSE);
2382   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
2383                              contained_signature == NULL) ||
2384                             (type == DBUS_TYPE_DICT_ENTRY &&
2385                              contained_signature == NULL) ||
2386                             (type == DBUS_TYPE_VARIANT &&
2387                              contained_signature != NULL) ||
2388                             (type == DBUS_TYPE_ARRAY &&
2389                              contained_signature != NULL), FALSE);
2390   
2391   /* this would fail if the contained_signature is a dict entry, since
2392    * dict entries are invalid signatures standalone (they must be in
2393    * an array)
2394    */
2395   _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
2396                             (contained_signature == NULL ||
2397                              _dbus_check_is_valid_signature (contained_signature)),
2398                             FALSE);
2399
2400   if (!_dbus_message_iter_open_signature (real))
2401     return FALSE;
2402
2403   *real_sub = *real;
2404
2405   if (contained_signature != NULL)
2406     {
2407       _dbus_string_init_const (&contained_str, contained_signature);
2408
2409       return _dbus_type_writer_recurse (&real->u.writer,
2410                                         type,
2411                                         &contained_str, 0,
2412                                         &real_sub->u.writer);
2413     }
2414   else
2415     {
2416       return _dbus_type_writer_recurse (&real->u.writer,
2417                                         type,
2418                                         NULL, 0,
2419                                         &real_sub->u.writer);
2420     } 
2421 }
2422
2423
2424 /**
2425  * Closes a container-typed value appended to the message; may write
2426  * out more information to the message known only after the entire
2427  * container is written, and may free resources created by
2428  * dbus_message_iter_open_container().
2429  *
2430  * @todo If this fails due to lack of memory, the message is hosed and
2431  * you have to start over building the whole message.
2432  *
2433  * @param iter the append iterator
2434  * @param sub sub-iterator to close
2435  * @returns #FALSE if not enough memory
2436  */
2437 dbus_bool_t
2438 dbus_message_iter_close_container (DBusMessageIter *iter,
2439                                    DBusMessageIter *sub)
2440 {
2441   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2442   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2443   dbus_bool_t ret;
2444
2445   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2446   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2447   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
2448   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2449
2450   ret = _dbus_type_writer_unrecurse (&real->u.writer,
2451                                      &real_sub->u.writer);
2452
2453   if (!_dbus_message_iter_close_signature (real))
2454     ret = FALSE;
2455
2456   return ret;
2457 }
2458
2459 /**
2460  * Abandons creation of a contained-typed value and frees resources created
2461  * by dbus_message_iter_open_container().  Once this returns, the message
2462  * is hosed and you have to start over building the whole message.
2463  *
2464  * This should only be used to abandon creation of a message when you have
2465  * open containers.
2466  *
2467  * @param iter the append iterator
2468  * @param sub sub-iterator to close
2469  */
2470 void
2471 dbus_message_iter_abandon_container (DBusMessageIter *iter,
2472                                      DBusMessageIter *sub)
2473 {
2474   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2475   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2476
2477   _dbus_return_if_fail (_dbus_message_iter_append_check (real));
2478   _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2479   _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
2480   _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2481
2482   _dbus_message_iter_abandon_signature (real);
2483 }
2484
2485 /**
2486  * Sets a flag indicating that the message does not want a reply; if
2487  * this flag is set, the other end of the connection may (but is not
2488  * required to) optimize by not sending method return or error
2489  * replies. If this flag is set, there is no way to know whether the
2490  * message successfully arrived at the remote end. Normally you know a
2491  * message was received when you receive the reply to it.
2492  *
2493  * The flag is #FALSE by default, that is by default the other end is
2494  * required to reply.
2495  *
2496  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
2497  * 
2498  * @param message the message
2499  * @param no_reply #TRUE if no reply is desired
2500  */
2501 void
2502 dbus_message_set_no_reply (DBusMessage *message,
2503                            dbus_bool_t  no_reply)
2504 {
2505   _dbus_return_if_fail (message != NULL);
2506   _dbus_return_if_fail (!message->locked);
2507
2508   _dbus_header_toggle_flag (&message->header,
2509                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
2510                             no_reply);
2511 }
2512
2513 /**
2514  * Returns #TRUE if the message does not expect
2515  * a reply.
2516  *
2517  * @param message the message
2518  * @returns #TRUE if the message sender isn't waiting for a reply
2519  */
2520 dbus_bool_t
2521 dbus_message_get_no_reply (DBusMessage *message)
2522 {
2523   _dbus_return_val_if_fail (message != NULL, FALSE);
2524
2525   return _dbus_header_get_flag (&message->header,
2526                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
2527 }
2528
2529 /**
2530  * Sets a flag indicating that an owner for the destination name will
2531  * be automatically started before the message is delivered. When this
2532  * flag is set, the message is held until a name owner finishes
2533  * starting up, or fails to start up. In case of failure, the reply
2534  * will be an error.
2535  *
2536  * The flag is set to #TRUE by default, i.e. auto starting is the default.
2537  *
2538  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
2539  * 
2540  * @param message the message
2541  * @param auto_start #TRUE if auto-starting is desired
2542  */
2543 void
2544 dbus_message_set_auto_start (DBusMessage *message,
2545                              dbus_bool_t  auto_start)
2546 {
2547   _dbus_return_if_fail (message != NULL);
2548   _dbus_return_if_fail (!message->locked);
2549
2550   _dbus_header_toggle_flag (&message->header,
2551                             DBUS_HEADER_FLAG_NO_AUTO_START,
2552                             !auto_start);
2553 }
2554
2555 /**
2556  * Returns #TRUE if the message will cause an owner for
2557  * destination name to be auto-started.
2558  *
2559  * @param message the message
2560  * @returns #TRUE if the message will use auto-start
2561  */
2562 dbus_bool_t
2563 dbus_message_get_auto_start (DBusMessage *message)
2564 {
2565   _dbus_return_val_if_fail (message != NULL, FALSE);
2566
2567   return !_dbus_header_get_flag (&message->header,
2568                                  DBUS_HEADER_FLAG_NO_AUTO_START);
2569 }
2570
2571
2572 /**
2573  * Sets the object path this message is being sent to (for
2574  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
2575  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
2576  *
2577  * The path must contain only valid characters as defined
2578  * in the D-Bus specification.
2579  *
2580  * @param message the message
2581  * @param object_path the path or #NULL to unset
2582  * @returns #FALSE if not enough memory
2583  */
2584 dbus_bool_t
2585 dbus_message_set_path (DBusMessage   *message,
2586                        const char    *object_path)
2587 {
2588   _dbus_return_val_if_fail (message != NULL, FALSE);
2589   _dbus_return_val_if_fail (!message->locked, FALSE);
2590   _dbus_return_val_if_fail (object_path == NULL ||
2591                             _dbus_check_is_valid_path (object_path),
2592                             FALSE);
2593
2594   return set_or_delete_string_field (message,
2595                                      DBUS_HEADER_FIELD_PATH,
2596                                      DBUS_TYPE_OBJECT_PATH,
2597                                      object_path);
2598 }
2599
2600 /**
2601  * Gets the object path this message is being sent to (for
2602  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
2603  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2604  *
2605  * See also dbus_message_get_path_decomposed().
2606  *
2607  * The returned string becomes invalid if the message is
2608  * modified, since it points into the wire-marshaled message data.
2609  * 
2610  * @param message the message
2611  * @returns the path (should not be freed) or #NULL
2612  */
2613 const char*
2614 dbus_message_get_path (DBusMessage   *message)
2615 {
2616   const char *v;
2617
2618   _dbus_return_val_if_fail (message != NULL, NULL);
2619
2620   v = NULL; /* in case field doesn't exist */
2621   _dbus_header_get_field_basic (&message->header,
2622                                 DBUS_HEADER_FIELD_PATH,
2623                                 DBUS_TYPE_OBJECT_PATH,
2624                                 &v);
2625   return v;
2626 }
2627
2628 /**
2629  * Checks if the message has a particular object path.  The object
2630  * path is the destination object for a method call or the emitting
2631  * object for a signal.
2632  *
2633  * @param message the message
2634  * @param path the path name
2635  * @returns #TRUE if there is a path field in the header
2636  */
2637 dbus_bool_t
2638 dbus_message_has_path (DBusMessage   *message,
2639                        const char    *path)
2640 {
2641   const char *msg_path;
2642   msg_path = dbus_message_get_path (message);
2643   
2644   if (msg_path == NULL)
2645     {
2646       if (path == NULL)
2647         return TRUE;
2648       else
2649         return FALSE;
2650     }
2651
2652   if (path == NULL)
2653     return FALSE;
2654    
2655   if (strcmp (msg_path, path) == 0)
2656     return TRUE;
2657
2658   return FALSE;
2659 }
2660
2661 /**
2662  * Gets the object path this message is being sent to
2663  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2664  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
2665  * format (one array element per path component).
2666  * Free the returned array with dbus_free_string_array().
2667  *
2668  * An empty but non-NULL path array means the path "/".
2669  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
2670  * and the path "/" becomes { NULL }.
2671  *
2672  * See also dbus_message_get_path().
2673  * 
2674  * @todo this could be optimized by using the len from the message
2675  * instead of calling strlen() again
2676  *
2677  * @param message the message
2678  * @param path place to store allocated array of path components; #NULL set here if no path field exists
2679  * @returns #FALSE if no memory to allocate the array
2680  */
2681 dbus_bool_t
2682 dbus_message_get_path_decomposed (DBusMessage   *message,
2683                                   char        ***path)
2684 {
2685   const char *v;
2686
2687   _dbus_return_val_if_fail (message != NULL, FALSE);
2688   _dbus_return_val_if_fail (path != NULL, FALSE);
2689
2690   *path = NULL;
2691
2692   v = dbus_message_get_path (message);
2693   if (v != NULL)
2694     {
2695       if (!_dbus_decompose_path (v, strlen (v),
2696                                  path, NULL))
2697         return FALSE;
2698     }
2699   return TRUE;
2700 }
2701
2702 /**
2703  * Sets the interface this message is being sent to
2704  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
2705  * the interface a signal is being emitted from
2706  * (for DBUS_MESSAGE_TYPE_SIGNAL).
2707  *
2708  * The interface name must contain only valid characters as defined
2709  * in the D-Bus specification.
2710  * 
2711  * @param message the message
2712  * @param interface the interface or #NULL to unset
2713  * @returns #FALSE if not enough memory
2714  */
2715 dbus_bool_t
2716 dbus_message_set_interface (DBusMessage  *message,
2717                             const char   *interface)
2718 {
2719   _dbus_return_val_if_fail (message != NULL, FALSE);
2720   _dbus_return_val_if_fail (!message->locked, FALSE);
2721   _dbus_return_val_if_fail (interface == NULL ||
2722                             _dbus_check_is_valid_interface (interface),
2723                             FALSE);
2724
2725   return set_or_delete_string_field (message,
2726                                      DBUS_HEADER_FIELD_INTERFACE,
2727                                      DBUS_TYPE_STRING,
2728                                      interface);
2729 }
2730
2731 /**
2732  * Gets the interface this message is being sent to
2733  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2734  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
2735  * The interface name is fully-qualified (namespaced).
2736  * Returns #NULL if none.
2737  *
2738  * The returned string becomes invalid if the message is
2739  * modified, since it points into the wire-marshaled message data.
2740  *
2741  * @param message the message
2742  * @returns the message interface (should not be freed) or #NULL
2743  */
2744 const char*
2745 dbus_message_get_interface (DBusMessage *message)
2746 {
2747   const char *v;
2748
2749   _dbus_return_val_if_fail (message != NULL, NULL);
2750
2751   v = NULL; /* in case field doesn't exist */
2752   _dbus_header_get_field_basic (&message->header,
2753                                 DBUS_HEADER_FIELD_INTERFACE,
2754                                 DBUS_TYPE_STRING,
2755                                 &v);
2756   return v;
2757 }
2758
2759 /**
2760  * Checks if the message has an interface
2761  *
2762  * @param message the message
2763  * @param interface the interface name
2764  * @returns #TRUE if the interface field in the header matches
2765  */
2766 dbus_bool_t
2767 dbus_message_has_interface (DBusMessage   *message,
2768                             const char    *interface)
2769 {
2770   const char *msg_interface;
2771   msg_interface = dbus_message_get_interface (message);
2772    
2773   if (msg_interface == NULL)
2774     {
2775       if (interface == NULL)
2776         return TRUE;
2777       else
2778         return FALSE;
2779     }
2780
2781   if (interface == NULL)
2782     return FALSE;
2783      
2784   if (strcmp (msg_interface, interface) == 0)
2785     return TRUE;
2786
2787   return FALSE;
2788
2789 }
2790
2791 /**
2792  * Sets the interface member being invoked
2793  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2794  * (DBUS_MESSAGE_TYPE_SIGNAL).
2795  *
2796  * The member name must contain only valid characters as defined
2797  * in the D-Bus specification.
2798  *
2799  * @param message the message
2800  * @param member the member or #NULL to unset
2801  * @returns #FALSE if not enough memory
2802  */
2803 dbus_bool_t
2804 dbus_message_set_member (DBusMessage  *message,
2805                          const char   *member)
2806 {
2807   _dbus_return_val_if_fail (message != NULL, FALSE);
2808   _dbus_return_val_if_fail (!message->locked, FALSE);
2809   _dbus_return_val_if_fail (member == NULL ||
2810                             _dbus_check_is_valid_member (member),
2811                             FALSE);
2812
2813   return set_or_delete_string_field (message,
2814                                      DBUS_HEADER_FIELD_MEMBER,
2815                                      DBUS_TYPE_STRING,
2816                                      member);
2817 }
2818
2819 /**
2820  * Gets the interface member being invoked
2821  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2822  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2823  *
2824  * The returned string becomes invalid if the message is
2825  * modified, since it points into the wire-marshaled message data.
2826  * 
2827  * @param message the message
2828  * @returns the member name (should not be freed) or #NULL
2829  */
2830 const char*
2831 dbus_message_get_member (DBusMessage *message)
2832 {
2833   const char *v;
2834
2835   _dbus_return_val_if_fail (message != NULL, NULL);
2836
2837   v = NULL; /* in case field doesn't exist */
2838   _dbus_header_get_field_basic (&message->header,
2839                                 DBUS_HEADER_FIELD_MEMBER,
2840                                 DBUS_TYPE_STRING,
2841                                 &v);
2842   return v;
2843 }
2844
2845 /**
2846  * Checks if the message has an interface member
2847  *
2848  * @param message the message
2849  * @param member the member name
2850  * @returns #TRUE if there is a member field in the header
2851  */
2852 dbus_bool_t
2853 dbus_message_has_member (DBusMessage   *message,
2854                          const char    *member)
2855 {
2856   const char *msg_member;
2857   msg_member = dbus_message_get_member (message);
2858  
2859   if (msg_member == NULL)
2860     {
2861       if (member == NULL)
2862         return TRUE;
2863       else
2864         return FALSE;
2865     }
2866
2867   if (member == NULL)
2868     return FALSE;
2869     
2870   if (strcmp (msg_member, member) == 0)
2871     return TRUE;
2872
2873   return FALSE;
2874
2875 }
2876
2877 /**
2878  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
2879  * The name is fully-qualified (namespaced).
2880  *
2881  * The error name must contain only valid characters as defined
2882  * in the D-Bus specification.
2883  *
2884  * @param message the message
2885  * @param error_name the name or #NULL to unset
2886  * @returns #FALSE if not enough memory
2887  */
2888 dbus_bool_t
2889 dbus_message_set_error_name (DBusMessage  *message,
2890                              const char   *error_name)
2891 {
2892   _dbus_return_val_if_fail (message != NULL, FALSE);
2893   _dbus_return_val_if_fail (!message->locked, FALSE);
2894   _dbus_return_val_if_fail (error_name == NULL ||
2895                             _dbus_check_is_valid_error_name (error_name),
2896                             FALSE);
2897
2898   return set_or_delete_string_field (message,
2899                                      DBUS_HEADER_FIELD_ERROR_NAME,
2900                                      DBUS_TYPE_STRING,
2901                                      error_name);
2902 }
2903
2904 /**
2905  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
2906  * or #NULL if none.
2907  *
2908  * The returned string becomes invalid if the message is
2909  * modified, since it points into the wire-marshaled message data.
2910  * 
2911  * @param message the message
2912  * @returns the error name (should not be freed) or #NULL
2913  */
2914 const char*
2915 dbus_message_get_error_name (DBusMessage *message)
2916 {
2917   const char *v;
2918
2919   _dbus_return_val_if_fail (message != NULL, NULL);
2920
2921   v = NULL; /* in case field doesn't exist */
2922   _dbus_header_get_field_basic (&message->header,
2923                                 DBUS_HEADER_FIELD_ERROR_NAME,
2924                                 DBUS_TYPE_STRING,
2925                                 &v);
2926   return v;
2927 }
2928
2929 /**
2930  * Sets the message's destination. The destination is the name of
2931  * another connection on the bus and may be either the unique name
2932  * assigned by the bus to each connection, or a well-known name
2933  * specified in advance.
2934  *
2935  * The destination name must contain only valid characters as defined
2936  * in the D-Bus specification.
2937  * 
2938  * @param message the message
2939  * @param destination the destination name or #NULL to unset
2940  * @returns #FALSE if not enough memory
2941  */
2942 dbus_bool_t
2943 dbus_message_set_destination (DBusMessage  *message,
2944                               const char   *destination)
2945 {
2946   _dbus_return_val_if_fail (message != NULL, FALSE);
2947   _dbus_return_val_if_fail (!message->locked, FALSE);
2948   _dbus_return_val_if_fail (destination == NULL ||
2949                             _dbus_check_is_valid_bus_name (destination),
2950                             FALSE);
2951
2952   return set_or_delete_string_field (message,
2953                                      DBUS_HEADER_FIELD_DESTINATION,
2954                                      DBUS_TYPE_STRING,
2955                                      destination);
2956 }
2957
2958 /**
2959  * Gets the destination of a message or #NULL if there is none set.
2960  *
2961  * The returned string becomes invalid if the message is
2962  * modified, since it points into the wire-marshaled message data.
2963  *
2964  * @param message the message
2965  * @returns the message destination (should not be freed) or #NULL
2966  */
2967 const char*
2968 dbus_message_get_destination (DBusMessage *message)
2969 {
2970   const char *v;
2971
2972   _dbus_return_val_if_fail (message != NULL, NULL);
2973
2974   v = NULL; /* in case field doesn't exist */
2975   _dbus_header_get_field_basic (&message->header,
2976                                 DBUS_HEADER_FIELD_DESTINATION,
2977                                 DBUS_TYPE_STRING,
2978                                 &v);
2979   return v;
2980 }
2981
2982 /**
2983  * Sets the message sender.
2984  *
2985  * The sender must be a valid bus name as defined in the D-Bus
2986  * specification.
2987  *
2988  * Usually you don't want to call this. The message bus daemon will
2989  * call it to set the origin of each message. If you aren't implementing
2990  * a message bus daemon you shouldn't need to set the sender.
2991  *
2992  * @param message the message
2993  * @param sender the sender or #NULL to unset
2994  * @returns #FALSE if not enough memory
2995  */
2996 dbus_bool_t
2997 dbus_message_set_sender (DBusMessage  *message,
2998                          const char   *sender)
2999 {
3000   _dbus_return_val_if_fail (message != NULL, FALSE);
3001   _dbus_return_val_if_fail (!message->locked, FALSE);
3002   _dbus_return_val_if_fail (sender == NULL ||
3003                             _dbus_check_is_valid_bus_name (sender),
3004                             FALSE);
3005
3006   return set_or_delete_string_field (message,
3007                                      DBUS_HEADER_FIELD_SENDER,
3008                                      DBUS_TYPE_STRING,
3009                                      sender);
3010 }
3011
3012 /**
3013  * Gets the unique name of the connection which originated this
3014  * message, or #NULL if unknown or inapplicable. The sender is filled
3015  * in by the message bus.
3016  *
3017  * Note, the returned sender is always the unique bus name.
3018  * Connections may own multiple other bus names, but those
3019  * are not found in the sender field.
3020  * 
3021  * The returned string becomes invalid if the message is
3022  * modified, since it points into the wire-marshaled message data.
3023  *
3024  * @param message the message
3025  * @returns the unique name of the sender or #NULL
3026  */
3027 const char*
3028 dbus_message_get_sender (DBusMessage *message)
3029 {
3030   const char *v;
3031
3032   _dbus_return_val_if_fail (message != NULL, NULL);
3033
3034   v = NULL; /* in case field doesn't exist */
3035   _dbus_header_get_field_basic (&message->header,
3036                                 DBUS_HEADER_FIELD_SENDER,
3037                                 DBUS_TYPE_STRING,
3038                                 &v);
3039   return v;
3040 }
3041
3042 /**
3043  * Gets the type signature of the message, i.e. the arguments in the
3044  * message payload. The signature includes only "in" arguments for
3045  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
3046  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
3047  * what you might expect (that is, it does not include the signature of the
3048  * entire C++-style method).
3049  *
3050  * The signature is a string made up of type codes such as
3051  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
3052  * the value of #DBUS_TYPE_INVALID).
3053  *
3054  * The returned string becomes invalid if the message is
3055  * modified, since it points into the wire-marshaled message data.
3056  *
3057  * @param message the message
3058  * @returns the type signature
3059  */
3060 const char*
3061 dbus_message_get_signature (DBusMessage *message)
3062 {
3063   const DBusString *type_str;
3064   int type_pos;
3065
3066   _dbus_return_val_if_fail (message != NULL, NULL);
3067
3068   get_const_signature (&message->header, &type_str, &type_pos);
3069
3070   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
3071 }
3072
3073 static dbus_bool_t
3074 _dbus_message_has_type_interface_member (DBusMessage *message,
3075                                          int          type,
3076                                          const char  *interface,
3077                                          const char  *member)
3078 {
3079   const char *n;
3080
3081   _dbus_assert (message != NULL);
3082   _dbus_assert (interface != NULL);
3083   _dbus_assert (member != NULL);
3084
3085   if (dbus_message_get_type (message) != type)
3086     return FALSE;
3087
3088   /* Optimize by checking the short member name first
3089    * instead of the longer interface name
3090    */
3091
3092   n = dbus_message_get_member (message);
3093
3094   if (n && strcmp (n, member) == 0)
3095     {
3096       n = dbus_message_get_interface (message);
3097
3098       if (n == NULL || strcmp (n, interface) == 0)
3099         return TRUE;
3100     }
3101
3102   return FALSE;
3103 }
3104
3105 /**
3106  * Checks whether the message is a method call with the given
3107  * interface and member fields.  If the message is not
3108  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
3109  * member field, returns #FALSE. If the interface field is missing,
3110  * then it will be assumed equal to the provided interface.  The D-Bus
3111  * protocol allows method callers to leave out the interface name.
3112  *
3113  * @param message the message
3114  * @param interface the name to check (must not be #NULL)
3115  * @param method the name to check (must not be #NULL)
3116  *
3117  * @returns #TRUE if the message is the specified method call
3118  */
3119 dbus_bool_t
3120 dbus_message_is_method_call (DBusMessage *message,
3121                              const char  *interface,
3122                              const char  *method)
3123 {
3124   _dbus_return_val_if_fail (message != NULL, FALSE);
3125   _dbus_return_val_if_fail (interface != NULL, FALSE);
3126   _dbus_return_val_if_fail (method != NULL, FALSE);
3127   /* don't check that interface/method are valid since it would be
3128    * expensive, and not catch many common errors
3129    */
3130
3131   return _dbus_message_has_type_interface_member (message,
3132                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
3133                                                   interface, method);
3134 }
3135
3136 /**
3137  * Checks whether the message is a signal with the given interface and
3138  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
3139  * has a different interface or member field, returns #FALSE.
3140  *
3141  * @param message the message
3142  * @param interface the name to check (must not be #NULL)
3143  * @param signal_name the name to check (must not be #NULL)
3144  *
3145  * @returns #TRUE if the message is the specified signal
3146  */
3147 dbus_bool_t
3148 dbus_message_is_signal (DBusMessage *message,
3149                         const char  *interface,
3150                         const char  *signal_name)
3151 {
3152   _dbus_return_val_if_fail (message != NULL, FALSE);
3153   _dbus_return_val_if_fail (interface != NULL, FALSE);
3154   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
3155   /* don't check that interface/name are valid since it would be
3156    * expensive, and not catch many common errors
3157    */
3158
3159   return _dbus_message_has_type_interface_member (message,
3160                                                   DBUS_MESSAGE_TYPE_SIGNAL,
3161                                                   interface, signal_name);
3162 }
3163
3164 /**
3165  * Checks whether the message is an error reply with the given error
3166  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
3167  * different name, returns #FALSE.
3168  *
3169  * @param message the message
3170  * @param error_name the name to check (must not be #NULL)
3171  *
3172  * @returns #TRUE if the message is the specified error
3173  */
3174 dbus_bool_t
3175 dbus_message_is_error (DBusMessage *message,
3176                        const char  *error_name)
3177 {
3178   const char *n;
3179
3180   _dbus_return_val_if_fail (message != NULL, FALSE);
3181   _dbus_return_val_if_fail (error_name != NULL, FALSE);
3182   /* don't check that error_name is valid since it would be expensive,
3183    * and not catch many common errors
3184    */
3185
3186   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3187     return FALSE;
3188
3189   n = dbus_message_get_error_name (message);
3190
3191   if (n && strcmp (n, error_name) == 0)
3192     return TRUE;
3193   else
3194     return FALSE;
3195 }
3196
3197 /**
3198  * Checks whether the message was sent to the given name.  If the
3199  * message has no destination specified or has a different
3200  * destination, returns #FALSE.
3201  *
3202  * @param message the message
3203  * @param name the name to check (must not be #NULL)
3204  *
3205  * @returns #TRUE if the message has the given destination name
3206  */
3207 dbus_bool_t
3208 dbus_message_has_destination (DBusMessage  *message,
3209                               const char   *name)
3210 {
3211   const char *s;
3212
3213   _dbus_return_val_if_fail (message != NULL, FALSE);
3214   _dbus_return_val_if_fail (name != NULL, FALSE);
3215   /* don't check that name is valid since it would be expensive, and
3216    * not catch many common errors
3217    */
3218
3219   s = dbus_message_get_destination (message);
3220
3221   if (s && strcmp (s, name) == 0)
3222     return TRUE;
3223   else
3224     return FALSE;
3225 }
3226
3227 /**
3228  * Checks whether the message has the given unique name as its sender.
3229  * If the message has no sender specified or has a different sender,
3230  * returns #FALSE. Note that a peer application will always have the
3231  * unique name of the connection as the sender. So you can't use this
3232  * function to see whether a sender owned a well-known name.
3233  *
3234  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
3235  * as the sender.
3236  *
3237  * @param message the message
3238  * @param name the name to check (must not be #NULL)
3239  *
3240  * @returns #TRUE if the message has the given sender
3241  */
3242 dbus_bool_t
3243 dbus_message_has_sender (DBusMessage  *message,
3244                          const char   *name)
3245 {
3246   const char *s;
3247
3248   _dbus_return_val_if_fail (message != NULL, FALSE);
3249   _dbus_return_val_if_fail (name != NULL, FALSE);
3250   /* don't check that name is valid since it would be expensive, and
3251    * not catch many common errors
3252    */
3253
3254   s = dbus_message_get_sender (message);
3255
3256   if (s && strcmp (s, name) == 0)
3257     return TRUE;
3258   else
3259     return FALSE;
3260 }
3261
3262 /**
3263  * Checks whether the message has the given signature; see
3264  * dbus_message_get_signature() for more details on what the signature
3265  * looks like.
3266  *
3267  * @param message the message
3268  * @param signature typecode array
3269  * @returns #TRUE if message has the given signature
3270 */
3271 dbus_bool_t
3272 dbus_message_has_signature (DBusMessage   *message,
3273                             const char    *signature)
3274 {
3275   const char *s;
3276
3277   _dbus_return_val_if_fail (message != NULL, FALSE);
3278   _dbus_return_val_if_fail (signature != NULL, FALSE);
3279   /* don't check that signature is valid since it would be expensive,
3280    * and not catch many common errors
3281    */
3282
3283   s = dbus_message_get_signature (message);
3284
3285   if (s && strcmp (s, signature) == 0)
3286     return TRUE;
3287   else
3288     return FALSE;
3289 }
3290
3291 /**
3292  * Sets a #DBusError based on the contents of the given
3293  * message. The error is only set if the message
3294  * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
3295  * The name of the error is set to the name of the message,
3296  * and the error message is set to the first argument
3297  * if the argument exists and is a string.
3298  *
3299  * The return value indicates whether the error was set (the error is
3300  * set if and only if the message is an error message).  So you can
3301  * check for an error reply and convert it to DBusError in one go:
3302  * @code
3303  *  if (dbus_set_error_from_message (error, reply))
3304  *    return error;
3305  *  else
3306  *    process reply;
3307  * @endcode
3308  *
3309  * @param error the error to set
3310  * @param message the message to set it from
3311  * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
3312  */
3313 dbus_bool_t
3314 dbus_set_error_from_message (DBusError   *error,
3315                              DBusMessage *message)
3316 {
3317   const char *str;
3318
3319   _dbus_return_val_if_fail (message != NULL, FALSE);
3320   _dbus_return_val_if_error_is_set (error, FALSE);
3321
3322   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3323     return FALSE;
3324
3325   str = NULL;
3326   dbus_message_get_args (message, NULL,
3327                          DBUS_TYPE_STRING, &str,
3328                          DBUS_TYPE_INVALID);
3329
3330   dbus_set_error (error, dbus_message_get_error_name (message),
3331                   str ? "%s" : NULL, str);
3332
3333   return TRUE;
3334 }
3335
3336 /** @} */
3337
3338 /**
3339  * @addtogroup DBusMessageInternals
3340  *
3341  * @{
3342  */
3343
3344 /**
3345  * The initial buffer size of the message loader.
3346  *
3347  * @todo this should be based on min header size plus some average
3348  * body size, or something. Or rather, the min header size only, if we
3349  * want to try to read only the header, store that in a DBusMessage,
3350  * then read only the body and store that, etc., depends on
3351  * how we optimize _dbus_message_loader_get_buffer() and what
3352  * the exact message format is.
3353  */
3354 #define INITIAL_LOADER_DATA_LEN 32
3355
3356 /**
3357  * Creates a new message loader. Returns #NULL if memory can't
3358  * be allocated.
3359  *
3360  * @returns new loader, or #NULL.
3361  */
3362 DBusMessageLoader*
3363 _dbus_message_loader_new (void)
3364 {
3365   DBusMessageLoader *loader;
3366
3367   loader = dbus_new0 (DBusMessageLoader, 1);
3368   if (loader == NULL)
3369     return NULL;
3370   
3371   loader->refcount = 1;
3372
3373   loader->corrupted = FALSE;
3374   loader->corruption_reason = DBUS_VALID;
3375
3376   /* this can be configured by the app, but defaults to the protocol max */
3377   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3378
3379   if (!_dbus_string_init (&loader->data))
3380     {
3381       dbus_free (loader);
3382       return NULL;
3383     }
3384
3385   /* preallocate the buffer for speed, ignore failure */
3386   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
3387   _dbus_string_set_length (&loader->data, 0);
3388
3389   return loader;
3390 }
3391
3392 /**
3393  * Increments the reference count of the loader.
3394  *
3395  * @param loader the loader.
3396  * @returns the loader
3397  */
3398 DBusMessageLoader *
3399 _dbus_message_loader_ref (DBusMessageLoader *loader)
3400 {
3401   loader->refcount += 1;
3402
3403   return loader;
3404 }
3405
3406 /**
3407  * Decrements the reference count of the loader and finalizes the
3408  * loader when the count reaches zero.
3409  *
3410  * @param loader the loader.
3411  */
3412 void
3413 _dbus_message_loader_unref (DBusMessageLoader *loader)
3414 {
3415   loader->refcount -= 1;
3416   if (loader->refcount == 0)
3417     {
3418       _dbus_list_foreach (&loader->messages,
3419                           (DBusForeachFunction) dbus_message_unref,
3420                           NULL);
3421       _dbus_list_clear (&loader->messages);
3422       _dbus_string_free (&loader->data);
3423       dbus_free (loader);
3424     }
3425 }
3426
3427 /**
3428  * Gets the buffer to use for reading data from the network.  Network
3429  * data is read directly into an allocated buffer, which is then used
3430  * in the DBusMessage, to avoid as many extra memcpy's as possible.
3431  * The buffer must always be returned immediately using
3432  * _dbus_message_loader_return_buffer(), even if no bytes are
3433  * successfully read.
3434  *
3435  * @todo this function can be a lot more clever. For example
3436  * it can probably always return a buffer size to read exactly
3437  * the body of the next message, thus avoiding any memory wastage
3438  * or reallocs.
3439  *
3440  * @todo we need to enforce a max length on strings in header fields.
3441  *
3442  * @param loader the message loader.
3443  * @param buffer the buffer
3444  */
3445 void
3446 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
3447                                  DBusString        **buffer)
3448 {
3449   _dbus_assert (!loader->buffer_outstanding);
3450
3451   *buffer = &loader->data;
3452
3453   loader->buffer_outstanding = TRUE;
3454 }
3455
3456 /**
3457  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
3458  * indicating to the loader how many bytes of the buffer were filled
3459  * in. This function must always be called, even if no bytes were
3460  * successfully read.
3461  *
3462  * @param loader the loader.
3463  * @param buffer the buffer.
3464  * @param bytes_read number of bytes that were read into the buffer.
3465  */
3466 void
3467 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
3468                                     DBusString         *buffer,
3469                                     int                 bytes_read)
3470 {
3471   _dbus_assert (loader->buffer_outstanding);
3472   _dbus_assert (buffer == &loader->data);
3473
3474   loader->buffer_outstanding = FALSE;
3475 }
3476
3477 /*
3478  * FIXME when we move the header out of the buffer, that memmoves all
3479  * buffered messages. Kind of crappy.
3480  *
3481  * Also we copy the header and body, which is kind of crappy.  To
3482  * avoid this, we have to allow header and body to be in a single
3483  * memory block, which is good for messages we read and bad for
3484  * messages we are creating. But we could move_len() the buffer into
3485  * this single memory block, and move_len() will just swap the buffers
3486  * if you're moving the entire buffer replacing the dest string.
3487  *
3488  * We could also have the message loader tell the transport how many
3489  * bytes to read; so it would first ask for some arbitrary number like
3490  * 256, then if the message was incomplete it would use the
3491  * header/body len to ask for exactly the size of the message (or
3492  * blocks the size of a typical kernel buffer for the socket). That
3493  * way we don't get trailing bytes in the buffer that have to be
3494  * memmoved. Though I suppose we also don't have a chance of reading a
3495  * bunch of small messages at once, so the optimization may be stupid.
3496  *
3497  * Another approach would be to keep a "start" index into
3498  * loader->data and only delete it occasionally, instead of after
3499  * each message is loaded.
3500  *
3501  * load_message() returns FALSE if not enough memory OR the loader was corrupted
3502  */
3503 static dbus_bool_t
3504 load_message (DBusMessageLoader *loader,
3505               DBusMessage       *message,
3506               int                byte_order,
3507               int                fields_array_len,
3508               int                header_len,
3509               int                body_len)
3510 {
3511   dbus_bool_t oom;
3512   DBusValidity validity;
3513   const DBusString *type_str;
3514   int type_pos;
3515   DBusValidationMode mode;
3516
3517   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
3518   
3519   oom = FALSE;
3520
3521 #if 0
3522   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
3523 #endif
3524
3525   /* 1. VALIDATE AND COPY OVER HEADER */
3526   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
3527   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
3528
3529   if (!_dbus_header_load (&message->header,
3530                           mode,
3531                           &validity,
3532                           byte_order,
3533                           fields_array_len,
3534                           header_len,
3535                           body_len,
3536                           &loader->data, 0,
3537                           _dbus_string_get_length (&loader->data)))
3538     {
3539       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
3540
3541       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
3542          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
3543       _dbus_assert (validity != DBUS_VALID);
3544
3545       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3546         oom = TRUE;
3547       else
3548         {
3549           loader->corrupted = TRUE;
3550           loader->corruption_reason = validity;
3551         }
3552       goto failed;
3553     }
3554
3555   _dbus_assert (validity == DBUS_VALID);
3556
3557   message->byte_order = byte_order;
3558
3559   /* 2. VALIDATE BODY */
3560   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
3561     {
3562       get_const_signature (&message->header, &type_str, &type_pos);
3563       
3564       /* Because the bytes_remaining arg is NULL, this validates that the
3565        * body is the right length
3566        */
3567       validity = _dbus_validate_body_with_reason (type_str,
3568                                                   type_pos,
3569                                                   byte_order,
3570                                                   NULL,
3571                                                   &loader->data,
3572                                                   header_len,
3573                                                   body_len);
3574       if (validity != DBUS_VALID)
3575         {
3576           _dbus_verbose ("Failed to validate message body code %d\n", validity);
3577
3578           loader->corrupted = TRUE;
3579           loader->corruption_reason = validity;
3580           
3581           goto failed;
3582         }
3583     }
3584
3585   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
3586
3587   if (!_dbus_list_append (&loader->messages, message))
3588     {
3589       _dbus_verbose ("Failed to append new message to loader queue\n");
3590       oom = TRUE;
3591       goto failed;
3592     }
3593
3594   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
3595   _dbus_assert (_dbus_string_get_length (&loader->data) >=
3596                 (header_len + body_len));
3597
3598   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
3599     {
3600       _dbus_verbose ("Failed to move body into new message\n");
3601       oom = TRUE;
3602       goto failed;
3603     }
3604
3605   _dbus_string_delete (&loader->data, 0, header_len + body_len);
3606
3607   /* don't waste more than 2k of memory */
3608   _dbus_string_compact (&loader->data, 2048);
3609
3610   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
3611   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
3612
3613   _dbus_verbose ("Loaded message %p\n", message);
3614
3615   _dbus_assert (!oom);
3616   _dbus_assert (!loader->corrupted);
3617   _dbus_assert (loader->messages != NULL);
3618   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3619
3620   return TRUE;
3621
3622  failed:
3623
3624   /* Clean up */
3625
3626   /* does nothing if the message isn't in the list */
3627   _dbus_list_remove_last (&loader->messages, message);
3628   
3629   if (oom)
3630     _dbus_assert (!loader->corrupted);
3631   else
3632     _dbus_assert (loader->corrupted);
3633
3634   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
3635
3636   return FALSE;
3637 }
3638
3639 /**
3640  * Converts buffered data into messages, if we have enough data.  If
3641  * we don't have enough data, does nothing.
3642  *
3643  * @todo we need to check that the proper named header fields exist
3644  * for each message type.
3645  *
3646  * @todo If a message has unknown type, we should probably eat it
3647  * right here rather than passing it out to applications.  However
3648  * it's not an error to see messages of unknown type.
3649  *
3650  * @param loader the loader.
3651  * @returns #TRUE if we had enough memory to finish.
3652  */
3653 dbus_bool_t
3654 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
3655 {
3656   while (!loader->corrupted &&
3657          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
3658     {
3659       DBusValidity validity;
3660       int byte_order, fields_array_len, header_len, body_len;
3661
3662       if (_dbus_header_have_message_untrusted (loader->max_message_size,
3663                                                &validity,
3664                                                &byte_order,
3665                                                &fields_array_len,
3666                                                &header_len,
3667                                                &body_len,
3668                                                &loader->data, 0,
3669                                                _dbus_string_get_length (&loader->data)))
3670         {
3671           DBusMessage *message;
3672
3673           _dbus_assert (validity == DBUS_VALID);
3674
3675           message = dbus_message_new_empty_header ();
3676           if (message == NULL)
3677             return FALSE;
3678
3679           if (!load_message (loader, message,
3680                              byte_order, fields_array_len,
3681                              header_len, body_len))
3682             {
3683               dbus_message_unref (message);
3684               /* load_message() returns false if corrupted or OOM; if
3685                * corrupted then return TRUE for not OOM
3686                */
3687               return loader->corrupted;
3688             }
3689
3690           _dbus_assert (loader->messages != NULL);
3691           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3692         }
3693       else
3694         {
3695           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
3696                          validity);
3697           if (validity != DBUS_VALID)
3698             {
3699               loader->corrupted = TRUE;
3700               loader->corruption_reason = validity;
3701             }
3702           return TRUE;
3703         }
3704     }
3705
3706   return TRUE;
3707 }
3708
3709 /**
3710  * Peeks at first loaded message, returns #NULL if no messages have
3711  * been queued.
3712  *
3713  * @param loader the loader.
3714  * @returns the next message, or #NULL if none.
3715  */
3716 DBusMessage*
3717 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
3718 {
3719   if (loader->messages)
3720     return loader->messages->data;
3721   else
3722     return NULL;
3723 }
3724
3725 /**
3726  * Pops a loaded message (passing ownership of the message
3727  * to the caller). Returns #NULL if no messages have been
3728  * queued.
3729  *
3730  * @param loader the loader.
3731  * @returns the next message, or #NULL if none.
3732  */
3733 DBusMessage*
3734 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
3735 {
3736   return _dbus_list_pop_first (&loader->messages);
3737 }
3738
3739 /**
3740  * Pops a loaded message inside a list link (passing ownership of the
3741  * message and link to the caller). Returns #NULL if no messages have
3742  * been loaded.
3743  *
3744  * @param loader the loader.
3745  * @returns the next message link, or #NULL if none.
3746  */
3747 DBusList*
3748 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
3749 {
3750   return _dbus_list_pop_first_link (&loader->messages);
3751 }
3752
3753 /**
3754  * Returns a popped message link, used to undo a pop.
3755  *
3756  * @param loader the loader
3757  * @param link the link with a message in it
3758  */
3759 void
3760 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
3761                                            DBusList           *link)
3762 {
3763   _dbus_list_prepend_link (&loader->messages, link);
3764 }
3765
3766 /**
3767  * Checks whether the loader is confused due to bad data.
3768  * If messages are received that are invalid, the
3769  * loader gets confused and gives up permanently.
3770  * This state is called "corrupted."
3771  *
3772  * @param loader the loader
3773  * @returns #TRUE if the loader is hosed.
3774  */
3775 dbus_bool_t
3776 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
3777 {
3778   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
3779                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
3780   return loader->corrupted;
3781 }
3782
3783 /**
3784  * Sets the maximum size message we allow.
3785  *
3786  * @param loader the loader
3787  * @param size the max message size in bytes
3788  */
3789 void
3790 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
3791                                            long                size)
3792 {
3793   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
3794     {
3795       _dbus_verbose ("clamping requested max message size %ld to %d\n",
3796                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
3797       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3798     }
3799   loader->max_message_size = size;
3800 }
3801
3802 /**
3803  * Gets the maximum allowed message size in bytes.
3804  *
3805  * @param loader the loader
3806  * @returns max size in bytes
3807  */
3808 long
3809 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
3810 {
3811   return loader->max_message_size;
3812 }
3813
3814 static DBusDataSlotAllocator slot_allocator;
3815 _DBUS_DEFINE_GLOBAL_LOCK (message_slots);
3816
3817 /**
3818  * Allocates an integer ID to be used for storing application-specific
3819  * data on any DBusMessage. The allocated ID may then be used
3820  * with dbus_message_set_data() and dbus_message_get_data().
3821  * The passed-in slot must be initialized to -1, and is filled in
3822  * with the slot ID. If the passed-in slot is not -1, it's assumed
3823  * to be already allocated, and its refcount is incremented.
3824  *
3825  * The allocated slot is global, i.e. all DBusMessage objects will
3826  * have a slot with the given integer ID reserved.
3827  *
3828  * @param slot_p address of a global variable storing the slot
3829  * @returns #FALSE on failure (no memory)
3830  */
3831 dbus_bool_t
3832 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
3833 {
3834   return _dbus_data_slot_allocator_alloc (&slot_allocator,
3835                                           &_DBUS_LOCK_NAME (message_slots),
3836                                           slot_p);
3837 }
3838
3839 /**
3840  * Deallocates a global ID for message data slots.
3841  * dbus_message_get_data() and dbus_message_set_data() may no
3842  * longer be used with this slot.  Existing data stored on existing
3843  * DBusMessage objects will be freed when the message is
3844  * finalized, but may not be retrieved (and may only be replaced if
3845  * someone else reallocates the slot).  When the refcount on the
3846  * passed-in slot reaches 0, it is set to -1.
3847  *
3848  * @param slot_p address storing the slot to deallocate
3849  */
3850 void
3851 dbus_message_free_data_slot (dbus_int32_t *slot_p)
3852 {
3853   _dbus_return_if_fail (*slot_p >= 0);
3854
3855   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
3856 }
3857
3858 /**
3859  * Stores a pointer on a DBusMessage, along
3860  * with an optional function to be used for freeing
3861  * the data when the data is set again, or when
3862  * the message is finalized. The slot number
3863  * must have been allocated with dbus_message_allocate_data_slot().
3864  *
3865  * @param message the message
3866  * @param slot the slot number
3867  * @param data the data to store
3868  * @param free_data_func finalizer function for the data
3869  * @returns #TRUE if there was enough memory to store the data
3870  */
3871 dbus_bool_t
3872 dbus_message_set_data (DBusMessage     *message,
3873                        dbus_int32_t     slot,
3874                        void            *data,
3875                        DBusFreeFunction free_data_func)
3876 {
3877   DBusFreeFunction old_free_func;
3878   void *old_data;
3879   dbus_bool_t retval;
3880
3881   _dbus_return_val_if_fail (message != NULL, FALSE);
3882   _dbus_return_val_if_fail (slot >= 0, FALSE);
3883
3884   retval = _dbus_data_slot_list_set (&slot_allocator,
3885                                      &message->slot_list,
3886                                      slot, data, free_data_func,
3887                                      &old_free_func, &old_data);
3888
3889   if (retval)
3890     {
3891       /* Do the actual free outside the message lock */
3892       if (old_free_func)
3893         (* old_free_func) (old_data);
3894     }
3895
3896   return retval;
3897 }
3898
3899 /**
3900  * Retrieves data previously set with dbus_message_set_data().
3901  * The slot must still be allocated (must not have been freed).
3902  *
3903  * @param message the message
3904  * @param slot the slot to get data from
3905  * @returns the data, or #NULL if not found
3906  */
3907 void*
3908 dbus_message_get_data (DBusMessage   *message,
3909                        dbus_int32_t   slot)
3910 {
3911   void *res;
3912
3913   _dbus_return_val_if_fail (message != NULL, NULL);
3914
3915   res = _dbus_data_slot_list_get (&slot_allocator,
3916                                   &message->slot_list,
3917                                   slot);
3918
3919   return res;
3920 }
3921
3922 /**
3923  * Utility function to convert a machine-readable (not translated)
3924  * string into a D-Bus message type.
3925  *
3926  * @code
3927  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
3928  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
3929  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
3930  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
3931  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
3932  * @endcode
3933  *
3934  */
3935 int
3936 dbus_message_type_from_string (const char *type_str)
3937 {
3938   if (strcmp (type_str, "method_call") == 0)
3939     return DBUS_MESSAGE_TYPE_METHOD_CALL;
3940   if (strcmp (type_str, "method_return") == 0)
3941     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
3942   else if (strcmp (type_str, "signal") == 0)
3943     return DBUS_MESSAGE_TYPE_SIGNAL;
3944   else if (strcmp (type_str, "error") == 0)
3945     return DBUS_MESSAGE_TYPE_ERROR;
3946   else
3947     return DBUS_MESSAGE_TYPE_INVALID;
3948 }
3949
3950 /**
3951  * Utility function to convert a D-Bus message type into a
3952  * machine-readable string (not translated).
3953  *
3954  * @code
3955  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
3956  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
3957  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
3958  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
3959  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
3960  * @endcode
3961  *
3962  */
3963 const char *
3964 dbus_message_type_to_string (int type)
3965 {
3966   switch (type)
3967     {
3968     case DBUS_MESSAGE_TYPE_METHOD_CALL:
3969       return "method_call";
3970     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
3971       return "method_return";
3972     case DBUS_MESSAGE_TYPE_SIGNAL:
3973       return "signal";
3974     case DBUS_MESSAGE_TYPE_ERROR:
3975       return "error";
3976     default:
3977       return "invalid";
3978     }
3979 }
3980
3981 /**
3982  * Turn a DBusMessage into the marshalled form as described in the D-Bus
3983  * specification.
3984  *
3985  * Generally, this function is only useful for encapsulating D-Bus messages in
3986  * a different protocol.
3987  *
3988  * @param msg the DBusMessage
3989  * @param marshalled_data_p the location to save the marshalled form to
3990  * @param len_p the location to save the length of the marshalled form to
3991  * @returns #FALSE if there was not enough memory
3992  */
3993 dbus_bool_t
3994 dbus_message_marshal (DBusMessage  *msg,
3995                       char        **marshalled_data_p,
3996                       int          *len_p)
3997 {
3998   DBusString tmp;
3999
4000   _dbus_return_val_if_fail (msg != NULL, FALSE);
4001   _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
4002   _dbus_return_val_if_fail (len_p != NULL, FALSE);
4003   
4004   if (!_dbus_string_init (&tmp))
4005     return FALSE;
4006
4007   if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
4008     goto fail;
4009
4010   *len_p = _dbus_string_get_length (&tmp);
4011
4012   if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
4013     goto fail;
4014
4015   *len_p = _dbus_string_get_length (&tmp);
4016
4017   if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
4018     goto fail;
4019
4020   _dbus_string_free (&tmp);
4021   return TRUE;
4022
4023  fail:
4024   _dbus_string_free (&tmp);
4025   return FALSE;
4026 }
4027
4028 /**
4029  * Demarshal a D-Bus message from the format described in the D-Bus
4030  * specification.
4031  *
4032  * Generally, this function is only useful for encapsulating D-Bus messages in
4033  * a different protocol.
4034  *
4035  * @param str the marshalled DBusMessage
4036  * @param len the length of str
4037  * @param error the location to save errors to
4038  * @returns #NULL if there was an error
4039  */
4040 DBusMessage *
4041 dbus_message_demarshal (const char *str,
4042                         int         len,
4043                         DBusError  *error)
4044 {
4045   DBusMessageLoader *loader;
4046   DBusString *buffer;
4047   DBusMessage *msg;
4048
4049   _dbus_return_val_if_fail (str != NULL, NULL);
4050
4051   loader = _dbus_message_loader_new ();
4052
4053   if (loader == NULL)
4054     return NULL;
4055
4056   _dbus_message_loader_get_buffer (loader, &buffer);
4057   _dbus_string_append_len (buffer, str, len);
4058   _dbus_message_loader_return_buffer (loader, buffer, len);
4059
4060   if (!_dbus_message_loader_queue_messages (loader))
4061     goto fail_oom;
4062
4063   if (_dbus_message_loader_get_is_corrupted (loader))
4064     goto fail_corrupt;
4065
4066   msg = _dbus_message_loader_pop_message (loader);
4067
4068   if (!msg)
4069     goto fail_oom;
4070
4071   _dbus_message_loader_unref (loader);
4072   return msg;
4073
4074  fail_corrupt:
4075   dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted");
4076   _dbus_message_loader_unref (loader);
4077   return NULL;
4078
4079  fail_oom:
4080   _DBUS_SET_OOM (error);
4081   _dbus_message_loader_unref (loader);
4082   return NULL;
4083 }
4084
4085 /**
4086  * Returns the number of bytes required to be in the buffer to demarshal a
4087  * D-Bus message.
4088  *
4089  * Generally, this function is only useful for encapsulating D-Bus messages in
4090  * a different protocol.
4091  *
4092  * @param str data to be marshalled
4093  * @param len the length of str
4094  * @param error the location to save errors to
4095  * @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
4096  * 
4097  */
4098 int 
4099 dbus_message_demarshal_bytes_needed(const char *buf, 
4100                                     int         len)
4101 {
4102   DBusString str;
4103   int byte_order, fields_array_len, header_len, body_len;
4104   DBusValidity validity = DBUS_VALID;
4105   int have_message;
4106
4107   if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
4108     return 0;
4109
4110   if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
4111     len = DBUS_MAXIMUM_MESSAGE_LENGTH;
4112   _dbus_string_init_const_len (&str, buf, len);
4113   
4114   validity = DBUS_VALID;
4115   have_message
4116     = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
4117                                           &validity, &byte_order,
4118                                           &fields_array_len,
4119                                           &header_len,
4120                                           &body_len,
4121                                           &str, 0,
4122                                           len);
4123   _dbus_string_free (&str);
4124
4125   if (validity == DBUS_VALID)
4126     {
4127       _dbus_assert(have_message);
4128       return header_len + body_len;
4129     }
4130   else
4131     {
4132       return -1; /* broken! */
4133     }
4134 }
4135
4136 /** @} */
4137
4138 /* tests in dbus-message-util.c */