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