Merge branch 'master' of drop.maemo.org:/git/monky
[monky] / src / 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 #ifndef DBUS_DISABLE_CHECKS
2204 static dbus_bool_t
2205 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
2206 {
2207   if (!_dbus_message_iter_check (iter))
2208     return FALSE;
2209
2210   if (iter->message->locked)
2211     {
2212       _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)\n");
2213       return FALSE;
2214     }
2215
2216   return TRUE;
2217 }
2218 #endif /* DBUS_DISABLE_CHECKS */
2219
2220 /**
2221  * Appends a basic-typed value to the message. The basic types are the
2222  * non-container types such as integer and string.
2223  *
2224  * The "value" argument should be the address of a basic-typed value.
2225  * So for string, const char**. For integer, dbus_int32_t*.
2226  *
2227  * @todo If this fails due to lack of memory, the message is hosed and
2228  * you have to start over building the whole message.
2229  *
2230  * @param iter the append iterator
2231  * @param type the type of the value
2232  * @param value the address of the value
2233  * @returns #FALSE if not enough memory
2234  */
2235 dbus_bool_t
2236 dbus_message_iter_append_basic (DBusMessageIter *iter,
2237                                 int              type,
2238                                 const void      *value)
2239 {
2240   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2241   dbus_bool_t ret;
2242
2243   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2244   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2245   _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
2246   _dbus_return_val_if_fail (value != NULL, FALSE);
2247
2248   if (!_dbus_message_iter_open_signature (real))
2249     return FALSE;
2250
2251   ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
2252
2253   if (!_dbus_message_iter_close_signature (real))
2254     ret = FALSE;
2255
2256   return ret;
2257 }
2258
2259 /**
2260  * Appends a block of fixed-length values to an array. The
2261  * fixed-length types are all basic types that are not string-like. So
2262  * int32, double, bool, etc. You must call
2263  * dbus_message_iter_open_container() to open an array of values
2264  * before calling this function. You may call this function multiple
2265  * times (and intermixed with calls to
2266  * dbus_message_iter_append_basic()) for the same array.
2267  *
2268  * The "value" argument should be the address of the array.  So for
2269  * integer, "dbus_int32_t**" is expected for example.
2270  *
2271  * @warning in C, given "int array[]", "&array == array" (the
2272  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
2273  * So if you're using an array instead of a pointer you have to create
2274  * a pointer variable, assign the array to it, then take the address
2275  * of the pointer variable.
2276  * @code
2277  * const dbus_int32_t array[] = { 1, 2, 3 };
2278  * const dbus_int32_t *v_ARRAY = array;
2279  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
2280  *   fprintf (stderr, "No memory!\n");
2281  * @endcode
2282  * For strings it works to write const char *array = "Hello" and then
2283  * use &array though.
2284  *
2285  * @todo If this fails due to lack of memory, the message is hosed and
2286  * you have to start over building the whole message.
2287  *
2288  * @param iter the append iterator
2289  * @param element_type the type of the array elements
2290  * @param value the address of the array
2291  * @param n_elements the number of elements to append
2292  * @returns #FALSE if not enough memory
2293  */
2294 dbus_bool_t
2295 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
2296                                       int              element_type,
2297                                       const void      *value,
2298                                       int              n_elements)
2299 {
2300   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2301   dbus_bool_t ret;
2302
2303   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2304   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2305   _dbus_return_val_if_fail (dbus_type_is_fixed (element_type), FALSE);
2306   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
2307   _dbus_return_val_if_fail (value != NULL, FALSE);
2308   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
2309   _dbus_return_val_if_fail (n_elements <=
2310                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
2311                             FALSE);
2312
2313   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
2314
2315   return ret;
2316 }
2317
2318 /**
2319  * Appends a container-typed value to the message; you are required to
2320  * append the contents of the container using the returned
2321  * sub-iterator, and then call
2322  * dbus_message_iter_close_container(). Container types are for
2323  * example struct, variant, and array. For variants, the
2324  * contained_signature should be the type of the single value inside
2325  * the variant. For structs and dict entries, contained_signature
2326  * should be #NULL; it will be set to whatever types you write into
2327  * the struct.  For arrays, contained_signature should be the type of
2328  * the array elements.
2329  *
2330  * @todo If this fails due to lack of memory, the message is hosed and
2331  * you have to start over building the whole message.
2332  *
2333  * @param iter the append iterator
2334  * @param type the type of the value
2335  * @param contained_signature the type of container contents
2336  * @param sub sub-iterator to initialize
2337  * @returns #FALSE if not enough memory
2338  */
2339 dbus_bool_t
2340 dbus_message_iter_open_container (DBusMessageIter *iter,
2341                                   int              type,
2342                                   const char      *contained_signature,
2343                                   DBusMessageIter *sub)
2344 {
2345   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2346   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2347   DBusString contained_str;
2348
2349   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2350   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2351   _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
2352   _dbus_return_val_if_fail (sub != NULL, FALSE);
2353   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
2354                              contained_signature == NULL) ||
2355                             (type == DBUS_TYPE_DICT_ENTRY &&
2356                              contained_signature == NULL) ||
2357                             (type == DBUS_TYPE_VARIANT &&
2358                              contained_signature != NULL) ||
2359                             (type == DBUS_TYPE_ARRAY &&
2360                              contained_signature != NULL), FALSE);
2361   
2362   /* this would fail if the contained_signature is a dict entry, since
2363    * dict entries are invalid signatures standalone (they must be in
2364    * an array)
2365    */
2366   _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
2367                             (contained_signature == NULL ||
2368                              _dbus_check_is_valid_signature (contained_signature)),
2369                             FALSE);
2370
2371   if (!_dbus_message_iter_open_signature (real))
2372     return FALSE;
2373
2374   *real_sub = *real;
2375
2376   if (contained_signature != NULL)
2377     {
2378       _dbus_string_init_const (&contained_str, contained_signature);
2379
2380       return _dbus_type_writer_recurse (&real->u.writer,
2381                                         type,
2382                                         &contained_str, 0,
2383                                         &real_sub->u.writer);
2384     }
2385   else
2386     {
2387       return _dbus_type_writer_recurse (&real->u.writer,
2388                                         type,
2389                                         NULL, 0,
2390                                         &real_sub->u.writer);
2391     } 
2392 }
2393
2394
2395 /**
2396  * Closes a container-typed value appended to the message; may write
2397  * out more information to the message known only after the entire
2398  * container is written, and may free resources created by
2399  * dbus_message_iter_open_container().
2400  *
2401  * @todo If this fails due to lack of memory, the message is hosed and
2402  * you have to start over building the whole message.
2403  *
2404  * @param iter the append iterator
2405  * @param sub sub-iterator to close
2406  * @returns #FALSE if not enough memory
2407  */
2408 dbus_bool_t
2409 dbus_message_iter_close_container (DBusMessageIter *iter,
2410                                    DBusMessageIter *sub)
2411 {
2412   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2413   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2414   dbus_bool_t ret;
2415
2416   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2417   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2418   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
2419   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2420
2421   ret = _dbus_type_writer_unrecurse (&real->u.writer,
2422                                      &real_sub->u.writer);
2423
2424   if (!_dbus_message_iter_close_signature (real))
2425     ret = FALSE;
2426
2427   return ret;
2428 }
2429
2430 /**
2431  * Sets a flag indicating that the message does not want a reply; if
2432  * this flag is set, the other end of the connection may (but is not
2433  * required to) optimize by not sending method return or error
2434  * replies. If this flag is set, there is no way to know whether the
2435  * message successfully arrived at the remote end. Normally you know a
2436  * message was received when you receive the reply to it.
2437  *
2438  * The flag is #FALSE by default, that is by default the other end is
2439  * required to reply.
2440  *
2441  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
2442  * 
2443  * @param message the message
2444  * @param no_reply #TRUE if no reply is desired
2445  */
2446 void
2447 dbus_message_set_no_reply (DBusMessage *message,
2448                            dbus_bool_t  no_reply)
2449 {
2450   _dbus_return_if_fail (message != NULL);
2451   _dbus_return_if_fail (!message->locked);
2452
2453   _dbus_header_toggle_flag (&message->header,
2454                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
2455                             no_reply);
2456 }
2457
2458 /**
2459  * Returns #TRUE if the message does not expect
2460  * a reply.
2461  *
2462  * @param message the message
2463  * @returns #TRUE if the message sender isn't waiting for a reply
2464  */
2465 dbus_bool_t
2466 dbus_message_get_no_reply (DBusMessage *message)
2467 {
2468   _dbus_return_val_if_fail (message != NULL, FALSE);
2469
2470   return _dbus_header_get_flag (&message->header,
2471                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
2472 }
2473
2474 /**
2475  * Sets a flag indicating that an owner for the destination name will
2476  * be automatically started before the message is delivered. When this
2477  * flag is set, the message is held until a name owner finishes
2478  * starting up, or fails to start up. In case of failure, the reply
2479  * will be an error.
2480  *
2481  * The flag is set to #TRUE by default, i.e. auto starting is the default.
2482  *
2483  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
2484  * 
2485  * @param message the message
2486  * @param auto_start #TRUE if auto-starting is desired
2487  */
2488 void
2489 dbus_message_set_auto_start (DBusMessage *message,
2490                              dbus_bool_t  auto_start)
2491 {
2492   _dbus_return_if_fail (message != NULL);
2493   _dbus_return_if_fail (!message->locked);
2494
2495   _dbus_header_toggle_flag (&message->header,
2496                             DBUS_HEADER_FLAG_NO_AUTO_START,
2497                             !auto_start);
2498 }
2499
2500 /**
2501  * Returns #TRUE if the message will cause an owner for
2502  * destination name to be auto-started.
2503  *
2504  * @param message the message
2505  * @returns #TRUE if the message will use auto-start
2506  */
2507 dbus_bool_t
2508 dbus_message_get_auto_start (DBusMessage *message)
2509 {
2510   _dbus_return_val_if_fail (message != NULL, FALSE);
2511
2512   return !_dbus_header_get_flag (&message->header,
2513                                  DBUS_HEADER_FLAG_NO_AUTO_START);
2514 }
2515
2516
2517 /**
2518  * Sets the object path this message is being sent to (for
2519  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
2520  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
2521  *
2522  * The path must contain only valid characters as defined
2523  * in the D-Bus specification.
2524  *
2525  * @param message the message
2526  * @param object_path the path or #NULL to unset
2527  * @returns #FALSE if not enough memory
2528  */
2529 dbus_bool_t
2530 dbus_message_set_path (DBusMessage   *message,
2531                        const char    *object_path)
2532 {
2533   _dbus_return_val_if_fail (message != NULL, FALSE);
2534   _dbus_return_val_if_fail (!message->locked, FALSE);
2535   _dbus_return_val_if_fail (object_path == NULL ||
2536                             _dbus_check_is_valid_path (object_path),
2537                             FALSE);
2538
2539   return set_or_delete_string_field (message,
2540                                      DBUS_HEADER_FIELD_PATH,
2541                                      DBUS_TYPE_OBJECT_PATH,
2542                                      object_path);
2543 }
2544
2545 /**
2546  * Gets the object path this message is being sent to (for
2547  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
2548  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2549  *
2550  * See also dbus_message_get_path_decomposed().
2551  *
2552  * The returned string becomes invalid if the message is
2553  * modified, since it points into the wire-marshaled message data.
2554  * 
2555  * @param message the message
2556  * @returns the path (should not be freed) or #NULL
2557  */
2558 const char*
2559 dbus_message_get_path (DBusMessage   *message)
2560 {
2561   const char *v;
2562
2563   _dbus_return_val_if_fail (message != NULL, NULL);
2564
2565   v = NULL; /* in case field doesn't exist */
2566   _dbus_header_get_field_basic (&message->header,
2567                                 DBUS_HEADER_FIELD_PATH,
2568                                 DBUS_TYPE_OBJECT_PATH,
2569                                 &v);
2570   return v;
2571 }
2572
2573 /**
2574  * Checks if the message has a particular object path.  The object
2575  * path is the destination object for a method call or the emitting
2576  * object for a signal.
2577  *
2578  * @param message the message
2579  * @param path the path name
2580  * @returns #TRUE if there is a path field in the header
2581  */
2582 dbus_bool_t
2583 dbus_message_has_path (DBusMessage   *message,
2584                        const char    *path)
2585 {
2586   const char *msg_path;
2587   msg_path = dbus_message_get_path (message);
2588   
2589   if (msg_path == NULL)
2590     {
2591       if (path == NULL)
2592         return TRUE;
2593       else
2594         return FALSE;
2595     }
2596
2597   if (path == NULL)
2598     return FALSE;
2599    
2600   if (strcmp (msg_path, path) == 0)
2601     return TRUE;
2602
2603   return FALSE;
2604 }
2605
2606 /**
2607  * Gets the object path this message is being sent to
2608  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2609  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
2610  * format (one array element per path component).
2611  * Free the returned array with dbus_free_string_array().
2612  *
2613  * An empty but non-NULL path array means the path "/".
2614  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
2615  * and the path "/" becomes { NULL }.
2616  *
2617  * See also dbus_message_get_path().
2618  * 
2619  * @todo this could be optimized by using the len from the message
2620  * instead of calling strlen() again
2621  *
2622  * @param message the message
2623  * @param path place to store allocated array of path components; #NULL set here if no path field exists
2624  * @returns #FALSE if no memory to allocate the array
2625  */
2626 dbus_bool_t
2627 dbus_message_get_path_decomposed (DBusMessage   *message,
2628                                   char        ***path)
2629 {
2630   const char *v;
2631
2632   _dbus_return_val_if_fail (message != NULL, FALSE);
2633   _dbus_return_val_if_fail (path != NULL, FALSE);
2634
2635   *path = NULL;
2636
2637   v = dbus_message_get_path (message);
2638   if (v != NULL)
2639     {
2640       if (!_dbus_decompose_path (v, strlen (v),
2641                                  path, NULL))
2642         return FALSE;
2643     }
2644   return TRUE;
2645 }
2646
2647 /**
2648  * Sets the interface this message is being sent to
2649  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
2650  * the interface a signal is being emitted from
2651  * (for DBUS_MESSAGE_TYPE_SIGNAL).
2652  *
2653  * The interface name must contain only valid characters as defined
2654  * in the D-Bus specification.
2655  * 
2656  * @param message the message
2657  * @param interface the interface or #NULL to unset
2658  * @returns #FALSE if not enough memory
2659  */
2660 dbus_bool_t
2661 dbus_message_set_interface (DBusMessage  *message,
2662                             const char   *interface)
2663 {
2664   _dbus_return_val_if_fail (message != NULL, FALSE);
2665   _dbus_return_val_if_fail (!message->locked, FALSE);
2666   _dbus_return_val_if_fail (interface == NULL ||
2667                             _dbus_check_is_valid_interface (interface),
2668                             FALSE);
2669
2670   return set_or_delete_string_field (message,
2671                                      DBUS_HEADER_FIELD_INTERFACE,
2672                                      DBUS_TYPE_STRING,
2673                                      interface);
2674 }
2675
2676 /**
2677  * Gets the interface this message is being sent to
2678  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2679  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
2680  * The interface name is fully-qualified (namespaced).
2681  * Returns #NULL if none.
2682  *
2683  * The returned string becomes invalid if the message is
2684  * modified, since it points into the wire-marshaled message data.
2685  *
2686  * @param message the message
2687  * @returns the message interface (should not be freed) or #NULL
2688  */
2689 const char*
2690 dbus_message_get_interface (DBusMessage *message)
2691 {
2692   const char *v;
2693
2694   _dbus_return_val_if_fail (message != NULL, NULL);
2695
2696   v = NULL; /* in case field doesn't exist */
2697   _dbus_header_get_field_basic (&message->header,
2698                                 DBUS_HEADER_FIELD_INTERFACE,
2699                                 DBUS_TYPE_STRING,
2700                                 &v);
2701   return v;
2702 }
2703
2704 /**
2705  * Checks if the message has an interface
2706  *
2707  * @param message the message
2708  * @param interface the interface name
2709  * @returns #TRUE if the interface field in the header matches
2710  */
2711 dbus_bool_t
2712 dbus_message_has_interface (DBusMessage   *message,
2713                             const char    *interface)
2714 {
2715   const char *msg_interface;
2716   msg_interface = dbus_message_get_interface (message);
2717    
2718   if (msg_interface == NULL)
2719     {
2720       if (interface == NULL)
2721         return TRUE;
2722       else
2723         return FALSE;
2724     }
2725
2726   if (interface == NULL)
2727     return FALSE;
2728      
2729   if (strcmp (msg_interface, interface) == 0)
2730     return TRUE;
2731
2732   return FALSE;
2733
2734 }
2735
2736 /**
2737  * Sets the interface member being invoked
2738  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2739  * (DBUS_MESSAGE_TYPE_SIGNAL).
2740  *
2741  * The member name must contain only valid characters as defined
2742  * in the D-Bus specification.
2743  *
2744  * @param message the message
2745  * @param member the member or #NULL to unset
2746  * @returns #FALSE if not enough memory
2747  */
2748 dbus_bool_t
2749 dbus_message_set_member (DBusMessage  *message,
2750                          const char   *member)
2751 {
2752   _dbus_return_val_if_fail (message != NULL, FALSE);
2753   _dbus_return_val_if_fail (!message->locked, FALSE);
2754   _dbus_return_val_if_fail (member == NULL ||
2755                             _dbus_check_is_valid_member (member),
2756                             FALSE);
2757
2758   return set_or_delete_string_field (message,
2759                                      DBUS_HEADER_FIELD_MEMBER,
2760                                      DBUS_TYPE_STRING,
2761                                      member);
2762 }
2763
2764 /**
2765  * Gets the interface member being invoked
2766  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
2767  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2768  *
2769  * The returned string becomes invalid if the message is
2770  * modified, since it points into the wire-marshaled message data.
2771  * 
2772  * @param message the message
2773  * @returns the member name (should not be freed) or #NULL
2774  */
2775 const char*
2776 dbus_message_get_member (DBusMessage *message)
2777 {
2778   const char *v;
2779
2780   _dbus_return_val_if_fail (message != NULL, NULL);
2781
2782   v = NULL; /* in case field doesn't exist */
2783   _dbus_header_get_field_basic (&message->header,
2784                                 DBUS_HEADER_FIELD_MEMBER,
2785                                 DBUS_TYPE_STRING,
2786                                 &v);
2787   return v;
2788 }
2789
2790 /**
2791  * Checks if the message has an interface member
2792  *
2793  * @param message the message
2794  * @param member the member name
2795  * @returns #TRUE if there is a member field in the header
2796  */
2797 dbus_bool_t
2798 dbus_message_has_member (DBusMessage   *message,
2799                          const char    *member)
2800 {
2801   const char *msg_member;
2802   msg_member = dbus_message_get_member (message);
2803  
2804   if (msg_member == NULL)
2805     {
2806       if (member == NULL)
2807         return TRUE;
2808       else
2809         return FALSE;
2810     }
2811
2812   if (member == NULL)
2813     return FALSE;
2814     
2815   if (strcmp (msg_member, member) == 0)
2816     return TRUE;
2817
2818   return FALSE;
2819
2820 }
2821
2822 /**
2823  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
2824  * The name is fully-qualified (namespaced).
2825  *
2826  * The error name must contain only valid characters as defined
2827  * in the D-Bus specification.
2828  *
2829  * @param message the message
2830  * @param error_name the name or #NULL to unset
2831  * @returns #FALSE if not enough memory
2832  */
2833 dbus_bool_t
2834 dbus_message_set_error_name (DBusMessage  *message,
2835                              const char   *error_name)
2836 {
2837   _dbus_return_val_if_fail (message != NULL, FALSE);
2838   _dbus_return_val_if_fail (!message->locked, FALSE);
2839   _dbus_return_val_if_fail (error_name == NULL ||
2840                             _dbus_check_is_valid_error_name (error_name),
2841                             FALSE);
2842
2843   return set_or_delete_string_field (message,
2844                                      DBUS_HEADER_FIELD_ERROR_NAME,
2845                                      DBUS_TYPE_STRING,
2846                                      error_name);
2847 }
2848
2849 /**
2850  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
2851  * or #NULL if none.
2852  *
2853  * The returned string becomes invalid if the message is
2854  * modified, since it points into the wire-marshaled message data.
2855  * 
2856  * @param message the message
2857  * @returns the error name (should not be freed) or #NULL
2858  */
2859 const char*
2860 dbus_message_get_error_name (DBusMessage *message)
2861 {
2862   const char *v;
2863
2864   _dbus_return_val_if_fail (message != NULL, NULL);
2865
2866   v = NULL; /* in case field doesn't exist */
2867   _dbus_header_get_field_basic (&message->header,
2868                                 DBUS_HEADER_FIELD_ERROR_NAME,
2869                                 DBUS_TYPE_STRING,
2870                                 &v);
2871   return v;
2872 }
2873
2874 /**
2875  * Sets the message's destination. The destination is the name of
2876  * another connection on the bus and may be either the unique name
2877  * assigned by the bus to each connection, or a well-known name
2878  * specified in advance.
2879  *
2880  * The destination name must contain only valid characters as defined
2881  * in the D-Bus specification.
2882  * 
2883  * @param message the message
2884  * @param destination the destination name or #NULL to unset
2885  * @returns #FALSE if not enough memory
2886  */
2887 dbus_bool_t
2888 dbus_message_set_destination (DBusMessage  *message,
2889                               const char   *destination)
2890 {
2891   _dbus_return_val_if_fail (message != NULL, FALSE);
2892   _dbus_return_val_if_fail (!message->locked, FALSE);
2893   _dbus_return_val_if_fail (destination == NULL ||
2894                             _dbus_check_is_valid_bus_name (destination),
2895                             FALSE);
2896
2897   return set_or_delete_string_field (message,
2898                                      DBUS_HEADER_FIELD_DESTINATION,
2899                                      DBUS_TYPE_STRING,
2900                                      destination);
2901 }
2902
2903 /**
2904  * Gets the destination of a message or #NULL if there is none set.
2905  *
2906  * The returned string becomes invalid if the message is
2907  * modified, since it points into the wire-marshaled message data.
2908  *
2909  * @param message the message
2910  * @returns the message destination (should not be freed) or #NULL
2911  */
2912 const char*
2913 dbus_message_get_destination (DBusMessage *message)
2914 {
2915   const char *v;
2916
2917   _dbus_return_val_if_fail (message != NULL, NULL);
2918
2919   v = NULL; /* in case field doesn't exist */
2920   _dbus_header_get_field_basic (&message->header,
2921                                 DBUS_HEADER_FIELD_DESTINATION,
2922                                 DBUS_TYPE_STRING,
2923                                 &v);
2924   return v;
2925 }
2926
2927 /**
2928  * Sets the message sender.
2929  *
2930  * The sender must be a valid bus name as defined in the D-Bus
2931  * specification.
2932  *
2933  * Usually you don't want to call this. The message bus daemon will
2934  * call it to set the origin of each message. If you aren't implementing
2935  * a message bus daemon you shouldn't need to set the sender.
2936  *
2937  * @param message the message
2938  * @param sender the sender or #NULL to unset
2939  * @returns #FALSE if not enough memory
2940  */
2941 dbus_bool_t
2942 dbus_message_set_sender (DBusMessage  *message,
2943                          const char   *sender)
2944 {
2945   _dbus_return_val_if_fail (message != NULL, FALSE);
2946   _dbus_return_val_if_fail (!message->locked, FALSE);
2947   _dbus_return_val_if_fail (sender == NULL ||
2948                             _dbus_check_is_valid_bus_name (sender),
2949                             FALSE);
2950
2951   return set_or_delete_string_field (message,
2952                                      DBUS_HEADER_FIELD_SENDER,
2953                                      DBUS_TYPE_STRING,
2954                                      sender);
2955 }
2956
2957 /**
2958  * Gets the unique name of the connection which originated this
2959  * message, or #NULL if unknown or inapplicable. The sender is filled
2960  * in by the message bus.
2961  *
2962  * Note, the returned sender is always the unique bus name.
2963  * Connections may own multiple other bus names, but those
2964  * are not found in the sender field.
2965  * 
2966  * The returned string becomes invalid if the message is
2967  * modified, since it points into the wire-marshaled message data.
2968  *
2969  * @param message the message
2970  * @returns the unique name of the sender or #NULL
2971  */
2972 const char*
2973 dbus_message_get_sender (DBusMessage *message)
2974 {
2975   const char *v;
2976
2977   _dbus_return_val_if_fail (message != NULL, NULL);
2978
2979   v = NULL; /* in case field doesn't exist */
2980   _dbus_header_get_field_basic (&message->header,
2981                                 DBUS_HEADER_FIELD_SENDER,
2982                                 DBUS_TYPE_STRING,
2983                                 &v);
2984   return v;
2985 }
2986
2987 /**
2988  * Gets the type signature of the message, i.e. the arguments in the
2989  * message payload. The signature includes only "in" arguments for
2990  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
2991  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
2992  * what you might expect (that is, it does not include the signature of the
2993  * entire C++-style method).
2994  *
2995  * The signature is a string made up of type codes such as
2996  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
2997  * the value of #DBUS_TYPE_INVALID).
2998  *
2999  * The returned string becomes invalid if the message is
3000  * modified, since it points into the wire-marshaled message data.
3001  *
3002  * @param message the message
3003  * @returns the type signature
3004  */
3005 const char*
3006 dbus_message_get_signature (DBusMessage *message)
3007 {
3008   const DBusString *type_str;
3009   int type_pos;
3010
3011   _dbus_return_val_if_fail (message != NULL, NULL);
3012
3013   get_const_signature (&message->header, &type_str, &type_pos);
3014
3015   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
3016 }
3017
3018 static dbus_bool_t
3019 _dbus_message_has_type_interface_member (DBusMessage *message,
3020                                          int          type,
3021                                          const char  *interface,
3022                                          const char  *member)
3023 {
3024   const char *n;
3025
3026   _dbus_assert (message != NULL);
3027   _dbus_assert (interface != NULL);
3028   _dbus_assert (member != NULL);
3029
3030   if (dbus_message_get_type (message) != type)
3031     return FALSE;
3032
3033   /* Optimize by checking the short member name first
3034    * instead of the longer interface name
3035    */
3036
3037   n = dbus_message_get_member (message);
3038
3039   if (n && strcmp (n, member) == 0)
3040     {
3041       n = dbus_message_get_interface (message);
3042
3043       if (n == NULL || strcmp (n, interface) == 0)
3044         return TRUE;
3045     }
3046
3047   return FALSE;
3048 }
3049
3050 /**
3051  * Checks whether the message is a method call with the given
3052  * interface and member fields.  If the message is not
3053  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
3054  * member field, returns #FALSE. If the interface field is missing,
3055  * then it will be assumed equal to the provided interface.  The D-Bus
3056  * protocol allows method callers to leave out the interface name.
3057  *
3058  * @param message the message
3059  * @param interface the name to check (must not be #NULL)
3060  * @param method the name to check (must not be #NULL)
3061  *
3062  * @returns #TRUE if the message is the specified method call
3063  */
3064 dbus_bool_t
3065 dbus_message_is_method_call (DBusMessage *message,
3066                              const char  *interface,
3067                              const char  *method)
3068 {
3069   _dbus_return_val_if_fail (message != NULL, FALSE);
3070   _dbus_return_val_if_fail (interface != NULL, FALSE);
3071   _dbus_return_val_if_fail (method != NULL, FALSE);
3072   /* don't check that interface/method are valid since it would be
3073    * expensive, and not catch many common errors
3074    */
3075
3076   return _dbus_message_has_type_interface_member (message,
3077                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
3078                                                   interface, method);
3079 }
3080
3081 /**
3082  * Checks whether the message is a signal with the given interface and
3083  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
3084  * has a different interface or member field, returns #FALSE.
3085  *
3086  * @param message the message
3087  * @param interface the name to check (must not be #NULL)
3088  * @param signal_name the name to check (must not be #NULL)
3089  *
3090  * @returns #TRUE if the message is the specified signal
3091  */
3092 dbus_bool_t
3093 dbus_message_is_signal (DBusMessage *message,
3094                         const char  *interface,
3095                         const char  *signal_name)
3096 {
3097   _dbus_return_val_if_fail (message != NULL, FALSE);
3098   _dbus_return_val_if_fail (interface != NULL, FALSE);
3099   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
3100   /* don't check that interface/name are valid since it would be
3101    * expensive, and not catch many common errors
3102    */
3103
3104   return _dbus_message_has_type_interface_member (message,
3105                                                   DBUS_MESSAGE_TYPE_SIGNAL,
3106                                                   interface, signal_name);
3107 }
3108
3109 /**
3110  * Checks whether the message is an error reply with the given error
3111  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
3112  * different name, returns #FALSE.
3113  *
3114  * @param message the message
3115  * @param error_name the name to check (must not be #NULL)
3116  *
3117  * @returns #TRUE if the message is the specified error
3118  */
3119 dbus_bool_t
3120 dbus_message_is_error (DBusMessage *message,
3121                        const char  *error_name)
3122 {
3123   const char *n;
3124
3125   _dbus_return_val_if_fail (message != NULL, FALSE);
3126   _dbus_return_val_if_fail (error_name != NULL, FALSE);
3127   /* don't check that error_name is valid since it would be expensive,
3128    * and not catch many common errors
3129    */
3130
3131   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3132     return FALSE;
3133
3134   n = dbus_message_get_error_name (message);
3135
3136   if (n && strcmp (n, error_name) == 0)
3137     return TRUE;
3138   else
3139     return FALSE;
3140 }
3141
3142 /**
3143  * Checks whether the message was sent to the given name.  If the
3144  * message has no destination specified or has a different
3145  * destination, returns #FALSE.
3146  *
3147  * @param message the message
3148  * @param name the name to check (must not be #NULL)
3149  *
3150  * @returns #TRUE if the message has the given destination name
3151  */
3152 dbus_bool_t
3153 dbus_message_has_destination (DBusMessage  *message,
3154                               const char   *name)
3155 {
3156   const char *s;
3157
3158   _dbus_return_val_if_fail (message != NULL, FALSE);
3159   _dbus_return_val_if_fail (name != NULL, FALSE);
3160   /* don't check that name is valid since it would be expensive, and
3161    * not catch many common errors
3162    */
3163
3164   s = dbus_message_get_destination (message);
3165
3166   if (s && strcmp (s, name) == 0)
3167     return TRUE;
3168   else
3169     return FALSE;
3170 }
3171
3172 /**
3173  * Checks whether the message has the given unique name as its sender.
3174  * If the message has no sender specified or has a different sender,
3175  * returns #FALSE. Note that a peer application will always have the
3176  * unique name of the connection as the sender. So you can't use this
3177  * function to see whether a sender owned a well-known name.
3178  *
3179  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
3180  * as the sender.
3181  *
3182  * @param message the message
3183  * @param name the name to check (must not be #NULL)
3184  *
3185  * @returns #TRUE if the message has the given sender
3186  */
3187 dbus_bool_t
3188 dbus_message_has_sender (DBusMessage  *message,
3189                          const char   *name)
3190 {
3191   const char *s;
3192
3193   _dbus_return_val_if_fail (message != NULL, FALSE);
3194   _dbus_return_val_if_fail (name != NULL, FALSE);
3195   /* don't check that name is valid since it would be expensive, and
3196    * not catch many common errors
3197    */
3198
3199   s = dbus_message_get_sender (message);
3200
3201   if (s && strcmp (s, name) == 0)
3202     return TRUE;
3203   else
3204     return FALSE;
3205 }
3206
3207 /**
3208  * Checks whether the message has the given signature; see
3209  * dbus_message_get_signature() for more details on what the signature
3210  * looks like.
3211  *
3212  * @param message the message
3213  * @param signature typecode array
3214  * @returns #TRUE if message has the given signature
3215 */
3216 dbus_bool_t
3217 dbus_message_has_signature (DBusMessage   *message,
3218                             const char    *signature)
3219 {
3220   const char *s;
3221
3222   _dbus_return_val_if_fail (message != NULL, FALSE);
3223   _dbus_return_val_if_fail (signature != NULL, FALSE);
3224   /* don't check that signature is valid since it would be expensive,
3225    * and not catch many common errors
3226    */
3227
3228   s = dbus_message_get_signature (message);
3229
3230   if (s && strcmp (s, signature) == 0)
3231     return TRUE;
3232   else
3233     return FALSE;
3234 }
3235
3236 /**
3237  * Sets a #DBusError based on the contents of the given
3238  * message. The error is only set if the message
3239  * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
3240  * The name of the error is set to the name of the message,
3241  * and the error message is set to the first argument
3242  * if the argument exists and is a string.
3243  *
3244  * The return value indicates whether the error was set (the error is
3245  * set if and only if the message is an error message).  So you can
3246  * check for an error reply and convert it to DBusError in one go:
3247  * @code
3248  *  if (dbus_set_error_from_message (error, reply))
3249  *    return error;
3250  *  else
3251  *    process reply;
3252  * @endcode
3253  *
3254  * @param error the error to set
3255  * @param message the message to set it from
3256  * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
3257  */
3258 dbus_bool_t
3259 dbus_set_error_from_message (DBusError   *error,
3260                              DBusMessage *message)
3261 {
3262   const char *str;
3263
3264   _dbus_return_val_if_fail (message != NULL, FALSE);
3265   _dbus_return_val_if_error_is_set (error, FALSE);
3266
3267   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3268     return FALSE;
3269
3270   str = NULL;
3271   dbus_message_get_args (message, NULL,
3272                          DBUS_TYPE_STRING, &str,
3273                          DBUS_TYPE_INVALID);
3274
3275   dbus_set_error (error, dbus_message_get_error_name (message),
3276                   str ? "%s" : NULL, str);
3277
3278   return TRUE;
3279 }
3280
3281 /** @} */
3282
3283 /**
3284  * @addtogroup DBusMessageInternals
3285  *
3286  * @{
3287  */
3288
3289 /**
3290  * The initial buffer size of the message loader.
3291  *
3292  * @todo this should be based on min header size plus some average
3293  * body size, or something. Or rather, the min header size only, if we
3294  * want to try to read only the header, store that in a DBusMessage,
3295  * then read only the body and store that, etc., depends on
3296  * how we optimize _dbus_message_loader_get_buffer() and what
3297  * the exact message format is.
3298  */
3299 #define INITIAL_LOADER_DATA_LEN 32
3300
3301 /**
3302  * Creates a new message loader. Returns #NULL if memory can't
3303  * be allocated.
3304  *
3305  * @returns new loader, or #NULL.
3306  */
3307 DBusMessageLoader*
3308 _dbus_message_loader_new (void)
3309 {
3310   DBusMessageLoader *loader;
3311
3312   loader = dbus_new0 (DBusMessageLoader, 1);
3313   if (loader == NULL)
3314     return NULL;
3315   
3316   loader->refcount = 1;
3317
3318   loader->corrupted = FALSE;
3319   loader->corruption_reason = DBUS_VALID;
3320
3321   /* this can be configured by the app, but defaults to the protocol max */
3322   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3323
3324   if (!_dbus_string_init (&loader->data))
3325     {
3326       dbus_free (loader);
3327       return NULL;
3328     }
3329
3330   /* preallocate the buffer for speed, ignore failure */
3331   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
3332   _dbus_string_set_length (&loader->data, 0);
3333
3334   return loader;
3335 }
3336
3337 /**
3338  * Increments the reference count of the loader.
3339  *
3340  * @param loader the loader.
3341  * @returns the loader
3342  */
3343 DBusMessageLoader *
3344 _dbus_message_loader_ref (DBusMessageLoader *loader)
3345 {
3346   loader->refcount += 1;
3347
3348   return loader;
3349 }
3350
3351 /**
3352  * Decrements the reference count of the loader and finalizes the
3353  * loader when the count reaches zero.
3354  *
3355  * @param loader the loader.
3356  */
3357 void
3358 _dbus_message_loader_unref (DBusMessageLoader *loader)
3359 {
3360   loader->refcount -= 1;
3361   if (loader->refcount == 0)
3362     {
3363       _dbus_list_foreach (&loader->messages,
3364                           (DBusForeachFunction) dbus_message_unref,
3365                           NULL);
3366       _dbus_list_clear (&loader->messages);
3367       _dbus_string_free (&loader->data);
3368       dbus_free (loader);
3369     }
3370 }
3371
3372 /**
3373  * Gets the buffer to use for reading data from the network.  Network
3374  * data is read directly into an allocated buffer, which is then used
3375  * in the DBusMessage, to avoid as many extra memcpy's as possible.
3376  * The buffer must always be returned immediately using
3377  * _dbus_message_loader_return_buffer(), even if no bytes are
3378  * successfully read.
3379  *
3380  * @todo this function can be a lot more clever. For example
3381  * it can probably always return a buffer size to read exactly
3382  * the body of the next message, thus avoiding any memory wastage
3383  * or reallocs.
3384  *
3385  * @todo we need to enforce a max length on strings in header fields.
3386  *
3387  * @param loader the message loader.
3388  * @param buffer the buffer
3389  */
3390 void
3391 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
3392                                  DBusString        **buffer)
3393 {
3394   _dbus_assert (!loader->buffer_outstanding);
3395
3396   *buffer = &loader->data;
3397
3398   loader->buffer_outstanding = TRUE;
3399 }
3400
3401 /**
3402  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
3403  * indicating to the loader how many bytes of the buffer were filled
3404  * in. This function must always be called, even if no bytes were
3405  * successfully read.
3406  *
3407  * @param loader the loader.
3408  * @param buffer the buffer.
3409  * @param bytes_read number of bytes that were read into the buffer.
3410  */
3411 void
3412 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
3413                                     DBusString         *buffer,
3414                                     int                 bytes_read)
3415 {
3416   _dbus_assert (loader->buffer_outstanding);
3417   _dbus_assert (buffer == &loader->data);
3418
3419   loader->buffer_outstanding = FALSE;
3420 }
3421
3422 /*
3423  * FIXME when we move the header out of the buffer, that memmoves all
3424  * buffered messages. Kind of crappy.
3425  *
3426  * Also we copy the header and body, which is kind of crappy.  To
3427  * avoid this, we have to allow header and body to be in a single
3428  * memory block, which is good for messages we read and bad for
3429  * messages we are creating. But we could move_len() the buffer into
3430  * this single memory block, and move_len() will just swap the buffers
3431  * if you're moving the entire buffer replacing the dest string.
3432  *
3433  * We could also have the message loader tell the transport how many
3434  * bytes to read; so it would first ask for some arbitrary number like
3435  * 256, then if the message was incomplete it would use the
3436  * header/body len to ask for exactly the size of the message (or
3437  * blocks the size of a typical kernel buffer for the socket). That
3438  * way we don't get trailing bytes in the buffer that have to be
3439  * memmoved. Though I suppose we also don't have a chance of reading a
3440  * bunch of small messages at once, so the optimization may be stupid.
3441  *
3442  * Another approach would be to keep a "start" index into
3443  * loader->data and only delete it occasionally, instead of after
3444  * each message is loaded.
3445  *
3446  * load_message() returns FALSE if not enough memory OR the loader was corrupted
3447  */
3448 static dbus_bool_t
3449 load_message (DBusMessageLoader *loader,
3450               DBusMessage       *message,
3451               int                byte_order,
3452               int                fields_array_len,
3453               int                header_len,
3454               int                body_len)
3455 {
3456   dbus_bool_t oom;
3457   DBusValidity validity;
3458   const DBusString *type_str;
3459   int type_pos;
3460   DBusValidationMode mode;
3461
3462   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
3463   
3464   oom = FALSE;
3465
3466 #if 0
3467   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
3468 #endif
3469
3470   /* 1. VALIDATE AND COPY OVER HEADER */
3471   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
3472   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
3473
3474   if (!_dbus_header_load (&message->header,
3475                           mode,
3476                           &validity,
3477                           byte_order,
3478                           fields_array_len,
3479                           header_len,
3480                           body_len,
3481                           &loader->data, 0,
3482                           _dbus_string_get_length (&loader->data)))
3483     {
3484       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
3485
3486       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
3487          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
3488       _dbus_assert (validity != DBUS_VALID);
3489
3490       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3491         oom = TRUE;
3492       else
3493         {
3494           loader->corrupted = TRUE;
3495           loader->corruption_reason = validity;
3496         }
3497       goto failed;
3498     }
3499
3500   _dbus_assert (validity == DBUS_VALID);
3501
3502   message->byte_order = byte_order;
3503
3504   /* 2. VALIDATE BODY */
3505   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
3506     {
3507       get_const_signature (&message->header, &type_str, &type_pos);
3508       
3509       /* Because the bytes_remaining arg is NULL, this validates that the
3510        * body is the right length
3511        */
3512       validity = _dbus_validate_body_with_reason (type_str,
3513                                                   type_pos,
3514                                                   byte_order,
3515                                                   NULL,
3516                                                   &loader->data,
3517                                                   header_len,
3518                                                   body_len);
3519       if (validity != DBUS_VALID)
3520         {
3521           _dbus_verbose ("Failed to validate message body code %d\n", validity);
3522
3523           loader->corrupted = TRUE;
3524           loader->corruption_reason = validity;
3525           
3526           goto failed;
3527         }
3528     }
3529
3530   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
3531
3532   if (!_dbus_list_append (&loader->messages, message))
3533     {
3534       _dbus_verbose ("Failed to append new message to loader queue\n");
3535       oom = TRUE;
3536       goto failed;
3537     }
3538
3539   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
3540   _dbus_assert (_dbus_string_get_length (&loader->data) >=
3541                 (header_len + body_len));
3542
3543   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
3544     {
3545       _dbus_verbose ("Failed to move body into new message\n");
3546       oom = TRUE;
3547       goto failed;
3548     }
3549
3550   _dbus_string_delete (&loader->data, 0, header_len + body_len);
3551
3552   /* don't waste more than 2k of memory */
3553   _dbus_string_compact (&loader->data, 2048);
3554
3555   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
3556   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
3557
3558   _dbus_verbose ("Loaded message %p\n", message);
3559
3560   _dbus_assert (!oom);
3561   _dbus_assert (!loader->corrupted);
3562   _dbus_assert (loader->messages != NULL);
3563   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3564
3565   return TRUE;
3566
3567  failed:
3568
3569   /* Clean up */
3570
3571   /* does nothing if the message isn't in the list */
3572   _dbus_list_remove_last (&loader->messages, message);
3573   
3574   if (oom)
3575     _dbus_assert (!loader->corrupted);
3576   else
3577     _dbus_assert (loader->corrupted);
3578
3579   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
3580
3581   return FALSE;
3582 }
3583
3584 /**
3585  * Converts buffered data into messages, if we have enough data.  If
3586  * we don't have enough data, does nothing.
3587  *
3588  * @todo we need to check that the proper named header fields exist
3589  * for each message type.
3590  *
3591  * @todo If a message has unknown type, we should probably eat it
3592  * right here rather than passing it out to applications.  However
3593  * it's not an error to see messages of unknown type.
3594  *
3595  * @param loader the loader.
3596  * @returns #TRUE if we had enough memory to finish.
3597  */
3598 dbus_bool_t
3599 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
3600 {
3601   while (!loader->corrupted &&
3602          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
3603     {
3604       DBusValidity validity;
3605       int byte_order, fields_array_len, header_len, body_len;
3606
3607       if (_dbus_header_have_message_untrusted (loader->max_message_size,
3608                                                &validity,
3609                                                &byte_order,
3610                                                &fields_array_len,
3611                                                &header_len,
3612                                                &body_len,
3613                                                &loader->data, 0,
3614                                                _dbus_string_get_length (&loader->data)))
3615         {
3616           DBusMessage *message;
3617
3618           _dbus_assert (validity == DBUS_VALID);
3619
3620           message = dbus_message_new_empty_header ();
3621           if (message == NULL)
3622             return FALSE;
3623
3624           if (!load_message (loader, message,
3625                              byte_order, fields_array_len,
3626                              header_len, body_len))
3627             {
3628               dbus_message_unref (message);
3629               /* load_message() returns false if corrupted or OOM; if
3630                * corrupted then return TRUE for not OOM
3631                */
3632               return loader->corrupted;
3633             }
3634
3635           _dbus_assert (loader->messages != NULL);
3636           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3637         }
3638       else
3639         {
3640           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
3641                          validity);
3642           if (validity != DBUS_VALID)
3643             {
3644               loader->corrupted = TRUE;
3645               loader->corruption_reason = validity;
3646             }
3647           return TRUE;
3648         }
3649     }
3650
3651   return TRUE;
3652 }
3653
3654 /**
3655  * Peeks at first loaded message, returns #NULL if no messages have
3656  * been queued.
3657  *
3658  * @param loader the loader.
3659  * @returns the next message, or #NULL if none.
3660  */
3661 DBusMessage*
3662 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
3663 {
3664   if (loader->messages)
3665     return loader->messages->data;
3666   else
3667     return NULL;
3668 }
3669
3670 /**
3671  * Pops a loaded message (passing ownership of the message
3672  * to the caller). Returns #NULL if no messages have been
3673  * queued.
3674  *
3675  * @param loader the loader.
3676  * @returns the next message, or #NULL if none.
3677  */
3678 DBusMessage*
3679 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
3680 {
3681   return _dbus_list_pop_first (&loader->messages);
3682 }
3683
3684 /**
3685  * Pops a loaded message inside a list link (passing ownership of the
3686  * message and link to the caller). Returns #NULL if no messages have
3687  * been loaded.
3688  *
3689  * @param loader the loader.
3690  * @returns the next message link, or #NULL if none.
3691  */
3692 DBusList*
3693 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
3694 {
3695   return _dbus_list_pop_first_link (&loader->messages);
3696 }
3697
3698 /**
3699  * Returns a popped message link, used to undo a pop.
3700  *
3701  * @param loader the loader
3702  * @param link the link with a message in it
3703  */
3704 void
3705 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
3706                                            DBusList           *link)
3707 {
3708   _dbus_list_prepend_link (&loader->messages, link);
3709 }
3710
3711 /**
3712  * Checks whether the loader is confused due to bad data.
3713  * If messages are received that are invalid, the
3714  * loader gets confused and gives up permanently.
3715  * This state is called "corrupted."
3716  *
3717  * @param loader the loader
3718  * @returns #TRUE if the loader is hosed.
3719  */
3720 dbus_bool_t
3721 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
3722 {
3723   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
3724                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
3725   return loader->corrupted;
3726 }
3727
3728 /**
3729  * Sets the maximum size message we allow.
3730  *
3731  * @param loader the loader
3732  * @param size the max message size in bytes
3733  */
3734 void
3735 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
3736                                            long                size)
3737 {
3738   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
3739     {
3740       _dbus_verbose ("clamping requested max message size %ld to %d\n",
3741                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
3742       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3743     }
3744   loader->max_message_size = size;
3745 }
3746
3747 /**
3748  * Gets the maximum allowed message size in bytes.
3749  *
3750  * @param loader the loader
3751  * @returns max size in bytes
3752  */
3753 long
3754 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
3755 {
3756   return loader->max_message_size;
3757 }
3758
3759 static DBusDataSlotAllocator slot_allocator;
3760 _DBUS_DEFINE_GLOBAL_LOCK (message_slots);
3761
3762 /**
3763  * Allocates an integer ID to be used for storing application-specific
3764  * data on any DBusMessage. The allocated ID may then be used
3765  * with dbus_message_set_data() and dbus_message_get_data().
3766  * The passed-in slot must be initialized to -1, and is filled in
3767  * with the slot ID. If the passed-in slot is not -1, it's assumed
3768  * to be already allocated, and its refcount is incremented.
3769  *
3770  * The allocated slot is global, i.e. all DBusMessage objects will
3771  * have a slot with the given integer ID reserved.
3772  *
3773  * @param slot_p address of a global variable storing the slot
3774  * @returns #FALSE on failure (no memory)
3775  */
3776 dbus_bool_t
3777 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
3778 {
3779   return _dbus_data_slot_allocator_alloc (&slot_allocator,
3780                                           &_DBUS_LOCK_NAME (message_slots),
3781                                           slot_p);
3782 }
3783
3784 /**
3785  * Deallocates a global ID for message data slots.
3786  * dbus_message_get_data() and dbus_message_set_data() may no
3787  * longer be used with this slot.  Existing data stored on existing
3788  * DBusMessage objects will be freed when the message is
3789  * finalized, but may not be retrieved (and may only be replaced if
3790  * someone else reallocates the slot).  When the refcount on the
3791  * passed-in slot reaches 0, it is set to -1.
3792  *
3793  * @param slot_p address storing the slot to deallocate
3794  */
3795 void
3796 dbus_message_free_data_slot (dbus_int32_t *slot_p)
3797 {
3798   _dbus_return_if_fail (*slot_p >= 0);
3799
3800   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
3801 }
3802
3803 /**
3804  * Stores a pointer on a DBusMessage, along
3805  * with an optional function to be used for freeing
3806  * the data when the data is set again, or when
3807  * the message is finalized. The slot number
3808  * must have been allocated with dbus_message_allocate_data_slot().
3809  *
3810  * @param message the message
3811  * @param slot the slot number
3812  * @param data the data to store
3813  * @param free_data_func finalizer function for the data
3814  * @returns #TRUE if there was enough memory to store the data
3815  */
3816 dbus_bool_t
3817 dbus_message_set_data (DBusMessage     *message,
3818                        dbus_int32_t     slot,
3819                        void            *data,
3820                        DBusFreeFunction free_data_func)
3821 {
3822   DBusFreeFunction old_free_func;
3823   void *old_data;
3824   dbus_bool_t retval;
3825
3826   _dbus_return_val_if_fail (message != NULL, FALSE);
3827   _dbus_return_val_if_fail (slot >= 0, FALSE);
3828
3829   retval = _dbus_data_slot_list_set (&slot_allocator,
3830                                      &message->slot_list,
3831                                      slot, data, free_data_func,
3832                                      &old_free_func, &old_data);
3833
3834   if (retval)
3835     {
3836       /* Do the actual free outside the message lock */
3837       if (old_free_func)
3838         (* old_free_func) (old_data);
3839     }
3840
3841   return retval;
3842 }
3843
3844 /**
3845  * Retrieves data previously set with dbus_message_set_data().
3846  * The slot must still be allocated (must not have been freed).
3847  *
3848  * @param message the message
3849  * @param slot the slot to get data from
3850  * @returns the data, or #NULL if not found
3851  */
3852 void*
3853 dbus_message_get_data (DBusMessage   *message,
3854                        dbus_int32_t   slot)
3855 {
3856   void *res;
3857
3858   _dbus_return_val_if_fail (message != NULL, NULL);
3859
3860   res = _dbus_data_slot_list_get (&slot_allocator,
3861                                   &message->slot_list,
3862                                   slot);
3863
3864   return res;
3865 }
3866
3867 /**
3868  * Utility function to convert a machine-readable (not translated)
3869  * string into a D-Bus message type.
3870  *
3871  * @code
3872  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
3873  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
3874  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
3875  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
3876  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
3877  * @endcode
3878  *
3879  */
3880 int
3881 dbus_message_type_from_string (const char *type_str)
3882 {
3883   if (strcmp (type_str, "method_call") == 0)
3884     return DBUS_MESSAGE_TYPE_METHOD_CALL;
3885   if (strcmp (type_str, "method_return") == 0)
3886     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
3887   else if (strcmp (type_str, "signal") == 0)
3888     return DBUS_MESSAGE_TYPE_SIGNAL;
3889   else if (strcmp (type_str, "error") == 0)
3890     return DBUS_MESSAGE_TYPE_ERROR;
3891   else
3892     return DBUS_MESSAGE_TYPE_INVALID;
3893 }
3894
3895 /**
3896  * Utility function to convert a D-Bus message type into a
3897  * machine-readable string (not translated).
3898  *
3899  * @code
3900  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
3901  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
3902  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
3903  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
3904  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
3905  * @endcode
3906  *
3907  */
3908 const char *
3909 dbus_message_type_to_string (int type)
3910 {
3911   switch (type)
3912     {
3913     case DBUS_MESSAGE_TYPE_METHOD_CALL:
3914       return "method_call";
3915     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
3916       return "method_return";
3917     case DBUS_MESSAGE_TYPE_SIGNAL:
3918       return "signal";
3919     case DBUS_MESSAGE_TYPE_ERROR:
3920       return "error";
3921     default:
3922       return "invalid";
3923     }
3924 }
3925
3926 /**
3927  * Turn a DBusMessage into the marshalled form as described in the D-Bus
3928  * specification.
3929  *
3930  * Generally, this function is only useful for encapsulating D-Bus messages in
3931  * a different protocol.
3932  *
3933  * @param msg the DBusMessage
3934  * @param marshalled_data_p the location to save the marshalled form to
3935  * @param len_p the location to save the length of the marshalled form to
3936  * @returns #FALSE if there was not enough memory
3937  */
3938 dbus_bool_t
3939 dbus_message_marshal (DBusMessage  *msg,
3940                       char        **marshalled_data_p,
3941                       int          *len_p)
3942 {
3943   DBusString tmp;
3944
3945   _dbus_return_val_if_fail (msg != NULL, FALSE);
3946   _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
3947   _dbus_return_val_if_fail (len_p != NULL, FALSE);
3948   
3949   if (!_dbus_string_init (&tmp))
3950     return FALSE;
3951
3952   if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
3953     goto fail;
3954
3955   *len_p = _dbus_string_get_length (&tmp);
3956
3957   if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
3958     goto fail;
3959
3960   *len_p = _dbus_string_get_length (&tmp);
3961
3962   if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
3963     goto fail;
3964
3965   _dbus_string_free (&tmp);
3966   return TRUE;
3967
3968  fail:
3969   _dbus_string_free (&tmp);
3970   return FALSE;
3971 }
3972
3973 /**
3974  * Demarshal a D-Bus message from the format described in the D-Bus
3975  * specification.
3976  *
3977  * Generally, this function is only useful for encapsulating D-Bus messages in
3978  * a different protocol.
3979  *
3980  * @param str the marshalled DBusMessage
3981  * @param len the length of str
3982  * @param error the location to save errors to
3983  * @returns #NULL if there was an error
3984  */
3985 DBusMessage *
3986 dbus_message_demarshal (const char *str,
3987                         int         len,
3988                         DBusError  *error)
3989 {
3990   DBusMessageLoader *loader;
3991   DBusString *buffer;
3992   DBusMessage *msg;
3993
3994   _dbus_return_val_if_fail (str != NULL, NULL);
3995
3996   loader = _dbus_message_loader_new ();
3997
3998   if (loader == NULL)
3999     return NULL;
4000
4001   _dbus_message_loader_get_buffer (loader, &buffer);
4002   _dbus_string_append_len (buffer, str, len);
4003   _dbus_message_loader_return_buffer (loader, buffer, len);
4004
4005   if (!_dbus_message_loader_queue_messages (loader))
4006     goto fail_oom;
4007
4008   if (_dbus_message_loader_get_is_corrupted (loader))
4009     goto fail_corrupt;
4010
4011   msg = _dbus_message_loader_pop_message (loader);
4012
4013   if (!msg)
4014     goto fail_oom;
4015
4016   _dbus_message_loader_unref (loader);
4017   return msg;
4018
4019  fail_corrupt:
4020   dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted");
4021   _dbus_message_loader_unref (loader);
4022   return NULL;
4023
4024  fail_oom:
4025   _DBUS_SET_OOM (error);
4026   _dbus_message_loader_unref (loader);
4027   return NULL;
4028 }
4029
4030 /**
4031  * Returns the number of bytes required to be in the buffer to demarshal a
4032  * D-Bus message.
4033  *
4034  * Generally, this function is only useful for encapsulating D-Bus messages in
4035  * a different protocol.
4036  *
4037  * @param str data to be marshalled
4038  * @param len the length of str
4039  * @param error the location to save errors to
4040  * @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
4041  * 
4042  */
4043 int 
4044 dbus_message_demarshal_bytes_needed(const char *buf, 
4045                                     int         len)
4046 {
4047   DBusString str;
4048   int byte_order, fields_array_len, header_len, body_len;
4049   DBusValidity validity = DBUS_VALID;
4050   int have_message;
4051
4052   if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
4053     return 0;
4054
4055   if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
4056     len = DBUS_MAXIMUM_MESSAGE_LENGTH;
4057   _dbus_string_init_const_len (&str, buf, len);
4058   
4059   validity = DBUS_VALID;
4060   have_message
4061     = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
4062                                           &validity, &byte_order,
4063                                           &fields_array_len,
4064                                           &header_len,
4065                                           &body_len,
4066                                           &str, 0,
4067                                           len);
4068   _dbus_string_free (&str);
4069
4070   if (validity == DBUS_VALID)
4071     {
4072       _dbus_assert(have_message);
4073       return header_len + body_len;
4074     }
4075   else
4076     {
4077       return -1; /* broken! */
4078     }
4079 }
4080
4081 /** @} */
4082
4083 /* tests in dbus-message-util.c */