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