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