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