doxygen: document that we don't support reading/writing arrays of unix fds in once...
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #include "dbus-internals.h"
26 #include "dbus-marshal-recursive.h"
27 #include "dbus-marshal-validate.h"
28 #include "dbus-marshal-byteswap.h"
29 #include "dbus-marshal-header.h"
30 #include "dbus-signature.h"
31 #include "dbus-message-private.h"
32 #include "dbus-object-tree.h"
33 #include "dbus-memory.h"
34 #include "dbus-list.h"
35 #include "dbus-threads-internal.h"
36 #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                                                   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                                                 &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                 goto failed;
1727             }
1728           else if (element_type == DBUS_TYPE_STRING ||
1729                    element_type == DBUS_TYPE_SIGNATURE ||
1730                    element_type == DBUS_TYPE_OBJECT_PATH)
1731             {
1732               const char ***value_p;
1733               const char **value;
1734               int n_elements;
1735               int i;
1736               
1737               value_p = va_arg (var_args, const char***);
1738               n_elements = va_arg (var_args, int);
1739
1740               value = *value_p;
1741               
1742               i = 0;
1743               while (i < n_elements)
1744                 {
1745                   if (!dbus_message_iter_append_basic (&array,
1746                                                        element_type,
1747                                                        &value[i]))
1748                     goto failed;
1749                   ++i;
1750                 }
1751             }
1752           else
1753             {
1754               _dbus_warn ("arrays of %s can't be appended with %s for now\n",
1755                           _dbus_type_to_string (element_type),
1756                           _DBUS_FUNCTION_NAME);
1757               goto failed;
1758             }
1759
1760           if (!dbus_message_iter_close_container (&iter, &array))
1761             goto failed;
1762         }
1763 #ifndef DBUS_DISABLE_CHECKS
1764       else
1765         {
1766           _dbus_warn ("type %s isn't supported yet in %s\n",
1767                       _dbus_type_to_string (type), _DBUS_FUNCTION_NAME);
1768           goto failed;
1769         }
1770 #endif
1771
1772       type = va_arg (var_args, int);
1773     }
1774
1775   return TRUE;
1776
1777  failed:
1778   return FALSE;
1779 }
1780
1781 /**
1782  * Gets arguments from a message given a variable argument list.  The
1783  * supported types include those supported by
1784  * dbus_message_append_args(); that is, basic types and arrays of
1785  * fixed-length basic types.  The arguments are the same as they would
1786  * be for dbus_message_iter_get_basic() or
1787  * dbus_message_iter_get_fixed_array().
1788  *
1789  * In addition to those types, arrays of string, object path, and
1790  * signature are supported; but these are returned as allocated memory
1791  * and must be freed with dbus_free_string_array(), while the other
1792  * types are returned as const references. To get a string array
1793  * pass in "char ***array_location" and "int *n_elements".
1794  *
1795  * Similar to dbus_message_get_fixed_array() this function does not
1796  * support arrays of type DBUS_TYPE_UNIX_FD. If you need to parse
1797  * messages with arrays of Unix file descriptors you need to recurse
1798  * into the array manually.
1799  *
1800  * Unix file descriptors that are read with this function will have
1801  * the FD_CLOEXEC flag set. If you need them without this flag set,
1802  * make sure to unset it with fcntl().
1803  *
1804  * The variable argument list should contain the type of the argument
1805  * followed by a pointer to where the value should be stored. The list
1806  * is terminated with #DBUS_TYPE_INVALID.
1807  *
1808  * Except for string arrays, the returned values are constant; do not
1809  * free them. They point into the #DBusMessage.
1810  *
1811  * If the requested arguments are not present, or do not have the
1812  * requested types, then an error will be set.
1813  *
1814  * If more arguments than requested are present, the requested
1815  * arguments are returned and the extra arguments are ignored.
1816  * 
1817  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1818  *
1819  * @param message the message
1820  * @param error error to be filled in on failure
1821  * @param first_arg_type the first argument type
1822  * @param ... location for first argument value, then list of type-location pairs
1823  * @returns #FALSE if the error was set
1824  */
1825 dbus_bool_t
1826 dbus_message_get_args (DBusMessage     *message,
1827                        DBusError       *error,
1828                        int              first_arg_type,
1829                        ...)
1830 {
1831   dbus_bool_t retval;
1832   va_list var_args;
1833
1834   _dbus_return_val_if_fail (message != NULL, FALSE);
1835   _dbus_return_val_if_error_is_set (error, FALSE);
1836
1837   va_start (var_args, first_arg_type);
1838   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
1839   va_end (var_args);
1840
1841   return retval;
1842 }
1843
1844 /**
1845  * Like dbus_message_get_args but takes a va_list for use by language bindings.
1846  *
1847  * @see dbus_message_get_args
1848  * @param message the message
1849  * @param error error to be filled in
1850  * @param first_arg_type type of the first argument
1851  * @param var_args return location for first argument, followed by list of type/location pairs
1852  * @returns #FALSE if error was set
1853  */
1854 dbus_bool_t
1855 dbus_message_get_args_valist (DBusMessage     *message,
1856                               DBusError       *error,
1857                               int              first_arg_type,
1858                               va_list          var_args)
1859 {
1860   DBusMessageIter iter;
1861
1862   _dbus_return_val_if_fail (message != NULL, FALSE);
1863   _dbus_return_val_if_error_is_set (error, FALSE);
1864
1865   dbus_message_iter_init (message, &iter);
1866   return _dbus_message_iter_get_args_valist (&iter, error, first_arg_type, var_args);
1867 }
1868
1869 static void
1870 _dbus_message_iter_init_common (DBusMessage         *message,
1871                                 DBusMessageRealIter *real,
1872                                 int                  iter_type)
1873 {
1874   _dbus_assert (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
1875
1876   /* Since the iterator will read or write who-knows-what from the
1877    * message, we need to get in the right byte order
1878    */
1879   ensure_byte_order (message);
1880   
1881   real->message = message;
1882   real->changed_stamp = message->changed_stamp;
1883   real->iter_type = iter_type;
1884   real->sig_refcount = 0;
1885 }
1886
1887 /**
1888  * Initializes a #DBusMessageIter for reading the arguments of the
1889  * message passed in.
1890  *
1891  * When possible, dbus_message_get_args() is much more convenient.
1892  * Some types of argument can only be read with #DBusMessageIter
1893  * however.
1894  *
1895  * The easiest way to iterate is like this: 
1896  * @code
1897  * dbus_message_iter_init (message, &iter);
1898  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
1899  *   dbus_message_iter_next (&iter);
1900  * @endcode
1901  *
1902  * #DBusMessageIter contains no allocated memory; it need not be
1903  * freed, and can be copied by assignment or memcpy().
1904  * 
1905  * @param message the message
1906  * @param iter pointer to an iterator to initialize
1907  * @returns #FALSE if the message has no arguments
1908  */
1909 dbus_bool_t
1910 dbus_message_iter_init (DBusMessage     *message,
1911                         DBusMessageIter *iter)
1912 {
1913   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1914   const DBusString *type_str;
1915   int type_pos;
1916
1917   _dbus_return_val_if_fail (message != NULL, FALSE);
1918   _dbus_return_val_if_fail (iter != NULL, FALSE);
1919
1920   get_const_signature (&message->header, &type_str, &type_pos);
1921
1922   _dbus_message_iter_init_common (message, real,
1923                                   DBUS_MESSAGE_ITER_TYPE_READER);
1924
1925   _dbus_type_reader_init (&real->u.reader,
1926                           message->byte_order,
1927                           type_str, type_pos,
1928                           &message->body,
1929                           0);
1930
1931   return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
1932 }
1933
1934 /**
1935  * Checks if an iterator has any more fields.
1936  *
1937  * @param iter the message iter
1938  * @returns #TRUE if there are more fields following
1939  */
1940 dbus_bool_t
1941 dbus_message_iter_has_next (DBusMessageIter *iter)
1942 {
1943   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1944
1945   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
1946   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1947
1948   return _dbus_type_reader_has_next (&real->u.reader);
1949 }
1950
1951 /**
1952  * Moves the iterator to the next field, if any. If there's no next
1953  * field, returns #FALSE. If the iterator moves forward, returns
1954  * #TRUE.
1955  *
1956  * @param iter the message iter
1957  * @returns #TRUE if the iterator was moved to the next field
1958  */
1959 dbus_bool_t
1960 dbus_message_iter_next (DBusMessageIter *iter)
1961 {
1962   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1963
1964   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
1965   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1966
1967   return _dbus_type_reader_next (&real->u.reader);
1968 }
1969
1970 /**
1971  * Returns the argument type of the argument that the message iterator
1972  * points to. If the iterator is at the end of the message, returns
1973  * #DBUS_TYPE_INVALID. You can thus write a loop as follows:
1974  *
1975  * @code
1976  * dbus_message_iter_init (&iter);
1977  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
1978  *   dbus_message_iter_next (&iter);
1979  * @endcode
1980  *
1981  * @param iter the message iter
1982  * @returns the argument type
1983  */
1984 int
1985 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
1986 {
1987   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
1988
1989   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
1990   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
1991
1992   return _dbus_type_reader_get_current_type (&real->u.reader);
1993 }
1994
1995 /**
1996  * Returns the element type of the array that the message iterator
1997  * points to. Note that you need to check that the iterator points to
1998  * an array prior to using this function.
1999  *
2000  * @param iter the message iter
2001  * @returns the array element type
2002  */
2003 int
2004 dbus_message_iter_get_element_type (DBusMessageIter *iter)
2005 {
2006   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2007
2008   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2009   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, DBUS_TYPE_INVALID);
2010   _dbus_return_val_if_fail (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY, DBUS_TYPE_INVALID);
2011
2012   return _dbus_type_reader_get_element_type (&real->u.reader);
2013 }
2014
2015 /**
2016  * Recurses into a container value when reading values from a message,
2017  * initializing a sub-iterator to use for traversing the child values
2018  * of the container.
2019  *
2020  * Note that this recurses into a value, not a type, so you can only
2021  * recurse if the value exists. The main implication of this is that
2022  * if you have for example an empty array of array of int32, you can
2023  * recurse into the outermost array, but it will have no values, so
2024  * you won't be able to recurse further. There's no array of int32 to
2025  * recurse into.
2026  *
2027  * If a container is an array of fixed-length types (except Unix file
2028  * descriptors), it is much more efficient to use
2029  * dbus_message_iter_get_fixed_array() to get the whole array in one
2030  * shot, rather than individually walking over the array elements.
2031  *
2032  * Be sure you have somehow checked that
2033  * dbus_message_iter_get_arg_type() matches the type you are expecting
2034  * to recurse into. Results of this function are undefined if there is
2035  * no container to recurse into at the current iterator position.
2036  *
2037  * @param iter the message iterator
2038  * @param sub the sub-iterator to initialize
2039  */
2040 void
2041 dbus_message_iter_recurse (DBusMessageIter  *iter,
2042                            DBusMessageIter  *sub)
2043 {
2044   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2045   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2046
2047   _dbus_return_if_fail (_dbus_message_iter_check (real));
2048   _dbus_return_if_fail (sub != NULL);
2049
2050   *real_sub = *real;
2051   _dbus_type_reader_recurse (&real->u.reader, &real_sub->u.reader);
2052 }
2053
2054 /**
2055  * Returns the current signature of a message iterator.  This
2056  * is useful primarily for dealing with variants; one can
2057  * recurse into a variant and determine the signature of
2058  * the variant's value.
2059  *
2060  * The returned string must be freed with dbus_free().
2061  * 
2062  * @param iter the message iterator
2063  * @returns the contained signature, or NULL if out of memory
2064  */
2065 char *
2066 dbus_message_iter_get_signature (DBusMessageIter *iter)
2067 {
2068   const DBusString *sig;
2069   DBusString retstr;
2070   char *ret;
2071   int start, len;
2072   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2073
2074   _dbus_return_val_if_fail (_dbus_message_iter_check (real), NULL);
2075
2076   if (!_dbus_string_init (&retstr))
2077     return NULL;
2078
2079   _dbus_type_reader_get_signature (&real->u.reader, &sig,
2080                                    &start, &len);
2081   if (!_dbus_string_append_len (&retstr,
2082                                 _dbus_string_get_const_data (sig) + start,
2083                                 len))
2084     return NULL;
2085   if (!_dbus_string_steal_data (&retstr, &ret))
2086     return NULL;
2087   _dbus_string_free (&retstr);
2088   return ret;
2089 }
2090
2091 /**
2092  * Reads a basic-typed value from the message iterator.
2093  * Basic types are the non-containers such as integer and string.
2094  *
2095  * The value argument should be the address of a location to store
2096  * the returned value. So for int32 it should be a "dbus_int32_t*"
2097  * and for string a "const char**". The returned value is
2098  * by reference and should not be freed.
2099  *
2100  * This call duplicates Unix file descriptors when reading them. It is
2101  * your job to close them when you don't need them anymore.
2102  *
2103  * Unix file descriptors that are read with this function will have
2104  * the FD_CLOEXEC flag set. If you need them without this flag set,
2105  * make sure to unset it with fcntl().
2106  *
2107  * Be sure you have somehow checked that
2108  * dbus_message_iter_get_arg_type() matches the type you are
2109  * expecting, or you'll crash when you try to use an integer as a
2110  * string or something.
2111  *
2112  * To read any container type (array, struct, dict) you will need to
2113  * recurse into the container with dbus_message_iter_recurse().  If
2114  * the container is an array of fixed-length values (except Unix file
2115  * descriptors), you can get all the array elements at once with
2116  * dbus_message_iter_get_fixed_array(). Otherwise, you have to iterate
2117  * over the container's contents one value at a time.
2118  * 
2119  * All basic-typed values are guaranteed to fit in 8 bytes. So you can
2120  * write code like this:
2121  *
2122  * @code
2123  * dbus_uint64_t value;
2124  * int type;
2125  * dbus_message_iter_get_basic (&read_iter, &value);
2126  * type = dbus_message_iter_get_arg_type (&read_iter);
2127  * dbus_message_iter_append_basic (&write_iter, type, &value);
2128  * @endcode
2129  *
2130  * On some really obscure platforms dbus_uint64_t might not exist, if
2131  * you need to worry about this you will know.  dbus_uint64_t is just
2132  * one example of a type that's large enough to hold any possible
2133  * value, you could use a struct or char[8] instead if you like.
2134  *
2135  * @param iter the iterator
2136  * @param value location to store the value
2137  */
2138 void
2139 dbus_message_iter_get_basic (DBusMessageIter  *iter,
2140                              void             *value)
2141 {
2142   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2143
2144   _dbus_return_if_fail (_dbus_message_iter_check (real));
2145   _dbus_return_if_fail (value != NULL);
2146
2147   if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UNIX_FD)
2148     {
2149 #ifdef HAVE_UNIX_FD_PASSING
2150       DBusBasicValue idx;
2151
2152       _dbus_type_reader_read_basic(&real->u.reader, &idx);
2153
2154       if (idx.u32 >= real->message->n_unix_fds) {
2155         /* Hmm, we cannot really signal an error here, so let's make
2156            sure to return an invalid fd. */
2157         *((int*) value) = -1;
2158         return;
2159       }
2160
2161       *((int*) value) = _dbus_dup(real->message->unix_fds[idx.u32], NULL);
2162 #else
2163       *((int*) value) = -1;
2164 #endif
2165     }
2166   else
2167     {
2168       _dbus_type_reader_read_basic (&real->u.reader,
2169                                     value);
2170     }
2171 }
2172
2173 /**
2174  * Returns the number of bytes in the array as marshaled in the wire
2175  * protocol. The iterator must currently be inside an array-typed
2176  * value.
2177  *
2178  * This function is deprecated on the grounds that it is stupid.  Why
2179  * would you want to know how many bytes are in the array as marshaled
2180  * in the wire protocol?  For now, use the n_elements returned from
2181  * dbus_message_iter_get_fixed_array() instead, or iterate over the
2182  * array values and count them.
2183  *
2184  * @todo introduce a variant of this get_n_elements that returns
2185  * the number of elements, though with a non-fixed array it will not
2186  * be very efficient, so maybe it's not good.
2187  * 
2188  * @param iter the iterator
2189  * @returns the number of bytes in the array
2190  */
2191 int
2192 dbus_message_iter_get_array_len (DBusMessageIter *iter)
2193 {
2194   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2195
2196   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2197
2198   return _dbus_type_reader_get_array_length (&real->u.reader);
2199 }
2200
2201 /**
2202  * Reads a block of fixed-length values from the message iterator.
2203  * Fixed-length values are those basic types that are not string-like,
2204  * such as integers, bool, double. The returned block will be from the
2205  * current position in the array until the end of the array.
2206  *
2207  * There is one exception here: although DBUS_TYPE_UNIX_FD is
2208  * considered a 'fixed' type arrays of this type may not be read with
2209  * this function.
2210  *
2211  * The message iter should be "in" the array (that is, you recurse into the
2212  * array, and then you call dbus_message_iter_get_fixed_array() on the
2213  * "sub-iterator" created by dbus_message_iter_recurse()).
2214  *
2215  * The value argument should be the address of a location to store the
2216  * returned array. So for int32 it should be a "const dbus_int32_t**"
2217  * The returned value is by reference and should not be freed.
2218  * 
2219  * This function should only be used if dbus_type_is_fixed() returns
2220  * #TRUE for the element type.
2221  *
2222  * If an array's elements are not fixed in size, you have to recurse
2223  * into the array with dbus_message_iter_recurse() and read the
2224  * elements one by one.
2225  * 
2226  * Because the array is not copied, this function runs in constant
2227  * time and is fast; it's much preferred over walking the entire array
2228  * with an iterator. (However, you can always use
2229  * dbus_message_iter_recurse(), even for fixed-length types;
2230  * dbus_message_iter_get_fixed_array() is just an optimization.)
2231  * 
2232  * @param iter the iterator
2233  * @param value location to store the block
2234  * @param n_elements number of elements in the block
2235  */
2236 void
2237 dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
2238                                    void             *value,
2239                                    int              *n_elements)
2240 {
2241   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2242   int subtype = _dbus_type_reader_get_current_type(&real->u.reader);
2243
2244   _dbus_return_if_fail (_dbus_message_iter_check (real));
2245   _dbus_return_if_fail (value != NULL);
2246   _dbus_return_if_fail ((subtype == DBUS_TYPE_INVALID) ||
2247                         (dbus_type_is_fixed (subtype) && subtype != DBUS_TYPE_UNIX_FD));
2248
2249   _dbus_type_reader_read_fixed_multi (&real->u.reader,
2250                                       value, n_elements);
2251 }
2252
2253 /**
2254  * Initializes a #DBusMessageIter for appending arguments to the end
2255  * of a message.
2256  *
2257  * @todo If appending any of the arguments fails due to lack of
2258  * memory, the message is hosed and you have to start over building
2259  * the whole message.
2260  *
2261  * @param message the message
2262  * @param iter pointer to an iterator to initialize
2263  */
2264 void
2265 dbus_message_iter_init_append (DBusMessage     *message,
2266                                DBusMessageIter *iter)
2267 {
2268   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2269
2270   _dbus_return_if_fail (message != NULL);
2271   _dbus_return_if_fail (iter != NULL);
2272
2273   _dbus_message_iter_init_common (message, real,
2274                                   DBUS_MESSAGE_ITER_TYPE_WRITER);
2275
2276   /* We create the signature string and point iterators at it "on demand"
2277    * when a value is actually appended. That means that init() never fails
2278    * due to OOM.
2279    */
2280   _dbus_type_writer_init_types_delayed (&real->u.writer,
2281                                         message->byte_order,
2282                                         &message->body,
2283                                         _dbus_string_get_length (&message->body));
2284 }
2285
2286 /**
2287  * Creates a temporary signature string containing the current
2288  * signature, stores it in the iterator, and points the iterator to
2289  * the end of it. Used any time we write to the message.
2290  *
2291  * @param real an iterator without a type_str
2292  * @returns #FALSE if no memory
2293  */
2294 static dbus_bool_t
2295 _dbus_message_iter_open_signature (DBusMessageRealIter *real)
2296 {
2297   DBusString *str;
2298   const DBusString *current_sig;
2299   int current_sig_pos;
2300
2301   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2302
2303   if (real->u.writer.type_str != NULL)
2304     {
2305       _dbus_assert (real->sig_refcount > 0);
2306       real->sig_refcount += 1;
2307       return TRUE;
2308     }
2309
2310   str = dbus_new (DBusString, 1);
2311   if (str == NULL)
2312     return FALSE;
2313
2314   if (!_dbus_header_get_field_raw (&real->message->header,
2315                                    DBUS_HEADER_FIELD_SIGNATURE,
2316                                    &current_sig, &current_sig_pos))
2317     current_sig = NULL;
2318
2319   if (current_sig)
2320     {
2321       int current_len;
2322
2323       current_len = _dbus_string_get_byte (current_sig, current_sig_pos);
2324       current_sig_pos += 1; /* move on to sig data */
2325
2326       if (!_dbus_string_init_preallocated (str, current_len + 4))
2327         {
2328           dbus_free (str);
2329           return FALSE;
2330         }
2331
2332       if (!_dbus_string_copy_len (current_sig, current_sig_pos, current_len,
2333                                   str, 0))
2334         {
2335           _dbus_string_free (str);
2336           dbus_free (str);
2337           return FALSE;
2338         }
2339     }
2340   else
2341     {
2342       if (!_dbus_string_init_preallocated (str, 4))
2343         {
2344           dbus_free (str);
2345           return FALSE;
2346         }
2347     }
2348
2349   real->sig_refcount = 1;
2350
2351   _dbus_type_writer_add_types (&real->u.writer,
2352                                str, _dbus_string_get_length (str));
2353   return TRUE;
2354 }
2355
2356 /**
2357  * Sets the new signature as the message signature, frees the
2358  * signature string, and marks the iterator as not having a type_str
2359  * anymore. Frees the signature even if it fails, so you can't
2360  * really recover from failure. Kinda busted.
2361  *
2362  * @param real an iterator without a type_str
2363  * @returns #FALSE if no memory
2364  */
2365 static dbus_bool_t
2366 _dbus_message_iter_close_signature (DBusMessageRealIter *real)
2367 {
2368   DBusString *str;
2369   const char *v_STRING;
2370   dbus_bool_t retval;
2371
2372   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2373   _dbus_assert (real->u.writer.type_str != NULL);
2374   _dbus_assert (real->sig_refcount > 0);
2375
2376   real->sig_refcount -= 1;
2377
2378   if (real->sig_refcount > 0)
2379     return TRUE;
2380   _dbus_assert (real->sig_refcount == 0);
2381
2382   retval = TRUE;
2383
2384   str = real->u.writer.type_str;
2385
2386   v_STRING = _dbus_string_get_const_data (str);
2387   if (!_dbus_header_set_field_basic (&real->message->header,
2388                                      DBUS_HEADER_FIELD_SIGNATURE,
2389                                      DBUS_TYPE_SIGNATURE,
2390                                      &v_STRING))
2391     retval = FALSE;
2392
2393   _dbus_type_writer_remove_types (&real->u.writer);
2394   _dbus_string_free (str);
2395   dbus_free (str);
2396
2397   return retval;
2398 }
2399
2400 #ifndef DBUS_DISABLE_CHECKS
2401 static dbus_bool_t
2402 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
2403 {
2404   if (!_dbus_message_iter_check (iter))
2405     return FALSE;
2406
2407   if (iter->message->locked)
2408     {
2409       _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)\n");
2410       return FALSE;
2411     }
2412
2413   return TRUE;
2414 }
2415 #endif /* DBUS_DISABLE_CHECKS */
2416
2417 #ifdef HAVE_UNIX_FD_PASSING
2418 static int *
2419 expand_fd_array(DBusMessage *m,
2420                 unsigned     n)
2421 {
2422   _dbus_assert(m);
2423
2424   /* This makes space for adding n new fds to the array and returns a
2425      pointer to the place were the first fd should be put. */
2426
2427   if (m->n_unix_fds + n > m->n_unix_fds_allocated)
2428     {
2429       unsigned k;
2430       int *p;
2431
2432       /* Make twice as much space as necessary */
2433       k = (m->n_unix_fds + n) * 2;
2434
2435       /* Allocate at least four */
2436       if (k < 4)
2437         k = 4;
2438
2439       p = dbus_realloc(m->unix_fds, k * sizeof(int));
2440       if (p == NULL)
2441         return NULL;
2442
2443       m->unix_fds = p;
2444       m->n_unix_fds_allocated = k;
2445     }
2446
2447   return m->unix_fds + m->n_unix_fds;
2448 }
2449 #endif
2450
2451 /**
2452  * Appends a basic-typed value to the message. The basic types are the
2453  * non-container types such as integer and string.
2454  *
2455  * The "value" argument should be the address of a basic-typed value.
2456  * So for string, const char**. For integer, dbus_int32_t*.
2457  *
2458  * For Unix file descriptors this function will internally duplicate
2459  * the descriptor you passed in. Hence you may close the descriptor
2460  * immediately after this call.
2461  *
2462  * @todo If this fails due to lack of memory, the message is hosed and
2463  * you have to start over building the whole message.
2464  *
2465  * @param iter the append iterator
2466  * @param type the type of the value
2467  * @param value the address of the value
2468  * @returns #FALSE if not enough memory
2469  */
2470 dbus_bool_t
2471 dbus_message_iter_append_basic (DBusMessageIter *iter,
2472                                 int              type,
2473                                 const void      *value)
2474 {
2475   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2476   dbus_bool_t ret;
2477
2478   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2479   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2480   _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
2481   _dbus_return_val_if_fail (value != NULL, FALSE);
2482
2483   if (!_dbus_message_iter_open_signature (real))
2484     return FALSE;
2485
2486   if (type == DBUS_TYPE_UNIX_FD)
2487     {
2488 #ifdef HAVE_UNIX_FD_PASSING
2489       int *fds;
2490       dbus_uint32_t u;
2491
2492       /* First step, include the fd in the fd list of this message */
2493       if (!(fds = expand_fd_array(real->message, 1)))
2494         return FALSE;
2495
2496       *fds = _dbus_dup(*(int*) value, NULL);
2497       if (*fds < 0)
2498         return FALSE;
2499
2500       u = real->message->n_unix_fds;
2501
2502       /* Second step, write the index to the fd */
2503       if (!(ret = _dbus_type_writer_write_basic (&real->u.writer, DBUS_TYPE_UNIX_FD, &u))) {
2504         _dbus_close(*fds, NULL);
2505         return FALSE;
2506       }
2507
2508       real->message->n_unix_fds += 1;
2509       u += 1;
2510
2511       /* Final step, update the header accordingly */
2512       ret = _dbus_header_set_field_basic (&real->message->header,
2513                                           DBUS_HEADER_FIELD_UNIX_FDS,
2514                                           DBUS_TYPE_UINT32,
2515                                           &u);
2516
2517       /* If any of these operations fail the message is
2518          hosed. However, no memory or fds should be leaked since what
2519          has been added to message has been added to the message, and
2520          can hence be accounted for when the message is being
2521          freed. */
2522 #else
2523       ret = FALSE;
2524 #endif
2525     }
2526   else
2527     {
2528       ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
2529     }
2530
2531   if (!_dbus_message_iter_close_signature (real))
2532     ret = FALSE;
2533
2534   return ret;
2535 }
2536
2537 /**
2538  * Appends a block of fixed-length values to an array. The
2539  * fixed-length types are all basic types that are not string-like. So
2540  * int32, double, bool, etc. (Unix file descriptors however are not
2541  * supported.) You must call dbus_message_iter_open_container() to
2542  * open an array of values before calling this function. You may call
2543  * this function multiple times (and intermixed with calls to
2544  * dbus_message_iter_append_basic()) for the same array.
2545  *
2546  * The "value" argument should be the address of the array.  So for
2547  * integer, "dbus_int32_t**" is expected for example.
2548  *
2549  * @warning in C, given "int array[]", "&array == array" (the
2550  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
2551  * So if you're using an array instead of a pointer you have to create
2552  * a pointer variable, assign the array to it, then take the address
2553  * of the pointer variable.
2554  * @code
2555  * const dbus_int32_t array[] = { 1, 2, 3 };
2556  * const dbus_int32_t *v_ARRAY = array;
2557  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
2558  *   fprintf (stderr, "No memory!\n");
2559  * @endcode
2560  * For strings it works to write const char *array = "Hello" and then
2561  * use &array though.
2562  *
2563  * @todo If this fails due to lack of memory, the message is hosed and
2564  * you have to start over building the whole message.
2565  *
2566  * For Unix file descriptors this function will internally duplicate
2567  * the descriptor you passed in. Hence you may close the descriptor
2568  * immediately after this call.
2569  *
2570  * @param iter the append iterator
2571  * @param element_type the type of the array elements
2572  * @param value the address of the array
2573  * @param n_elements the number of elements to append
2574  * @returns #FALSE if not enough memory
2575  */
2576 dbus_bool_t
2577 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
2578                                       int              element_type,
2579                                       const void      *value,
2580                                       int              n_elements)
2581 {
2582   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2583   dbus_bool_t ret;
2584
2585   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2586   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2587   _dbus_return_val_if_fail (dbus_type_is_fixed (element_type) && element_type != DBUS_TYPE_UNIX_FD, FALSE);
2588   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
2589   _dbus_return_val_if_fail (value != NULL, FALSE);
2590   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
2591   _dbus_return_val_if_fail (n_elements <=
2592                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
2593                             FALSE);
2594
2595   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
2596
2597   return ret;
2598 }
2599
2600 /**
2601  * Appends a container-typed value to the message; you are required to
2602  * append the contents of the container using the returned
2603  * sub-iterator, and then call
2604  * dbus_message_iter_close_container(). Container types are for
2605  * example struct, variant, and array. For variants, the
2606  * contained_signature should be the type of the single value inside
2607  * the variant. For structs and dict entries, contained_signature
2608  * should be #NULL; it will be set to whatever types you write into
2609  * the struct.  For arrays, contained_signature should be the type of
2610  * the array elements.
2611  *
2612  * @todo If this fails due to lack of memory, the message is hosed and
2613  * you have to start over building the whole message.
2614  *
2615  * @param iter the append iterator
2616  * @param type the type of the value
2617  * @param contained_signature the type of container contents
2618  * @param sub sub-iterator to initialize
2619  * @returns #FALSE if not enough memory
2620  */
2621 dbus_bool_t
2622 dbus_message_iter_open_container (DBusMessageIter *iter,
2623                                   int              type,
2624                                   const char      *contained_signature,
2625                                   DBusMessageIter *sub)
2626 {
2627   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2628   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2629   DBusString contained_str;
2630
2631   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2632   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2633   _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
2634   _dbus_return_val_if_fail (sub != NULL, FALSE);
2635   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
2636                              contained_signature == NULL) ||
2637                             (type == DBUS_TYPE_DICT_ENTRY &&
2638                              contained_signature == NULL) ||
2639                             (type == DBUS_TYPE_VARIANT &&
2640                              contained_signature != NULL) ||
2641                             (type == DBUS_TYPE_ARRAY &&
2642                              contained_signature != NULL), FALSE);
2643   
2644   /* this would fail if the contained_signature is a dict entry, since
2645    * dict entries are invalid signatures standalone (they must be in
2646    * an array)
2647    */
2648   _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
2649                             (contained_signature == NULL ||
2650                              _dbus_check_is_valid_signature (contained_signature)),
2651                             FALSE);
2652
2653   if (!_dbus_message_iter_open_signature (real))
2654     return FALSE;
2655
2656   *real_sub = *real;
2657
2658   if (contained_signature != NULL)
2659     {
2660       _dbus_string_init_const (&contained_str, contained_signature);
2661
2662       return _dbus_type_writer_recurse (&real->u.writer,
2663                                         type,
2664                                         &contained_str, 0,
2665                                         &real_sub->u.writer);
2666     }
2667   else
2668     {
2669       return _dbus_type_writer_recurse (&real->u.writer,
2670                                         type,
2671                                         NULL, 0,
2672                                         &real_sub->u.writer);
2673     } 
2674 }
2675
2676
2677 /**
2678  * Closes a container-typed value appended to the message; may write
2679  * out more information to the message known only after the entire
2680  * container is written, and may free resources created by
2681  * dbus_message_iter_open_container().
2682  *
2683  * @todo If this fails due to lack of memory, the message is hosed and
2684  * you have to start over building the whole message.
2685  *
2686  * @param iter the append iterator
2687  * @param sub sub-iterator to close
2688  * @returns #FALSE if not enough memory
2689  */
2690 dbus_bool_t
2691 dbus_message_iter_close_container (DBusMessageIter *iter,
2692                                    DBusMessageIter *sub)
2693 {
2694   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2695   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2696   dbus_bool_t ret;
2697
2698   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2699   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2700   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
2701   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2702
2703   ret = _dbus_type_writer_unrecurse (&real->u.writer,
2704                                      &real_sub->u.writer);
2705
2706   if (!_dbus_message_iter_close_signature (real))
2707     ret = FALSE;
2708
2709   return ret;
2710 }
2711
2712 /**
2713  * Sets a flag indicating that the message does not want a reply; if
2714  * this flag is set, the other end of the connection may (but is not
2715  * required to) optimize by not sending method return or error
2716  * replies. If this flag is set, there is no way to know whether the
2717  * message successfully arrived at the remote end. Normally you know a
2718  * message was received when you receive the reply to it.
2719  *
2720  * The flag is #FALSE by default, that is by default the other end is
2721  * required to reply.
2722  *
2723  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
2724  * 
2725  * @param message the message
2726  * @param no_reply #TRUE if no reply is desired
2727  */
2728 void
2729 dbus_message_set_no_reply (DBusMessage *message,
2730                            dbus_bool_t  no_reply)
2731 {
2732   _dbus_return_if_fail (message != NULL);
2733   _dbus_return_if_fail (!message->locked);
2734
2735   _dbus_header_toggle_flag (&message->header,
2736                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
2737                             no_reply);
2738 }
2739
2740 /**
2741  * Returns #TRUE if the message does not expect
2742  * a reply.
2743  *
2744  * @param message the message
2745  * @returns #TRUE if the message sender isn't waiting for a reply
2746  */
2747 dbus_bool_t
2748 dbus_message_get_no_reply (DBusMessage *message)
2749 {
2750   _dbus_return_val_if_fail (message != NULL, FALSE);
2751
2752   return _dbus_header_get_flag (&message->header,
2753                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
2754 }
2755
2756 /**
2757  * Sets a flag indicating that an owner for the destination name will
2758  * be automatically started before the message is delivered. When this
2759  * flag is set, the message is held until a name owner finishes
2760  * starting up, or fails to start up. In case of failure, the reply
2761  * will be an error.
2762  *
2763  * The flag is set to #TRUE by default, i.e. auto starting is the default.
2764  *
2765  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
2766  * 
2767  * @param message the message
2768  * @param auto_start #TRUE if auto-starting is desired
2769  */
2770 void
2771 dbus_message_set_auto_start (DBusMessage *message,
2772                              dbus_bool_t  auto_start)
2773 {
2774   _dbus_return_if_fail (message != NULL);
2775   _dbus_return_if_fail (!message->locked);
2776
2777   _dbus_header_toggle_flag (&message->header,
2778                             DBUS_HEADER_FLAG_NO_AUTO_START,
2779                             !auto_start);
2780 }
2781
2782 /**
2783  * Returns #TRUE if the message will cause an owner for
2784  * destination name to be auto-started.
2785  *
2786  * @param message the message
2787  * @returns #TRUE if the message will use auto-start
2788  */
2789 dbus_bool_t
2790 dbus_message_get_auto_start (DBusMessage *message)
2791 {
2792   _dbus_return_val_if_fail (message != NULL, FALSE);
2793
2794   return !_dbus_header_get_flag (&message->header,
2795                                  DBUS_HEADER_FLAG_NO_AUTO_START);
2796 }
2797
2798
2799 /**
2800  * Sets the object path this message is being sent to (for
2801  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
2802  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
2803  *
2804  * The path must contain only valid characters as defined
2805  * in the D-Bus specification.
2806  *
2807  * @param message the message
2808  * @param object_path the path or #NULL to unset
2809  * @returns #FALSE if not enough memory
2810  */
2811 dbus_bool_t
2812 dbus_message_set_path (DBusMessage   *message,
2813                        const char    *object_path)
2814 {
2815   _dbus_return_val_if_fail (message != NULL, FALSE);
2816   _dbus_return_val_if_fail (!message->locked, FALSE);
2817   _dbus_return_val_if_fail (object_path == NULL ||
2818                             _dbus_check_is_valid_path (object_path),
2819                             FALSE);
2820
2821   return set_or_delete_string_field (message,
2822                                      DBUS_HEADER_FIELD_PATH,
2823                                      DBUS_TYPE_OBJECT_PATH,
2824                                      object_path);
2825 }
2826
2827 /**
2828  * Gets the object path this message is being sent to (for
2829  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
2830  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
2831  *
2832  * See also dbus_message_get_path_decomposed().
2833  *
2834  * The returned string becomes invalid if the message is
2835  * modified, since it points into the wire-marshaled message data.
2836  * 
2837  * @param message the message
2838  * @returns the path (should not be freed) or #NULL
2839  */
2840 const char*
2841 dbus_message_get_path (DBusMessage   *message)
2842 {
2843   const char *v;
2844
2845   _dbus_return_val_if_fail (message != NULL, NULL);
2846
2847   v = NULL; /* in case field doesn't exist */
2848   _dbus_header_get_field_basic (&message->header,
2849                                 DBUS_HEADER_FIELD_PATH,
2850                                 DBUS_TYPE_OBJECT_PATH,
2851                                 &v);
2852   return v;
2853 }
2854
2855 /**
2856  * Checks if the message has a particular object path.  The object
2857  * path is the destination object for a method call or the emitting
2858  * object for a signal.
2859  *
2860  * @param message the message
2861  * @param path the path name
2862  * @returns #TRUE if there is a path field in the header
2863  */
2864 dbus_bool_t
2865 dbus_message_has_path (DBusMessage   *message,
2866                        const char    *path)
2867 {
2868   const char *msg_path;
2869   msg_path = dbus_message_get_path (message);
2870   
2871   if (msg_path == NULL)
2872     {
2873       if (path == NULL)
2874         return TRUE;
2875       else
2876         return FALSE;
2877     }
2878
2879   if (path == NULL)
2880     return FALSE;
2881    
2882   if (strcmp (msg_path, path) == 0)
2883     return TRUE;
2884
2885   return FALSE;
2886 }
2887
2888 /**
2889  * Gets the object path this message is being sent to
2890  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2891  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
2892  * format (one array element per path component).
2893  * Free the returned array with dbus_free_string_array().
2894  *
2895  * An empty but non-NULL path array means the path "/".
2896  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
2897  * and the path "/" becomes { NULL }.
2898  *
2899  * See also dbus_message_get_path().
2900  * 
2901  * @todo this could be optimized by using the len from the message
2902  * instead of calling strlen() again
2903  *
2904  * @param message the message
2905  * @param path place to store allocated array of path components; #NULL set here if no path field exists
2906  * @returns #FALSE if no memory to allocate the array
2907  */
2908 dbus_bool_t
2909 dbus_message_get_path_decomposed (DBusMessage   *message,
2910                                   char        ***path)
2911 {
2912   const char *v;
2913
2914   _dbus_return_val_if_fail (message != NULL, FALSE);
2915   _dbus_return_val_if_fail (path != NULL, FALSE);
2916
2917   *path = NULL;
2918
2919   v = dbus_message_get_path (message);
2920   if (v != NULL)
2921     {
2922       if (!_dbus_decompose_path (v, strlen (v),
2923                                  path, NULL))
2924         return FALSE;
2925     }
2926   return TRUE;
2927 }
2928
2929 /**
2930  * Sets the interface this message is being sent to
2931  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
2932  * the interface a signal is being emitted from
2933  * (for DBUS_MESSAGE_TYPE_SIGNAL).
2934  *
2935  * The interface name must contain only valid characters as defined
2936  * in the D-Bus specification.
2937  * 
2938  * @param message the message
2939  * @param interface the interface or #NULL to unset
2940  * @returns #FALSE if not enough memory
2941  */
2942 dbus_bool_t
2943 dbus_message_set_interface (DBusMessage  *message,
2944                             const char   *interface)
2945 {
2946   _dbus_return_val_if_fail (message != NULL, FALSE);
2947   _dbus_return_val_if_fail (!message->locked, FALSE);
2948   _dbus_return_val_if_fail (interface == NULL ||
2949                             _dbus_check_is_valid_interface (interface),
2950                             FALSE);
2951
2952   return set_or_delete_string_field (message,
2953                                      DBUS_HEADER_FIELD_INTERFACE,
2954                                      DBUS_TYPE_STRING,
2955                                      interface);
2956 }
2957
2958 /**
2959  * Gets the interface this message is being sent to
2960  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
2961  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
2962  * The interface name is fully-qualified (namespaced).
2963  * Returns #NULL if none.
2964  *
2965  * The returned string becomes invalid if the message is
2966  * modified, since it points into the wire-marshaled message data.
2967  *
2968  * @param message the message
2969  * @returns the message interface (should not be freed) or #NULL
2970  */
2971 const char*
2972 dbus_message_get_interface (DBusMessage *message)
2973 {
2974   const char *v;
2975
2976   _dbus_return_val_if_fail (message != NULL, NULL);
2977
2978   v = NULL; /* in case field doesn't exist */
2979   _dbus_header_get_field_basic (&message->header,
2980                                 DBUS_HEADER_FIELD_INTERFACE,
2981                                 DBUS_TYPE_STRING,
2982                                 &v);
2983   return v;
2984 }
2985
2986 /**
2987  * Checks if the message has an interface
2988  *
2989  * @param message the message
2990  * @param interface the interface name
2991  * @returns #TRUE if the interface field in the header matches
2992  */
2993 dbus_bool_t
2994 dbus_message_has_interface (DBusMessage   *message,
2995                             const char    *interface)
2996 {
2997   const char *msg_interface;
2998   msg_interface = dbus_message_get_interface (message);
2999    
3000   if (msg_interface == NULL)
3001     {
3002       if (interface == NULL)
3003         return TRUE;
3004       else
3005         return FALSE;
3006     }
3007
3008   if (interface == NULL)
3009     return FALSE;
3010      
3011   if (strcmp (msg_interface, interface) == 0)
3012     return TRUE;
3013
3014   return FALSE;
3015
3016 }
3017
3018 /**
3019  * Sets the interface member being invoked
3020  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3021  * (DBUS_MESSAGE_TYPE_SIGNAL).
3022  *
3023  * The member name must contain only valid characters as defined
3024  * in the D-Bus specification.
3025  *
3026  * @param message the message
3027  * @param member the member or #NULL to unset
3028  * @returns #FALSE if not enough memory
3029  */
3030 dbus_bool_t
3031 dbus_message_set_member (DBusMessage  *message,
3032                          const char   *member)
3033 {
3034   _dbus_return_val_if_fail (message != NULL, FALSE);
3035   _dbus_return_val_if_fail (!message->locked, FALSE);
3036   _dbus_return_val_if_fail (member == NULL ||
3037                             _dbus_check_is_valid_member (member),
3038                             FALSE);
3039
3040   return set_or_delete_string_field (message,
3041                                      DBUS_HEADER_FIELD_MEMBER,
3042                                      DBUS_TYPE_STRING,
3043                                      member);
3044 }
3045
3046 /**
3047  * Gets the interface member being invoked
3048  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3049  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3050  *
3051  * The returned string becomes invalid if the message is
3052  * modified, since it points into the wire-marshaled message data.
3053  * 
3054  * @param message the message
3055  * @returns the member name (should not be freed) or #NULL
3056  */
3057 const char*
3058 dbus_message_get_member (DBusMessage *message)
3059 {
3060   const char *v;
3061
3062   _dbus_return_val_if_fail (message != NULL, NULL);
3063
3064   v = NULL; /* in case field doesn't exist */
3065   _dbus_header_get_field_basic (&message->header,
3066                                 DBUS_HEADER_FIELD_MEMBER,
3067                                 DBUS_TYPE_STRING,
3068                                 &v);
3069   return v;
3070 }
3071
3072 /**
3073  * Checks if the message has an interface member
3074  *
3075  * @param message the message
3076  * @param member the member name
3077  * @returns #TRUE if there is a member field in the header
3078  */
3079 dbus_bool_t
3080 dbus_message_has_member (DBusMessage   *message,
3081                          const char    *member)
3082 {
3083   const char *msg_member;
3084   msg_member = dbus_message_get_member (message);
3085  
3086   if (msg_member == NULL)
3087     {
3088       if (member == NULL)
3089         return TRUE;
3090       else
3091         return FALSE;
3092     }
3093
3094   if (member == NULL)
3095     return FALSE;
3096     
3097   if (strcmp (msg_member, member) == 0)
3098     return TRUE;
3099
3100   return FALSE;
3101
3102 }
3103
3104 /**
3105  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
3106  * The name is fully-qualified (namespaced).
3107  *
3108  * The error name must contain only valid characters as defined
3109  * in the D-Bus specification.
3110  *
3111  * @param message the message
3112  * @param error_name the name or #NULL to unset
3113  * @returns #FALSE if not enough memory
3114  */
3115 dbus_bool_t
3116 dbus_message_set_error_name (DBusMessage  *message,
3117                              const char   *error_name)
3118 {
3119   _dbus_return_val_if_fail (message != NULL, FALSE);
3120   _dbus_return_val_if_fail (!message->locked, FALSE);
3121   _dbus_return_val_if_fail (error_name == NULL ||
3122                             _dbus_check_is_valid_error_name (error_name),
3123                             FALSE);
3124
3125   return set_or_delete_string_field (message,
3126                                      DBUS_HEADER_FIELD_ERROR_NAME,
3127                                      DBUS_TYPE_STRING,
3128                                      error_name);
3129 }
3130
3131 /**
3132  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
3133  * or #NULL if none.
3134  *
3135  * The returned string becomes invalid if the message is
3136  * modified, since it points into the wire-marshaled message data.
3137  * 
3138  * @param message the message
3139  * @returns the error name (should not be freed) or #NULL
3140  */
3141 const char*
3142 dbus_message_get_error_name (DBusMessage *message)
3143 {
3144   const char *v;
3145
3146   _dbus_return_val_if_fail (message != NULL, NULL);
3147
3148   v = NULL; /* in case field doesn't exist */
3149   _dbus_header_get_field_basic (&message->header,
3150                                 DBUS_HEADER_FIELD_ERROR_NAME,
3151                                 DBUS_TYPE_STRING,
3152                                 &v);
3153   return v;
3154 }
3155
3156 /**
3157  * Sets the message's destination. The destination is the name of
3158  * another connection on the bus and may be either the unique name
3159  * assigned by the bus to each connection, or a well-known name
3160  * specified in advance.
3161  *
3162  * The destination name must contain only valid characters as defined
3163  * in the D-Bus specification.
3164  * 
3165  * @param message the message
3166  * @param destination the destination name or #NULL to unset
3167  * @returns #FALSE if not enough memory
3168  */
3169 dbus_bool_t
3170 dbus_message_set_destination (DBusMessage  *message,
3171                               const char   *destination)
3172 {
3173   _dbus_return_val_if_fail (message != NULL, FALSE);
3174   _dbus_return_val_if_fail (!message->locked, FALSE);
3175   _dbus_return_val_if_fail (destination == NULL ||
3176                             _dbus_check_is_valid_bus_name (destination),
3177                             FALSE);
3178
3179   return set_or_delete_string_field (message,
3180                                      DBUS_HEADER_FIELD_DESTINATION,
3181                                      DBUS_TYPE_STRING,
3182                                      destination);
3183 }
3184
3185 /**
3186  * Gets the destination of a message or #NULL if there is none set.
3187  *
3188  * The returned string becomes invalid if the message is
3189  * modified, since it points into the wire-marshaled message data.
3190  *
3191  * @param message the message
3192  * @returns the message destination (should not be freed) or #NULL
3193  */
3194 const char*
3195 dbus_message_get_destination (DBusMessage *message)
3196 {
3197   const char *v;
3198
3199   _dbus_return_val_if_fail (message != NULL, NULL);
3200
3201   v = NULL; /* in case field doesn't exist */
3202   _dbus_header_get_field_basic (&message->header,
3203                                 DBUS_HEADER_FIELD_DESTINATION,
3204                                 DBUS_TYPE_STRING,
3205                                 &v);
3206   return v;
3207 }
3208
3209 /**
3210  * Sets the message sender.
3211  *
3212  * The sender must be a valid bus name as defined in the D-Bus
3213  * specification.
3214  *
3215  * Usually you don't want to call this. The message bus daemon will
3216  * call it to set the origin of each message. If you aren't implementing
3217  * a message bus daemon you shouldn't need to set the sender.
3218  *
3219  * @param message the message
3220  * @param sender the sender or #NULL to unset
3221  * @returns #FALSE if not enough memory
3222  */
3223 dbus_bool_t
3224 dbus_message_set_sender (DBusMessage  *message,
3225                          const char   *sender)
3226 {
3227   _dbus_return_val_if_fail (message != NULL, FALSE);
3228   _dbus_return_val_if_fail (!message->locked, FALSE);
3229   _dbus_return_val_if_fail (sender == NULL ||
3230                             _dbus_check_is_valid_bus_name (sender),
3231                             FALSE);
3232
3233   return set_or_delete_string_field (message,
3234                                      DBUS_HEADER_FIELD_SENDER,
3235                                      DBUS_TYPE_STRING,
3236                                      sender);
3237 }
3238
3239 /**
3240  * Gets the unique name of the connection which originated this
3241  * message, or #NULL if unknown or inapplicable. The sender is filled
3242  * in by the message bus.
3243  *
3244  * Note, the returned sender is always the unique bus name.
3245  * Connections may own multiple other bus names, but those
3246  * are not found in the sender field.
3247  * 
3248  * The returned string becomes invalid if the message is
3249  * modified, since it points into the wire-marshaled message data.
3250  *
3251  * @param message the message
3252  * @returns the unique name of the sender or #NULL
3253  */
3254 const char*
3255 dbus_message_get_sender (DBusMessage *message)
3256 {
3257   const char *v;
3258
3259   _dbus_return_val_if_fail (message != NULL, NULL);
3260
3261   v = NULL; /* in case field doesn't exist */
3262   _dbus_header_get_field_basic (&message->header,
3263                                 DBUS_HEADER_FIELD_SENDER,
3264                                 DBUS_TYPE_STRING,
3265                                 &v);
3266   return v;
3267 }
3268
3269 /**
3270  * Gets the type signature of the message, i.e. the arguments in the
3271  * message payload. The signature includes only "in" arguments for
3272  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
3273  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
3274  * what you might expect (that is, it does not include the signature of the
3275  * entire C++-style method).
3276  *
3277  * The signature is a string made up of type codes such as
3278  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
3279  * the value of #DBUS_TYPE_INVALID).
3280  *
3281  * The returned string becomes invalid if the message is
3282  * modified, since it points into the wire-marshaled message data.
3283  *
3284  * @param message the message
3285  * @returns the type signature
3286  */
3287 const char*
3288 dbus_message_get_signature (DBusMessage *message)
3289 {
3290   const DBusString *type_str;
3291   int type_pos;
3292
3293   _dbus_return_val_if_fail (message != NULL, NULL);
3294
3295   get_const_signature (&message->header, &type_str, &type_pos);
3296
3297   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
3298 }
3299
3300 static dbus_bool_t
3301 _dbus_message_has_type_interface_member (DBusMessage *message,
3302                                          int          type,
3303                                          const char  *interface,
3304                                          const char  *member)
3305 {
3306   const char *n;
3307
3308   _dbus_assert (message != NULL);
3309   _dbus_assert (interface != NULL);
3310   _dbus_assert (member != NULL);
3311
3312   if (dbus_message_get_type (message) != type)
3313     return FALSE;
3314
3315   /* Optimize by checking the short member name first
3316    * instead of the longer interface name
3317    */
3318
3319   n = dbus_message_get_member (message);
3320
3321   if (n && strcmp (n, member) == 0)
3322     {
3323       n = dbus_message_get_interface (message);
3324
3325       if (n == NULL || strcmp (n, interface) == 0)
3326         return TRUE;
3327     }
3328
3329   return FALSE;
3330 }
3331
3332 /**
3333  * Checks whether the message is a method call with the given
3334  * interface and member fields.  If the message is not
3335  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
3336  * member field, returns #FALSE. If the interface field is missing,
3337  * then it will be assumed equal to the provided interface.  The D-Bus
3338  * protocol allows method callers to leave out the interface name.
3339  *
3340  * @param message the message
3341  * @param interface the name to check (must not be #NULL)
3342  * @param method the name to check (must not be #NULL)
3343  *
3344  * @returns #TRUE if the message is the specified method call
3345  */
3346 dbus_bool_t
3347 dbus_message_is_method_call (DBusMessage *message,
3348                              const char  *interface,
3349                              const char  *method)
3350 {
3351   _dbus_return_val_if_fail (message != NULL, FALSE);
3352   _dbus_return_val_if_fail (interface != NULL, FALSE);
3353   _dbus_return_val_if_fail (method != NULL, FALSE);
3354   /* don't check that interface/method are valid since it would be
3355    * expensive, and not catch many common errors
3356    */
3357
3358   return _dbus_message_has_type_interface_member (message,
3359                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
3360                                                   interface, method);
3361 }
3362
3363 /**
3364  * Checks whether the message is a signal with the given interface and
3365  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
3366  * has a different interface or member field, returns #FALSE.
3367  *
3368  * @param message the message
3369  * @param interface the name to check (must not be #NULL)
3370  * @param signal_name the name to check (must not be #NULL)
3371  *
3372  * @returns #TRUE if the message is the specified signal
3373  */
3374 dbus_bool_t
3375 dbus_message_is_signal (DBusMessage *message,
3376                         const char  *interface,
3377                         const char  *signal_name)
3378 {
3379   _dbus_return_val_if_fail (message != NULL, FALSE);
3380   _dbus_return_val_if_fail (interface != NULL, FALSE);
3381   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
3382   /* don't check that interface/name are valid since it would be
3383    * expensive, and not catch many common errors
3384    */
3385
3386   return _dbus_message_has_type_interface_member (message,
3387                                                   DBUS_MESSAGE_TYPE_SIGNAL,
3388                                                   interface, signal_name);
3389 }
3390
3391 /**
3392  * Checks whether the message is an error reply with the given error
3393  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
3394  * different name, returns #FALSE.
3395  *
3396  * @param message the message
3397  * @param error_name the name to check (must not be #NULL)
3398  *
3399  * @returns #TRUE if the message is the specified error
3400  */
3401 dbus_bool_t
3402 dbus_message_is_error (DBusMessage *message,
3403                        const char  *error_name)
3404 {
3405   const char *n;
3406
3407   _dbus_return_val_if_fail (message != NULL, FALSE);
3408   _dbus_return_val_if_fail (error_name != NULL, FALSE);
3409   /* don't check that error_name is valid since it would be expensive,
3410    * and not catch many common errors
3411    */
3412
3413   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3414     return FALSE;
3415
3416   n = dbus_message_get_error_name (message);
3417
3418   if (n && strcmp (n, error_name) == 0)
3419     return TRUE;
3420   else
3421     return FALSE;
3422 }
3423
3424 /**
3425  * Checks whether the message was sent to the given name.  If the
3426  * message has no destination specified or has a different
3427  * destination, returns #FALSE.
3428  *
3429  * @param message the message
3430  * @param name the name to check (must not be #NULL)
3431  *
3432  * @returns #TRUE if the message has the given destination name
3433  */
3434 dbus_bool_t
3435 dbus_message_has_destination (DBusMessage  *message,
3436                               const char   *name)
3437 {
3438   const char *s;
3439
3440   _dbus_return_val_if_fail (message != NULL, FALSE);
3441   _dbus_return_val_if_fail (name != NULL, FALSE);
3442   /* don't check that name is valid since it would be expensive, and
3443    * not catch many common errors
3444    */
3445
3446   s = dbus_message_get_destination (message);
3447
3448   if (s && strcmp (s, name) == 0)
3449     return TRUE;
3450   else
3451     return FALSE;
3452 }
3453
3454 /**
3455  * Checks whether the message has the given unique name as its sender.
3456  * If the message has no sender specified or has a different sender,
3457  * returns #FALSE. Note that a peer application will always have the
3458  * unique name of the connection as the sender. So you can't use this
3459  * function to see whether a sender owned a well-known name.
3460  *
3461  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
3462  * as the sender.
3463  *
3464  * @param message the message
3465  * @param name the name to check (must not be #NULL)
3466  *
3467  * @returns #TRUE if the message has the given sender
3468  */
3469 dbus_bool_t
3470 dbus_message_has_sender (DBusMessage  *message,
3471                          const char   *name)
3472 {
3473   const char *s;
3474
3475   _dbus_return_val_if_fail (message != NULL, FALSE);
3476   _dbus_return_val_if_fail (name != NULL, FALSE);
3477   /* don't check that name is valid since it would be expensive, and
3478    * not catch many common errors
3479    */
3480
3481   s = dbus_message_get_sender (message);
3482
3483   if (s && strcmp (s, name) == 0)
3484     return TRUE;
3485   else
3486     return FALSE;
3487 }
3488
3489 /**
3490  * Checks whether the message has the given signature; see
3491  * dbus_message_get_signature() for more details on what the signature
3492  * looks like.
3493  *
3494  * @param message the message
3495  * @param signature typecode array
3496  * @returns #TRUE if message has the given signature
3497 */
3498 dbus_bool_t
3499 dbus_message_has_signature (DBusMessage   *message,
3500                             const char    *signature)
3501 {
3502   const char *s;
3503
3504   _dbus_return_val_if_fail (message != NULL, FALSE);
3505   _dbus_return_val_if_fail (signature != NULL, FALSE);
3506   /* don't check that signature is valid since it would be expensive,
3507    * and not catch many common errors
3508    */
3509
3510   s = dbus_message_get_signature (message);
3511
3512   if (s && strcmp (s, signature) == 0)
3513     return TRUE;
3514   else
3515     return FALSE;
3516 }
3517
3518 /**
3519  * Sets a #DBusError based on the contents of the given
3520  * message. The error is only set if the message
3521  * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
3522  * The name of the error is set to the name of the message,
3523  * and the error message is set to the first argument
3524  * if the argument exists and is a string.
3525  *
3526  * The return value indicates whether the error was set (the error is
3527  * set if and only if the message is an error message).  So you can
3528  * check for an error reply and convert it to DBusError in one go:
3529  * @code
3530  *  if (dbus_set_error_from_message (error, reply))
3531  *    return error;
3532  *  else
3533  *    process reply;
3534  * @endcode
3535  *
3536  * @param error the error to set
3537  * @param message the message to set it from
3538  * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
3539  */
3540 dbus_bool_t
3541 dbus_set_error_from_message (DBusError   *error,
3542                              DBusMessage *message)
3543 {
3544   const char *str;
3545
3546   _dbus_return_val_if_fail (message != NULL, FALSE);
3547   _dbus_return_val_if_error_is_set (error, FALSE);
3548
3549   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
3550     return FALSE;
3551
3552   str = NULL;
3553   dbus_message_get_args (message, NULL,
3554                          DBUS_TYPE_STRING, &str,
3555                          DBUS_TYPE_INVALID);
3556
3557   dbus_set_error (error, dbus_message_get_error_name (message),
3558                   str ? "%s" : NULL, str);
3559
3560   return TRUE;
3561 }
3562
3563 /** @} */
3564
3565 /**
3566  * @addtogroup DBusMessageInternals
3567  *
3568  * @{
3569  */
3570
3571 /**
3572  * The initial buffer size of the message loader.
3573  *
3574  * @todo this should be based on min header size plus some average
3575  * body size, or something. Or rather, the min header size only, if we
3576  * want to try to read only the header, store that in a DBusMessage,
3577  * then read only the body and store that, etc., depends on
3578  * how we optimize _dbus_message_loader_get_buffer() and what
3579  * the exact message format is.
3580  */
3581 #define INITIAL_LOADER_DATA_LEN 32
3582
3583 /**
3584  * Creates a new message loader. Returns #NULL if memory can't
3585  * be allocated.
3586  *
3587  * @returns new loader, or #NULL.
3588  */
3589 DBusMessageLoader*
3590 _dbus_message_loader_new (void)
3591 {
3592   DBusMessageLoader *loader;
3593
3594   loader = dbus_new0 (DBusMessageLoader, 1);
3595   if (loader == NULL)
3596     return NULL;
3597   
3598   loader->refcount = 1;
3599
3600   loader->corrupted = FALSE;
3601   loader->corruption_reason = DBUS_VALID;
3602
3603   /* this can be configured by the app, but defaults to the protocol max */
3604   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
3605
3606   /* We set a very relatively conservative default here since due to how
3607   SCM_RIGHTS works we need to preallocate an fd array of the maximum
3608   number of unix fds we want to receive in advance. A
3609   try-and-reallocate loop is not possible. */
3610   loader->max_message_unix_fds = 1024;
3611
3612   if (!_dbus_string_init (&loader->data))
3613     {
3614       dbus_free (loader);
3615       return NULL;
3616     }
3617
3618   /* preallocate the buffer for speed, ignore failure */
3619   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
3620   _dbus_string_set_length (&loader->data, 0);
3621
3622 #ifdef HAVE_UNIX_FD_PASSING
3623   loader->unix_fds = NULL;
3624   loader->n_unix_fds = loader->n_unix_fds_allocated = 0;
3625   loader->unix_fds_outstanding = FALSE;
3626 #endif
3627
3628   return loader;
3629 }
3630
3631 /**
3632  * Increments the reference count of the loader.
3633  *
3634  * @param loader the loader.
3635  * @returns the loader
3636  */
3637 DBusMessageLoader *
3638 _dbus_message_loader_ref (DBusMessageLoader *loader)
3639 {
3640   loader->refcount += 1;
3641
3642   return loader;
3643 }
3644
3645 /**
3646  * Decrements the reference count of the loader and finalizes the
3647  * loader when the count reaches zero.
3648  *
3649  * @param loader the loader.
3650  */
3651 void
3652 _dbus_message_loader_unref (DBusMessageLoader *loader)
3653 {
3654   loader->refcount -= 1;
3655   if (loader->refcount == 0)
3656     {
3657 #ifdef HAVE_UNIX_FD_PASSING
3658       close_unix_fds(loader->unix_fds, &loader->n_unix_fds);
3659       dbus_free(loader->unix_fds);
3660 #endif
3661       _dbus_list_foreach (&loader->messages,
3662                           (DBusForeachFunction) dbus_message_unref,
3663                           NULL);
3664       _dbus_list_clear (&loader->messages);
3665       _dbus_string_free (&loader->data);
3666       dbus_free (loader);
3667     }
3668 }
3669
3670 /**
3671  * Gets the buffer to use for reading data from the network.  Network
3672  * data is read directly into an allocated buffer, which is then used
3673  * in the DBusMessage, to avoid as many extra memcpy's as possible.
3674  * The buffer must always be returned immediately using
3675  * _dbus_message_loader_return_buffer(), even if no bytes are
3676  * successfully read.
3677  *
3678  * @todo this function can be a lot more clever. For example
3679  * it can probably always return a buffer size to read exactly
3680  * the body of the next message, thus avoiding any memory wastage
3681  * or reallocs.
3682  *
3683  * @todo we need to enforce a max length on strings in header fields.
3684  *
3685  * @param loader the message loader.
3686  * @param buffer the buffer
3687  */
3688 void
3689 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
3690                                  DBusString        **buffer)
3691 {
3692   _dbus_assert (!loader->buffer_outstanding);
3693
3694   *buffer = &loader->data;
3695
3696   loader->buffer_outstanding = TRUE;
3697 }
3698
3699 /**
3700  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
3701  * indicating to the loader how many bytes of the buffer were filled
3702  * in. This function must always be called, even if no bytes were
3703  * successfully read.
3704  *
3705  * @param loader the loader.
3706  * @param buffer the buffer.
3707  * @param bytes_read number of bytes that were read into the buffer.
3708  */
3709 void
3710 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
3711                                     DBusString         *buffer,
3712                                     int                 bytes_read)
3713 {
3714   _dbus_assert (loader->buffer_outstanding);
3715   _dbus_assert (buffer == &loader->data);
3716
3717   loader->buffer_outstanding = FALSE;
3718 }
3719
3720 /**
3721  * Gets the buffer to use for reading unix fds from the network.
3722  *
3723  * This works similar to _dbus_message_loader_get_buffer()
3724  *
3725  * @param loader the message loader.
3726  * @param fds the array to read fds into
3727  * @param max_n_fds how many fds to read at most
3728  * @return TRUE on success, FALSE on OOM
3729  */
3730 dbus_bool_t
3731 _dbus_message_loader_get_unix_fds(DBusMessageLoader  *loader,
3732                                   int               **fds,
3733                                   unsigned           *max_n_fds)
3734 {
3735 #ifdef HAVE_UNIX_FD_PASSING
3736   _dbus_assert (!loader->unix_fds_outstanding);
3737
3738   /* Allocate space where we can put the fds we read. We allocate
3739      space for max_message_unix_fds since this is an
3740      upper limit how many fds can be received within a single
3741      message. Since SCM_RIGHTS doesn't allow a reallocate+retry logic
3742      we are allocating the maximum possible array size right from the
3743      beginning. This sucks a bit, however unless SCM_RIGHTS is fixed
3744      there is no better way. */
3745
3746   if (loader->n_unix_fds_allocated < loader->max_message_unix_fds)
3747     {
3748       int *a = dbus_realloc(loader->unix_fds,
3749                             loader->max_message_unix_fds * sizeof(loader->unix_fds[0]));
3750
3751       if (!a)
3752         return FALSE;
3753
3754       loader->unix_fds = a;
3755       loader->n_unix_fds_allocated = loader->max_message_unix_fds;
3756     }
3757
3758   *fds = loader->unix_fds + loader->n_unix_fds;
3759   *max_n_fds = loader->n_unix_fds_allocated - loader->n_unix_fds;
3760
3761   loader->unix_fds_outstanding = TRUE;
3762   return TRUE;
3763 #else
3764   _dbus_assert_not_reached("Platform doesn't support unix fd passing");
3765 #endif
3766 }
3767
3768 /**
3769  * Returns a buffer obtained from _dbus_message_loader_get_unix_fds().
3770  *
3771  * This works similar to _dbus_message_loader_return_buffer()
3772  *
3773  * @param loader the message loader.
3774  * @param fds the array fds were read into
3775  * @param max_n_fds how many fds were read
3776  */
3777
3778 void
3779 _dbus_message_loader_return_unix_fds(DBusMessageLoader  *loader,
3780                                      int                *fds,
3781                                      unsigned            n_fds)
3782 {
3783 #ifdef HAVE_UNIX_FD_PASSING
3784   _dbus_assert(loader->unix_fds_outstanding);
3785   _dbus_assert(loader->unix_fds + loader->n_unix_fds == fds);
3786   _dbus_assert(loader->n_unix_fds + n_fds <= loader->n_unix_fds_allocated);
3787
3788   loader->n_unix_fds += n_fds;
3789   loader->unix_fds_outstanding = FALSE;
3790 #else
3791   _dbus_assert_not_reached("Platform doesn't support unix fd passing");
3792 #endif
3793 }
3794
3795 /*
3796  * FIXME when we move the header out of the buffer, that memmoves all
3797  * buffered messages. Kind of crappy.
3798  *
3799  * Also we copy the header and body, which is kind of crappy.  To
3800  * avoid this, we have to allow header and body to be in a single
3801  * memory block, which is good for messages we read and bad for
3802  * messages we are creating. But we could move_len() the buffer into
3803  * this single memory block, and move_len() will just swap the buffers
3804  * if you're moving the entire buffer replacing the dest string.
3805  *
3806  * We could also have the message loader tell the transport how many
3807  * bytes to read; so it would first ask for some arbitrary number like
3808  * 256, then if the message was incomplete it would use the
3809  * header/body len to ask for exactly the size of the message (or
3810  * blocks the size of a typical kernel buffer for the socket). That
3811  * way we don't get trailing bytes in the buffer that have to be
3812  * memmoved. Though I suppose we also don't have a chance of reading a
3813  * bunch of small messages at once, so the optimization may be stupid.
3814  *
3815  * Another approach would be to keep a "start" index into
3816  * loader->data and only delete it occasionally, instead of after
3817  * each message is loaded.
3818  *
3819  * load_message() returns FALSE if not enough memory OR the loader was corrupted
3820  */
3821 static dbus_bool_t
3822 load_message (DBusMessageLoader *loader,
3823               DBusMessage       *message,
3824               int                byte_order,
3825               int                fields_array_len,
3826               int                header_len,
3827               int                body_len)
3828 {
3829   dbus_bool_t oom;
3830   DBusValidity validity;
3831   const DBusString *type_str;
3832   int type_pos;
3833   DBusValidationMode mode;
3834   dbus_uint32_t n_unix_fds = 0;
3835
3836   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
3837   
3838   oom = FALSE;
3839
3840 #if 0
3841   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
3842 #endif
3843
3844   /* 1. VALIDATE AND COPY OVER HEADER */
3845   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
3846   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
3847
3848   if (!_dbus_header_load (&message->header,
3849                           mode,
3850                           &validity,
3851                           byte_order,
3852                           fields_array_len,
3853                           header_len,
3854                           body_len,
3855                           &loader->data, 0,
3856                           _dbus_string_get_length (&loader->data)))
3857     {
3858       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
3859
3860       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
3861          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
3862       _dbus_assert (validity != DBUS_VALID);
3863
3864       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3865         oom = TRUE;
3866       else
3867         {
3868           loader->corrupted = TRUE;
3869           loader->corruption_reason = validity;
3870         }
3871       goto failed;
3872     }
3873
3874   _dbus_assert (validity == DBUS_VALID);
3875
3876   message->byte_order = byte_order;
3877
3878   /* 2. VALIDATE BODY */
3879   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
3880     {
3881       get_const_signature (&message->header, &type_str, &type_pos);
3882       
3883       /* Because the bytes_remaining arg is NULL, this validates that the
3884        * body is the right length
3885        */
3886       validity = _dbus_validate_body_with_reason (type_str,
3887                                                   type_pos,
3888                                                   byte_order,
3889                                                   NULL,
3890                                                   &loader->data,
3891                                                   header_len,
3892                                                   body_len);
3893       if (validity != DBUS_VALID)
3894         {
3895           _dbus_verbose ("Failed to validate message body code %d\n", validity);
3896
3897           loader->corrupted = TRUE;
3898           loader->corruption_reason = validity;
3899           
3900           goto failed;
3901         }
3902     }
3903
3904   /* 3. COPY OVER UNIX FDS */
3905   _dbus_header_get_field_basic(&message->header,
3906                                DBUS_HEADER_FIELD_UNIX_FDS,
3907                                DBUS_TYPE_UINT32,
3908                                &n_unix_fds);
3909
3910 #ifdef HAVE_UNIX_FD_PASSING
3911
3912   if (n_unix_fds > loader->n_unix_fds)
3913     {
3914       _dbus_verbose("Message contains references to more unix fds than were sent %u != %u\n",
3915                     n_unix_fds, loader->n_unix_fds);
3916
3917       loader->corrupted = TRUE;
3918       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
3919       goto failed;
3920     }
3921
3922   /* If this was a recycled message there might still be
3923      some memory allocated for the fds */
3924   dbus_free(message->unix_fds);
3925
3926   if (n_unix_fds > 0)
3927     {
3928       message->unix_fds = _dbus_memdup(loader->unix_fds, n_unix_fds * sizeof(message->unix_fds[0]));
3929       if (message->unix_fds == NULL)
3930         {
3931           _dbus_verbose ("Failed to allocate file descriptor array\n");
3932           oom = TRUE;
3933           goto failed;
3934         }
3935
3936       message->n_unix_fds_allocated = message->n_unix_fds = n_unix_fds;
3937       loader->n_unix_fds -= n_unix_fds;
3938       memmove(loader->unix_fds + n_unix_fds, loader->unix_fds, loader->n_unix_fds);
3939     }
3940   else
3941     message->unix_fds = NULL;
3942
3943 #else
3944
3945   if (n_unix_fds > 0)
3946     {
3947       _dbus_verbose ("Hmm, message claims to come with file descriptors "
3948                      "but that's not supported on our platform, disconnecting.\n");
3949
3950       loader->corrupted = TRUE;
3951       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
3952       goto failed;
3953     }
3954
3955 #endif
3956
3957   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
3958
3959   if (!_dbus_list_append (&loader->messages, message))
3960     {
3961       _dbus_verbose ("Failed to append new message to loader queue\n");
3962       oom = TRUE;
3963       goto failed;
3964     }
3965
3966   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
3967   _dbus_assert (_dbus_string_get_length (&loader->data) >=
3968                 (header_len + body_len));
3969
3970   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
3971     {
3972       _dbus_verbose ("Failed to move body into new message\n");
3973       oom = TRUE;
3974       goto failed;
3975     }
3976
3977   _dbus_string_delete (&loader->data, 0, header_len + body_len);
3978
3979   /* don't waste more than 2k of memory */
3980   _dbus_string_compact (&loader->data, 2048);
3981
3982   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
3983   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
3984
3985   _dbus_verbose ("Loaded message %p\n", message);
3986
3987   _dbus_assert (!oom);
3988   _dbus_assert (!loader->corrupted);
3989   _dbus_assert (loader->messages != NULL);
3990   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
3991
3992   return TRUE;
3993
3994  failed:
3995
3996   /* Clean up */
3997
3998   /* does nothing if the message isn't in the list */
3999   _dbus_list_remove_last (&loader->messages, message);
4000   
4001   if (oom)
4002     _dbus_assert (!loader->corrupted);
4003   else
4004     _dbus_assert (loader->corrupted);
4005
4006   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
4007
4008   return FALSE;
4009 }
4010
4011 /**
4012  * Converts buffered data into messages, if we have enough data.  If
4013  * we don't have enough data, does nothing.
4014  *
4015  * @todo we need to check that the proper named header fields exist
4016  * for each message type.
4017  *
4018  * @todo If a message has unknown type, we should probably eat it
4019  * right here rather than passing it out to applications.  However
4020  * it's not an error to see messages of unknown type.
4021  *
4022  * @param loader the loader.
4023  * @returns #TRUE if we had enough memory to finish.
4024  */
4025 dbus_bool_t
4026 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
4027 {
4028   while (!loader->corrupted &&
4029          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
4030     {
4031       DBusValidity validity;
4032       int byte_order, fields_array_len, header_len, body_len;
4033
4034       if (_dbus_header_have_message_untrusted (loader->max_message_size,
4035                                                &validity,
4036                                                &byte_order,
4037                                                &fields_array_len,
4038                                                &header_len,
4039                                                &body_len,
4040                                                &loader->data, 0,
4041                                                _dbus_string_get_length (&loader->data)))
4042         {
4043           DBusMessage *message;
4044
4045           _dbus_assert (validity == DBUS_VALID);
4046
4047           message = dbus_message_new_empty_header ();
4048           if (message == NULL)
4049             return FALSE;
4050
4051           if (!load_message (loader, message,
4052                              byte_order, fields_array_len,
4053                              header_len, body_len))
4054             {
4055               dbus_message_unref (message);
4056               /* load_message() returns false if corrupted or OOM; if
4057                * corrupted then return TRUE for not OOM
4058                */
4059               return loader->corrupted;
4060             }
4061
4062           _dbus_assert (loader->messages != NULL);
4063           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4064         }
4065       else
4066         {
4067           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
4068                          validity);
4069           if (validity != DBUS_VALID)
4070             {
4071               loader->corrupted = TRUE;
4072               loader->corruption_reason = validity;
4073             }
4074           return TRUE;
4075         }
4076     }
4077
4078   return TRUE;
4079 }
4080
4081 /**
4082  * Peeks at first loaded message, returns #NULL if no messages have
4083  * been queued.
4084  *
4085  * @param loader the loader.
4086  * @returns the next message, or #NULL if none.
4087  */
4088 DBusMessage*
4089 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
4090 {
4091   if (loader->messages)
4092     return loader->messages->data;
4093   else
4094     return NULL;
4095 }
4096
4097 /**
4098  * Pops a loaded message (passing ownership of the message
4099  * to the caller). Returns #NULL if no messages have been
4100  * queued.
4101  *
4102  * @param loader the loader.
4103  * @returns the next message, or #NULL if none.
4104  */
4105 DBusMessage*
4106 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
4107 {
4108   return _dbus_list_pop_first (&loader->messages);
4109 }
4110
4111 /**
4112  * Pops a loaded message inside a list link (passing ownership of the
4113  * message and link to the caller). Returns #NULL if no messages have
4114  * been loaded.
4115  *
4116  * @param loader the loader.
4117  * @returns the next message link, or #NULL if none.
4118  */
4119 DBusList*
4120 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
4121 {
4122   return _dbus_list_pop_first_link (&loader->messages);
4123 }
4124
4125 /**
4126  * Returns a popped message link, used to undo a pop.
4127  *
4128  * @param loader the loader
4129  * @param link the link with a message in it
4130  */
4131 void
4132 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
4133                                            DBusList           *link)
4134 {
4135   _dbus_list_prepend_link (&loader->messages, link);
4136 }
4137
4138 /**
4139  * Checks whether the loader is confused due to bad data.
4140  * If messages are received that are invalid, the
4141  * loader gets confused and gives up permanently.
4142  * This state is called "corrupted."
4143  *
4144  * @param loader the loader
4145  * @returns #TRUE if the loader is hosed.
4146  */
4147 dbus_bool_t
4148 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
4149 {
4150   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
4151                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
4152   return loader->corrupted;
4153 }
4154
4155 /**
4156  * Sets the maximum size message we allow.
4157  *
4158  * @param loader the loader
4159  * @param size the max message size in bytes
4160  */
4161 void
4162 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
4163                                            long                size)
4164 {
4165   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
4166     {
4167       _dbus_verbose ("clamping requested max message size %ld to %d\n",
4168                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
4169       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
4170     }
4171   loader->max_message_size = size;
4172 }
4173
4174 /**
4175  * Gets the maximum allowed message size in bytes.
4176  *
4177  * @param loader the loader
4178  * @returns max size in bytes
4179  */
4180 long
4181 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
4182 {
4183   return loader->max_message_size;
4184 }
4185
4186 /**
4187  * Sets the maximum unix fds per message we allow.
4188  *
4189  * @param loader the loader
4190  * @param size the max number of unix fds in a message
4191  */
4192 void
4193 _dbus_message_loader_set_max_message_unix_fds (DBusMessageLoader  *loader,
4194                                                long                n)
4195 {
4196   if (n > DBUS_MAXIMUM_MESSAGE_UNIX_FDS)
4197     {
4198       _dbus_verbose ("clamping requested max message unix_fds %ld to %d\n",
4199                      n, DBUS_MAXIMUM_MESSAGE_UNIX_FDS);
4200       n = DBUS_MAXIMUM_MESSAGE_UNIX_FDS;
4201     }
4202   loader->max_message_unix_fds = n;
4203 }
4204
4205 /**
4206  * Gets the maximum allowed number of unix fds per message
4207  *
4208  * @param loader the loader
4209  * @returns max unix fds
4210  */
4211 long
4212 _dbus_message_loader_get_max_message_unix_fds (DBusMessageLoader  *loader)
4213 {
4214   return loader->max_message_unix_fds;
4215 }
4216
4217 static DBusDataSlotAllocator slot_allocator;
4218 _DBUS_DEFINE_GLOBAL_LOCK (message_slots);
4219
4220 /**
4221  * Allocates an integer ID to be used for storing application-specific
4222  * data on any DBusMessage. The allocated ID may then be used
4223  * with dbus_message_set_data() and dbus_message_get_data().
4224  * The passed-in slot must be initialized to -1, and is filled in
4225  * with the slot ID. If the passed-in slot is not -1, it's assumed
4226  * to be already allocated, and its refcount is incremented.
4227  *
4228  * The allocated slot is global, i.e. all DBusMessage objects will
4229  * have a slot with the given integer ID reserved.
4230  *
4231  * @param slot_p address of a global variable storing the slot
4232  * @returns #FALSE on failure (no memory)
4233  */
4234 dbus_bool_t
4235 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
4236 {
4237   return _dbus_data_slot_allocator_alloc (&slot_allocator,
4238                                           &_DBUS_LOCK_NAME (message_slots),
4239                                           slot_p);
4240 }
4241
4242 /**
4243  * Deallocates a global ID for message data slots.
4244  * dbus_message_get_data() and dbus_message_set_data() may no
4245  * longer be used with this slot.  Existing data stored on existing
4246  * DBusMessage objects will be freed when the message is
4247  * finalized, but may not be retrieved (and may only be replaced if
4248  * someone else reallocates the slot).  When the refcount on the
4249  * passed-in slot reaches 0, it is set to -1.
4250  *
4251  * @param slot_p address storing the slot to deallocate
4252  */
4253 void
4254 dbus_message_free_data_slot (dbus_int32_t *slot_p)
4255 {
4256   _dbus_return_if_fail (*slot_p >= 0);
4257
4258   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
4259 }
4260
4261 /**
4262  * Stores a pointer on a DBusMessage, along
4263  * with an optional function to be used for freeing
4264  * the data when the data is set again, or when
4265  * the message is finalized. The slot number
4266  * must have been allocated with dbus_message_allocate_data_slot().
4267  *
4268  * @param message the message
4269  * @param slot the slot number
4270  * @param data the data to store
4271  * @param free_data_func finalizer function for the data
4272  * @returns #TRUE if there was enough memory to store the data
4273  */
4274 dbus_bool_t
4275 dbus_message_set_data (DBusMessage     *message,
4276                        dbus_int32_t     slot,
4277                        void            *data,
4278                        DBusFreeFunction free_data_func)
4279 {
4280   DBusFreeFunction old_free_func;
4281   void *old_data;
4282   dbus_bool_t retval;
4283
4284   _dbus_return_val_if_fail (message != NULL, FALSE);
4285   _dbus_return_val_if_fail (slot >= 0, FALSE);
4286
4287   retval = _dbus_data_slot_list_set (&slot_allocator,
4288                                      &message->slot_list,
4289                                      slot, data, free_data_func,
4290                                      &old_free_func, &old_data);
4291
4292   if (retval)
4293     {
4294       /* Do the actual free outside the message lock */
4295       if (old_free_func)
4296         (* old_free_func) (old_data);
4297     }
4298
4299   return retval;
4300 }
4301
4302 /**
4303  * Retrieves data previously set with dbus_message_set_data().
4304  * The slot must still be allocated (must not have been freed).
4305  *
4306  * @param message the message
4307  * @param slot the slot to get data from
4308  * @returns the data, or #NULL if not found
4309  */
4310 void*
4311 dbus_message_get_data (DBusMessage   *message,
4312                        dbus_int32_t   slot)
4313 {
4314   void *res;
4315
4316   _dbus_return_val_if_fail (message != NULL, NULL);
4317
4318   res = _dbus_data_slot_list_get (&slot_allocator,
4319                                   &message->slot_list,
4320                                   slot);
4321
4322   return res;
4323 }
4324
4325 /**
4326  * Utility function to convert a machine-readable (not translated)
4327  * string into a D-Bus message type.
4328  *
4329  * @code
4330  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
4331  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
4332  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
4333  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
4334  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
4335  * @endcode
4336  *
4337  */
4338 int
4339 dbus_message_type_from_string (const char *type_str)
4340 {
4341   if (strcmp (type_str, "method_call") == 0)
4342     return DBUS_MESSAGE_TYPE_METHOD_CALL;
4343   if (strcmp (type_str, "method_return") == 0)
4344     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
4345   else if (strcmp (type_str, "signal") == 0)
4346     return DBUS_MESSAGE_TYPE_SIGNAL;
4347   else if (strcmp (type_str, "error") == 0)
4348     return DBUS_MESSAGE_TYPE_ERROR;
4349   else
4350     return DBUS_MESSAGE_TYPE_INVALID;
4351 }
4352
4353 /**
4354  * Utility function to convert a D-Bus message type into a
4355  * machine-readable string (not translated).
4356  *
4357  * @code
4358  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
4359  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
4360  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
4361  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
4362  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
4363  * @endcode
4364  *
4365  */
4366 const char *
4367 dbus_message_type_to_string (int type)
4368 {
4369   switch (type)
4370     {
4371     case DBUS_MESSAGE_TYPE_METHOD_CALL:
4372       return "method_call";
4373     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
4374       return "method_return";
4375     case DBUS_MESSAGE_TYPE_SIGNAL:
4376       return "signal";
4377     case DBUS_MESSAGE_TYPE_ERROR:
4378       return "error";
4379     default:
4380       return "invalid";
4381     }
4382 }
4383
4384 /**
4385  * Turn a DBusMessage into the marshalled form as described in the D-Bus
4386  * specification.
4387  *
4388  * Generally, this function is only useful for encapsulating D-Bus messages in
4389  * a different protocol.
4390  *
4391  * @param msg the DBusMessage
4392  * @param marshalled_data_p the location to save the marshalled form to
4393  * @param len_p the location to save the length of the marshalled form to
4394  * @returns #FALSE if there was not enough memory
4395  */
4396 dbus_bool_t
4397 dbus_message_marshal (DBusMessage  *msg,
4398                       char        **marshalled_data_p,
4399                       int          *len_p)
4400 {
4401   DBusString tmp;
4402
4403   _dbus_return_val_if_fail (msg != NULL, FALSE);
4404   _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
4405   _dbus_return_val_if_fail (len_p != NULL, FALSE);
4406   
4407   if (!_dbus_string_init (&tmp))
4408     return FALSE;
4409
4410   if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
4411     goto fail;
4412
4413   *len_p = _dbus_string_get_length (&tmp);
4414
4415   if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
4416     goto fail;
4417
4418   *len_p = _dbus_string_get_length (&tmp);
4419
4420   if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
4421     goto fail;
4422
4423   _dbus_string_free (&tmp);
4424   return TRUE;
4425
4426  fail:
4427   _dbus_string_free (&tmp);
4428   return FALSE;
4429 }
4430
4431 /**
4432  * Demarshal a D-Bus message from the format described in the D-Bus
4433  * specification.
4434  *
4435  * Generally, this function is only useful for encapsulating D-Bus messages in
4436  * a different protocol.
4437  *
4438  * @param str the marshalled DBusMessage
4439  * @param len the length of str
4440  * @param error the location to save errors to
4441  * @returns #NULL if there was an error
4442  */
4443 DBusMessage *
4444 dbus_message_demarshal (const char *str,
4445                         int         len,
4446                         DBusError  *error)
4447 {
4448   DBusMessageLoader *loader;
4449   DBusString *buffer;
4450   DBusMessage *msg;
4451
4452   _dbus_return_val_if_fail (str != NULL, NULL);
4453
4454   loader = _dbus_message_loader_new ();
4455
4456   if (loader == NULL)
4457     return NULL;
4458
4459   _dbus_message_loader_get_buffer (loader, &buffer);
4460   _dbus_string_append_len (buffer, str, len);
4461   _dbus_message_loader_return_buffer (loader, buffer, len);
4462
4463   if (!_dbus_message_loader_queue_messages (loader))
4464     goto fail_oom;
4465
4466   if (_dbus_message_loader_get_is_corrupted (loader))
4467     goto fail_corrupt;
4468
4469   msg = _dbus_message_loader_pop_message (loader);
4470
4471   if (!msg)
4472     goto fail_oom;
4473
4474   _dbus_message_loader_unref (loader);
4475   return msg;
4476
4477  fail_corrupt:
4478   dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted");
4479   _dbus_message_loader_unref (loader);
4480   return NULL;
4481
4482  fail_oom:
4483   _DBUS_SET_OOM (error);
4484   _dbus_message_loader_unref (loader);
4485   return NULL;
4486 }
4487
4488 /**
4489  * Returns the number of bytes required to be in the buffer to demarshal a
4490  * D-Bus message.
4491  *
4492  * Generally, this function is only useful for encapsulating D-Bus messages in
4493  * a different protocol.
4494  *
4495  * @param str data to be marshalled
4496  * @param len the length of str
4497  * @param error the location to save errors to
4498  * @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
4499  * 
4500  */
4501 int 
4502 dbus_message_demarshal_bytes_needed(const char *buf, 
4503                                     int         len)
4504 {
4505   DBusString str;
4506   int byte_order, fields_array_len, header_len, body_len;
4507   DBusValidity validity = DBUS_VALID;
4508   int have_message;
4509
4510   if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
4511     return 0;
4512
4513   if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
4514     len = DBUS_MAXIMUM_MESSAGE_LENGTH;
4515   _dbus_string_init_const_len (&str, buf, len);
4516   
4517   validity = DBUS_VALID;
4518   have_message
4519     = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
4520                                           &validity, &byte_order,
4521                                           &fields_array_len,
4522                                           &header_len,
4523                                           &body_len,
4524                                           &str, 0,
4525                                           len);
4526   _dbus_string_free (&str);
4527
4528   if (validity == DBUS_VALID)
4529     {
4530       _dbus_assert(have_message);
4531       return header_len + body_len;
4532     }
4533   else
4534     {
4535       return -1; /* broken! */
4536     }
4537 }
4538
4539 /** @} */
4540
4541 /* tests in dbus-message-util.c */