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