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