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