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