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