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