GVariant: fix dbus_message_copy()
[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  * Copyright (C) 2015  Samsung Electronics
7  *
8  * Licensed under the Academic Free License version 2.1
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
23  *
24  */
25
26 #include <config.h>
27 #include "dbus-internals.h"
28 #include "dbus-marshal-recursive.h"
29 #include "dbus-marshal-validate.h"
30 #include "dbus-marshal-byteswap.h"
31 #include "dbus-marshal-header.h"
32 #include "dbus-signature.h"
33 #include "dbus-message-private.h"
34 #include "dbus-object-tree.h"
35 #include "dbus-memory.h"
36 #include "dbus-list.h"
37 #include "dbus-threads-internal.h"
38 #ifdef HAVE_UNIX_FD_PASSING
39 #include "dbus-sysdeps.h"
40 #include "dbus-sysdeps-unix.h"
41 #endif
42 #include "dbus-marshal-gvariant.h"
43 #include "dbus-protocol-gvariant.h"
44
45 #include <string.h>
46
47 #define _DBUS_TYPE_IS_STRINGLIKE(type) \
48   (type == DBUS_TYPE_STRING || type == DBUS_TYPE_SIGNATURE || \
49    type == DBUS_TYPE_OBJECT_PATH)
50
51 static unsigned char _dbus_default_protocol_version = DBUS_MAJOR_PROTOCOL_VERSION; /* DBUS_PROTOCOL_VERSION_GVARIANT; */
52 static dbus_bool_t _dbus_first_bus_open = FALSE;
53
54 static void protocol_strategy_last_type (int type);
55 static void protocol_strategy_static (int type);
56
57 typedef void (*DBusProtocolStrategyFunction)(int type);
58 static DBusProtocolStrategyFunction _dbus_protocol_strategy_bus_function = protocol_strategy_last_type;
59 static DBusProtocolStrategyFunction _dbus_protocol_strategy_message_function = protocol_strategy_static;
60
61 static void dbus_message_finalize (DBusMessage *message);
62
63 /**
64  * @defgroup DBusMessageInternals DBusMessage implementation details
65  * @ingroup DBusInternals
66  * @brief DBusMessage private implementation details.
67  *
68  * The guts of DBusMessage and its methods.
69  *
70  * @{
71  */
72
73 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
74 static dbus_bool_t
75 _dbus_enable_message_cache (void)
76 {
77   static int enabled = -1;
78
79   if (enabled < 0)
80     {
81       const char *s = _dbus_getenv ("DBUS_MESSAGE_CACHE");
82
83       enabled = TRUE;
84
85       if (s && *s)
86         {
87           if (*s == '0')
88             enabled = FALSE;
89           else if (*s == '1')
90             enabled = TRUE;
91           else
92             _dbus_warn ("DBUS_MESSAGE_CACHE should be 0 or 1 if set, not '%s'",
93                 s);
94         }
95     }
96
97   return enabled;
98 }
99 #else
100     /* constant expression, should be optimized away */
101 #   define _dbus_enable_message_cache() (TRUE)
102 #endif
103
104 #ifndef _dbus_message_trace_ref
105 void
106 _dbus_message_trace_ref (DBusMessage *message,
107                          int          old_refcount,
108                          int          new_refcount,
109                          const char  *why)
110 {
111   static int enabled = -1;
112
113   _dbus_trace_ref ("DBusMessage", message, old_refcount, new_refcount, why,
114       "DBUS_MESSAGE_TRACE", &enabled);
115 }
116 #endif
117
118 /* Not thread locked, but strictly const/read-only so should be OK
119  */
120 /** An static string representing an empty signature */
121 _DBUS_STRING_DEFINE_STATIC(_dbus_empty_signature_str,  "");
122
123 /* these have wacky values to help trap uninitialized iterators;
124  * but has to fit in 3 bits
125  */
126 enum {
127   DBUS_MESSAGE_ITER_TYPE_READER = 3,
128   DBUS_MESSAGE_ITER_TYPE_WRITER = 7
129 };
130
131 /** typedef for internals of message iterator */
132 typedef struct DBusMessageRealIter DBusMessageRealIter;
133
134 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
135
136 /**
137  * @brief Internals of DBusMessageIter
138  *
139  * Object representing a position in a message. All fields are internal.
140  */
141 struct DBusMessageRealIter
142 {
143   DBusMessage *message; /**< Message used */
144   dbus_uint32_t changed_stamp : CHANGED_STAMP_BITS; /**< stamp to detect invalid iters */
145   dbus_uint32_t iter_type : 3;      /**< whether this is a reader or writer iter */
146   dbus_uint32_t sig_refcount : 8;   /**< depth of open_signature() */
147   union
148   {
149     DBusTypeWriter writer; /**< writer */
150     DBusTypeReader reader; /**< reader */
151   } u; /**< the type writer or reader that does all the work */
152 };
153
154 static dbus_bool_t
155 _dbus_header_is_gvariant (const DBusHeader *header)
156 {
157   return (header->protocol_version == DBUS_PROTOCOL_VERSION_GVARIANT);
158 }
159
160 static dbus_bool_t
161 _dbus_message_is_gvariant (const DBusMessage *message)
162 {
163   return _dbus_header_is_gvariant (&message->header);
164 }
165
166 static void
167 _dbus_message_toggle_gvariant (DBusMessage *message, dbus_bool_t gvariant)
168 {
169   message->header.protocol_version = gvariant ? DBUS_PROTOCOL_VERSION_GVARIANT : DBUS_MAJOR_PROTOCOL_VERSION;
170 }
171
172 /**
173  * Layout of a DBusMessageIter on the stack in dbus 1.10.0. This is no
174  * longer used, but for ABI compatibility we need to assert that the
175  * new layout is the same size.
176  */
177 typedef struct
178 {
179   void *dummy1;
180   dbus_uint32_t dummy3a : 21;
181   dbus_uint32_t dummy3b : 3;
182   dbus_uint32_t dummy3c : 8;
183
184   union {
185     struct
186     {
187       dbus_uint32_t dummy1a : 8;
188       dbus_uint32_t dummy1b : 1;
189       dbus_uint32_t dummy1c : 3;
190       dbus_uint32_t dummy1d : 1;
191       dbus_uint32_t dummy1e : 1;
192       dbus_uint32_t dummy1f : 1;
193       void *dummy2;
194       int dummy3;
195       void *dummy4;
196       int dummy5;
197       int dummy6;
198       size_t dummy7;
199       size_t dummy8;
200       int dummy9;
201
202       void *dummy10;
203       union
204       {
205         struct {
206           int dummy11;
207         };
208       } u;
209     } s1;
210
211     struct
212     {
213       dbus_uint32_t dummy1a : 8;
214       dbus_uint32_t dummy1b : 8;
215       dbus_uint32_t dummy1c : 1;
216       dbus_uint32_t dummy1d : 1;
217       dbus_uint32_t dummy1e : 1;
218       dbus_uint32_t dummy1f : 1;
219       dbus_uint32_t dummy1g : 1;
220
221       void *dummy2;
222       int dummy3;
223       void *dummy4;
224       int dummy5;
225       size_t dummy6;
226       void *dummy7;
227       int dummy8;
228       char dummy9;
229
230       union
231       {
232         struct {
233           int dummy10;
234           int dummy11;
235           int dummy12;
236         };
237         struct {
238           size_t dummy13;
239         };
240         struct {
241           size_t *dummy14;
242           size_t *dummy15;
243         };
244       } u;
245     } s2;
246   } u;
247 } DBusMessageIter_1_10_0;
248
249 static void
250 get_const_signature (DBusMessage       *message,
251                      const DBusString **type_str_p,
252                      int               *type_pos_p)
253 {
254   dbus_bool_t got_signature = FALSE;
255   if (_dbus_message_is_gvariant (message) && message->locked)
256     {
257       /* only locked GVariant messages have signatures in the body */
258       /*
259        * in case of received GVariant message, there may be no signature field in a header,
260        * but in the body. However, it is not nul-terminated.
261        * So, we need to allocate space and put it into message.
262        * It could also happen before, so check message->signature for already existing.
263        * FIXME: That may kinda break oom-safety.
264        *        For now - if oom, then return empty signature.
265        */
266       if (message->signature == NULL)
267         {
268           int type_str_len;
269           got_signature = _dbus_message_gvariant_get_signature (message,
270                                                                 type_str_p,
271                                                                 type_pos_p,
272                                                                 &type_str_len);
273           if (got_signature && type_str_len > 1)
274             {
275               message->signature = dbus_new (DBusString, 1);
276               got_signature = got_signature &&
277                              _dbus_string_init_preallocated (message->signature, type_str_len - 1);
278
279               /* we need to copy the signature, but to ensure backward compatibility
280                * it must be stripped off outer parentheses - they are always there */
281               got_signature = got_signature &&
282                               _dbus_string_copy_len (*type_str_p, *type_pos_p + 1, type_str_len - 2,
283                                                      message->signature, 0);
284               got_signature = got_signature &&
285                               _dbus_string_append_byte (message->signature, 0);
286             }
287         }
288       else
289         got_signature = TRUE;
290
291       if (got_signature)
292         {
293           *type_str_p = message->signature;
294           *type_pos_p = 0;
295         }
296     }
297   else if (_dbus_header_get_field_raw (&message->header,
298                                        DBUS_HEADER_FIELD_SIGNATURE,
299                                        type_str_p,
300                                        type_pos_p))
301     {
302       if (!_dbus_message_is_gvariant (message))
303         *type_pos_p += 1; /* skip the signature length which is 1 byte */
304       got_signature = TRUE;
305     }
306   if (!got_signature)
307     {
308       *type_str_p = &_dbus_empty_signature_str;
309       *type_pos_p = 0;
310     }
311 }
312
313 /**
314  * Swaps the message to compiler byte order if required
315  *
316  * @param message the message
317  */
318 static void
319 _dbus_message_byteswap (DBusMessage *message)
320 {
321   const DBusString *type_str;
322   int type_pos;
323   char byte_order;
324
325   byte_order = _dbus_header_get_byte_order (&message->header);
326
327   if (byte_order == DBUS_COMPILER_BYTE_ORDER)
328     return;
329
330   _dbus_verbose ("Swapping message into compiler byte order\n");
331
332   get_const_signature (message, &type_str, &type_pos);
333
334   _dbus_marshal_byteswap (type_str, type_pos,
335                           byte_order,
336                           DBUS_COMPILER_BYTE_ORDER,
337                           &message->body, 0);
338
339   _dbus_header_byteswap (&message->header, DBUS_COMPILER_BYTE_ORDER);
340   _dbus_assert (_dbus_header_get_byte_order (&message->header) ==
341                 DBUS_COMPILER_BYTE_ORDER);
342 }
343
344 /** byte-swap the message if it doesn't match our byte order.
345  *  Called only when we need the message in our own byte order,
346  *  normally when reading arrays of integers or doubles.
347  *  Otherwise should not be called since it would do needless
348  *  work.
349  */
350 #define ensure_byte_order(message) _dbus_message_byteswap (message)
351
352 /**
353  * Gets the data to be sent over the network for this message.
354  * The header and then the body should be written out.
355  * This function is guaranteed to always return the same
356  * data once a message is locked (with dbus_message_lock()).
357  *
358  * @param message the message.
359  * @param header return location for message header data.
360  * @param body return location for message body data.
361  */
362 void
363 _dbus_message_get_network_data (DBusMessage          *message,
364                                 const DBusString    **header,
365                                 const DBusString    **body)
366 {
367   _dbus_assert (message->locked);
368
369   *header = &message->header.data;
370   *body = &message->body;
371 }
372
373 void _dbus_message_set_timeout_ms(DBusMessage *message, int timeout_ms) {
374   message->timeout_ms = timeout_ms;
375 }
376 int _dbus_message_get_timeout_ms(DBusMessage const *message) {
377   return message->timeout_ms;
378 }
379
380 /**
381  * Gets the unix fds to be sent over the network for this message.
382  * This function is guaranteed to always return the same data once a
383  * message is locked (with dbus_message_lock()).
384  *
385  * @param message the message.
386  * @param fds return location of unix fd array
387  * @param n_fds return number of entries in array
388  */
389 void _dbus_message_get_unix_fds(DBusMessage *message,
390                                 const int  **fds,
391                                 unsigned    *n_fds)
392 {
393   _dbus_assert (message->locked);
394
395 #ifdef HAVE_UNIX_FD_PASSING
396   *fds = message->unix_fds;
397   *n_fds = message->n_unix_fds;
398 #else
399   *fds = NULL;
400   *n_fds = 0;
401 #endif
402 }
403
404 /**
405  * Sets the serial number of a message.
406  * This can only be done once on a message.
407  *
408  * DBusConnection will automatically set the serial to an appropriate value
409  * when the message is sent; this function is only needed when encapsulating
410  * messages in another protocol, or otherwise bypassing DBusConnection.
411  *
412  * @param message the message
413  * @param serial the serial
414  */
415 void
416 dbus_message_set_serial (DBusMessage   *message,
417                          dbus_uint32_t  serial)
418 {
419   _dbus_return_if_fail (message != NULL);
420   _dbus_return_if_fail (!message->locked);
421
422   _dbus_header_set_serial (&message->header, serial);
423 }
424
425 /**
426  * Adds a counter to be incremented immediately with the size/unix fds
427  * of this message, and decremented by the size/unix fds of this
428  * message when this message if finalized.  The link contains a
429  * counter with its refcount already incremented, but the counter
430  * itself not incremented.  Ownership of link and counter refcount is
431  * passed to the message.
432  *
433  * This function may be called with locks held. As a result, the counter's
434  * notify function is not called; the caller is expected to either call
435  * _dbus_counter_notify() on the counter when they are no longer holding
436  * locks, or take the same action that would be taken by the notify function.
437  *
438  * @param message the message
439  * @param link link with counter as data
440  */
441 void
442 _dbus_message_add_counter_link (DBusMessage  *message,
443                                 DBusList     *link)
444 {
445   /* right now we don't recompute the delta when message
446    * size changes, and that's OK for current purposes
447    * I think, but could be important to change later.
448    * Do recompute it whenever there are no outstanding counters,
449    * since it's basically free.
450    */
451   if (message->counters == NULL)
452     {
453       message->size_counter_delta =
454         _dbus_string_get_length (&message->header.data) +
455         _dbus_string_get_length (&message->body);
456
457 #ifdef HAVE_UNIX_FD_PASSING
458       message->unix_fd_counter_delta = message->n_unix_fds;
459 #endif
460
461 #if 0
462       _dbus_verbose ("message has size %ld\n",
463                      message->size_counter_delta);
464 #endif
465     }
466
467   _dbus_list_append_link (&message->counters, link);
468
469   _dbus_counter_adjust_size (link->data, message->size_counter_delta);
470
471 #ifdef HAVE_UNIX_FD_PASSING
472   _dbus_counter_adjust_unix_fd (link->data, message->unix_fd_counter_delta);
473 #endif
474 }
475
476 /**
477  * Adds a counter to be incremented immediately with the size/unix fds
478  * of this message, and decremented by the size/unix fds of this
479  * message when this message if finalized.
480  *
481  * This function may be called with locks held. As a result, the counter's
482  * notify function is not called; the caller is expected to either call
483  * _dbus_counter_notify() on the counter when they are no longer holding
484  * locks, or take the same action that would be taken by the notify function.
485  *
486  * @param message the message
487  * @param counter the counter
488  * @returns #FALSE if no memory
489  */
490 dbus_bool_t
491 _dbus_message_add_counter (DBusMessage *message,
492                            DBusCounter *counter)
493 {
494   DBusList *link;
495
496   link = _dbus_list_alloc_link (counter);
497   if (link == NULL)
498     return FALSE;
499
500   _dbus_counter_ref (counter);
501   _dbus_message_add_counter_link (message, link);
502
503   return TRUE;
504 }
505
506 /**
507  * Removes a counter tracking the size/unix fds of this message, and
508  * decrements the counter by the size/unix fds of this message.
509  *
510  * @param message the message
511  * @param counter the counter
512  */
513 void
514 _dbus_message_remove_counter (DBusMessage  *message,
515                               DBusCounter  *counter)
516 {
517   DBusList *link;
518
519   link = _dbus_list_find_last (&message->counters,
520                                counter);
521   _dbus_assert (link != NULL);
522
523   _dbus_list_remove_link (&message->counters, link);
524
525   _dbus_counter_adjust_size (counter, - message->size_counter_delta);
526
527 #ifdef HAVE_UNIX_FD_PASSING
528   _dbus_counter_adjust_unix_fd (counter, - message->unix_fd_counter_delta);
529 #endif
530
531   _dbus_counter_notify (counter);
532   _dbus_counter_unref (counter);
533 }
534
535 /**
536  * Locks a message. Allows checking that applications don't keep a
537  * reference to a message in the outgoing queue and change it
538  * underneath us. Messages are locked when they enter the outgoing
539  * queue (dbus_connection_send_message()), and the library complains
540  * if the message is modified while locked. This function may also
541  * called externally, for applications wrapping D-Bus in another protocol.
542  *
543  * @param message the message to lock.
544  */
545 void
546 dbus_message_lock (DBusMessage  *message)
547 {
548   if (!message->locked)
549     {
550       if (!_dbus_message_is_gvariant (message))
551         _dbus_header_update_lengths (&message->header,
552                                      _dbus_string_get_length (&message->body));
553       else
554         _dbus_message_finalize_gvariant (message, TRUE);
555
556       /* must have a signature if you have a body */
557       _dbus_assert (_dbus_string_get_length (&message->body) == 0 ||
558                     dbus_message_get_signature (message) != NULL);
559
560       message->locked = TRUE;
561     }
562 }
563
564 static dbus_bool_t
565 set_or_delete_string_field (DBusMessage *message,
566                             int          field,
567                             int          typecode,
568                             const char  *value)
569 {
570   if (value == NULL)
571     return _dbus_header_delete_field (&message->header, field);
572   else
573     return _dbus_header_set_field_basic (&message->header,
574                                          field,
575                                          typecode,
576                                          &value);
577 }
578
579 /* Message Cache
580  *
581  * We cache some DBusMessage to reduce the overhead of allocating
582  * them.  In my profiling this consistently made about an 8%
583  * difference.  It avoids the malloc for the message, the malloc for
584  * the slot list, the malloc for the header string and body string,
585  * and the associated free() calls. It does introduce another global
586  * lock which could be a performance issue in certain cases.
587  *
588  * For the echo client/server the round trip time goes from around
589  * .000077 to .000069 with the message cache on my laptop. The sysprof
590  * change is as follows (numbers are cumulative percentage):
591  *
592  *  with message cache implemented as array as it is now (0.000069 per):
593  *    new_empty_header           1.46
594  *      mutex_lock               0.56    # i.e. _DBUS_LOCK(message_cache)
595  *      mutex_unlock             0.25
596  *      self                     0.41
597  *    unref                      2.24
598  *      self                     0.68
599  *      list_clear               0.43
600  *      mutex_lock               0.33    # i.e. _DBUS_LOCK(message_cache)
601  *      mutex_unlock             0.25
602  *
603  *  with message cache implemented as list (0.000070 per roundtrip):
604  *    new_empty_header           2.72
605  *      list_pop_first           1.88
606  *    unref                      3.3
607  *      list_prepend             1.63
608  *
609  * without cache (0.000077 per roundtrip):
610  *    new_empty_header           6.7
611  *      string_init_preallocated 3.43
612  *        dbus_malloc            2.43
613  *      dbus_malloc0             2.59
614  *
615  *    unref                      4.02
616  *      string_free              1.82
617  *        dbus_free              1.63
618  *      dbus_free                0.71
619  *
620  * If you implement the message_cache with a list, the primary reason
621  * it's slower is that you add another thread lock (on the DBusList
622  * mempool).
623  */
624
625 /** Avoid caching huge messages */
626 #define MAX_MESSAGE_SIZE_TO_CACHE 10 * _DBUS_ONE_KILOBYTE
627
628 /** Avoid caching too many messages */
629 #define MAX_MESSAGE_CACHE_SIZE    5
630
631 /* Protected by _DBUS_LOCK (message_cache) */
632 static DBusMessage *message_cache[MAX_MESSAGE_CACHE_SIZE];
633 static int message_cache_count = 0;
634 static dbus_bool_t message_cache_shutdown_registered = FALSE;
635
636 static void
637 dbus_message_cache_shutdown (void *data)
638 {
639   int i;
640
641   if (!_DBUS_LOCK (message_cache))
642     _dbus_assert_not_reached ("we would have initialized global locks "
643         "before registering a shutdown function");
644
645   i = 0;
646   while (i < MAX_MESSAGE_CACHE_SIZE)
647     {
648       if (message_cache[i])
649         dbus_message_finalize (message_cache[i]);
650
651       ++i;
652     }
653
654   message_cache_count = 0;
655   message_cache_shutdown_registered = FALSE;
656
657   _DBUS_UNLOCK (message_cache);
658 }
659
660 /**
661  * Tries to get a message from the message cache.  The retrieved
662  * message will have junk in it, so it still needs to be cleared out
663  * in dbus_message_new_empty_header()
664  *
665  * @returns the message, or #NULL if none cached
666  */
667 static DBusMessage*
668 dbus_message_get_cached (void)
669 {
670   DBusMessage *message;
671   int i;
672
673   message = NULL;
674
675   if (!_DBUS_LOCK (message_cache))
676     {
677       /* we'd have initialized global locks before caching anything,
678        * so there can't be anything in the cache */
679       return NULL;
680     }
681
682   _dbus_assert (message_cache_count >= 0);
683
684   if (message_cache_count == 0)
685     {
686       _DBUS_UNLOCK (message_cache);
687       return NULL;
688     }
689
690   /* This is not necessarily true unless count > 0, and
691    * message_cache is uninitialized until the shutdown is
692    * registered
693    */
694   _dbus_assert (message_cache_shutdown_registered);
695
696   i = 0;
697   while (i < MAX_MESSAGE_CACHE_SIZE)
698     {
699       if (message_cache[i])
700         {
701           message = message_cache[i];
702           message_cache[i] = NULL;
703           message_cache_count -= 1;
704           break;
705         }
706       ++i;
707     }
708   _dbus_assert (message_cache_count >= 0);
709   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
710   _dbus_assert (message != NULL);
711
712   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
713
714   _dbus_assert (message->counters == NULL);
715
716   _DBUS_UNLOCK (message_cache);
717
718   return message;
719 }
720
721 #ifdef HAVE_UNIX_FD_PASSING
722 static void
723 close_unix_fds(int *fds, unsigned *n_fds)
724 {
725   DBusError e;
726   unsigned int i;
727
728   if (*n_fds <= 0)
729     return;
730
731   dbus_error_init(&e);
732
733   for (i = 0; i < *n_fds; i++)
734     {
735       if (!_dbus_close(fds[i], &e))
736         {
737           _dbus_warn("Failed to close file descriptor: %s", e.message);
738           dbus_error_free(&e);
739         }
740     }
741
742   *n_fds = 0;
743
744   /* We don't free the array here, in case we can recycle it later */
745 }
746 #endif
747
748 static void
749 free_counter (void *element,
750               void *data)
751 {
752   DBusCounter *counter = element;
753   DBusMessage *message = data;
754
755   _dbus_counter_adjust_size (counter, - message->size_counter_delta);
756 #ifdef HAVE_UNIX_FD_PASSING
757   _dbus_counter_adjust_unix_fd (counter, - message->unix_fd_counter_delta);
758 #endif
759
760   _dbus_counter_notify (counter);
761   _dbus_counter_unref (counter);
762 }
763
764 /**
765  * Tries to cache a message, otherwise finalize it.
766  *
767  * @param message the message
768  */
769 static void
770 dbus_message_cache_or_finalize (DBusMessage *message)
771 {
772   dbus_bool_t was_cached;
773   int i;
774
775   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
776
777   /* This calls application code and has to be done first thing
778    * without holding the lock
779    */
780   _dbus_data_slot_list_clear (&message->slot_list);
781
782   _dbus_list_foreach (&message->counters,
783                       free_counter, message);
784   _dbus_list_clear (&message->counters);
785
786 #ifdef HAVE_UNIX_FD_PASSING
787   close_unix_fds(message->unix_fds, &message->n_unix_fds);
788 #endif
789
790   if (NULL != message->signature)
791   {
792     _dbus_string_free (message->signature);
793     dbus_free (message->signature);
794     message->signature = NULL;
795   }
796
797   if (NULL != message->unique_sender)
798   {
799     _dbus_string_free (message->unique_sender);
800     dbus_free (message->unique_sender);
801     message->unique_sender = NULL;
802   }
803
804   was_cached = FALSE;
805
806   if (!_DBUS_LOCK (message_cache))
807     {
808       /* The only way to get a non-null message goes through
809        * dbus_message_get_cached() which takes the lock. */
810       _dbus_assert_not_reached ("we would have initialized global locks "
811           "the first time we constructed a message");
812     }
813
814   if (!message_cache_shutdown_registered)
815     {
816       _dbus_assert (message_cache_count == 0);
817
818       if (!_dbus_register_shutdown_func (dbus_message_cache_shutdown, NULL))
819         goto out;
820
821       i = 0;
822       while (i < MAX_MESSAGE_CACHE_SIZE)
823         {
824           message_cache[i] = NULL;
825           ++i;
826         }
827
828       message_cache_shutdown_registered = TRUE;
829     }
830
831   _dbus_assert (message_cache_count >= 0);
832
833   if (!_dbus_enable_message_cache ())
834     goto out;
835
836   if ((_dbus_string_get_length (&message->header.data) +
837        _dbus_string_get_length (&message->body)) >
838       MAX_MESSAGE_SIZE_TO_CACHE)
839     goto out;
840
841   if (message_cache_count >= MAX_MESSAGE_CACHE_SIZE)
842     goto out;
843
844   /* Find empty slot */
845   i = 0;
846   while (message_cache[i] != NULL)
847     ++i;
848
849   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
850
851   _dbus_assert (message_cache[i] == NULL);
852   message_cache[i] = message;
853   message_cache_count += 1;
854   was_cached = TRUE;
855 #ifndef DBUS_DISABLE_CHECKS
856   message->in_cache = TRUE;
857 #endif
858
859  out:
860   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
861
862   _DBUS_UNLOCK (message_cache);
863
864   if (!was_cached)
865     dbus_message_finalize (message);
866 }
867
868 /*
869  * Arrange for iter to be something that _dbus_message_iter_check() would
870  * reject as not a valid iterator.
871  */
872 static void
873 _dbus_message_real_iter_zero (DBusMessageRealIter *iter)
874 {
875   _dbus_assert (iter != NULL);
876   _DBUS_ZERO (*iter);
877   /* NULL is not, strictly speaking, guaranteed to be all-bits-zero */
878   iter->message = NULL;
879 }
880
881 /**
882  * Initialize iter as if with #DBUS_MESSAGE_ITER_INIT_CLOSED. The only valid
883  * operation for such an iterator is
884  * dbus_message_iter_abandon_container_if_open(), which does nothing.
885  */
886 void
887 dbus_message_iter_init_closed (DBusMessageIter *iter)
888 {
889   _dbus_return_if_fail (iter != NULL);
890   _dbus_message_real_iter_zero ((DBusMessageRealIter *) iter);
891 }
892
893 static dbus_bool_t
894 _dbus_message_real_iter_is_zeroed (DBusMessageRealIter *iter)
895 {
896   return (iter != NULL && iter->message == NULL && iter->changed_stamp == 0 &&
897           iter->iter_type == 0 && iter->sig_refcount == 0);
898 }
899
900 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
901 static dbus_bool_t
902 _dbus_message_iter_check (DBusMessageRealIter *iter)
903 {
904   char byte_order;
905
906   if (iter == NULL)
907     {
908       _dbus_warn_check_failed ("dbus message iterator is NULL");
909       return FALSE;
910     }
911
912   if (iter->message == NULL || iter->iter_type == 0)
913     {
914       _dbus_warn_check_failed ("dbus message iterator has already been "
915                                "closed, or is uninitialized or corrupt");
916       return FALSE;
917     }
918
919   byte_order = _dbus_header_get_byte_order (&iter->message->header);
920
921   if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_READER)
922     {
923       if (iter->u.reader.byte_order != byte_order)
924         {
925           _dbus_warn_check_failed ("dbus message changed byte order since iterator was created");
926           return FALSE;
927         }
928       /* because we swap the message into compiler order when you init an iter */
929       _dbus_assert (iter->u.reader.byte_order == DBUS_COMPILER_BYTE_ORDER);
930     }
931   else if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER)
932     {
933       if (iter->u.writer.byte_order != byte_order)
934         {
935           _dbus_warn_check_failed ("dbus message changed byte order since append iterator was created");
936           return FALSE;
937         }
938       /* because we swap the message into compiler order when you init an iter */
939       _dbus_assert (iter->u.writer.byte_order == DBUS_COMPILER_BYTE_ORDER);
940     }
941   else
942     {
943       _dbus_warn_check_failed ("dbus message iterator looks uninitialized or corrupted");
944       return FALSE;
945     }
946
947   if (iter->changed_stamp != iter->message->changed_stamp)
948     {
949       _dbus_warn_check_failed ("dbus message iterator invalid because the message has been modified (or perhaps the iterator is just uninitialized)");
950       return FALSE;
951     }
952
953   return TRUE;
954 }
955 #endif /* DBUS_ENABLE_CHECKS || DBUS_ENABLE_ASSERT */
956
957 /**
958  * Implementation of the varargs arg-getting functions.
959  * dbus_message_get_args() is the place to go for complete
960  * documentation.
961  *
962  * @see dbus_message_get_args
963  * @param iter the message iter
964  * @param error error to be filled in
965  * @param first_arg_type type of the first argument
966  * @param var_args return location for first argument, followed by list of type/location pairs
967  * @returns #FALSE if error was set
968  */
969 dbus_bool_t
970 _dbus_message_iter_get_args_valist (DBusMessageIter *iter,
971                                     DBusError       *error,
972                                     int              first_arg_type,
973                                     va_list          var_args)
974 {
975   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
976   int spec_type, msg_type, i, j;
977   dbus_bool_t retval;
978   va_list copy_args;
979
980   _dbus_assert (_dbus_message_iter_check (real));
981
982   retval = FALSE;
983
984   spec_type = first_arg_type;
985   i = 0;
986
987   /* copy var_args first, then we can do another iteration over it to
988    * free memory and close unix fds if parse failed at some point.
989    */
990   DBUS_VA_COPY (copy_args, var_args);
991
992   while (spec_type != DBUS_TYPE_INVALID)
993     {
994       msg_type = dbus_message_iter_get_arg_type (iter);
995
996       if (msg_type != spec_type)
997         {
998           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
999                           "Argument %d is specified to be of type \"%s\", but "
1000                           "is actually of type \"%s\"\n", i,
1001                           _dbus_type_to_string (spec_type),
1002                           _dbus_type_to_string (msg_type));
1003
1004           goto out;
1005         }
1006
1007       if (spec_type == DBUS_TYPE_UNIX_FD)
1008         {
1009 #ifdef HAVE_UNIX_FD_PASSING
1010           DBusBasicValue idx;
1011           int *pfd, nfd;
1012
1013           pfd = va_arg (var_args, int*);
1014           _dbus_assert(pfd);
1015
1016           _dbus_type_reader_read_basic(&real->u.reader, &idx);
1017
1018           if (idx.u32 >= real->message->n_unix_fds)
1019             {
1020               dbus_set_error (error, DBUS_ERROR_INCONSISTENT_MESSAGE,
1021                               "Message refers to file descriptor at index %i,"
1022                               "but has only %i descriptors attached.\n",
1023                               idx.u32,
1024                               real->message->n_unix_fds);
1025               goto out;
1026             }
1027
1028           if ((nfd = _dbus_dup(real->message->unix_fds[idx.u32], error)) < 0)
1029             goto out;
1030
1031           *pfd = nfd;
1032 #else
1033           dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
1034                           "Platform does not support file desciptor passing.\n");
1035           goto out;
1036 #endif
1037         }
1038       else if (dbus_type_is_basic (spec_type))
1039         {
1040           DBusBasicValue *ptr;
1041
1042           ptr = va_arg (var_args, DBusBasicValue*);
1043
1044           _dbus_assert (ptr != NULL);
1045
1046           _dbus_type_reader_read_basic (&real->u.reader,
1047                                         ptr);
1048         }
1049       else if (spec_type == DBUS_TYPE_ARRAY)
1050         {
1051           int element_type;
1052           int spec_element_type;
1053           const DBusBasicValue **ptr;
1054           int *n_elements_p;
1055           DBusTypeReader array;
1056
1057           spec_element_type = va_arg (var_args, int);
1058           element_type = _dbus_type_reader_get_element_type (&real->u.reader);
1059
1060           if (spec_element_type != element_type)
1061             {
1062               dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1063                               "Argument %d is specified to be an array of \"%s\", but "
1064                               "is actually an array of \"%s\"\n",
1065                               i,
1066                               _dbus_type_to_string (spec_element_type),
1067                               _dbus_type_to_string (element_type));
1068
1069               goto out;
1070             }
1071
1072           if (dbus_type_is_fixed (spec_element_type) &&
1073               element_type != DBUS_TYPE_UNIX_FD)
1074             {
1075               ptr = va_arg (var_args, const DBusBasicValue**);
1076               n_elements_p = va_arg (var_args, int*);
1077
1078               _dbus_assert (ptr != NULL);
1079               _dbus_assert (n_elements_p != NULL);
1080
1081               _dbus_type_reader_recurse (&real->u.reader, &array);
1082
1083               _dbus_type_reader_read_fixed_multi (&array,
1084                                                   (void *) ptr, n_elements_p);
1085             }
1086           else if (_DBUS_TYPE_IS_STRINGLIKE (spec_element_type))
1087             {
1088               char ***str_array_p;
1089               int n_elements;
1090               char **str_array;
1091
1092               str_array_p = va_arg (var_args, char***);
1093               n_elements_p = va_arg (var_args, int*);
1094
1095               _dbus_assert (str_array_p != NULL);
1096               _dbus_assert (n_elements_p != NULL);
1097
1098               /* Count elements in the array */
1099               _dbus_type_reader_recurse (&real->u.reader, &array);
1100
1101               n_elements = 0;
1102               while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
1103                 {
1104                   ++n_elements;
1105                   _dbus_type_reader_next (&array);
1106                 }
1107
1108               str_array = dbus_new0 (char*, n_elements + 1);
1109               if (str_array == NULL)
1110                 {
1111                   _DBUS_SET_OOM (error);
1112                   goto out;
1113                 }
1114
1115               /* Now go through and dup each string */
1116               _dbus_type_reader_recurse (&real->u.reader, &array);
1117
1118               j = 0;
1119               while (j < n_elements)
1120                 {
1121                   const char *s;
1122                   _dbus_type_reader_read_basic (&array,
1123                                                 (void *) &s);
1124
1125                   str_array[j] = _dbus_strdup (s);
1126                   if (str_array[j] == NULL)
1127                     {
1128                       dbus_free_string_array (str_array);
1129                       _DBUS_SET_OOM (error);
1130                       goto out;
1131                     }
1132
1133                   ++j;
1134
1135                   if (!_dbus_type_reader_next (&array))
1136                     _dbus_assert (j == n_elements);
1137                 }
1138
1139               _dbus_assert (_dbus_type_reader_get_current_type (&array) == DBUS_TYPE_INVALID);
1140               _dbus_assert (j == n_elements);
1141               _dbus_assert (str_array[j] == NULL);
1142
1143               *str_array_p = str_array;
1144               *n_elements_p = n_elements;
1145             }
1146 #ifndef DBUS_DISABLE_CHECKS
1147           else
1148             {
1149               _dbus_warn ("you can't read arrays of container types (struct, variant, array) with %s for now",
1150                           _DBUS_FUNCTION_NAME);
1151               goto out;
1152             }
1153 #endif
1154         }
1155 #ifndef DBUS_DISABLE_CHECKS
1156       else
1157         {
1158           _dbus_warn ("you can only read arrays and basic types with %s for now",
1159                       _DBUS_FUNCTION_NAME);
1160           goto out;
1161         }
1162 #endif
1163
1164       /* how many arguments already handled */
1165       i++;
1166
1167       spec_type = va_arg (var_args, int);
1168       if (!_dbus_type_reader_next (&real->u.reader) && spec_type != DBUS_TYPE_INVALID)
1169         {
1170           dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1171                           "Message has only %d arguments, but more were expected", i);
1172           goto out;
1173         }
1174     }
1175
1176   retval = TRUE;
1177
1178  out:
1179   /* there may memory or unix fd leak in the above iteration if parse failed.
1180    * so we have another iteration over copy_args to free memory and close
1181    * unix fds.
1182    */
1183   if (!retval)
1184     {
1185       spec_type = first_arg_type;
1186       j = 0;
1187
1188       while (j < i)
1189         {
1190           if (spec_type == DBUS_TYPE_UNIX_FD)
1191             {
1192 #ifdef HAVE_UNIX_FD_PASSING
1193               int *pfd;
1194
1195               pfd = va_arg (copy_args, int *);
1196               _dbus_assert(pfd);
1197               if (*pfd >= 0)
1198                 {
1199                   _dbus_close (*pfd, NULL);
1200                   *pfd = -1;
1201                 }
1202 #endif
1203             }
1204           else if (dbus_type_is_basic (spec_type))
1205             {
1206               /* move the index forward */
1207               va_arg (copy_args, DBusBasicValue *);
1208             }
1209           else if (spec_type == DBUS_TYPE_ARRAY)
1210             {
1211               int spec_element_type;
1212
1213               spec_element_type = va_arg (copy_args, int);
1214               if (dbus_type_is_fixed (spec_element_type))
1215                 {
1216                   /* move the index forward */
1217                   va_arg (copy_args, const DBusBasicValue **);
1218                   va_arg (copy_args, int *);
1219                 }
1220               else if (_DBUS_TYPE_IS_STRINGLIKE (spec_element_type))
1221                 {
1222                   char ***str_array_p;
1223
1224                   str_array_p = va_arg (copy_args, char ***);
1225                   /* move the index forward */
1226                   va_arg (copy_args, int *);
1227                   _dbus_assert (str_array_p != NULL);
1228                   dbus_free_string_array (*str_array_p);
1229                   *str_array_p = NULL;
1230                 }
1231             }
1232
1233           spec_type = va_arg (copy_args, int);
1234           j++;
1235         }
1236     }
1237
1238   va_end (copy_args);
1239   return retval;
1240 }
1241
1242 /** @} */
1243
1244 /**
1245  * @defgroup DBusMessage DBusMessage
1246  * @ingroup  DBus
1247  * @brief Message to be sent or received over a #DBusConnection.
1248  *
1249  * A DBusMessage is the most basic unit of communication over a
1250  * DBusConnection. A DBusConnection represents a stream of messages
1251  * received from a remote application, and a stream of messages
1252  * sent to a remote application.
1253  *
1254  * A message has a message type, returned from
1255  * dbus_message_get_type().  This indicates whether the message is a
1256  * method call, a reply to a method call, a signal, or an error reply.
1257  *
1258  * A message has header fields such as the sender, destination, method
1259  * or signal name, and so forth. DBusMessage has accessor functions for
1260  * these, such as dbus_message_get_member().
1261  *
1262  * Convenience functions dbus_message_is_method_call(), dbus_message_is_signal(),
1263  * and dbus_message_is_error() check several header fields at once and are
1264  * slightly more efficient than checking the header fields with individual
1265  * accessor functions.
1266  *
1267  * Finally, a message has arguments. The number and types of arguments
1268  * are in the message's signature header field (accessed with
1269  * dbus_message_get_signature()).  Simple argument values are usually
1270  * retrieved with dbus_message_get_args() but more complex values such
1271  * as structs may require the use of #DBusMessageIter.
1272  *
1273  * The D-Bus specification goes into some more detail about header fields and
1274  * message types.
1275  *
1276  * @{
1277  */
1278
1279 /**
1280  * @typedef DBusMessage
1281  *
1282  * Opaque data type representing a message received from or to be
1283  * sent to another application.
1284  */
1285
1286 /**
1287  * Returns the serial of a message or 0 if none has been specified.
1288  * The message's serial number is provided by the application sending
1289  * the message and is used to identify replies to this message.
1290  *
1291  * All messages received on a connection will have a serial provided
1292  * by the remote application.
1293  *
1294  * For messages you're sending, dbus_connection_send() will assign a
1295  * serial and return it to you.
1296  *
1297  * @param message the message
1298  * @returns the serial
1299  */
1300 dbus_uint32_t
1301 dbus_message_get_serial (DBusMessage *message)
1302 {
1303   _dbus_return_val_if_fail (message != NULL, 0);
1304
1305   return _dbus_header_get_serial (&message->header);
1306 }
1307
1308 /**
1309  * Sets the reply serial of a message (the serial of the message this
1310  * is a reply to).
1311  *
1312  * @param message the message
1313  * @param reply_serial the serial we're replying to
1314  * @returns #FALSE if not enough memory
1315  */
1316 dbus_bool_t
1317 dbus_message_set_reply_serial (DBusMessage   *message,
1318                                dbus_uint32_t  reply_serial)
1319 {
1320   DBusBasicValue value;
1321   int type;
1322
1323   _dbus_return_val_if_fail (message != NULL, FALSE);
1324   _dbus_return_val_if_fail (!message->locked, FALSE);
1325   _dbus_return_val_if_fail (reply_serial != 0, FALSE); /* 0 is invalid */
1326
1327   if (_dbus_message_is_gvariant (message))
1328     {
1329       type = DBUS_TYPE_UINT64;
1330       value.u64 = reply_serial;
1331     }
1332   else
1333     {
1334       type = DBUS_TYPE_UINT32;
1335       value.u32 = reply_serial;
1336     }
1337
1338   return _dbus_header_set_field_basic (&message->header,
1339                                        DBUS_HEADER_FIELD_REPLY_SERIAL,
1340                                        type,
1341                                        &value);
1342 }
1343
1344 /**
1345  * Returns the serial that the message is a reply to or 0 if none.
1346  *
1347  * @param message the message
1348  * @returns the reply serial
1349  */
1350 dbus_uint32_t
1351 dbus_message_get_reply_serial  (DBusMessage *message)
1352 {
1353   dbus_uint32_t v_UINT32;
1354   dbus_uint64_t v_UINT64;
1355   int type = DBUS_TYPE_UINT32;
1356   void *value = &v_UINT32;
1357
1358   _dbus_return_val_if_fail (message != NULL, 0);
1359
1360   if (_dbus_message_is_gvariant (message))
1361     {
1362       type = DBUS_TYPE_UINT64;
1363       value = &v_UINT64;
1364     }
1365
1366   if (_dbus_header_get_field_basic (&message->header,
1367                                     DBUS_HEADER_FIELD_REPLY_SERIAL,
1368                                     type,
1369                                     value))
1370     {
1371       if (_dbus_message_is_gvariant (message))
1372         return v_UINT64;
1373       else
1374         return v_UINT32;
1375     }
1376   else
1377     return 0;
1378 }
1379
1380 static void
1381 dbus_message_finalize (DBusMessage *message)
1382 {
1383   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
1384
1385   /* This calls application callbacks! */
1386   _dbus_data_slot_list_free (&message->slot_list);
1387
1388   _dbus_list_foreach (&message->counters,
1389                       free_counter, message);
1390   _dbus_list_clear (&message->counters);
1391
1392   _dbus_header_free (&message->header);
1393   _dbus_string_free (&message->body);
1394
1395 #ifdef HAVE_UNIX_FD_PASSING
1396   close_unix_fds(message->unix_fds, &message->n_unix_fds);
1397   dbus_free(message->unix_fds);
1398 #endif
1399
1400   _dbus_assert (_dbus_atomic_get (&message->refcount) == 0);
1401
1402   dbus_free (message);
1403 }
1404
1405 static DBusMessage*
1406 dbus_message_new_empty_header (dbus_bool_t gvariant)
1407 {
1408   DBusMessage *message;
1409   dbus_bool_t from_cache;
1410
1411   message = dbus_message_get_cached ();
1412
1413   if (message != NULL)
1414     {
1415       from_cache = TRUE;
1416     }
1417   else
1418     {
1419       from_cache = FALSE;
1420       message = dbus_new0 (DBusMessage, 1);
1421       if (message == NULL)
1422         return NULL;
1423 #ifndef DBUS_DISABLE_CHECKS
1424       message->generation = _dbus_current_generation;
1425 #endif
1426
1427 #ifdef HAVE_UNIX_FD_PASSING
1428       message->unix_fds = NULL;
1429       message->n_unix_fds_allocated = 0;
1430 #endif
1431     }
1432
1433   _dbus_atomic_inc (&message->refcount);
1434
1435   _dbus_message_trace_ref (message, 0, 1, "new_empty_header");
1436
1437   message->locked = FALSE;
1438 #ifndef DBUS_DISABLE_CHECKS
1439   message->in_cache = FALSE;
1440 #endif
1441   message->counters = NULL;
1442   message->size_counter_delta = 0;
1443   message->timeout_ms = -1;
1444   message->changed_stamp = 0;
1445
1446 #ifdef HAVE_UNIX_FD_PASSING
1447   message->n_unix_fds = 0;
1448   message->n_unix_fds_allocated = 0;
1449   message->unix_fd_counter_delta = 0;
1450 #endif
1451
1452   _dbus_message_toggle_gvariant (message, gvariant);  /* this works only if kdbus is enabled */
1453
1454   if (!from_cache)
1455     _dbus_data_slot_list_init (&message->slot_list);
1456
1457   if (from_cache)
1458     {
1459       _dbus_header_reinit (&message->header);
1460       _dbus_string_set_length (&message->body, 0);
1461     }
1462   else
1463     {
1464       if (!_dbus_header_init (&message->header))
1465         {
1466           dbus_free (message);
1467           return NULL;
1468         }
1469
1470       if (!_dbus_string_init_preallocated (&message->body, 32))
1471         {
1472           _dbus_header_free (&message->header);
1473           dbus_free (message);
1474           return NULL;
1475         }
1476     }
1477
1478   message->signature = NULL;
1479   message->unique_sender = NULL;
1480   message->gvariant_body_last_offset = GVARIANT_LAST_OFFSET_NOT_SET;
1481   message->gvariant_body_last_pos = 0;
1482
1483   return message;
1484 }
1485
1486 static DBusMessage*
1487 _dbus_message_create_protocol_version (int         message_type,
1488                             const char  *destination,
1489                             const char  *path,
1490                             const char  *interface,
1491                             const char  *member,
1492                             const char  *error_name,
1493                             dbus_bool_t gvariant)
1494 {
1495   DBusMessage *message;
1496
1497   _dbus_assert (message_type != DBUS_MESSAGE_TYPE_INVALID);
1498
1499   message = dbus_message_new_empty_header (gvariant);
1500   if (message == NULL)
1501     return NULL;
1502
1503   if (!(_dbus_message_is_gvariant(message) ? _dbus_header_gvariant_create : _dbus_header_create) (&message->header,
1504                             DBUS_COMPILER_BYTE_ORDER,
1505                             message_type,
1506                             destination, path, interface, member, error_name))
1507     {
1508       dbus_message_unref (message);
1509       return NULL;
1510     }
1511
1512   return message;
1513 }
1514
1515 static DBusMessage*
1516 _dbus_message_create (int         message_type,
1517                             const char  *destination,
1518                             const char  *path,
1519                             const char  *interface,
1520                             const char  *member,
1521                             const char  *error_name)
1522 {
1523         return _dbus_message_create_protocol_version(message_type,
1524                                              destination,
1525                                              path,
1526                                              interface,
1527                                              member,
1528                                              error_name,
1529                                              _dbus_default_protocol_version == DBUS_PROTOCOL_VERSION_GVARIANT);
1530 }
1531
1532 /**
1533  * Constructs a new message of the given message type.
1534  * Types include #DBUS_MESSAGE_TYPE_METHOD_CALL,
1535  * #DBUS_MESSAGE_TYPE_SIGNAL, and so forth.
1536  *
1537  * Usually you want to use dbus_message_new_method_call(),
1538  * dbus_message_new_method_return(), dbus_message_new_signal(),
1539  * or dbus_message_new_error() instead.
1540  *
1541  * @param message_type type of message
1542  * @returns new message or #NULL if no memory
1543  */
1544 DBusMessage*
1545 dbus_message_new (int message_type)
1546 {
1547   return _dbus_message_create(message_type,
1548                                    NULL, NULL, NULL, NULL, NULL);
1549 }
1550
1551 /**
1552  * Constructs a new message to invoke a method on a remote
1553  * object. Returns #NULL if memory can't be allocated for the
1554  * message. The destination may be #NULL in which case no destination
1555  * is set; this is appropriate when using D-Bus in a peer-to-peer
1556  * context (no message bus). The interface may be #NULL, which means
1557  * that if multiple methods with the given name exist it is undefined
1558  * which one will be invoked.
1559  *
1560  * The path and method names may not be #NULL.
1561  *
1562  * Destination, path, interface, and method name can't contain
1563  * any invalid characters (see the D-Bus specification).
1564  *
1565  * @param destination name that the message should be sent to or #NULL
1566  * @param path object path the message should be sent to
1567  * @param iface interface to invoke method on, or #NULL
1568  * @param method method to invoke
1569  *
1570  * @returns a new DBusMessage, free with dbus_message_unref()
1571  */
1572 DBusMessage*
1573 dbus_message_new_method_call (const char *destination,
1574                               const char *path,
1575                               const char *iface,
1576                               const char *method)
1577 {
1578   _dbus_return_val_if_fail (path != NULL, NULL);
1579   _dbus_return_val_if_fail (method != NULL, NULL);
1580   _dbus_return_val_if_fail (destination == NULL ||
1581                             _dbus_check_is_valid_bus_name (destination), NULL);
1582   _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
1583   _dbus_return_val_if_fail (iface == NULL ||
1584                             _dbus_check_is_valid_interface (iface), NULL);
1585   _dbus_return_val_if_fail (_dbus_check_is_valid_member (method), NULL);
1586
1587   return _dbus_message_create(DBUS_MESSAGE_TYPE_METHOD_CALL,
1588                                    destination, path, iface, method, NULL);
1589 }
1590
1591 /**
1592  * Constructs a message that is a reply to a method call. Returns
1593  * #NULL if memory can't be allocated for the message.
1594  *
1595  * @param method_call the message being replied to
1596  * @returns a new DBusMessage, free with dbus_message_unref()
1597  */
1598 DBusMessage*
1599 dbus_message_new_method_return (DBusMessage *method_call)
1600 {
1601   DBusMessage *message;
1602   const char *sender;
1603
1604   _dbus_return_val_if_fail (method_call != NULL, NULL);
1605
1606   sender = dbus_message_get_sender (method_call);
1607
1608   /* sender is allowed to be null here in peer-to-peer case */
1609
1610   message = _dbus_message_create (DBUS_MESSAGE_TYPE_METHOD_RETURN,
1611                                        sender, NULL, NULL, NULL, NULL);
1612   if (message == NULL)
1613     return NULL;
1614
1615   dbus_message_set_no_reply (message, TRUE);
1616
1617   if (!dbus_message_set_reply_serial (message,
1618                                       dbus_message_get_serial (method_call)))
1619     {
1620       dbus_message_unref (message);
1621       return NULL;
1622     }
1623
1624   return message;
1625 }
1626
1627 /**
1628  * Constructs a new message representing a signal emission. Returns
1629  * #NULL if memory can't be allocated for the message.  A signal is
1630  * identified by its originating object path, interface, and the name
1631  * of the signal.
1632  *
1633  * Path, interface, and signal name must all be valid (the D-Bus
1634  * specification defines the syntax of these fields).
1635  *
1636  * @param path the path to the object emitting the signal
1637  * @param iface the interface the signal is emitted from
1638  * @param name name of the signal
1639  * @returns a new DBusMessage, free with dbus_message_unref()
1640  */
1641 DBusMessage*
1642 dbus_message_new_signal (const char *path,
1643                          const char *iface,
1644                          const char *name)
1645 {
1646   DBusMessage *message;
1647
1648   _dbus_return_val_if_fail (path != NULL, NULL);
1649   _dbus_return_val_if_fail (iface != NULL, NULL);
1650   _dbus_return_val_if_fail (name != NULL, NULL);
1651   _dbus_return_val_if_fail (_dbus_check_is_valid_path (path), NULL);
1652   _dbus_return_val_if_fail (_dbus_check_is_valid_interface (iface), NULL);
1653   _dbus_return_val_if_fail (_dbus_check_is_valid_member (name), NULL);
1654
1655   message = _dbus_message_create (DBUS_MESSAGE_TYPE_SIGNAL,
1656                                   NULL, path, iface, name, NULL);
1657   if (message == NULL)
1658     return NULL;
1659
1660   dbus_message_set_no_reply (message, TRUE);
1661
1662   return message;
1663 }
1664
1665 /**
1666  * Creates a new message that is an error reply to another message.
1667  * Error replies are most common in response to method calls, but
1668  * can be returned in reply to any message.
1669  *
1670  * The error name must be a valid error name according to the syntax
1671  * given in the D-Bus specification. If you don't want to make
1672  * up an error name just use #DBUS_ERROR_FAILED.
1673  *
1674  * @param reply_to the message we're replying to
1675  * @param error_name the error name
1676  * @param error_message the error message string (or #NULL for none, but please give a message)
1677  * @returns a new error message object, free with dbus_message_unref()
1678  */
1679 DBusMessage*
1680 dbus_message_new_error (DBusMessage *reply_to,
1681                         const char  *error_name,
1682                         const char  *error_message)
1683 {
1684   DBusMessage *message;
1685   const char *sender;
1686   DBusMessageIter iter;
1687
1688   _dbus_return_val_if_fail (reply_to != NULL, NULL);
1689   _dbus_return_val_if_fail (error_name != NULL, NULL);
1690   _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
1691
1692   sender = dbus_message_get_sender (reply_to);
1693
1694   /* sender may be NULL for non-message-bus case or
1695    * when the message bus is dealing with an unregistered
1696    * connection.
1697    */
1698   message = _dbus_message_create (DBUS_MESSAGE_TYPE_ERROR,
1699                                   sender, NULL, NULL, NULL, error_name);
1700   if (message == NULL)
1701     return NULL;
1702
1703   dbus_message_set_no_reply (message, TRUE);
1704
1705   if (!dbus_message_set_reply_serial (message,
1706                                       dbus_message_get_serial (reply_to)))
1707     {
1708       dbus_message_unref (message);
1709       return NULL;
1710     }
1711
1712   if (error_message != NULL)
1713     {
1714       dbus_message_iter_init_append (message, &iter);
1715       if (!dbus_message_iter_append_basic (&iter,
1716                                            DBUS_TYPE_STRING,
1717                                            &error_message))
1718         {
1719           dbus_message_unref (message);
1720           return NULL;
1721         }
1722     }
1723
1724   return message;
1725 }
1726
1727 /**
1728  * Creates a new message that is an error reply to another message, allowing
1729  * you to use printf formatting.
1730  *
1731  * See dbus_message_new_error() for details - this function is the same
1732  * aside from the printf formatting.
1733  *
1734  * @todo add _DBUS_GNUC_PRINTF to this (requires moving _DBUS_GNUC_PRINTF to
1735  * public header, see DBUS_DEPRECATED for an example)
1736  *
1737  * @param reply_to the original message
1738  * @param error_name the error name
1739  * @param error_format the error message format as with printf
1740  * @param ... format string arguments
1741  * @returns a new error message
1742  */
1743 DBusMessage*
1744 dbus_message_new_error_printf (DBusMessage *reply_to,
1745                                const char  *error_name,
1746                                const char  *error_format,
1747                                ...)
1748 {
1749   va_list args;
1750   DBusString str;
1751   DBusMessage *message;
1752
1753   _dbus_return_val_if_fail (reply_to != NULL, NULL);
1754   _dbus_return_val_if_fail (error_name != NULL, NULL);
1755   _dbus_return_val_if_fail (_dbus_check_is_valid_error_name (error_name), NULL);
1756
1757   if (!_dbus_string_init (&str))
1758     return NULL;
1759
1760   va_start (args, error_format);
1761
1762   if (_dbus_string_append_printf_valist (&str, error_format, args))
1763     message = dbus_message_new_error (reply_to, error_name,
1764                                       _dbus_string_get_const_data (&str));
1765   else
1766     message = NULL;
1767
1768   _dbus_string_free (&str);
1769
1770   va_end (args);
1771
1772   return message;
1773 }
1774
1775
1776 /**
1777  * Creates a new message that is an exact replica of the message
1778  * specified, except that its refcount is set to 1, its message serial
1779  * is reset to 0, and if the original message was "locked" (in the
1780  * outgoing message queue and thus not modifiable) the new message
1781  * will not be locked.
1782  *
1783  * @todo This function can't be used in programs that try to recover from OOM errors.
1784  *
1785  * @param message the message
1786  * @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.
1787  */
1788 DBusMessage *
1789 dbus_message_copy (const DBusMessage *message)
1790 {
1791   DBusMessage *retval;
1792
1793   _dbus_return_val_if_fail (message != NULL, NULL);
1794
1795   retval = dbus_new0 (DBusMessage, 1);
1796   if (retval == NULL)
1797     return NULL;
1798
1799   _dbus_atomic_inc (&retval->refcount);
1800
1801   retval->locked = FALSE;
1802 #ifndef DBUS_DISABLE_CHECKS
1803   retval->generation = message->generation;
1804 #endif
1805   _dbus_message_toggle_gvariant (retval, _dbus_message_is_gvariant (message));
1806
1807   if (!_dbus_header_copy (&message->header, &retval->header))
1808     {
1809       dbus_free (retval);
1810       return NULL;
1811     }
1812
1813   if (!_dbus_string_init_preallocated (&retval->body,
1814                                        _dbus_string_get_length (&message->body)))
1815     {
1816       _dbus_header_free (&retval->header);
1817       dbus_free (retval);
1818       return NULL;
1819     }
1820
1821   if (!_dbus_string_copy (&message->body, 0,
1822                           &retval->body, 0))
1823     goto failed_copy;
1824
1825 #ifdef HAVE_UNIX_FD_PASSING
1826   retval->unix_fds = dbus_new(int, message->n_unix_fds);
1827   if (retval->unix_fds == NULL && message->n_unix_fds > 0)
1828     goto failed_copy;
1829
1830   retval->n_unix_fds_allocated = message->n_unix_fds;
1831
1832   for (retval->n_unix_fds = 0;
1833        retval->n_unix_fds < message->n_unix_fds;
1834        retval->n_unix_fds++)
1835     {
1836       retval->unix_fds[retval->n_unix_fds] = _dbus_dup(message->unix_fds[retval->n_unix_fds], NULL);
1837
1838       if (retval->unix_fds[retval->n_unix_fds] < 0)
1839         goto failed_copy;
1840     }
1841
1842 #endif
1843
1844   if (_dbus_message_is_gvariant(message))
1845     {
1846       if (message->locked)
1847         {
1848           /* This is a copy of locked GVariant message, so temporarily set it
1849            * to locked to correctly extract data. Locked messages contain
1850            * signature in the message body, while in unlocked messages it is
1851            * in the struct DBusMessage in the header.
1852            */
1853           retval->locked = TRUE;
1854           if (!_dbus_message_gvariant_convert_to_unlocked (retval))
1855             goto failed_copy;
1856         }
1857
1858       if (message->unique_sender)
1859         {
1860           retval->unique_sender = dbus_new (DBusString, 1);
1861
1862           if (!retval->unique_sender)
1863             goto failed_copy;
1864
1865           if (!_dbus_string_init_preallocated (retval->unique_sender,
1866                                                _dbus_string_get_length (message->unique_sender)))
1867             goto failed_copy_unique_sender;
1868
1869           if (!_dbus_string_copy (message->unique_sender, 0, retval->unique_sender, 0))
1870             goto failed_copy_unique_sender;
1871         }
1872     }
1873
1874   _dbus_message_trace_ref (retval, 0, 1, "copy");
1875   return retval;
1876
1877  failed_copy_unique_sender:
1878   _dbus_string_free (retval->unique_sender);
1879   dbus_free (retval->unique_sender);
1880
1881  failed_copy:
1882   _dbus_header_free (&retval->header);
1883   _dbus_string_free (&retval->body);
1884
1885 #ifdef HAVE_UNIX_FD_PASSING
1886   close_unix_fds(retval->unix_fds, &retval->n_unix_fds);
1887   dbus_free(retval->unix_fds);
1888 #endif
1889
1890   dbus_free (retval);
1891
1892   return NULL;
1893 }
1894
1895
1896 /**
1897  * Increments the reference count of a DBusMessage.
1898  *
1899  * @param message the message
1900  * @returns the message
1901  * @see dbus_message_unref
1902  */
1903 DBusMessage *
1904 dbus_message_ref (DBusMessage *message)
1905 {
1906   dbus_int32_t old_refcount;
1907
1908   _dbus_return_val_if_fail (message != NULL, NULL);
1909   _dbus_return_val_if_fail (message->generation == _dbus_current_generation, NULL);
1910   _dbus_return_val_if_fail (!message->in_cache, NULL);
1911
1912   old_refcount = _dbus_atomic_inc (&message->refcount);
1913   _dbus_assert (old_refcount >= 1);
1914   _dbus_message_trace_ref (message, old_refcount, old_refcount + 1, "ref");
1915
1916   return message;
1917 }
1918
1919 /**
1920  * Decrements the reference count of a DBusMessage, freeing the
1921  * message if the count reaches 0.
1922  *
1923  * @param message the message
1924  * @see dbus_message_ref
1925  */
1926 void
1927 dbus_message_unref (DBusMessage *message)
1928 {
1929  dbus_int32_t old_refcount;
1930
1931   _dbus_return_if_fail (message != NULL);
1932   _dbus_return_if_fail (message->generation == _dbus_current_generation);
1933   _dbus_return_if_fail (!message->in_cache);
1934
1935   old_refcount = _dbus_atomic_dec (&message->refcount);
1936
1937   _dbus_assert (old_refcount >= 1);
1938
1939   _dbus_message_trace_ref (message, old_refcount, old_refcount - 1, "unref");
1940
1941   if (old_refcount == 1)
1942     {
1943       /* Calls application callbacks! */
1944       dbus_message_cache_or_finalize (message);
1945     }
1946 }
1947
1948 /**
1949  * Gets the type of a message. Types include
1950  * #DBUS_MESSAGE_TYPE_METHOD_CALL, #DBUS_MESSAGE_TYPE_METHOD_RETURN,
1951  * #DBUS_MESSAGE_TYPE_ERROR, #DBUS_MESSAGE_TYPE_SIGNAL, but other
1952  * types are allowed and all code must silently ignore messages of
1953  * unknown type. #DBUS_MESSAGE_TYPE_INVALID will never be returned.
1954  *
1955  * @param message the message
1956  * @returns the type of the message
1957  */
1958 int
1959 dbus_message_get_type (DBusMessage *message)
1960 {
1961   _dbus_return_val_if_fail (message != NULL, DBUS_MESSAGE_TYPE_INVALID);
1962
1963   return _dbus_header_get_message_type (&message->header);
1964 }
1965
1966 /**
1967  * Appends fields to a message given a variable argument list. The
1968  * variable argument list should contain the type of each argument
1969  * followed by the value to append. Appendable types are basic types,
1970  * and arrays of fixed-length basic types (except arrays of Unix file
1971  * descriptors). To append variable-length basic types, or any more
1972  * complex value, you have to use an iterator rather than this
1973  * function.
1974  *
1975  * To append a basic type, specify its type code followed by the
1976  * address of the value. For example:
1977  *
1978  * @code
1979  *
1980  * dbus_int32_t v_INT32 = 42;
1981  * const char *v_STRING = "Hello World";
1982  * dbus_message_append_args (message,
1983  *                           DBUS_TYPE_INT32, &v_INT32,
1984  *                           DBUS_TYPE_STRING, &v_STRING,
1985  *                           DBUS_TYPE_INVALID);
1986  * @endcode
1987  *
1988  * To append an array of fixed-length basic types (except Unix file
1989  * descriptors), pass in the DBUS_TYPE_ARRAY typecode, the element
1990  * typecode, the address of the array pointer, and a 32-bit integer
1991  * giving the number of elements in the array. So for example:
1992  *
1993  * @code
1994  *
1995  * const dbus_int32_t array[] = { 1, 2, 3 };
1996  * const dbus_int32_t *v_ARRAY = array;
1997  * dbus_message_append_args (message,
1998  *                           DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY, 3,
1999  *                           DBUS_TYPE_INVALID);
2000  *
2001  * @endcode
2002  *
2003  * This function does not support arrays of Unix file descriptors. If
2004  * you need those you need to manually recurse into the array.
2005  *
2006  * For Unix file descriptors this function will internally duplicate
2007  * the descriptor you passed in. Hence you may close the descriptor
2008  * immediately after this call.
2009  *
2010  * @warning in C, given "int array[]", "&array == array" (the
2011  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
2012  * So if you're using an array instead of a pointer you have to create
2013  * a pointer variable, assign the array to it, then take the address
2014  * of the pointer variable. For strings it works to write
2015  * const char *array = "Hello" and then use &array though.
2016  *
2017  * The last argument to this function must be #DBUS_TYPE_INVALID,
2018  * marking the end of the argument list. If you don't do this
2019  * then libdbus won't know to stop and will read invalid memory.
2020  *
2021  * String/signature/path arrays should be passed in as "const char***
2022  * address_of_array" and "int n_elements"
2023  *
2024  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
2025  *
2026  * @todo If this fails due to lack of memory, the message is hosed and
2027  * you have to start over building the whole message.
2028  *
2029  * @param message the message
2030  * @param first_arg_type type of the first argument
2031  * @param ... value of first argument, list of additional type-value pairs
2032  * @returns #TRUE on success
2033  */
2034 dbus_bool_t
2035 dbus_message_append_args (DBusMessage *message,
2036                           int          first_arg_type,
2037                           ...)
2038 {
2039   dbus_bool_t retval;
2040   va_list var_args;
2041
2042   _dbus_return_val_if_fail (message != NULL, FALSE);
2043
2044   va_start (var_args, first_arg_type);
2045   retval = dbus_message_append_args_valist (message,
2046                                             first_arg_type,
2047                                             var_args);
2048   va_end (var_args);
2049
2050   return retval;
2051 }
2052
2053 /**
2054  * Like dbus_message_append_args() but takes a va_list for use by language bindings.
2055  *
2056  * @todo for now, if this function fails due to OOM it will leave
2057  * the message half-written and you have to discard the message
2058  * and start over.
2059  *
2060  * @see dbus_message_append_args.
2061  * @param message the message
2062  * @param first_arg_type type of first argument
2063  * @param var_args value of first argument, then list of type/value pairs
2064  * @returns #TRUE on success
2065  */
2066 dbus_bool_t
2067 dbus_message_append_args_valist (DBusMessage *message,
2068                                  int          first_arg_type,
2069                                  va_list      var_args)
2070 {
2071   int type;
2072   DBusMessageIter iter;
2073
2074   _dbus_return_val_if_fail (message != NULL, FALSE);
2075
2076   type = first_arg_type;
2077
2078   dbus_message_iter_init_append (message, &iter);
2079
2080   while (type != DBUS_TYPE_INVALID)
2081     {
2082       if (dbus_type_is_basic (type))
2083         {
2084           const DBusBasicValue *value;
2085           value = va_arg (var_args, const DBusBasicValue*);
2086
2087           if (!dbus_message_iter_append_basic (&iter,
2088                                                type,
2089                                                value))
2090             goto failed;
2091         }
2092       else if (type == DBUS_TYPE_ARRAY)
2093         {
2094           int element_type;
2095           DBusMessageIter array;
2096           char buf[2];
2097
2098           element_type = va_arg (var_args, int);
2099
2100           buf[0] = element_type;
2101           buf[1] = '\0';
2102           if (!dbus_message_iter_open_container (&iter,
2103                                                  DBUS_TYPE_ARRAY,
2104                                                  buf,
2105                                                  &array))
2106             goto failed;
2107
2108           if (dbus_type_is_fixed (element_type) &&
2109               element_type != DBUS_TYPE_UNIX_FD)
2110             {
2111               const DBusBasicValue **value;
2112               int n_elements;
2113
2114               value = va_arg (var_args, const DBusBasicValue**);
2115               n_elements = va_arg (var_args, int);
2116
2117               if (!dbus_message_iter_append_fixed_array (&array,
2118                                                          element_type,
2119                                                          value,
2120                                                          n_elements)) {
2121                 dbus_message_iter_abandon_container (&iter, &array);
2122                 goto failed;
2123               }
2124             }
2125           else if (_DBUS_TYPE_IS_STRINGLIKE (element_type))
2126             {
2127               const char ***value_p;
2128               const char **value;
2129               int n_elements;
2130               int i;
2131
2132               value_p = va_arg (var_args, const char***);
2133               n_elements = va_arg (var_args, int);
2134
2135               value = *value_p;
2136
2137               i = 0;
2138               while (i < n_elements)
2139                 {
2140                   if (!dbus_message_iter_append_basic (&array,
2141                                                        element_type,
2142                                                        &value[i])) {
2143                     dbus_message_iter_abandon_container (&iter, &array);
2144                     goto failed;
2145                   }
2146                   ++i;
2147                 }
2148             }
2149           else
2150             {
2151               _dbus_warn ("arrays of %s can't be appended with %s for now",
2152                           _dbus_type_to_string (element_type),
2153                           _DBUS_FUNCTION_NAME);
2154               dbus_message_iter_abandon_container (&iter, &array);
2155               goto failed;
2156             }
2157
2158           if (!dbus_message_iter_close_container (&iter, &array))
2159             goto failed;
2160         }
2161 #ifndef DBUS_DISABLE_CHECKS
2162       else
2163         {
2164           _dbus_warn ("type %s isn't supported yet in %s",
2165                       _dbus_type_to_string (type), _DBUS_FUNCTION_NAME);
2166           goto failed;
2167         }
2168 #endif
2169
2170       type = va_arg (var_args, int);
2171     }
2172
2173   return TRUE;
2174
2175  failed:
2176   return FALSE;
2177 }
2178
2179 /**
2180  * Gets arguments from a message given a variable argument list.  The
2181  * supported types include those supported by
2182  * dbus_message_append_args(); that is, basic types and arrays of
2183  * fixed-length basic types.  The arguments are the same as they would
2184  * be for dbus_message_iter_get_basic() or
2185  * dbus_message_iter_get_fixed_array().
2186  *
2187  * In addition to those types, arrays of string, object path, and
2188  * signature are supported; but these are returned as allocated memory
2189  * and must be freed with dbus_free_string_array(), while the other
2190  * types are returned as const references. To get a string array
2191  * pass in "char ***array_location" and "int *n_elements".
2192  *
2193  * Similar to dbus_message_get_fixed_array() this function does not
2194  * support arrays of type DBUS_TYPE_UNIX_FD. If you need to parse
2195  * messages with arrays of Unix file descriptors you need to recurse
2196  * into the array manually.
2197  *
2198  * Unix file descriptors that are read with this function will have
2199  * the FD_CLOEXEC flag set. If you need them without this flag set,
2200  * make sure to unset it with fcntl().
2201  *
2202  * The variable argument list should contain the type of the argument
2203  * followed by a pointer to where the value should be stored. The list
2204  * is terminated with #DBUS_TYPE_INVALID.
2205  *
2206  * Except for string arrays, the returned values are constant; do not
2207  * free them. They point into the #DBusMessage.
2208  *
2209  * If the requested arguments are not present, or do not have the
2210  * requested types, then an error will be set.
2211  *
2212  * If more arguments than requested are present, the requested
2213  * arguments are returned and the extra arguments are ignored.
2214  *
2215  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
2216  *
2217  * @param message the message
2218  * @param error error to be filled in on failure
2219  * @param first_arg_type the first argument type
2220  * @param ... location for first argument value, then list of type-location pairs
2221  * @returns #FALSE if the error was set
2222  */
2223 dbus_bool_t
2224 dbus_message_get_args (DBusMessage     *message,
2225                        DBusError       *error,
2226                        int              first_arg_type,
2227                        ...)
2228 {
2229   dbus_bool_t retval;
2230   va_list var_args;
2231
2232   _dbus_return_val_if_fail (message != NULL, FALSE);
2233   _dbus_return_val_if_error_is_set (error, FALSE);
2234
2235   va_start (var_args, first_arg_type);
2236   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
2237   va_end (var_args);
2238
2239   return retval;
2240 }
2241
2242 /**
2243  * Like dbus_message_get_args but takes a va_list for use by language bindings.
2244  *
2245  * @see dbus_message_get_args
2246  * @param message the message
2247  * @param error error to be filled in
2248  * @param first_arg_type type of the first argument
2249  * @param var_args return location for first argument, followed by list of type/location pairs
2250  * @returns #FALSE if error was set
2251  */
2252 dbus_bool_t
2253 dbus_message_get_args_valist (DBusMessage     *message,
2254                               DBusError       *error,
2255                               int              first_arg_type,
2256                               va_list          var_args)
2257 {
2258   DBusMessageIter iter;
2259
2260   _dbus_return_val_if_fail (message != NULL, FALSE);
2261   _dbus_return_val_if_error_is_set (error, FALSE);
2262
2263   dbus_message_iter_init (message, &iter);
2264   return _dbus_message_iter_get_args_valist (&iter, error, first_arg_type, var_args);
2265 }
2266
2267 static void
2268 _dbus_message_iter_init_common (DBusMessage         *message,
2269                                 DBusMessageRealIter *real,
2270                                 int                  iter_type)
2271 {
2272   /* If these static assertions fail on your platform, report it as a bug. */
2273   _DBUS_STATIC_ASSERT (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
2274   _DBUS_STATIC_ASSERT (_DBUS_ALIGNOF (DBusMessageRealIter) <=
2275       _DBUS_ALIGNOF (DBusMessageIter));
2276   /* A failure of these two assertions would indicate that we've broken
2277    * ABI on this platform since 1.10.0. */
2278   _DBUS_STATIC_ASSERT (sizeof (DBusMessageIter_1_10_0) ==
2279       sizeof (DBusMessageIter));
2280   _DBUS_STATIC_ASSERT (_DBUS_ALIGNOF (DBusMessageIter_1_10_0) ==
2281       _DBUS_ALIGNOF (DBusMessageIter));
2282   /* If this static assertion fails, it means the DBusMessageIter struct
2283    * is not "packed", which might result in "iter = other_iter" not copying
2284    * every byte. */
2285   _DBUS_STATIC_ASSERT (sizeof (DBusMessageIter) ==
2286       10 * sizeof (void *) + sizeof (dbus_uint32_t) + 3 * sizeof (int));
2287
2288   /* Since the iterator will read or write who-knows-what from the
2289    * message, we need to get in the right byte order
2290    */
2291   ensure_byte_order (message);
2292
2293   real->message = message;
2294   real->changed_stamp = message->changed_stamp;
2295   real->iter_type = iter_type;
2296   real->sig_refcount = 0;
2297 }
2298
2299 /**
2300  * Initializes a #DBusMessageIter for reading the arguments of the
2301  * message passed in.
2302  *
2303  * When possible, dbus_message_get_args() is much more convenient.
2304  * Some types of argument can only be read with #DBusMessageIter
2305  * however.
2306  *
2307  * The easiest way to iterate is like this:
2308  * @code
2309  * dbus_message_iter_init (message, &iter);
2310  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
2311  *   dbus_message_iter_next (&iter);
2312  * @endcode
2313  *
2314  * #DBusMessageIter contains no allocated memory; it need not be
2315  * freed, and can be copied by assignment or memcpy().
2316  *
2317  * @param message the message
2318  * @param iter pointer to an iterator to initialize
2319  * @returns #FALSE if the message has no arguments
2320  */
2321 dbus_bool_t
2322 dbus_message_iter_init (DBusMessage     *message,
2323                         DBusMessageIter *iter)
2324 {
2325   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2326   const DBusString *type_str;
2327   int type_pos;
2328
2329   BUILD_BUG_ON (sizeof(DBusMessageIter) != sizeof(DBusMessageRealIter));
2330
2331   _dbus_return_val_if_fail (message != NULL, FALSE);
2332   _dbus_return_val_if_fail (iter != NULL, FALSE);
2333
2334   get_const_signature (message, &type_str, &type_pos);
2335
2336   _dbus_message_iter_init_common (message, real,
2337                                   DBUS_MESSAGE_ITER_TYPE_READER);
2338
2339   _dbus_type_reader_init (&real->u.reader,
2340                                    _dbus_header_get_byte_order (&message->header),
2341                                    type_str, type_pos,
2342                                    &message->body,
2343                                    0);
2344
2345   if (_dbus_message_is_gvariant (message))
2346     _dbus_type_reader_gvariant_init (&real->u.reader, message);
2347
2348   return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
2349 }
2350
2351 /**
2352  * Checks if an iterator has any more fields.
2353  *
2354  * @param iter the message iter
2355  * @returns #TRUE if there are more fields following
2356  */
2357 dbus_bool_t
2358 dbus_message_iter_has_next (DBusMessageIter *iter)
2359 {
2360   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2361
2362   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
2363   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2364
2365   return _dbus_type_reader_has_next (&real->u.reader);
2366 }
2367
2368 /**
2369  * Moves the iterator to the next field, if any. If there's no next
2370  * field, returns #FALSE. If the iterator moves forward, returns
2371  * #TRUE.
2372  *
2373  * @param iter the message iter
2374  * @returns #TRUE if the iterator was moved to the next field
2375  */
2376 dbus_bool_t
2377 dbus_message_iter_next (DBusMessageIter *iter)
2378 {
2379   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2380
2381   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
2382   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2383
2384   return _dbus_type_reader_next (&real->u.reader);
2385 }
2386
2387 /**
2388  * Returns the argument type of the argument that the message iterator
2389  * points to. If the iterator is at the end of the message, returns
2390  * #DBUS_TYPE_INVALID. You can thus write a loop as follows:
2391  *
2392  * @code
2393  * dbus_message_iter_init (message, &iter);
2394  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
2395  *   dbus_message_iter_next (&iter);
2396  * @endcode
2397  *
2398  * @param iter the message iter
2399  * @returns the argument type
2400  */
2401 int
2402 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
2403 {
2404   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2405
2406   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2407   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2408
2409   return _dbus_type_reader_get_current_type (&real->u.reader);
2410 }
2411
2412 /**
2413  * Returns the element type of the array that the message iterator
2414  * points to. Note that you need to check that the iterator points to
2415  * an array prior to using this function.
2416  *
2417  * @param iter the message iter
2418  * @returns the array element type
2419  */
2420 int
2421 dbus_message_iter_get_element_type (DBusMessageIter *iter)
2422 {
2423   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2424
2425   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2426   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, DBUS_TYPE_INVALID);
2427   _dbus_return_val_if_fail (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY, DBUS_TYPE_INVALID);
2428
2429   return _dbus_type_reader_get_element_type (&real->u.reader);
2430 }
2431
2432 /**
2433  * Recurses into a container value when reading values from a message,
2434  * initializing a sub-iterator to use for traversing the child values
2435  * of the container.
2436  *
2437  * Note that this recurses into a value, not a type, so you can only
2438  * recurse if the value exists. The main implication of this is that
2439  * if you have for example an empty array of array of int32, you can
2440  * recurse into the outermost array, but it will have no values, so
2441  * you won't be able to recurse further. There's no array of int32 to
2442  * recurse into.
2443  *
2444  * If a container is an array of fixed-length types (except Unix file
2445  * descriptors), it is much more efficient to use
2446  * dbus_message_iter_get_fixed_array() to get the whole array in one
2447  * shot, rather than individually walking over the array elements.
2448  *
2449  * Be sure you have somehow checked that
2450  * dbus_message_iter_get_arg_type() matches the type you are expecting
2451  * to recurse into. Results of this function are undefined if there is
2452  * no container to recurse into at the current iterator position.
2453  *
2454  * @param iter the message iterator
2455  * @param sub the sub-iterator to initialize
2456  */
2457 void
2458 dbus_message_iter_recurse (DBusMessageIter  *iter,
2459                            DBusMessageIter  *sub)
2460 {
2461   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2462   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2463
2464   _dbus_return_if_fail (_dbus_message_iter_check (real));
2465   _dbus_return_if_fail (sub != NULL);
2466
2467   *real_sub = *real;
2468   _dbus_type_reader_recurse (&real->u.reader, &real_sub->u.reader);
2469 }
2470
2471 /**
2472  * Returns the current signature of a message iterator.  This
2473  * is useful primarily for dealing with variants; one can
2474  * recurse into a variant and determine the signature of
2475  * the variant's value.
2476  *
2477  * The returned string must be freed with dbus_free().
2478  *
2479  * @param iter the message iterator
2480  * @returns the contained signature, or NULL if out of memory
2481  */
2482 char *
2483 dbus_message_iter_get_signature (DBusMessageIter *iter)
2484 {
2485   const DBusString *sig;
2486   DBusString retstr;
2487   char *ret;
2488   int start, len;
2489   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2490
2491   _dbus_return_val_if_fail (_dbus_message_iter_check (real), NULL);
2492
2493   if (!_dbus_string_init (&retstr))
2494     return NULL;
2495
2496   _dbus_type_reader_get_signature (&real->u.reader, &sig,
2497                                    &start, &len);
2498   if (!_dbus_string_append_len (&retstr,
2499                                 _dbus_string_get_const_data (sig) + start,
2500                                 len))
2501     return NULL;
2502   if (!_dbus_string_steal_data (&retstr, &ret))
2503     return NULL;
2504   _dbus_string_free (&retstr);
2505   return ret;
2506 }
2507
2508 /**
2509  * Reads a basic-typed value from the message iterator.
2510  * Basic types are the non-containers such as integer and string.
2511  *
2512  * The value argument should be the address of a location to store
2513  * the returned value. So for int32 it should be a "dbus_int32_t*"
2514  * and for string a "const char**". The returned value is
2515  * by reference and should not be freed.
2516  *
2517  * This call duplicates Unix file descriptors when reading them. It is
2518  * your job to close them when you don't need them anymore.
2519  *
2520  * Unix file descriptors that are read with this function will have
2521  * the FD_CLOEXEC flag set. If you need them without this flag set,
2522  * make sure to unset it with fcntl().
2523  *
2524  * Be sure you have somehow checked that
2525  * dbus_message_iter_get_arg_type() matches the type you are
2526  * expecting, or you'll crash when you try to use an integer as a
2527  * string or something.
2528  *
2529  * To read any container type (array, struct, dict) you will need to
2530  * recurse into the container with dbus_message_iter_recurse().  If
2531  * the container is an array of fixed-length values (except Unix file
2532  * descriptors), you can get all the array elements at once with
2533  * dbus_message_iter_get_fixed_array(). Otherwise, you have to iterate
2534  * over the container's contents one value at a time.
2535  *
2536  * All basic-typed values are guaranteed to fit in a #DBusBasicValue,
2537  * so in versions of libdbus that have that type, you can write code like this:
2538  *
2539  * @code
2540  * DBusBasicValue value;
2541  * int type;
2542  * dbus_message_iter_get_basic (&read_iter, &value);
2543  * type = dbus_message_iter_get_arg_type (&read_iter);
2544  * dbus_message_iter_append_basic (&write_iter, type, &value);
2545  * @endcode
2546  *
2547  * (All D-Bus basic types are either numeric and 8 bytes or smaller, or
2548  * behave like a string; so in older versions of libdbus, DBusBasicValue
2549  * can be replaced with union { char *string; unsigned char bytes[8]; },
2550  * for instance.)
2551  *
2552  * @param iter the iterator
2553  * @param value location to store the value
2554  */
2555 void
2556 dbus_message_iter_get_basic (DBusMessageIter  *iter,
2557                              void             *value)
2558 {
2559   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2560
2561   _dbus_return_if_fail (_dbus_message_iter_check (real));
2562   _dbus_return_if_fail (value != NULL);
2563
2564   if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UNIX_FD)
2565     {
2566 #ifdef HAVE_UNIX_FD_PASSING
2567       DBusBasicValue idx;
2568
2569       _dbus_type_reader_read_basic(&real->u.reader, &idx);
2570
2571       if (idx.u32 >= real->message->n_unix_fds) {
2572         /* Hmm, we cannot really signal an error here, so let's make
2573            sure to return an invalid fd. */
2574         *((int*) value) = -1;
2575         return;
2576       }
2577
2578       *((int*) value) = _dbus_dup(real->message->unix_fds[idx.u32], NULL);
2579 #else
2580       *((int*) value) = -1;
2581 #endif
2582     }
2583   else
2584     {
2585       _dbus_type_reader_read_basic (&real->u.reader,
2586                                     value);
2587     }
2588 }
2589
2590 /**
2591  * Returns the number of elements in the array-typed value pointed
2592  * to by the iterator.
2593  * Note that this function is O(1) for arrays of fixed-size types
2594  * but O(n) for arrays of variable-length types such as strings,
2595  * so it may be a bad idea to use it.
2596  *
2597  * @param iter the iterator
2598  * @returns the number of elements in the array
2599  */
2600 int
2601 dbus_message_iter_get_element_count (DBusMessageIter *iter)
2602 {
2603   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2604   DBusTypeReader array;
2605   int element_type;
2606   int n_elements = 0;
2607
2608   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2609   _dbus_return_val_if_fail (_dbus_type_reader_get_current_type (&real->u.reader)
2610                             == DBUS_TYPE_ARRAY, 0);
2611
2612   element_type = _dbus_type_reader_get_element_type (&real->u.reader);
2613   _dbus_type_reader_recurse (&real->u.reader, &array);
2614   if (dbus_type_is_fixed (element_type))
2615     {
2616       int alignment = _dbus_type_get_alignment (element_type);
2617       int total_len = _dbus_type_reader_get_array_length (&array);
2618       n_elements = total_len / alignment;
2619     }
2620   else
2621     {
2622       while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
2623         {
2624           ++n_elements;
2625           _dbus_type_reader_next (&array);
2626         }
2627     }
2628
2629    return n_elements;
2630 }
2631
2632 /**
2633  * Returns the number of bytes in the array as marshaled in the wire
2634  * protocol. The iterator must currently be inside an array-typed
2635  * value.
2636  *
2637  * This function is deprecated on the grounds that it is stupid.  Why
2638  * would you want to know how many bytes are in the array as marshaled
2639  * in the wire protocol?  Use dbus_message_iter_get_element_count() instead.
2640  *
2641  * @param iter the iterator
2642  * @returns the number of bytes in the array
2643  */
2644 int
2645 dbus_message_iter_get_array_len (DBusMessageIter *iter)
2646 {
2647   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2648
2649   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2650
2651   return _dbus_type_reader_get_array_length (&real->u.reader);
2652 }
2653
2654 /**
2655  * Reads a block of fixed-length values from the message iterator.
2656  * Fixed-length values are those basic types that are not string-like,
2657  * such as integers, bool, double. The returned block will be from the
2658  * current position in the array until the end of the array.
2659  *
2660  * There is one exception here: although DBUS_TYPE_UNIX_FD is
2661  * considered a 'fixed' type arrays of this type may not be read with
2662  * this function.
2663  *
2664  * The message iter should be "in" the array (that is, you recurse into the
2665  * array, and then you call dbus_message_iter_get_fixed_array() on the
2666  * "sub-iterator" created by dbus_message_iter_recurse()).
2667  *
2668  * The value argument should be the address of a location to store the
2669  * returned array. So for int32 it should be a "const dbus_int32_t**"
2670  * The returned value is by reference and should not be freed.
2671  *
2672  * This function should only be used if dbus_type_is_fixed() returns
2673  * #TRUE for the element type.
2674  *
2675  * If an array's elements are not fixed in size, you have to recurse
2676  * into the array with dbus_message_iter_recurse() and read the
2677  * elements one by one.
2678  *
2679  * Because the array is not copied, this function runs in constant
2680  * time and is fast; it's much preferred over walking the entire array
2681  * with an iterator. (However, you can always use
2682  * dbus_message_iter_recurse(), even for fixed-length types;
2683  * dbus_message_iter_get_fixed_array() is just an optimization.)
2684  *
2685  * @param iter the iterator
2686  * @param value location to store the block
2687  * @param n_elements number of elements in the block
2688  */
2689 void
2690 dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
2691                                    void             *value,
2692                                    int              *n_elements)
2693 {
2694   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2695 #ifndef DBUS_DISABLE_CHECKS
2696   int subtype = _dbus_type_reader_get_current_type(&real->u.reader);
2697
2698   _dbus_return_if_fail (_dbus_message_iter_check (real));
2699   _dbus_return_if_fail (value != NULL);
2700   _dbus_return_if_fail ((subtype == DBUS_TYPE_INVALID) ||
2701                         (dbus_type_is_fixed (subtype) && subtype != DBUS_TYPE_UNIX_FD));
2702 #endif
2703
2704   _dbus_type_reader_read_fixed_multi (&real->u.reader,
2705                                       value, n_elements);
2706 }
2707
2708 /**
2709  * Initializes a #DBusMessageIter for appending arguments to the end
2710  * of a message.
2711  *
2712  * @todo If appending any of the arguments fails due to lack of
2713  * memory, the message is hosed and you have to start over building
2714  * the whole message.
2715  *
2716  * @param message the message
2717  * @param iter pointer to an iterator to initialize
2718  */
2719 void
2720 dbus_message_iter_init_append (DBusMessage     *message,
2721                                DBusMessageIter *iter)
2722 {
2723   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2724
2725   _dbus_return_if_fail (message != NULL);
2726   _dbus_return_if_fail (iter != NULL);
2727
2728   _dbus_message_iter_init_common (message, real,
2729                                   DBUS_MESSAGE_ITER_TYPE_WRITER);
2730
2731   /* We create the signature string and point iterators at it "on demand"
2732    * when a value is actually appended. That means that init() never fails
2733    * due to OOM.
2734    */
2735   _dbus_type_writer_gvariant_init_types_delayed (
2736                               &real->u.writer,
2737                               _dbus_header_get_byte_order (&message->header),
2738                               &message->body,
2739                               _dbus_string_get_length (&message->body),
2740                               _dbus_message_is_gvariant (message),
2741                               &message->gvariant_body_last_offset,
2742                               &message->gvariant_body_last_pos);
2743 }
2744
2745 /**
2746  * Creates a temporary signature string containing the current
2747  * signature, stores it in the iterator, and points the iterator to
2748  * the end of it. Used any time we write to the message.
2749  *
2750  * @param real an iterator without a type_str
2751  * @returns #FALSE if no memory
2752  */
2753 static dbus_bool_t
2754 _dbus_message_iter_open_signature (DBusMessageRealIter *real)
2755 {
2756   DBusString *str;
2757   const DBusString *current_sig;
2758   int current_sig_pos;
2759
2760   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2761
2762   if (real->u.writer.type_str != NULL)
2763     {
2764       _dbus_assert (real->sig_refcount > 0);
2765       real->sig_refcount += 1;
2766       return TRUE;
2767     }
2768
2769   str = dbus_new (DBusString, 1);
2770   if (str == NULL)
2771     return FALSE;
2772
2773   if (!_dbus_header_get_field_raw (&real->message->header,
2774                                    DBUS_HEADER_FIELD_SIGNATURE,
2775                                    &current_sig, &current_sig_pos))
2776     current_sig = NULL;
2777
2778   if (current_sig)
2779     {
2780       int current_len;
2781       int additional_size_for_len = 0;
2782
2783       if (!real->u.writer.gvariant)
2784       {
2785         current_len = _dbus_string_get_byte (current_sig, current_sig_pos);
2786         current_sig_pos += 1; /* move on to sig data */
2787         additional_size_for_len = 4;
2788       }
2789       else
2790       {
2791         /* GVariant has no length field, simply string */
2792         current_len = strlen (_dbus_string_get_const_data (current_sig) + current_sig_pos);
2793       }
2794
2795       if (!_dbus_string_init_preallocated (str, current_len + additional_size_for_len))
2796         {
2797           dbus_free (str);
2798           return FALSE;
2799         }
2800
2801       if (!_dbus_string_copy_len (current_sig, current_sig_pos, current_len,
2802                                   str, 0))
2803         {
2804           _dbus_string_free (str);
2805           dbus_free (str);
2806           return FALSE;
2807         }
2808     }
2809   else
2810     {
2811       if (!_dbus_string_init_preallocated (str, 4))
2812         {
2813           dbus_free (str);
2814           return FALSE;
2815         }
2816     }
2817
2818   real->sig_refcount = 1;
2819
2820   /* If this assertion failed, then str would be neither stored in u.writer
2821    * nor freed by this function, resulting in a memory leak. */
2822   _dbus_assert (real->u.writer.type_str == NULL);
2823   _dbus_type_writer_add_types (&real->u.writer,
2824                                str, _dbus_string_get_length (str));
2825   return TRUE;
2826 }
2827
2828 /**
2829  * Sets the new signature as the message signature, frees the
2830  * signature string, and marks the iterator as not having a type_str
2831  * anymore. Frees the signature even if it fails, so you can't
2832  * really recover from failure. Kinda busted.
2833  *
2834  * @param real an iterator without a type_str
2835  * @returns #FALSE if no memory
2836  */
2837 static dbus_bool_t
2838 _dbus_message_iter_close_signature (DBusMessageRealIter *real)
2839 {
2840   DBusString *str;
2841   const char *v_STRING;
2842   dbus_bool_t retval;
2843
2844   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2845   _dbus_assert (real->u.writer.type_str != NULL);
2846   _dbus_assert (real->sig_refcount > 0);
2847
2848   real->sig_refcount -= 1;
2849
2850   if (real->sig_refcount > 0)
2851     return TRUE;
2852   _dbus_assert (real->sig_refcount == 0);
2853
2854   retval = TRUE;
2855
2856   str = real->u.writer.type_str;
2857
2858   v_STRING = _dbus_string_get_const_data (str);
2859   if (!_dbus_header_set_field_basic (&real->message->header,
2860                                      DBUS_HEADER_FIELD_SIGNATURE,
2861                                      DBUS_TYPE_SIGNATURE,
2862                                      &v_STRING))
2863     retval = FALSE;
2864
2865   _dbus_type_writer_remove_types (&real->u.writer);
2866   _dbus_string_free (str);
2867   dbus_free (str);
2868
2869   return retval;
2870 }
2871
2872 /**
2873  * Frees the signature string and marks the iterator as not having a
2874  * type_str anymore.  Since the new signature is not set, the message
2875  * will generally be hosed after this is called.
2876  *
2877  * @param real an iterator without a type_str
2878  */
2879 static void
2880 _dbus_message_iter_abandon_signature (DBusMessageRealIter *real)
2881 {
2882   DBusString *str;
2883
2884   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2885   _dbus_assert (real->u.writer.type_str != NULL);
2886   _dbus_assert (real->sig_refcount > 0);
2887
2888   real->sig_refcount -= 1;
2889
2890   if (real->sig_refcount > 0)
2891     return;
2892   _dbus_assert (real->sig_refcount == 0);
2893
2894   str = real->u.writer.type_str;
2895
2896   _dbus_type_writer_remove_types (&real->u.writer);
2897   _dbus_string_free (str);
2898   dbus_free (str);
2899 }
2900
2901 #ifndef DBUS_DISABLE_CHECKS
2902 static dbus_bool_t
2903 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
2904 {
2905   if (!_dbus_message_iter_check (iter))
2906     return FALSE;
2907
2908   if (iter->message->locked)
2909     {
2910       _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)");
2911       return FALSE;
2912     }
2913
2914   return TRUE;
2915 }
2916 #endif /* DBUS_DISABLE_CHECKS */
2917
2918 #ifdef HAVE_UNIX_FD_PASSING
2919 static int *
2920 expand_fd_array(DBusMessage *m,
2921                 unsigned     n)
2922 {
2923   _dbus_assert(m);
2924
2925   /* This makes space for adding n new fds to the array and returns a
2926      pointer to the place were the first fd should be put. */
2927
2928   if (m->n_unix_fds + n > m->n_unix_fds_allocated)
2929     {
2930       unsigned k;
2931       int *p;
2932
2933       /* Make twice as much space as necessary */
2934       k = (m->n_unix_fds + n) * 2;
2935
2936       /* Allocate at least four */
2937       if (k < 4)
2938         k = 4;
2939
2940       p = dbus_realloc(m->unix_fds, k * sizeof(int));
2941       if (p == NULL)
2942         return NULL;
2943
2944       m->unix_fds = p;
2945       m->n_unix_fds_allocated = k;
2946     }
2947
2948   return m->unix_fds + m->n_unix_fds;
2949 }
2950 #endif
2951
2952 /**
2953  * Appends a basic-typed value to the message. The basic types are the
2954  * non-container types such as integer and string.
2955  *
2956  * The "value" argument should be the address of a basic-typed value.
2957  * So for string, const char**. For integer, dbus_int32_t*.
2958  *
2959  * For Unix file descriptors this function will internally duplicate
2960  * the descriptor you passed in. Hence you may close the descriptor
2961  * immediately after this call.
2962  *
2963  * @todo If this fails due to lack of memory, the message is hosed and
2964  * you have to start over building the whole message.
2965  *
2966  * @param iter the append iterator
2967  * @param type the type of the value
2968  * @param value the address of the value
2969  * @returns #FALSE if not enough memory
2970  */
2971 dbus_bool_t
2972 dbus_message_iter_append_basic (DBusMessageIter *iter,
2973                                 int              type,
2974                                 const void      *value)
2975 {
2976   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2977   dbus_bool_t ret;
2978
2979   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2980   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2981   _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
2982   _dbus_return_val_if_fail (value != NULL, FALSE);
2983
2984 #ifndef DBUS_DISABLE_CHECKS
2985   switch (type)
2986     {
2987       DBusString str;
2988       DBusValidity signature_validity;
2989       const char * const *string_p;
2990       const dbus_bool_t *bool_p;
2991
2992       case DBUS_TYPE_STRING:
2993         string_p = value;
2994         _dbus_return_val_if_fail (_dbus_check_is_valid_utf8 (*string_p), FALSE);
2995         break;
2996
2997       case DBUS_TYPE_OBJECT_PATH:
2998         string_p = value;
2999         _dbus_return_val_if_fail (_dbus_check_is_valid_path (*string_p), FALSE);
3000         break;
3001
3002       case DBUS_TYPE_SIGNATURE:
3003         string_p = value;
3004         _dbus_string_init_const (&str, *string_p);
3005         signature_validity = _dbus_validate_signature_with_reason (&str,
3006                                                                    0,
3007                                                                    _dbus_string_get_length (&str));
3008
3009         if (signature_validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3010           return FALSE;
3011
3012         _dbus_return_val_if_fail (signature_validity == DBUS_VALID, FALSE);
3013         break;
3014
3015       case DBUS_TYPE_BOOLEAN:
3016         bool_p = value;
3017         _dbus_return_val_if_fail (*bool_p == 0 || *bool_p == 1, FALSE);
3018         break;
3019
3020       default:
3021           {
3022             /* nothing to check, all possible values are allowed */
3023           }
3024     }
3025 #endif
3026
3027   if (!_dbus_message_iter_open_signature (real))
3028     return FALSE;
3029
3030   if (type == DBUS_TYPE_UNIX_FD)
3031     {
3032 #ifdef HAVE_UNIX_FD_PASSING
3033       int *fds;
3034       dbus_uint32_t u;
3035
3036       ret = FALSE;
3037
3038       /* First step, include the fd in the fd list of this message */
3039       if (!(fds = expand_fd_array(real->message, 1)))
3040         goto out;
3041
3042       *fds = _dbus_dup(*(int*) value, NULL);
3043       if (*fds < 0)
3044         goto out;
3045
3046       u = real->message->n_unix_fds;
3047
3048       /* Second step, write the index to the fd */
3049       if (!(ret = _dbus_type_writer_write_basic (&real->u.writer, DBUS_TYPE_UNIX_FD, &u))) {
3050         _dbus_close(*fds, NULL);
3051         goto out;
3052       }
3053
3054       real->message->n_unix_fds += 1;
3055       u += 1;
3056
3057       /* Final step, update the header accordingly */
3058       ret = _dbus_header_set_field_basic (&real->message->header,
3059                                           DBUS_HEADER_FIELD_UNIX_FDS,
3060                                           DBUS_TYPE_UINT32,
3061                                           &u);
3062
3063       /* If any of these operations fail the message is
3064          hosed. However, no memory or fds should be leaked since what
3065          has been added to message has been added to the message, and
3066          can hence be accounted for when the message is being
3067          freed. */
3068 #else
3069       ret = FALSE;
3070       /* This is redundant (we could just fall through), but it avoids
3071        * -Wunused-label in builds that don't HAVE_UNIX_FD_PASSING */
3072       goto out;
3073 #endif
3074     }
3075   else
3076     {
3077       ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
3078     }
3079
3080 out:
3081   if (!_dbus_message_iter_close_signature (real))
3082     ret = FALSE;
3083
3084   return ret;
3085 }
3086
3087 /**
3088  * Appends a block of fixed-length values to an array. The
3089  * fixed-length types are all basic types that are not string-like. So
3090  * int32, double, bool, etc. (Unix file descriptors however are not
3091  * supported.) You must call dbus_message_iter_open_container() to
3092  * open an array of values before calling this function. You may call
3093  * this function multiple times (and intermixed with calls to
3094  * dbus_message_iter_append_basic()) for the same array.
3095  *
3096  * The "value" argument should be the address of the array.  So for
3097  * integer, "dbus_int32_t**" is expected for example.
3098  *
3099  * @warning in C, given "int array[]", "&array == array" (the
3100  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
3101  * So if you're using an array instead of a pointer you have to create
3102  * a pointer variable, assign the array to it, then take the address
3103  * of the pointer variable.
3104  * @code
3105  * const dbus_int32_t array[] = { 1, 2, 3 };
3106  * const dbus_int32_t *v_ARRAY = array;
3107  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
3108  *   fprintf (stderr, "No memory!\n");
3109  * @endcode
3110  * For strings it works to write const char *array = "Hello" and then
3111  * use &array though.
3112  *
3113  * @todo If this fails due to lack of memory, the message is hosed and
3114  * you have to start over building the whole message.
3115  *
3116  * @param iter the append iterator
3117  * @param element_type the type of the array elements
3118  * @param value the address of the array
3119  * @param n_elements the number of elements to append
3120  * @returns #FALSE if not enough memory
3121  */
3122 dbus_bool_t
3123 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
3124                                       int              element_type,
3125                                       const void      *value,
3126                                       int              n_elements)
3127 {
3128   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3129   dbus_bool_t ret;
3130
3131   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
3132   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3133   _dbus_return_val_if_fail (dbus_type_is_fixed (element_type) && element_type != DBUS_TYPE_UNIX_FD, FALSE);
3134   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
3135   _dbus_return_val_if_fail (value != NULL, FALSE);
3136   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
3137   _dbus_return_val_if_fail (n_elements <=
3138                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
3139                             FALSE);
3140
3141 #ifndef DBUS_DISABLE_CHECKS
3142   if (element_type == DBUS_TYPE_BOOLEAN)
3143     {
3144       const dbus_bool_t * const *bools = value;
3145       int i;
3146
3147       for (i = 0; i < n_elements; i++)
3148         {
3149           _dbus_return_val_if_fail ((*bools)[i] == 0 || (*bools)[i] == 1, FALSE);
3150         }
3151     }
3152 #endif
3153
3154   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
3155
3156   return ret;
3157 }
3158
3159 /**
3160  * Appends a container-typed value to the message. On success, you are
3161  * required to append the contents of the container using the returned
3162  * sub-iterator, and then call
3163  * dbus_message_iter_close_container(). Container types are for
3164  * example struct, variant, and array. For variants, the
3165  * contained_signature should be the type of the single value inside
3166  * the variant. For structs and dict entries, contained_signature
3167  * should be #NULL; it will be set to whatever types you write into
3168  * the struct.  For arrays, contained_signature should be the type of
3169  * the array elements.
3170  *
3171  * @todo If this fails due to lack of memory, the message is hosed and
3172  * you have to start over building the whole message.
3173  *
3174  * If this function fails, the sub-iterator remains invalid, and must
3175  * not be closed with dbus_message_iter_close_container() or abandoned
3176  * with dbus_message_iter_abandon_container(). However, after this
3177  * function has either succeeded or failed, it is valid to call
3178  * dbus_message_iter_abandon_container_if_open().
3179  *
3180  * @param iter the append iterator
3181  * @param type the type of the value
3182  * @param contained_signature the type of container contents
3183  * @param sub sub-iterator to initialize
3184  * @returns #FALSE if not enough memory
3185  */
3186 dbus_bool_t
3187 dbus_message_iter_open_container (DBusMessageIter *iter,
3188                                   int              type,
3189                                   const char      *contained_signature,
3190                                   DBusMessageIter *sub)
3191 {
3192   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3193   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3194   DBusString contained_str;
3195   DBusValidity contained_signature_validity;
3196   dbus_bool_t ret;
3197
3198   _dbus_return_val_if_fail (sub != NULL, FALSE);
3199   /* Do our best to make sure the sub-iterator doesn't contain something
3200    * valid-looking on failure */
3201   _dbus_message_real_iter_zero (real_sub);
3202
3203   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
3204   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3205   _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
3206   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
3207                              contained_signature == NULL) ||
3208                             (type == DBUS_TYPE_DICT_ENTRY &&
3209                              contained_signature == NULL) ||
3210                             (type == DBUS_TYPE_VARIANT &&
3211                              contained_signature != NULL) ||
3212                             (type == DBUS_TYPE_ARRAY &&
3213                              contained_signature != NULL), FALSE);
3214
3215   /* this would fail if the contained_signature is a dict entry, since
3216    * dict entries are invalid signatures standalone (they must be in
3217    * an array)
3218    */
3219   if (contained_signature != NULL)
3220     {
3221       _dbus_string_init_const (&contained_str, contained_signature);
3222       contained_signature_validity = _dbus_validate_signature_with_reason (&contained_str,
3223           0,
3224           _dbus_string_get_length (&contained_str));
3225
3226       if (contained_signature_validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3227         return FALSE;
3228     }
3229   else
3230     {
3231       /* just some placeholder value */
3232       contained_signature_validity = DBUS_VALID_BUT_INCOMPLETE;
3233     }
3234
3235   _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
3236                             contained_signature == NULL ||
3237                             contained_signature_validity == DBUS_VALID,
3238                             FALSE);
3239
3240   if (!_dbus_message_iter_open_signature (real))
3241     return FALSE;
3242
3243   ret = FALSE;
3244   *real_sub = *real;
3245
3246   if (contained_signature != NULL)
3247     {
3248       _dbus_string_init_const (&contained_str, contained_signature);
3249
3250       ret = _dbus_type_writer_recurse (&real->u.writer,
3251                                        type,
3252                                        &contained_str, 0,
3253                                        &real_sub->u.writer);
3254     }
3255   else
3256     {
3257       ret = _dbus_type_writer_recurse (&real->u.writer,
3258                                        type,
3259                                        NULL, 0,
3260                                        &real_sub->u.writer);
3261     }
3262
3263   if (!ret)
3264     _dbus_message_iter_abandon_signature (real);
3265
3266   return ret;
3267 }
3268
3269
3270 /**
3271  * Closes a container-typed value appended to the message; may write
3272  * out more information to the message known only after the entire
3273  * container is written, and may free resources created by
3274  * dbus_message_iter_open_container().
3275  *
3276  * Even if this function fails due to lack of memory, the sub-iterator sub
3277  * has been closed and invalidated. It must not be closed again with this
3278  * function, or abandoned with dbus_message_iter_abandon_container().
3279  * However, it remains valid to call
3280  * dbus_message_iter_abandon_container_if_open().
3281  *
3282  * @todo If this fails due to lack of memory, the message is hosed and
3283  * you have to start over building the whole message.
3284  *
3285  * @param iter the append iterator
3286  * @param sub sub-iterator to close
3287  * @returns #FALSE if not enough memory
3288  */
3289 dbus_bool_t
3290 dbus_message_iter_close_container (DBusMessageIter *iter,
3291                                    DBusMessageIter *sub)
3292 {
3293   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3294   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3295   dbus_bool_t ret;
3296
3297   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
3298   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3299   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
3300   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3301
3302   ret = _dbus_type_writer_unrecurse (&real->u.writer,
3303                                      &real_sub->u.writer);
3304   _dbus_message_real_iter_zero (real_sub);
3305
3306   if (!_dbus_message_iter_close_signature (real))
3307     ret = FALSE;
3308
3309   return ret;
3310 }
3311
3312 /**
3313  * Abandons creation of a contained-typed value and frees resources created
3314  * by dbus_message_iter_open_container().  Once this returns, the message
3315  * is hosed and you have to start over building the whole message.
3316  *
3317  * This should only be used to abandon creation of a message when you have
3318  * open containers.
3319  *
3320  * @param iter the append iterator
3321  * @param sub sub-iterator to close
3322  */
3323 void
3324 dbus_message_iter_abandon_container (DBusMessageIter *iter,
3325                                      DBusMessageIter *sub)
3326 {
3327   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3328   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3329
3330 #ifndef DBUS_DISABLE_CHECKS
3331   _dbus_return_if_fail (_dbus_message_iter_append_check (real));
3332   _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3333   _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
3334   _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3335 #endif
3336
3337   _dbus_message_iter_abandon_signature (real);
3338   _dbus_message_real_iter_zero (real_sub);
3339 }
3340
3341 /**
3342  * Abandons creation of a contained-typed value and frees resources created
3343  * by dbus_message_iter_open_container().  Once this returns, the message
3344  * is hosed and you have to start over building the whole message.
3345  *
3346  * Unlike dbus_message_iter_abandon_container(), it is valid to call this
3347  * function on an iterator that was initialized with
3348  * #DBUS_MESSAGE_ITER_INIT_CLOSED, or an iterator that was already closed
3349  * or abandoned. However, it is not valid to call this function on
3350  * uninitialized memory. This is intended to be used in error cleanup
3351  * code paths, similar to this pattern:
3352  *
3353  *       DBusMessageIter outer = DBUS_MESSAGE_ITER_INIT_CLOSED;
3354  *       DBusMessageIter inner = DBUS_MESSAGE_ITER_INIT_CLOSED;
3355  *       dbus_bool_t result = FALSE;
3356  *
3357  *       if (!dbus_message_iter_open_container (iter, ..., &outer))
3358  *         goto out;
3359  *
3360  *       if (!dbus_message_iter_open_container (&outer, ..., &inner))
3361  *         goto out;
3362  *
3363  *       if (!dbus_message_iter_append_basic (&inner, ...))
3364  *         goto out;
3365  *
3366  *       if (!dbus_message_iter_close_container (&outer, ..., &inner))
3367  *         goto out;
3368  *
3369  *       if (!dbus_message_iter_close_container (iter, ..., &outer))
3370  *         goto out;
3371  *
3372  *       result = TRUE;
3373  *
3374  *     out:
3375  *       dbus_message_iter_abandon_container_if_open (&outer, &inner);
3376  *       dbus_message_iter_abandon_container_if_open (iter, &outer);
3377  *       return result;
3378  *
3379  * @param iter the append iterator
3380  * @param sub sub-iterator to close
3381  */
3382 void
3383 dbus_message_iter_abandon_container_if_open (DBusMessageIter *iter,
3384                                              DBusMessageIter *sub)
3385 {
3386   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3387   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3388
3389   /* If both the parent and the child are zeroed out, then either we didn't
3390    * even get as far as successfully recursing into the parent, or we already
3391    * closed both the child and the parent. For example, in the code sample
3392    * in the doc-comment above, this happens for
3393    * abandon_container_if_open (&outer, &inner) if the first open_container
3394    * call failed, or if we reached result = TRUE and fell through. */
3395   if (_dbus_message_real_iter_is_zeroed (real) &&
3396       _dbus_message_real_iter_is_zeroed (real_sub))
3397     return;
3398
3399 #ifndef DBUS_DISABLE_CHECKS
3400   /* If the child is not zeroed out, but the parent is, then something has
3401    * gone horribly wrong (in practice that would probably mean both are
3402    * uninitialized or corrupt, and the parent happens to have ended up
3403    * all-bytes-zero). */
3404   _dbus_return_if_fail (_dbus_message_iter_append_check (real));
3405   _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3406 #endif
3407
3408   /* If the parent is not zeroed out, but the child is, then either we did
3409    * not successfully open the child, or we already closed the child. This
3410    * means we do not own a reference to the parent's signature, so it would
3411    * be wrong to release it; so we must not call abandon_signature() here.
3412    * In the code sample in the doc-comment above, this happens for
3413    * abandon_container_if_open (&outer, &inner) if the second open_container
3414    * call failed, or if the second close_container call failed. */
3415   if (_dbus_message_real_iter_is_zeroed (real_sub))
3416     return;
3417
3418 #ifndef DBUS_DISABLE_CHECKS
3419   _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
3420   _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3421 #endif
3422
3423   /* If neither the parent nor the child is zeroed out, then we genuinely
3424    * have an open container; close it. In the code sample in the doc-comment,
3425    * this happens for abandon_container_if_open (&outer, &inner) if the
3426    * append_basic call failed. */
3427   _dbus_message_iter_abandon_signature (real);
3428   _dbus_message_real_iter_zero (real_sub);
3429 }
3430
3431 /**
3432  * Sets a flag indicating that the message does not want a reply; if
3433  * this flag is set, the other end of the connection may (but is not
3434  * required to) optimize by not sending method return or error
3435  * replies. If this flag is set, there is no way to know whether the
3436  * message successfully arrived at the remote end. Normally you know a
3437  * message was received when you receive the reply to it.
3438  *
3439  * The flag is #FALSE by default, that is by default the other end is
3440  * required to reply.
3441  *
3442  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
3443  *
3444  * @param message the message
3445  * @param no_reply #TRUE if no reply is desired
3446  */
3447 void
3448 dbus_message_set_no_reply (DBusMessage *message,
3449                            dbus_bool_t  no_reply)
3450 {
3451   _dbus_return_if_fail (message != NULL);
3452   _dbus_return_if_fail (!message->locked);
3453
3454   _dbus_header_toggle_flag (&message->header,
3455                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
3456                             no_reply);
3457 }
3458
3459 /**
3460  * Returns #TRUE if the message does not expect
3461  * a reply.
3462  *
3463  * @param message the message
3464  * @returns #TRUE if the message sender isn't waiting for a reply
3465  */
3466 dbus_bool_t
3467 dbus_message_get_no_reply (DBusMessage *message)
3468 {
3469   _dbus_return_val_if_fail (message != NULL, FALSE);
3470
3471   return _dbus_header_get_flag (&message->header,
3472                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
3473 }
3474
3475 /**
3476  * Sets a flag indicating that an owner for the destination name will
3477  * be automatically started before the message is delivered. When this
3478  * flag is set, the message is held until a name owner finishes
3479  * starting up, or fails to start up. In case of failure, the reply
3480  * will be an error.
3481  *
3482  * The flag is set to #TRUE by default, i.e. auto starting is the default.
3483  *
3484  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
3485  *
3486  * @param message the message
3487  * @param auto_start #TRUE if auto-starting is desired
3488  */
3489 void
3490 dbus_message_set_auto_start (DBusMessage *message,
3491                              dbus_bool_t  auto_start)
3492 {
3493   _dbus_return_if_fail (message != NULL);
3494   _dbus_return_if_fail (!message->locked);
3495
3496   _dbus_header_toggle_flag (&message->header,
3497                             DBUS_HEADER_FLAG_NO_AUTO_START,
3498                             !auto_start);
3499 }
3500
3501 /**
3502  * Returns #TRUE if the message will cause an owner for
3503  * destination name to be auto-started.
3504  *
3505  * @param message the message
3506  * @returns #TRUE if the message will use auto-start
3507  */
3508 dbus_bool_t
3509 dbus_message_get_auto_start (DBusMessage *message)
3510 {
3511   _dbus_return_val_if_fail (message != NULL, FALSE);
3512
3513   return !_dbus_header_get_flag (&message->header,
3514                                  DBUS_HEADER_FLAG_NO_AUTO_START);
3515 }
3516
3517
3518 /**
3519  * Sets the object path this message is being sent to (for
3520  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
3521  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
3522  *
3523  * The path must contain only valid characters as defined
3524  * in the D-Bus specification.
3525  *
3526  * @param message the message
3527  * @param object_path the path or #NULL to unset
3528  * @returns #FALSE if not enough memory
3529  */
3530 dbus_bool_t
3531 dbus_message_set_path (DBusMessage   *message,
3532                        const char    *object_path)
3533 {
3534   _dbus_return_val_if_fail (message != NULL, FALSE);
3535   _dbus_return_val_if_fail (!message->locked, FALSE);
3536   _dbus_return_val_if_fail (object_path == NULL ||
3537                             _dbus_check_is_valid_path (object_path),
3538                             FALSE);
3539
3540   return set_or_delete_string_field (message,
3541                                      DBUS_HEADER_FIELD_PATH,
3542                                      DBUS_TYPE_OBJECT_PATH,
3543                                      object_path);
3544 }
3545
3546 /**
3547  * Gets the object path this message is being sent to (for
3548  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
3549  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3550  *
3551  * See also dbus_message_get_path_decomposed().
3552  *
3553  * The returned string becomes invalid if the message is
3554  * modified, since it points into the wire-marshaled message data.
3555  *
3556  * @param message the message
3557  * @returns the path (should not be freed) or #NULL
3558  */
3559 const char*
3560 dbus_message_get_path (DBusMessage   *message)
3561 {
3562   const char *v;
3563
3564   _dbus_return_val_if_fail (message != NULL, NULL);
3565
3566   v = NULL; /* in case field doesn't exist */
3567   _dbus_header_get_field_basic (&message->header,
3568                                 DBUS_HEADER_FIELD_PATH,
3569                                 DBUS_TYPE_OBJECT_PATH,
3570                                 (void *) &v);
3571   return v;
3572 }
3573
3574 /**
3575  * Checks if the message has a particular object path.  The object
3576  * path is the destination object for a method call or the emitting
3577  * object for a signal.
3578  *
3579  * @param message the message
3580  * @param path the path name
3581  * @returns #TRUE if there is a path field in the header
3582  */
3583 dbus_bool_t
3584 dbus_message_has_path (DBusMessage   *message,
3585                        const char    *path)
3586 {
3587   const char *msg_path;
3588   msg_path = dbus_message_get_path (message);
3589
3590   if (msg_path == NULL)
3591     {
3592       if (path == NULL)
3593         return TRUE;
3594       else
3595         return FALSE;
3596     }
3597
3598   if (path == NULL)
3599     return FALSE;
3600
3601   if (strcmp (msg_path, path) == 0)
3602     return TRUE;
3603
3604   return FALSE;
3605 }
3606
3607 /**
3608  * Gets the object path this message is being sent to
3609  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
3610  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
3611  * format (one array element per path component).
3612  * Free the returned array with dbus_free_string_array().
3613  *
3614  * An empty but non-NULL path array means the path "/".
3615  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
3616  * and the path "/" becomes { NULL }.
3617  *
3618  * See also dbus_message_get_path().
3619  *
3620  * @todo this could be optimized by using the len from the message
3621  * instead of calling strlen() again
3622  *
3623  * @param message the message
3624  * @param path place to store allocated array of path components; #NULL set here if no path field exists
3625  * @returns #FALSE if no memory to allocate the array
3626  */
3627 dbus_bool_t
3628 dbus_message_get_path_decomposed (DBusMessage   *message,
3629                                   char        ***path)
3630 {
3631   const char *v;
3632
3633   _dbus_return_val_if_fail (message != NULL, FALSE);
3634   _dbus_return_val_if_fail (path != NULL, FALSE);
3635
3636   *path = NULL;
3637
3638   v = dbus_message_get_path (message);
3639   if (v != NULL)
3640     {
3641       if (!_dbus_decompose_path (v, strlen (v),
3642                                  path, NULL))
3643         return FALSE;
3644     }
3645   return TRUE;
3646 }
3647
3648 /**
3649  * Sets the interface this message is being sent to
3650  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
3651  * the interface a signal is being emitted from
3652  * (for DBUS_MESSAGE_TYPE_SIGNAL).
3653  *
3654  * The interface name must contain only valid characters as defined
3655  * in the D-Bus specification.
3656  *
3657  * @param message the message
3658  * @param iface the interface or #NULL to unset
3659  * @returns #FALSE if not enough memory
3660  */
3661 dbus_bool_t
3662 dbus_message_set_interface (DBusMessage  *message,
3663                             const char   *iface)
3664 {
3665   _dbus_return_val_if_fail (message != NULL, FALSE);
3666   _dbus_return_val_if_fail (!message->locked, FALSE);
3667   _dbus_return_val_if_fail (iface == NULL ||
3668                             _dbus_check_is_valid_interface (iface),
3669                             FALSE);
3670
3671   return set_or_delete_string_field (message,
3672                                      DBUS_HEADER_FIELD_INTERFACE,
3673                                      DBUS_TYPE_STRING,
3674                                      iface);
3675 }
3676
3677 /**
3678  * Gets the interface this message is being sent to
3679  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
3680  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
3681  * The interface name is fully-qualified (namespaced).
3682  * Returns #NULL if none.
3683  *
3684  * The returned string becomes invalid if the message is
3685  * modified, since it points into the wire-marshaled message data.
3686  *
3687  * @param message the message
3688  * @returns the message interface (should not be freed) or #NULL
3689  */
3690 const char*
3691 dbus_message_get_interface (DBusMessage *message)
3692 {
3693   const char *v;
3694
3695   _dbus_return_val_if_fail (message != NULL, NULL);
3696
3697   v = NULL; /* in case field doesn't exist */
3698   _dbus_header_get_field_basic (&message->header,
3699                                 DBUS_HEADER_FIELD_INTERFACE,
3700                                 DBUS_TYPE_STRING,
3701                                 (void *) &v);
3702   return v;
3703 }
3704
3705 /**
3706  * Checks if the message has an interface
3707  *
3708  * @param message the message
3709  * @param iface the interface name
3710  * @returns #TRUE if the interface field in the header matches
3711  */
3712 dbus_bool_t
3713 dbus_message_has_interface (DBusMessage   *message,
3714                             const char    *iface)
3715 {
3716   const char *msg_interface;
3717   msg_interface = dbus_message_get_interface (message);
3718
3719   if (msg_interface == NULL)
3720     {
3721       if (iface == NULL)
3722         return TRUE;
3723       else
3724         return FALSE;
3725     }
3726
3727   if (iface == NULL)
3728     return FALSE;
3729
3730   if (strcmp (msg_interface, iface) == 0)
3731     return TRUE;
3732
3733   return FALSE;
3734
3735 }
3736
3737 /**
3738  * Sets the interface member being invoked
3739  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3740  * (DBUS_MESSAGE_TYPE_SIGNAL).
3741  *
3742  * The member name must contain only valid characters as defined
3743  * in the D-Bus specification.
3744  *
3745  * @param message the message
3746  * @param member the member or #NULL to unset
3747  * @returns #FALSE if not enough memory
3748  */
3749 dbus_bool_t
3750 dbus_message_set_member (DBusMessage  *message,
3751                          const char   *member)
3752 {
3753   _dbus_return_val_if_fail (message != NULL, FALSE);
3754   _dbus_return_val_if_fail (!message->locked, FALSE);
3755   _dbus_return_val_if_fail (member == NULL ||
3756                             _dbus_check_is_valid_member (member),
3757                             FALSE);
3758
3759   return set_or_delete_string_field (message,
3760                                      DBUS_HEADER_FIELD_MEMBER,
3761                                      DBUS_TYPE_STRING,
3762                                      member);
3763 }
3764
3765 /**
3766  * Gets the interface member being invoked
3767  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3768  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3769  *
3770  * The returned string becomes invalid if the message is
3771  * modified, since it points into the wire-marshaled message data.
3772  *
3773  * @param message the message
3774  * @returns the member name (should not be freed) or #NULL
3775  */
3776 const char*
3777 dbus_message_get_member (DBusMessage *message)
3778 {
3779   const char *v;
3780
3781   _dbus_return_val_if_fail (message != NULL, NULL);
3782
3783   v = NULL; /* in case field doesn't exist */
3784   _dbus_header_get_field_basic (&message->header,
3785                                 DBUS_HEADER_FIELD_MEMBER,
3786                                 DBUS_TYPE_STRING,
3787                                 (void *) &v);
3788   return v;
3789 }
3790
3791 /**
3792  * Checks if the message has an interface member
3793  *
3794  * @param message the message
3795  * @param member the member name
3796  * @returns #TRUE if there is a member field in the header
3797  */
3798 dbus_bool_t
3799 dbus_message_has_member (DBusMessage   *message,
3800                          const char    *member)
3801 {
3802   const char *msg_member;
3803   msg_member = dbus_message_get_member (message);
3804
3805   if (msg_member == NULL)
3806     {
3807       if (member == NULL)
3808         return TRUE;
3809       else
3810         return FALSE;
3811     }
3812
3813   if (member == NULL)
3814     return FALSE;
3815
3816   if (strcmp (msg_member, member) == 0)
3817     return TRUE;
3818
3819   return FALSE;
3820
3821 }
3822
3823 /**
3824  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
3825  * The name is fully-qualified (namespaced).
3826  *
3827  * The error name must contain only valid characters as defined
3828  * in the D-Bus specification.
3829  *
3830  * @param message the message
3831  * @param error_name the name or #NULL to unset
3832  * @returns #FALSE if not enough memory
3833  */
3834 dbus_bool_t
3835 dbus_message_set_error_name (DBusMessage  *message,
3836                              const char   *error_name)
3837 {
3838   _dbus_return_val_if_fail (message != NULL, FALSE);
3839   _dbus_return_val_if_fail (!message->locked, FALSE);
3840   _dbus_return_val_if_fail (error_name == NULL ||
3841                             _dbus_check_is_valid_error_name (error_name),
3842                             FALSE);
3843
3844   return set_or_delete_string_field (message,
3845                                      DBUS_HEADER_FIELD_ERROR_NAME,
3846                                      DBUS_TYPE_STRING,
3847                                      error_name);
3848 }
3849
3850 /**
3851  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
3852  * or #NULL if none.
3853  *
3854  * The returned string becomes invalid if the message is
3855  * modified, since it points into the wire-marshaled message data.
3856  *
3857  * @param message the message
3858  * @returns the error name (should not be freed) or #NULL
3859  */
3860 const char*
3861 dbus_message_get_error_name (DBusMessage *message)
3862 {
3863   const char *v;
3864
3865   _dbus_return_val_if_fail (message != NULL, NULL);
3866
3867   v = NULL; /* in case field doesn't exist */
3868   _dbus_header_get_field_basic (&message->header,
3869                                 DBUS_HEADER_FIELD_ERROR_NAME,
3870                                 DBUS_TYPE_STRING,
3871                                 (void *) &v);
3872   return v;
3873 }
3874
3875 /**
3876  * Sets the message's destination. The destination is the name of
3877  * another connection on the bus and may be either the unique name
3878  * assigned by the bus to each connection, or a well-known name
3879  * specified in advance.
3880  *
3881  * The destination name must contain only valid characters as defined
3882  * in the D-Bus specification.
3883  *
3884  * @param message the message
3885  * @param destination the destination name or #NULL to unset
3886  * @returns #FALSE if not enough memory
3887  */
3888 dbus_bool_t
3889 dbus_message_set_destination (DBusMessage  *message,
3890                               const char   *destination)
3891 {
3892   _dbus_return_val_if_fail (message != NULL, FALSE);
3893   _dbus_return_val_if_fail (!message->locked, FALSE);
3894   _dbus_return_val_if_fail (destination == NULL ||
3895                             _dbus_check_is_valid_bus_name (destination),
3896                             FALSE);
3897
3898   return set_or_delete_string_field (message,
3899                                      DBUS_HEADER_FIELD_DESTINATION,
3900                                      DBUS_TYPE_STRING,
3901                                      destination);
3902 }
3903
3904 /**
3905  * Gets the destination of a message or #NULL if there is none set.
3906  *
3907  * The returned string becomes invalid if the message is
3908  * modified, since it points into the wire-marshaled message data.
3909  *
3910  * @param message the message
3911  * @returns the message destination (should not be freed) or #NULL
3912  */
3913 const char*
3914 dbus_message_get_destination (DBusMessage *message)
3915 {
3916   const char *v;
3917
3918   _dbus_return_val_if_fail (message != NULL, NULL);
3919
3920   v = NULL; /* in case field doesn't exist */
3921   _dbus_header_get_field_basic (&message->header,
3922                                 DBUS_HEADER_FIELD_DESTINATION,
3923                                 DBUS_TYPE_STRING,
3924                                 (void *) &v);
3925   return v;
3926 }
3927
3928 /**
3929  * Sets the message sender.
3930  *
3931  * The sender must be a valid bus name as defined in the D-Bus
3932  * specification.
3933  *
3934  * Usually you don't want to call this. The message bus daemon will
3935  * call it to set the origin of each message. If you aren't implementing
3936  * a message bus daemon you shouldn't need to set the sender.
3937  *
3938  * @param message the message
3939  * @param sender the sender or #NULL to unset
3940  * @returns #FALSE if not enough memory
3941  */
3942 dbus_bool_t
3943 dbus_message_set_sender (DBusMessage  *message,
3944                          const char   *sender)
3945 {
3946   _dbus_return_val_if_fail (message != NULL, FALSE);
3947   _dbus_return_val_if_fail (!message->locked, FALSE);
3948   _dbus_return_val_if_fail (sender == NULL ||
3949                             _dbus_check_is_valid_bus_name (sender),
3950                             FALSE);
3951
3952   return set_or_delete_string_field (message,
3953                                      DBUS_HEADER_FIELD_SENDER,
3954                                      DBUS_TYPE_STRING,
3955                                      sender);
3956 }
3957
3958 /**
3959  * Gets the unique name of the connection which originated this
3960  * message, or #NULL if unknown or inapplicable. The sender is filled
3961  * in by the message bus.
3962  *
3963  * Note, the returned sender is always the unique bus name.
3964  * Connections may own multiple other bus names, but those
3965  * are not found in the sender field.
3966  *
3967  * The returned string becomes invalid if the message is
3968  * modified, since it points into the wire-marshaled message data.
3969  *
3970  * @param message the message
3971  * @returns the unique name of the sender or #NULL
3972  */
3973 const char*
3974 dbus_message_get_sender (DBusMessage *message)
3975 {
3976   const char *v;
3977
3978   _dbus_return_val_if_fail (message != NULL, NULL);
3979
3980   if (NULL != message->unique_sender)
3981     return _dbus_string_get_const_data (message->unique_sender);
3982
3983   v = NULL; /* in case field doesn't exist */
3984   _dbus_header_get_field_basic (&message->header,
3985                                 DBUS_HEADER_FIELD_SENDER,
3986                                 DBUS_TYPE_STRING,
3987                                 (void *) &v);
3988   return v;
3989 }
3990
3991 /**
3992  * Gets the type signature of the message, i.e. the arguments in the
3993  * message payload. The signature includes only "in" arguments for
3994  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
3995  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
3996  * what you might expect (that is, it does not include the signature of the
3997  * entire C++-style method).
3998  *
3999  * The signature is a string made up of type codes such as
4000  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
4001  * the value of #DBUS_TYPE_INVALID).
4002  *
4003  * The returned string becomes invalid if the message is
4004  * modified, since it points into the wire-marshaled message data.
4005  *
4006  * @param message the message
4007  * @returns the type signature
4008  */
4009 const char*
4010 dbus_message_get_signature (DBusMessage *message)
4011 {
4012   const DBusString *type_str;
4013   int type_pos;
4014
4015   _dbus_return_val_if_fail (message != NULL, NULL);
4016
4017   get_const_signature (message, &type_str, &type_pos);
4018
4019   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
4020 }
4021
4022 static dbus_bool_t
4023 _dbus_message_has_type_interface_member (DBusMessage *message,
4024                                          int          type,
4025                                          const char  *iface,
4026                                          const char  *member)
4027 {
4028   const char *n;
4029
4030   _dbus_assert (message != NULL);
4031   _dbus_assert (iface != NULL);
4032   _dbus_assert (member != NULL);
4033
4034   if (dbus_message_get_type (message) != type)
4035     return FALSE;
4036
4037   /* Optimize by checking the short member name first
4038    * instead of the longer interface name
4039    */
4040
4041   n = dbus_message_get_member (message);
4042
4043   if (n && strcmp (n, member) == 0)
4044     {
4045       n = dbus_message_get_interface (message);
4046
4047       if (n == NULL || strcmp (n, iface) == 0)
4048         return TRUE;
4049     }
4050
4051   return FALSE;
4052 }
4053
4054 /**
4055  * Checks whether the message is a method call with the given
4056  * interface and member fields.  If the message is not
4057  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
4058  * member field, returns #FALSE. If the interface field is missing,
4059  * then it will be assumed equal to the provided interface.  The D-Bus
4060  * protocol allows method callers to leave out the interface name.
4061  *
4062  * @param message the message
4063  * @param iface the name to check (must not be #NULL)
4064  * @param method the name to check (must not be #NULL)
4065  *
4066  * @returns #TRUE if the message is the specified method call
4067  */
4068 dbus_bool_t
4069 dbus_message_is_method_call (DBusMessage *message,
4070                              const char  *iface,
4071                              const char  *method)
4072 {
4073   _dbus_return_val_if_fail (message != NULL, FALSE);
4074   _dbus_return_val_if_fail (iface != NULL, FALSE);
4075   _dbus_return_val_if_fail (method != NULL, FALSE);
4076   /* don't check that interface/method are valid since it would be
4077    * expensive, and not catch many common errors
4078    */
4079
4080   return _dbus_message_has_type_interface_member (message,
4081                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
4082                                                   iface, method);
4083 }
4084
4085 /**
4086  * Checks whether the message is a signal with the given interface and
4087  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
4088  * has a different interface or member field, returns #FALSE.
4089  *
4090  * @param message the message
4091  * @param iface the name to check (must not be #NULL)
4092  * @param signal_name the name to check (must not be #NULL)
4093  *
4094  * @returns #TRUE if the message is the specified signal
4095  */
4096 dbus_bool_t
4097 dbus_message_is_signal (DBusMessage *message,
4098                         const char  *iface,
4099                         const char  *signal_name)
4100 {
4101   _dbus_return_val_if_fail (message != NULL, FALSE);
4102   _dbus_return_val_if_fail (iface != NULL, FALSE);
4103   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
4104   /* don't check that interface/name are valid since it would be
4105    * expensive, and not catch many common errors
4106    */
4107
4108   return _dbus_message_has_type_interface_member (message,
4109                                                   DBUS_MESSAGE_TYPE_SIGNAL,
4110                                                   iface, signal_name);
4111 }
4112
4113 /**
4114  * Checks whether the message is an error reply with the given error
4115  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
4116  * different name, returns #FALSE.
4117  *
4118  * @param message the message
4119  * @param error_name the name to check (must not be #NULL)
4120  *
4121  * @returns #TRUE if the message is the specified error
4122  */
4123 dbus_bool_t
4124 dbus_message_is_error (DBusMessage *message,
4125                        const char  *error_name)
4126 {
4127   const char *n;
4128
4129   _dbus_return_val_if_fail (message != NULL, FALSE);
4130   _dbus_return_val_if_fail (error_name != NULL, FALSE);
4131   /* don't check that error_name is valid since it would be expensive,
4132    * and not catch many common errors
4133    */
4134
4135   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
4136     return FALSE;
4137
4138   n = dbus_message_get_error_name (message);
4139
4140   if (n && strcmp (n, error_name) == 0)
4141     return TRUE;
4142   else
4143     return FALSE;
4144 }
4145
4146 /**
4147  * Checks whether the message was sent to the given name.  If the
4148  * message has no destination specified or has a different
4149  * destination, returns #FALSE.
4150  *
4151  * @param message the message
4152  * @param name the name to check (must not be #NULL)
4153  *
4154  * @returns #TRUE if the message has the given destination name
4155  */
4156 dbus_bool_t
4157 dbus_message_has_destination (DBusMessage  *message,
4158                               const char   *name)
4159 {
4160   const char *s;
4161
4162   _dbus_return_val_if_fail (message != NULL, FALSE);
4163   _dbus_return_val_if_fail (name != NULL, FALSE);
4164   /* don't check that name is valid since it would be expensive, and
4165    * not catch many common errors
4166    */
4167
4168   s = dbus_message_get_destination (message);
4169
4170   if (s && strcmp (s, name) == 0)
4171     return TRUE;
4172   else
4173     return FALSE;
4174 }
4175
4176 /**
4177  * Checks whether the message has the given unique name as its sender.
4178  * If the message has no sender specified or has a different sender,
4179  * returns #FALSE. Note that a peer application will always have the
4180  * unique name of the connection as the sender. So you can't use this
4181  * function to see whether a sender owned a well-known name.
4182  *
4183  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
4184  * as the sender.
4185  *
4186  * @param message the message
4187  * @param name the name to check (must not be #NULL)
4188  *
4189  * @returns #TRUE if the message has the given sender
4190  */
4191 dbus_bool_t
4192 dbus_message_has_sender (DBusMessage  *message,
4193                          const char   *name)
4194 {
4195   const char *s;
4196
4197   _dbus_return_val_if_fail (message != NULL, FALSE);
4198   _dbus_return_val_if_fail (name != NULL, FALSE);
4199   /* don't check that name is valid since it would be expensive, and
4200    * not catch many common errors
4201    */
4202
4203   s = dbus_message_get_sender (message);
4204
4205   if (s && strcmp (s, name) == 0)
4206     return TRUE;
4207   else
4208     return FALSE;
4209 }
4210
4211 /**
4212  * Checks whether the message has the given signature; see
4213  * dbus_message_get_signature() for more details on what the signature
4214  * looks like.
4215  *
4216  * @param message the message
4217  * @param signature typecode array
4218  * @returns #TRUE if message has the given signature
4219 */
4220 dbus_bool_t
4221 dbus_message_has_signature (DBusMessage   *message,
4222                             const char    *signature)
4223 {
4224   const char *s;
4225
4226   _dbus_return_val_if_fail (message != NULL, FALSE);
4227   _dbus_return_val_if_fail (signature != NULL, FALSE);
4228   /* don't check that signature is valid since it would be expensive,
4229    * and not catch many common errors
4230    */
4231
4232   s = dbus_message_get_signature (message);
4233
4234   if (s && strcmp (s, signature) == 0)
4235     return TRUE;
4236   else
4237     return FALSE;
4238 }
4239
4240 /**
4241  * Sets a #DBusError based on the contents of the given
4242  * message. The error is only set if the message
4243  * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
4244  * The name of the error is set to the name of the message,
4245  * and the error message is set to the first argument
4246  * if the argument exists and is a string.
4247  *
4248  * The return value indicates whether the error was set (the error is
4249  * set if and only if the message is an error message).  So you can
4250  * check for an error reply and convert it to DBusError in one go:
4251  * @code
4252  *  if (dbus_set_error_from_message (error, reply))
4253  *    return error;
4254  *  else
4255  *    process reply;
4256  * @endcode
4257  *
4258  * @param error the error to set
4259  * @param message the message to set it from
4260  * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
4261  */
4262 dbus_bool_t
4263 dbus_set_error_from_message (DBusError   *error,
4264                              DBusMessage *message)
4265 {
4266   const char *str;
4267
4268   _dbus_return_val_if_fail (message != NULL, FALSE);
4269   _dbus_return_val_if_error_is_set (error, FALSE);
4270
4271   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
4272     return FALSE;
4273
4274   str = NULL;
4275   dbus_message_get_args (message, NULL,
4276                          DBUS_TYPE_STRING, &str,
4277                          DBUS_TYPE_INVALID);
4278
4279   dbus_set_error (error, dbus_message_get_error_name (message),
4280                   str ? "%s" : NULL, str);
4281
4282   return TRUE;
4283 }
4284
4285 /**
4286  * Checks whether a message contains unix fds
4287  *
4288  * @param message the message
4289  * @returns #TRUE if the message contains unix fds
4290  */
4291 dbus_bool_t
4292 dbus_message_contains_unix_fds(DBusMessage *message)
4293 {
4294 #ifdef HAVE_UNIX_FD_PASSING
4295   _dbus_assert(message);
4296
4297   return message->n_unix_fds > 0;
4298 #else
4299   return FALSE;
4300 #endif
4301 }
4302
4303 /** @} */
4304
4305 /**
4306  * @addtogroup DBusMessageInternals
4307  *
4308  * @{
4309  */
4310
4311 /**
4312  * The initial buffer size of the message loader.
4313  *
4314  * @todo this should be based on min header size plus some average
4315  * body size, or something. Or rather, the min header size only, if we
4316  * want to try to read only the header, store that in a DBusMessage,
4317  * then read only the body and store that, etc., depends on
4318  * how we optimize _dbus_message_loader_get_buffer() and what
4319  * the exact message format is.
4320  */
4321 #define INITIAL_LOADER_DATA_LEN 32
4322
4323 /**
4324  * Creates a new message loader. Returns #NULL if memory can't
4325  * be allocated.
4326  *
4327  * @returns new loader, or #NULL.
4328  */
4329 DBusMessageLoader*
4330 _dbus_message_loader_new (void)
4331 {
4332   DBusMessageLoader *loader;
4333
4334   loader = dbus_new0 (DBusMessageLoader, 1);
4335   if (loader == NULL)
4336     return NULL;
4337
4338   loader->refcount = 1;
4339
4340   loader->corrupted = FALSE;
4341   loader->corruption_reason = DBUS_VALID;
4342
4343   /* this can be configured by the app, but defaults to the protocol max */
4344   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
4345
4346   /* We set a very relatively conservative default here since due to how
4347   SCM_RIGHTS works we need to preallocate an fd array of the maximum
4348   number of unix fds we want to receive in advance. A
4349   try-and-reallocate loop is not possible. */
4350   loader->max_message_unix_fds = DBUS_DEFAULT_MESSAGE_UNIX_FDS;
4351
4352   if (!_dbus_string_init (&loader->data))
4353     {
4354       dbus_free (loader);
4355       return NULL;
4356     }
4357
4358   /* preallocate the buffer for speed, ignore failure */
4359   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
4360   _dbus_string_set_length (&loader->data, 0);
4361
4362 #ifdef HAVE_UNIX_FD_PASSING
4363   loader->unix_fds = NULL;
4364   loader->n_unix_fds = loader->n_unix_fds_allocated = 0;
4365   loader->unix_fds_outstanding = FALSE;
4366 #endif
4367
4368   return loader;
4369 }
4370
4371 /**
4372  * Increments the reference count of the loader.
4373  *
4374  * @param loader the loader.
4375  * @returns the loader
4376  */
4377 DBusMessageLoader *
4378 _dbus_message_loader_ref (DBusMessageLoader *loader)
4379 {
4380   loader->refcount += 1;
4381
4382   return loader;
4383 }
4384
4385 /**
4386  * Decrements the reference count of the loader and finalizes the
4387  * loader when the count reaches zero.
4388  *
4389  * @param loader the loader.
4390  */
4391 void
4392 _dbus_message_loader_unref (DBusMessageLoader *loader)
4393 {
4394   loader->refcount -= 1;
4395   if (loader->refcount == 0)
4396     {
4397 #ifdef HAVE_UNIX_FD_PASSING
4398       close_unix_fds(loader->unix_fds, &loader->n_unix_fds);
4399       dbus_free(loader->unix_fds);
4400 #endif
4401       _dbus_list_foreach (&loader->messages,
4402                           (DBusForeachFunction) dbus_message_unref,
4403                           NULL);
4404       _dbus_list_clear (&loader->messages);
4405       _dbus_string_free (&loader->data);
4406       dbus_free (loader);
4407     }
4408 }
4409
4410 /**
4411  * Gets the buffer to use for reading data from the network.  Network
4412  * data is read directly into an allocated buffer, which is then used
4413  * in the DBusMessage, to avoid as many extra memcpy's as possible.
4414  * The buffer must always be returned immediately using
4415  * _dbus_message_loader_return_buffer(), even if no bytes are
4416  * successfully read.
4417  *
4418  * @todo this function can be a lot more clever. For example
4419  * it can probably always return a buffer size to read exactly
4420  * the body of the next message, thus avoiding any memory wastage
4421  * or reallocs.
4422  *
4423  * @todo we need to enforce a max length on strings in header fields.
4424  *
4425  * @param loader the message loader.
4426  * @param buffer the buffer
4427  */
4428 void
4429 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
4430                                  DBusString        **buffer,
4431                                  int                *max_to_read,
4432                                  dbus_bool_t        *may_read_fds)
4433 {
4434   _dbus_assert (!loader->buffer_outstanding);
4435
4436   *buffer = &loader->data;
4437
4438   loader->buffer_outstanding = TRUE;
4439
4440   if (max_to_read != NULL)
4441     {
4442 #ifdef HAVE_UNIX_FD_PASSING
4443       int offset = 0;
4444       int remain;
4445       int byte_order;
4446       int fields_array_len;
4447       int header_len;
4448       int body_len;
4449 #endif
4450
4451       *max_to_read = DBUS_MAXIMUM_MESSAGE_LENGTH;
4452       *may_read_fds = TRUE;
4453
4454 #ifdef HAVE_UNIX_FD_PASSING
4455       /* If we aren't holding onto any fds, we can read as much as we want
4456        * (fast path). */
4457       if (loader->n_unix_fds == 0)
4458         return;
4459
4460       /* Slow path: we have a message with some fds in it. We don't want
4461        * to start on the next message until this one is out of the way;
4462        * otherwise a legitimate sender can keep us processing messages
4463        * containing fds, until we disconnect it for having had fds pending
4464        * for too long, a limit that is in place to stop malicious senders
4465        * from setting up recursive fd-passing that takes up our quota and
4466        * will never go away. */
4467
4468       remain = _dbus_string_get_length (&loader->data);
4469
4470       while (remain > 0)
4471         {
4472           DBusValidity validity = DBUS_VALIDITY_UNKNOWN;
4473           int needed;
4474           dbus_bool_t is_gvariant;
4475
4476           /* If 0 < remain < DBUS_MINIMUM_HEADER_SIZE, then we've had at
4477            * least the first byte of a message, but we don't know how
4478            * much more to read. Only read the rest of the
4479            * DBUS_MINIMUM_HEADER_SIZE for now; then we'll know. */
4480           if (remain < DBUS_MINIMUM_HEADER_SIZE)
4481             {
4482               *max_to_read = DBUS_MINIMUM_HEADER_SIZE - remain;
4483               *may_read_fds = FALSE;
4484               return;
4485             }
4486
4487           if (!_dbus_header_have_message_untrusted (loader->max_message_size,
4488                                                     &validity,
4489                                                     &byte_order,
4490                                                     &fields_array_len,
4491                                                     &header_len,
4492                                                     &body_len,
4493                                                     &loader->data,
4494                                                     offset,
4495                                                     remain,
4496                                                     &is_gvariant))
4497             {
4498               /* If a message in the buffer is invalid, we're going to
4499                * disconnect the sender anyway, so reading an arbitrary amount
4500                * is fine. */
4501               if (validity != DBUS_VALID)
4502                 return;
4503
4504               /* We have a partial message, with the
4505                * DBUS_MINIMUM_HEADER_SIZE-byte fixed part of the header (which
4506                * lets us work out how much more we need), but no more. Read
4507                * the rest of the message. */
4508               needed = header_len + body_len;
4509               _dbus_assert (needed > remain);
4510               *max_to_read = needed - remain;
4511               *may_read_fds = FALSE;
4512               return;
4513             }
4514
4515           /* Skip over entire messages until we have less than a message
4516            * remaining. */
4517           needed = header_len + body_len;
4518           _dbus_assert (needed > DBUS_MINIMUM_HEADER_SIZE);
4519           _dbus_assert (remain >= needed);
4520           remain -= needed;
4521           offset += needed;
4522         }
4523 #endif
4524     }
4525 }
4526
4527 /**
4528  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
4529  * indicating to the loader how many bytes of the buffer were filled
4530  * in. This function must always be called, even if no bytes were
4531  * successfully read.
4532  *
4533  * @param loader the loader.
4534  * @param buffer the buffer.
4535  */
4536 void
4537 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
4538                                     DBusString         *buffer)
4539 {
4540   _dbus_assert (loader->buffer_outstanding);
4541   _dbus_assert (buffer == &loader->data);
4542
4543   loader->buffer_outstanding = FALSE;
4544 }
4545
4546 #ifdef HAVE_UNIX_FD_PASSING
4547 /**
4548  * Gets the buffer to use for reading unix fds from the network.
4549  *
4550  * This works similar to _dbus_message_loader_get_buffer()
4551  *
4552  * @param loader the message loader.
4553  * @param fds the array to read fds into
4554  * @param max_n_fds how many fds to read at most
4555  * @return TRUE on success, FALSE on OOM
4556  */
4557 dbus_bool_t
4558 _dbus_message_loader_get_unix_fds(DBusMessageLoader  *loader,
4559                                   int               **fds,
4560                                   unsigned           *max_n_fds)
4561 {
4562   _dbus_assert (!loader->unix_fds_outstanding);
4563
4564   /* Allocate space where we can put the fds we read. We allocate
4565      space for max_message_unix_fds since this is an
4566      upper limit how many fds can be received within a single
4567      message. Since SCM_RIGHTS doesn't allow a reallocate+retry logic
4568      we are allocating the maximum possible array size right from the
4569      beginning. This sucks a bit, however unless SCM_RIGHTS is fixed
4570      there is no better way. */
4571
4572   if (loader->n_unix_fds_allocated < loader->max_message_unix_fds)
4573     {
4574       int *a = dbus_realloc(loader->unix_fds,
4575                             loader->max_message_unix_fds * sizeof(loader->unix_fds[0]));
4576
4577       if (!a)
4578         return FALSE;
4579
4580       loader->unix_fds = a;
4581       loader->n_unix_fds_allocated = loader->max_message_unix_fds;
4582     }
4583
4584   *fds = loader->unix_fds + loader->n_unix_fds;
4585   *max_n_fds = loader->n_unix_fds_allocated - loader->n_unix_fds;
4586
4587   loader->unix_fds_outstanding = TRUE;
4588   return TRUE;
4589 }
4590
4591 /**
4592  * Returns a buffer obtained from _dbus_message_loader_get_unix_fds().
4593  *
4594  * This works similar to _dbus_message_loader_return_buffer()
4595  *
4596  * @param loader the message loader.
4597  * @param fds the array fds were read into
4598  * @param n_fds how many fds were read
4599  */
4600
4601 void
4602 _dbus_message_loader_return_unix_fds(DBusMessageLoader  *loader,
4603                                      int                *fds,
4604                                      unsigned            n_fds)
4605 {
4606   _dbus_assert(loader->unix_fds_outstanding);
4607   _dbus_assert(loader->unix_fds + loader->n_unix_fds == fds);
4608   _dbus_assert(loader->n_unix_fds + n_fds <= loader->n_unix_fds_allocated);
4609
4610   loader->n_unix_fds += n_fds;
4611   loader->unix_fds_outstanding = FALSE;
4612
4613   if (n_fds && loader->unix_fds_change)
4614     loader->unix_fds_change (loader->unix_fds_change_data);
4615 }
4616 #endif
4617
4618 /*
4619  * FIXME when we move the header out of the buffer, that memmoves all
4620  * buffered messages. Kind of crappy.
4621  *
4622  * Also we copy the header and body, which is kind of crappy.  To
4623  * avoid this, we have to allow header and body to be in a single
4624  * memory block, which is good for messages we read and bad for
4625  * messages we are creating. But we could move_len() the buffer into
4626  * this single memory block, and move_len() will just swap the buffers
4627  * if you're moving the entire buffer replacing the dest string.
4628  *
4629  * We could also have the message loader tell the transport how many
4630  * bytes to read; so it would first ask for some arbitrary number like
4631  * 256, then if the message was incomplete it would use the
4632  * header/body len to ask for exactly the size of the message (or
4633  * blocks the size of a typical kernel buffer for the socket). That
4634  * way we don't get trailing bytes in the buffer that have to be
4635  * memmoved. Though I suppose we also don't have a chance of reading a
4636  * bunch of small messages at once, so the optimization may be stupid.
4637  *
4638  * Another approach would be to keep a "start" index into
4639  * loader->data and only delete it occasionally, instead of after
4640  * each message is loaded.
4641  *
4642  * load_message() returns FALSE if not enough memory OR the loader was corrupted
4643  */
4644 static dbus_bool_t
4645 load_message (DBusMessageLoader *loader,
4646               DBusMessage       *message,
4647               int                byte_order,
4648               int                fields_array_len,
4649               int                header_len,
4650               int                body_len)
4651 {
4652   dbus_bool_t oom;
4653   DBusValidity validity;
4654   const DBusString *type_str;
4655   int type_pos;
4656   DBusValidationMode mode;
4657   dbus_uint32_t n_unix_fds = 0;
4658
4659   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
4660
4661   oom = FALSE;
4662
4663 #if 0
4664   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
4665 #endif
4666
4667   /* 1. VALIDATE AND COPY OVER HEADER */
4668   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
4669   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
4670
4671   if (!_dbus_header_load (&message->header,
4672                           mode,
4673                           &validity,
4674                           byte_order,
4675                           fields_array_len,
4676                           header_len,
4677                           body_len,
4678                           &loader->data, 0,
4679                           _dbus_string_get_length (&loader->data)))
4680     {
4681       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
4682
4683       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
4684          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
4685       _dbus_assert (validity != DBUS_VALID);
4686
4687       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
4688         oom = TRUE;
4689       else
4690         {
4691           loader->corrupted = TRUE;
4692           loader->corruption_reason = validity;
4693         }
4694       goto failed;
4695     }
4696
4697   _dbus_assert (validity == DBUS_VALID);
4698
4699   /* 2. VALIDATE BODY */
4700   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
4701     {
4702       if (_dbus_message_is_gvariant (message))
4703         {
4704           type_str = NULL;
4705           type_pos = 0;
4706           validity = _dbus_validate_gvariant_body_with_reason (type_str,
4707                                                                type_pos,
4708                                                                byte_order,
4709                                                                NULL,
4710                                                                &loader->data,
4711                                                                header_len,
4712                                                                body_len);
4713         }
4714       else
4715         {
4716
4717           get_const_signature (message, &type_str, &type_pos);
4718
4719           /* Because the bytes_remaining arg is NULL, this validates that the
4720            * body is the right length
4721            */
4722
4723           validity = _dbus_validate_body_with_reason (type_str,
4724                                                       type_pos,
4725                                                       byte_order,
4726                                                       NULL,
4727                                                       &loader->data,
4728                                                       header_len,
4729                                                       body_len);
4730         }
4731       if (validity != DBUS_VALID)
4732         {
4733           _dbus_verbose ("Failed to validate message body code %d\n", validity);
4734
4735           loader->corrupted = TRUE;
4736           loader->corruption_reason = validity;
4737
4738           goto failed;
4739         }
4740     }
4741
4742   /* 3. COPY OVER UNIX FDS */
4743   _dbus_header_get_field_basic(&message->header,
4744                                DBUS_HEADER_FIELD_UNIX_FDS,
4745                                DBUS_TYPE_UINT32,
4746                                &n_unix_fds);
4747
4748 #ifdef HAVE_UNIX_FD_PASSING
4749
4750   if (n_unix_fds > loader->n_unix_fds)
4751     {
4752       _dbus_verbose("Message contains references to more unix fds than were sent %u != %u\n",
4753                     n_unix_fds, loader->n_unix_fds);
4754
4755       loader->corrupted = TRUE;
4756       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
4757       goto failed;
4758     }
4759
4760   /* If this was a recycled message there might still be
4761      some memory allocated for the fds */
4762   dbus_free(message->unix_fds);
4763
4764   if (n_unix_fds > 0)
4765     {
4766       message->unix_fds = _dbus_memdup(loader->unix_fds, n_unix_fds * sizeof(message->unix_fds[0]));
4767       if (message->unix_fds == NULL)
4768         {
4769           _dbus_verbose ("Failed to allocate file descriptor array\n");
4770           oom = TRUE;
4771           goto failed;
4772         }
4773
4774       message->n_unix_fds_allocated = message->n_unix_fds = n_unix_fds;
4775       loader->n_unix_fds -= n_unix_fds;
4776       memmove (loader->unix_fds, loader->unix_fds + n_unix_fds, loader->n_unix_fds * sizeof (loader->unix_fds[0]));
4777
4778       if (loader->unix_fds_change)
4779         loader->unix_fds_change (loader->unix_fds_change_data);
4780     }
4781   else
4782     message->unix_fds = NULL;
4783
4784 #else
4785
4786   if (n_unix_fds > 0)
4787     {
4788       _dbus_verbose ("Hmm, message claims to come with file descriptors "
4789                      "but that's not supported on our platform, disconnecting.\n");
4790
4791       loader->corrupted = TRUE;
4792       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
4793       goto failed;
4794     }
4795
4796 #endif
4797
4798   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
4799
4800   if (!_dbus_list_append (&loader->messages, message))
4801     {
4802       _dbus_verbose ("Failed to append new message to loader queue\n");
4803       oom = TRUE;
4804       goto failed;
4805     }
4806
4807   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
4808   _dbus_assert (_dbus_string_get_length (&loader->data) >=
4809                 (header_len + body_len));
4810
4811   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
4812     {
4813       _dbus_verbose ("Failed to move body into new message\n");
4814       oom = TRUE;
4815       goto failed;
4816     }
4817
4818   _dbus_string_delete (&loader->data, 0, header_len + body_len);
4819
4820   /* don't waste more than 2k of memory */
4821   _dbus_string_compact (&loader->data, 2048);
4822
4823   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
4824   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
4825
4826   _dbus_verbose ("Loaded message %p\n", message);
4827
4828   _dbus_assert (!oom);
4829   _dbus_assert (!loader->corrupted);
4830   _dbus_assert (loader->messages != NULL);
4831   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4832
4833   return TRUE;
4834
4835  failed:
4836
4837   /* Clean up */
4838
4839   /* does nothing if the message isn't in the list */
4840   _dbus_list_remove_last (&loader->messages, message);
4841
4842   if (oom)
4843     _dbus_assert (!loader->corrupted);
4844   else
4845     _dbus_assert (loader->corrupted);
4846
4847   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
4848
4849   return FALSE;
4850 }
4851
4852 static dbus_bool_t
4853 set_unique_sender (DBusMessage *message, uint64_t unique_sender_id)
4854 {
4855   if (NULL == message->unique_sender)
4856     {
4857       message->unique_sender = dbus_new (DBusString, 1);
4858       if (NULL == message->unique_sender)
4859         return FALSE;
4860
4861       if (!_dbus_string_init (message->unique_sender))
4862         return FALSE;
4863     }
4864
4865   _dbus_string_set_length (message->unique_sender, 0);
4866
4867   if (!_dbus_string_append_printf (message->unique_sender, ":1.%llu", (unsigned long long)unique_sender_id))
4868     {
4869       _dbus_string_free (message->unique_sender);
4870       dbus_free (message->unique_sender);
4871       message->unique_sender = NULL;
4872       return FALSE;
4873     }
4874
4875   return TRUE;
4876 }
4877
4878 /**
4879  * Converts buffered data into messages, if we have enough data.  If
4880  * we don't have enough data, does nothing.
4881  *
4882  * @todo we need to check that the proper named header fields exist
4883  * for each message type.
4884  *
4885  * @todo If a message has unknown type, we should probably eat it
4886  * right here rather than passing it out to applications.  However
4887  * it's not an error to see messages of unknown type.
4888  *
4889  * @param loader the loader.
4890  * @returns #TRUE if we had enough memory to finish.
4891  */
4892 dbus_bool_t
4893 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
4894 {
4895   while (!loader->corrupted &&
4896          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
4897     {
4898       DBusValidity validity;
4899       int byte_order, fields_array_len, header_len, body_len;
4900       dbus_bool_t is_gvariant;
4901
4902       if (_dbus_header_have_message_untrusted (loader->max_message_size,
4903                                                &validity,
4904                                                &byte_order,
4905                                                &fields_array_len,
4906                                                &header_len,
4907                                                &body_len,
4908                                                &loader->data, 0,
4909                                                _dbus_string_get_length (&loader->data),
4910                                                &is_gvariant))
4911         {
4912           DBusMessage *message;
4913
4914           _dbus_assert (validity == DBUS_VALID);
4915
4916           message = dbus_message_new_empty_header (is_gvariant);
4917           if (message == NULL)
4918             return FALSE;
4919
4920           if (!load_message (loader, message,
4921                              byte_order, fields_array_len,
4922                              header_len, body_len))
4923             {
4924               dbus_message_unref (message);
4925               /* load_message() returns false if corrupted or OOM; if
4926                * corrupted then return TRUE for not OOM
4927                */
4928               return loader->corrupted;
4929             }
4930
4931           if (_dbus_message_is_gvariant (message))
4932             {
4933               set_unique_sender (message, _dbus_message_loader_get_unique_sender_id (loader));
4934               message->locked = TRUE;
4935             }
4936
4937           _dbus_assert (loader->messages != NULL);
4938           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4939         }
4940       else
4941         {
4942           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
4943                          validity);
4944           if (validity != DBUS_VALID)
4945             {
4946               loader->corrupted = TRUE;
4947               loader->corruption_reason = validity;
4948             }
4949           return TRUE;
4950         }
4951     }
4952
4953   return TRUE;
4954 }
4955
4956 DBusMessage *
4957 _dbus_decode_kmsg (DBusString  *data,
4958                    uint64_t     sender_id,
4959                    int         *fds,
4960                    unsigned     n_fds)
4961 {
4962   if (_dbus_string_get_length (data) >= DBUS_MINIMUM_HEADER_SIZE)
4963     {
4964
4965       DBusValidity validity;
4966       int byte_order, fields_array_len, header_len, body_len;
4967       dbus_bool_t is_gvariant;
4968
4969       if (_dbus_header_have_message_untrusted (DBUS_MAXIMUM_MESSAGE_LENGTH,
4970                                                &validity,
4971                                                &byte_order,
4972                                                &fields_array_len,
4973                                                &header_len,
4974                                                &body_len,
4975                                                data, 0,
4976                                                _dbus_string_get_length (data),
4977                                                &is_gvariant))
4978         {
4979           DBusMessage *message;
4980           dbus_uint32_t n_unix_fds = 0;
4981           const DBusString *type_str = NULL;
4982           int type_pos = 0;
4983
4984           _dbus_assert (validity == DBUS_VALID);
4985
4986           message = dbus_message_new_empty_header (is_gvariant);
4987           if (message == NULL)
4988             return NULL;
4989
4990           /*
4991            * Validate and copy over header
4992            */
4993           _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
4994           _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (data));
4995
4996           if (!_dbus_header_load (&message->header,
4997                                   DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED,
4998                                   &validity,
4999                                   byte_order,
5000                                   fields_array_len,
5001                                   header_len,
5002                                   body_len,
5003                                   data, 0,
5004                                   _dbus_string_get_length (data)))
5005             {
5006               _dbus_verbose ("Failed to load header for new message code %d\n", validity);
5007               dbus_message_unref (message);
5008               return NULL;
5009             }
5010
5011           _dbus_assert (validity == DBUS_VALID);
5012
5013           /*
5014            * Validate body
5015            */
5016           if (_dbus_message_is_gvariant (message))
5017             {
5018               validity = _dbus_validate_gvariant_body_with_reason (type_str,
5019                                                                    type_pos,
5020                                                                    byte_order,
5021                                                                    NULL,
5022                                                                    data,
5023                                                                    header_len,
5024                                                                    body_len);
5025             }
5026           else
5027             {
5028               _dbus_verbose ("Not valid GVariant dbus message\n");
5029               dbus_message_unref (message);
5030               return NULL;
5031             }
5032
5033           if (validity != DBUS_VALID)
5034             {
5035               _dbus_verbose ("Failed to validate message body code %d\n", validity);
5036               dbus_message_unref (message);
5037               return NULL;
5038             }
5039
5040           /*
5041            * Copy over Unix FDS
5042            */
5043           _dbus_header_get_field_basic(&message->header,
5044                                        DBUS_HEADER_FIELD_UNIX_FDS,
5045                                        DBUS_TYPE_UINT32,
5046                                        &n_unix_fds);
5047
5048 #ifdef HAVE_UNIX_FD_PASSING
5049
5050           if (n_unix_fds > n_fds)
5051             {
5052               _dbus_verbose("Message contains references to more unix fds than were sent %u != %u\n",
5053                             n_unix_fds, message->n_unix_fds);
5054               dbus_message_unref (message);
5055               return NULL;
5056             }
5057
5058           /* If this was a recycled message there might still be
5059              some memory allocated for the fds */
5060           dbus_free(message->unix_fds);
5061
5062           if (n_unix_fds > 0)
5063             {
5064               message->unix_fds = _dbus_memdup(fds, n_unix_fds * sizeof(message->unix_fds[0]));
5065               if (message->unix_fds == NULL)
5066                 {
5067                   _dbus_verbose ("Failed to allocate file descriptor array\n");
5068                   dbus_message_unref (message);
5069                   return NULL;
5070                 }
5071
5072               message->n_unix_fds_allocated = message->n_unix_fds = n_unix_fds;
5073             }
5074           else
5075             message->unix_fds = NULL;
5076 #else
5077           if (n_unix_fds > 0)
5078             {
5079               _dbus_verbose ("Hmm, message claims to come with file descriptors "
5080                              "but that's not supported on our platform, disconnecting.\n");
5081               dbus_message_unref (message);
5082               return NULL;
5083             }
5084 #endif
5085
5086           /*
5087            * Copy over message body
5088            */
5089           _dbus_assert (_dbus_string_get_length (&message->body) == 0);
5090           _dbus_assert (_dbus_string_get_length (data) >= (header_len + body_len));
5091
5092           if (!_dbus_string_copy_len (data, header_len, body_len, &message->body, 0))
5093             {
5094               _dbus_verbose ("Failed to move body into new message\n");
5095               dbus_message_unref (message);
5096               return NULL;
5097             }
5098
5099           _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
5100           _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
5101
5102            set_unique_sender (message, sender_id);
5103            message->locked = TRUE;
5104
5105            /* Yupi, we have DBusMessage* */
5106            return message;
5107         }
5108       else
5109         {
5110           _dbus_verbose ("Data broken with invalid code %d\n", validity);
5111           return NULL;
5112         } /* if _dbus_header_have_message_untrusted() */
5113
5114     }
5115   else
5116     {
5117       _dbus_verbose ("message size < DBUS_MINIMUM_HEADER_SIZE\n");
5118       return NULL;
5119     } /* if DBUS_MINIMUM_HEADER_SIZE */
5120 }
5121
5122 /**
5123  * Peeks at first loaded message, returns #NULL if no messages have
5124  * been queued.
5125  *
5126  * @param loader the loader.
5127  * @returns the next message, or #NULL if none.
5128  */
5129 DBusMessage*
5130 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
5131 {
5132   if (loader->messages)
5133     return loader->messages->data;
5134   else
5135     return NULL;
5136 }
5137
5138 /**
5139  * Pops a loaded message (passing ownership of the message
5140  * to the caller). Returns #NULL if no messages have been
5141  * queued.
5142  *
5143  * @param loader the loader.
5144  * @returns the next message, or #NULL if none.
5145  */
5146 DBusMessage*
5147 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
5148 {
5149   return _dbus_list_pop_first (&loader->messages);
5150 }
5151
5152 /**
5153  * Pops a loaded message inside a list link (passing ownership of the
5154  * message and link to the caller). Returns #NULL if no messages have
5155  * been loaded.
5156  *
5157  * @param loader the loader.
5158  * @returns the next message link, or #NULL if none.
5159  */
5160 DBusList*
5161 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
5162 {
5163   return _dbus_list_pop_first_link (&loader->messages);
5164 }
5165
5166 /**
5167  * Returns a popped message link, used to undo a pop.
5168  *
5169  * @param loader the loader
5170  * @param link the link with a message in it
5171  */
5172 void
5173 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
5174                                            DBusList           *link)
5175 {
5176   _dbus_list_prepend_link (&loader->messages, link);
5177 }
5178
5179 /**
5180  * Checks whether the loader is confused due to bad data.
5181  * If messages are received that are invalid, the
5182  * loader gets confused and gives up permanently.
5183  * This state is called "corrupted."
5184  *
5185  * @param loader the loader
5186  * @returns #TRUE if the loader is hosed.
5187  */
5188 dbus_bool_t
5189 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
5190 {
5191   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
5192                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
5193   return loader->corrupted;
5194 }
5195
5196 /**
5197  * Checks what kind of bad data confused the loader.
5198  *
5199  * @param loader the loader
5200  * @returns why the loader is hosed, or DBUS_VALID if it isn't.
5201  */
5202 DBusValidity
5203 _dbus_message_loader_get_corruption_reason (DBusMessageLoader *loader)
5204 {
5205   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
5206                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
5207
5208   return loader->corruption_reason;
5209 }
5210
5211 /**
5212  * Sets the maximum size message we allow.
5213  *
5214  * @param loader the loader
5215  * @param size the max message size in bytes
5216  */
5217 void
5218 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
5219                                            long                size)
5220 {
5221   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
5222     {
5223       _dbus_verbose ("clamping requested max message size %ld to %d\n",
5224                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
5225       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
5226     }
5227   loader->max_message_size = size;
5228 }
5229
5230 /**
5231  * Gets the maximum allowed message size in bytes.
5232  *
5233  * @param loader the loader
5234  * @returns max size in bytes
5235  */
5236 long
5237 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
5238 {
5239   return loader->max_message_size;
5240 }
5241
5242 /**
5243  * Sets the maximum unix fds per message we allow.
5244  *
5245  * @param loader the loader
5246  * @param n the max number of unix fds in a message
5247  */
5248 void
5249 _dbus_message_loader_set_max_message_unix_fds (DBusMessageLoader  *loader,
5250                                                long                n)
5251 {
5252   if (n > DBUS_MAXIMUM_MESSAGE_UNIX_FDS)
5253     {
5254       _dbus_verbose ("clamping requested max message unix_fds %ld to %d\n",
5255                      n, DBUS_MAXIMUM_MESSAGE_UNIX_FDS);
5256       n = DBUS_MAXIMUM_MESSAGE_UNIX_FDS;
5257     }
5258   loader->max_message_unix_fds = n;
5259 }
5260
5261 /**
5262  * Gets the maximum allowed number of unix fds per message
5263  *
5264  * @param loader the loader
5265  * @returns max unix fds
5266  */
5267 long
5268 _dbus_message_loader_get_max_message_unix_fds (DBusMessageLoader  *loader)
5269 {
5270   return loader->max_message_unix_fds;
5271 }
5272
5273 /**
5274  * Return how many file descriptors are pending in the loader
5275  *
5276  * @param loader the loader
5277  */
5278 int
5279 _dbus_message_loader_get_pending_fds_count (DBusMessageLoader *loader)
5280 {
5281 #ifdef HAVE_UNIX_FD_PASSING
5282   return loader->n_unix_fds;
5283 #else
5284   return 0;
5285 #endif
5286 }
5287
5288 /**
5289  * Register a function to be called whenever the number of pending file
5290  * descriptors in the loader change.
5291  *
5292  * @param loader the loader
5293  * @param callback the callback
5294  * @param data the data for the callback
5295  */
5296 void
5297 _dbus_message_loader_set_pending_fds_function (DBusMessageLoader *loader,
5298                                                void (* callback) (void *),
5299                                                void *data)
5300 {
5301 #ifdef HAVE_UNIX_FD_PASSING
5302   loader->unix_fds_change = callback;
5303   loader->unix_fds_change_data = data;
5304 #endif
5305 }
5306
5307 void
5308 _dbus_message_loader_set_unique_sender_id (DBusMessageLoader *loader,
5309                                            uint64_t           id)
5310 {
5311   loader->unique_sender_id = id;
5312 }
5313
5314 uint64_t
5315 _dbus_message_loader_get_unique_sender_id (DBusMessageLoader *loader)
5316 {
5317   return loader->unique_sender_id;
5318 }
5319
5320 static DBusDataSlotAllocator slot_allocator =
5321   _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (message_slots));
5322
5323 /**
5324  * Allocates an integer ID to be used for storing application-specific
5325  * data on any DBusMessage. The allocated ID may then be used
5326  * with dbus_message_set_data() and dbus_message_get_data().
5327  * The passed-in slot must be initialized to -1, and is filled in
5328  * with the slot ID. If the passed-in slot is not -1, it's assumed
5329  * to be already allocated, and its refcount is incremented.
5330  *
5331  * The allocated slot is global, i.e. all DBusMessage objects will
5332  * have a slot with the given integer ID reserved.
5333  *
5334  * @param slot_p address of a global variable storing the slot
5335  * @returns #FALSE on failure (no memory)
5336  */
5337 dbus_bool_t
5338 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
5339 {
5340   return _dbus_data_slot_allocator_alloc (&slot_allocator,
5341                                           slot_p);
5342 }
5343
5344 /**
5345  * Deallocates a global ID for message data slots.
5346  * dbus_message_get_data() and dbus_message_set_data() may no
5347  * longer be used with this slot.  Existing data stored on existing
5348  * DBusMessage objects will be freed when the message is
5349  * finalized, but may not be retrieved (and may only be replaced if
5350  * someone else reallocates the slot).  When the refcount on the
5351  * passed-in slot reaches 0, it is set to -1.
5352  *
5353  * @param slot_p address storing the slot to deallocate
5354  */
5355 void
5356 dbus_message_free_data_slot (dbus_int32_t *slot_p)
5357 {
5358   _dbus_return_if_fail (*slot_p >= 0);
5359
5360   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5361 }
5362
5363 /**
5364  * Stores a pointer on a DBusMessage, along
5365  * with an optional function to be used for freeing
5366  * the data when the data is set again, or when
5367  * the message is finalized. The slot number
5368  * must have been allocated with dbus_message_allocate_data_slot().
5369  *
5370  * @param message the message
5371  * @param slot the slot number
5372  * @param data the data to store
5373  * @param free_data_func finalizer function for the data
5374  * @returns #TRUE if there was enough memory to store the data
5375  */
5376 dbus_bool_t
5377 dbus_message_set_data (DBusMessage     *message,
5378                        dbus_int32_t     slot,
5379                        void            *data,
5380                        DBusFreeFunction free_data_func)
5381 {
5382   DBusFreeFunction old_free_func;
5383   void *old_data;
5384   dbus_bool_t retval;
5385
5386   _dbus_return_val_if_fail (message != NULL, FALSE);
5387   _dbus_return_val_if_fail (slot >= 0, FALSE);
5388
5389   retval = _dbus_data_slot_list_set (&slot_allocator,
5390                                      &message->slot_list,
5391                                      slot, data, free_data_func,
5392                                      &old_free_func, &old_data);
5393
5394   if (retval)
5395     {
5396       /* Do the actual free outside the message lock */
5397       if (old_free_func)
5398         (* old_free_func) (old_data);
5399     }
5400
5401   return retval;
5402 }
5403
5404 /**
5405  * Retrieves data previously set with dbus_message_set_data().
5406  * The slot must still be allocated (must not have been freed).
5407  *
5408  * @param message the message
5409  * @param slot the slot to get data from
5410  * @returns the data, or #NULL if not found
5411  */
5412 void*
5413 dbus_message_get_data (DBusMessage   *message,
5414                        dbus_int32_t   slot)
5415 {
5416   void *res;
5417
5418   _dbus_return_val_if_fail (message != NULL, NULL);
5419
5420   res = _dbus_data_slot_list_get (&slot_allocator,
5421                                   &message->slot_list,
5422                                   slot);
5423
5424   return res;
5425 }
5426
5427 /**
5428  * Utility function to convert a machine-readable (not translated)
5429  * string into a D-Bus message type.
5430  *
5431  * @code
5432  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
5433  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
5434  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
5435  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
5436  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
5437  * @endcode
5438  *
5439  */
5440 int
5441 dbus_message_type_from_string (const char *type_str)
5442 {
5443   if (strcmp (type_str, "method_call") == 0)
5444     return DBUS_MESSAGE_TYPE_METHOD_CALL;
5445   if (strcmp (type_str, "method_return") == 0)
5446     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
5447   else if (strcmp (type_str, "signal") == 0)
5448     return DBUS_MESSAGE_TYPE_SIGNAL;
5449   else if (strcmp (type_str, "error") == 0)
5450     return DBUS_MESSAGE_TYPE_ERROR;
5451   else
5452     return DBUS_MESSAGE_TYPE_INVALID;
5453 }
5454
5455 /**
5456  * Utility function to convert a D-Bus message type into a
5457  * machine-readable string (not translated).
5458  *
5459  * @code
5460  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
5461  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
5462  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
5463  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
5464  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
5465  * @endcode
5466  *
5467  */
5468 const char *
5469 dbus_message_type_to_string (int type)
5470 {
5471   switch (type)
5472     {
5473     case DBUS_MESSAGE_TYPE_METHOD_CALL:
5474       return "method_call";
5475     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
5476       return "method_return";
5477     case DBUS_MESSAGE_TYPE_SIGNAL:
5478       return "signal";
5479     case DBUS_MESSAGE_TYPE_ERROR:
5480       return "error";
5481     default:
5482       return "invalid";
5483     }
5484 }
5485
5486 /**
5487  * Turn a DBusMessage into the marshalled form as described in the D-Bus
5488  * specification.
5489  *
5490  * Generally, this function is only useful for encapsulating D-Bus messages in
5491  * a different protocol.
5492  *
5493  * @param msg the DBusMessage
5494  * @param marshalled_data_p the location to save the marshalled form to
5495  * @param len_p the location to save the length of the marshalled form to
5496  * @returns #FALSE if there was not enough memory
5497  */
5498 dbus_bool_t
5499 dbus_message_marshal (DBusMessage  *msg,
5500                       char        **marshalled_data_p,
5501                       int          *len_p)
5502 {
5503   DBusString tmp;
5504   dbus_bool_t was_locked;
5505
5506   _dbus_return_val_if_fail (msg != NULL, FALSE);
5507   _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
5508   _dbus_return_val_if_fail (len_p != NULL, FALSE);
5509
5510   if (!_dbus_string_init (&tmp))
5511     return FALSE;
5512
5513   /* Ensure the message is locked, to ensure the length header is filled in. */
5514   was_locked = msg->locked;
5515
5516   if (!was_locked)
5517     dbus_message_lock (msg);
5518
5519   if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
5520     goto fail;
5521
5522   *len_p = _dbus_string_get_length (&tmp);
5523
5524   if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
5525     goto fail;
5526
5527   *len_p = _dbus_string_get_length (&tmp);
5528
5529   if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
5530     goto fail;
5531
5532   _dbus_string_free (&tmp);
5533
5534   if (!was_locked)
5535     msg->locked = FALSE;
5536
5537   return TRUE;
5538
5539  fail:
5540   _dbus_string_free (&tmp);
5541
5542   if (!was_locked)
5543     msg->locked = FALSE;
5544
5545   return FALSE;
5546 }
5547
5548 /**
5549  * Demarshal a D-Bus message from the format described in the D-Bus
5550  * specification.
5551  *
5552  * Generally, this function is only useful for encapsulating D-Bus messages in
5553  * a different protocol.
5554  *
5555  * @param str the marshalled DBusMessage
5556  * @param len the length of str
5557  * @param error the location to save errors to
5558  * @returns #NULL if there was an error
5559  */
5560 DBusMessage *
5561 dbus_message_demarshal (const char *str,
5562                         int         len,
5563                         DBusError  *error)
5564 {
5565   DBusMessageLoader *loader;
5566   DBusString *buffer;
5567   DBusMessage *msg;
5568
5569   _dbus_return_val_if_fail (str != NULL, NULL);
5570
5571   loader = _dbus_message_loader_new ();
5572
5573   if (loader == NULL)
5574     return NULL;
5575
5576   _dbus_message_loader_get_buffer (loader, &buffer, NULL, NULL);
5577
5578   if (!_dbus_string_append_len (buffer, str, len))
5579     goto fail_oom;
5580
5581   _dbus_message_loader_return_buffer (loader, buffer);
5582
5583   if (!_dbus_message_loader_queue_messages (loader))
5584     goto fail_oom;
5585
5586   if (_dbus_message_loader_get_is_corrupted (loader))
5587     goto fail_corrupt;
5588
5589   msg = _dbus_message_loader_pop_message (loader);
5590
5591   if (!msg)
5592     goto fail_oom;
5593
5594   _dbus_message_loader_unref (loader);
5595   return msg;
5596
5597  fail_corrupt:
5598   dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted (%s)",
5599                   _dbus_validity_to_error_message (loader->corruption_reason));
5600   _dbus_message_loader_unref (loader);
5601   return NULL;
5602
5603  fail_oom:
5604   _DBUS_SET_OOM (error);
5605   _dbus_message_loader_unref (loader);
5606   return NULL;
5607 }
5608
5609 /**
5610  * Returns the number of bytes required to be in the buffer to demarshal a
5611  * D-Bus message.
5612  *
5613  * Generally, this function is only useful for encapsulating D-Bus messages in
5614  * a different protocol.
5615  *
5616  * @param buf data to be marshalled
5617  * @param len the length of @p buf
5618  * @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
5619  *
5620  */
5621 int
5622 dbus_message_demarshal_bytes_needed(const char *buf,
5623                                     int         len)
5624 {
5625   DBusString str;
5626   int byte_order, fields_array_len, header_len, body_len;
5627   DBusValidity validity = DBUS_VALID;
5628   int have_message;
5629   dbus_bool_t is_gvariant;
5630
5631   if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
5632     return 0;
5633
5634   if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
5635     len = DBUS_MAXIMUM_MESSAGE_LENGTH;
5636   _dbus_string_init_const_len (&str, buf, len);
5637
5638   validity = DBUS_VALID;
5639   have_message
5640     = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
5641                                           &validity, &byte_order,
5642                                           &fields_array_len,
5643                                           &header_len,
5644                                           &body_len,
5645                                           &str, 0,
5646                                           len,
5647                                           &is_gvariant);
5648   _dbus_string_free (&str);
5649
5650   if (validity == DBUS_VALID)
5651     {
5652       _dbus_assert (have_message || (header_len + body_len) > len);
5653       (void) have_message; /* unused unless asserting */
5654       return header_len + body_len;
5655     }
5656   else
5657     {
5658       return -1; /* broken! */
5659     }
5660 }
5661
5662 static dbus_bool_t
5663 _dbus_message_copy_recursive(DBusMessageIter *iter, DBusMessageIter *dest)
5664 {
5665   dbus_bool_t res = TRUE;
5666   int current_type;
5667
5668   while ((current_type = dbus_message_iter_get_arg_type (iter)) != DBUS_TYPE_INVALID) {
5669     if (dbus_type_is_basic(current_type)) {
5670       DBusBasicValue value;
5671       dbus_message_iter_get_basic (iter, &value);
5672       dbus_message_iter_append_basic (dest, current_type, &value);
5673     }
5674     else {
5675       DBusMessageIter sub;
5676       DBusMessageIter dest_sub;
5677       char *sig = NULL;
5678
5679       dbus_message_iter_recurse (iter, &sub);
5680       if (DBUS_TYPE_VARIANT == current_type)
5681         sig = dbus_message_iter_get_signature (&sub);
5682       else if (DBUS_TYPE_ARRAY == current_type)
5683         sig = dbus_message_iter_get_signature (&sub);
5684
5685       res = res && dbus_message_iter_open_container (dest, current_type, sig, &dest_sub);
5686       dbus_free(sig);
5687       res = res && _dbus_message_copy_recursive (&sub, &dest_sub);
5688       res = res && dbus_message_iter_close_container (dest, &dest_sub);
5689
5690       if (!res) {
5691         return FALSE;
5692       }
5693    }
5694
5695    dbus_message_iter_next (iter);
5696   }
5697
5698   return TRUE;
5699 }
5700
5701 void
5702 _dbus_on_new_bus (int type)
5703 {
5704   _dbus_assert (type == DBUS_MAJOR_PROTOCOL_VERSION || type == DBUS_PROTOCOL_VERSION_GVARIANT);
5705   _dbus_protocol_strategy_bus_function (type);
5706 }
5707
5708 static void
5709 _dbus_on_send_message (int type)
5710 {
5711   _dbus_assert (type == DBUS_MAJOR_PROTOCOL_VERSION || type == DBUS_PROTOCOL_VERSION_GVARIANT);
5712   _dbus_protocol_strategy_message_function (type);
5713 }
5714
5715 DBusMessage *
5716 _dbus_message_remarshal (DBusMessage *message, dbus_bool_t gvariant)
5717 {
5718   DBusMessage *ret;
5719   DBusMessageIter iter, ret_iter;
5720   size_t i;
5721   dbus_uint32_t serial;
5722   const char *sender;
5723
5724   _dbus_assert (message->locked);
5725
5726   _dbus_on_send_message (gvariant ? DBUS_PROTOCOL_VERSION_GVARIANT : DBUS_MAJOR_PROTOCOL_VERSION);
5727
5728   ret = _dbus_message_create_protocol_version (dbus_message_get_type(message),
5729                                                dbus_message_get_destination(message),
5730                                                dbus_message_get_path(message),
5731                                                dbus_message_get_interface(message),
5732                                                dbus_message_get_member(message),
5733                                                dbus_message_get_error_name(message),
5734                                                gvariant);
5735
5736   dbus_message_iter_init (message, &iter);
5737   dbus_message_iter_init_append (ret, &ret_iter);
5738   if (!_dbus_message_copy_recursive(&iter, &ret_iter))
5739     return NULL;
5740
5741 #ifdef HAVE_UNIX_FD_PASSING
5742   ret->unix_fds = dbus_new(int, message->n_unix_fds);
5743   if (ret->unix_fds == NULL && message->n_unix_fds > 0)
5744     goto err;
5745
5746   ret->n_unix_fds_allocated = message->n_unix_fds;
5747
5748   for (i = 0; i < message->n_unix_fds; ++i) {
5749     ret->unix_fds[i] = _dbus_dup(message->unix_fds[i], NULL);
5750
5751     if (ret->unix_fds[i] < 0) {
5752       ret->n_unix_fds = i;
5753       goto err;
5754     }
5755   }
5756
5757   ret->n_unix_fds = message->n_unix_fds;
5758 #endif
5759
5760   /* Remarshal data in header:
5761      byte order (already set)
5762      type (already set)
5763      flags - only those we understand
5764      version (already set)
5765      body length
5766      serial
5767      fields array (length)
5768      fields:
5769          path (already set)
5770          interface (already set)
5771          member (already set)
5772          error name (already set)
5773          reply serial
5774          destination (already set)
5775          sender
5776          signature (set during copy, but an action needed for conversion to GVariant)
5777          unix fds
5778    */
5779
5780   /* FLAGS */
5781   _dbus_header_toggle_flag (&ret->header, DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
5782       _dbus_header_get_flag (&message->header, DBUS_HEADER_FLAG_NO_REPLY_EXPECTED));
5783
5784   _dbus_header_toggle_flag (&ret->header, DBUS_HEADER_FLAG_NO_AUTO_START,
5785       _dbus_header_get_flag (&message->header, DBUS_HEADER_FLAG_NO_AUTO_START));
5786
5787   /* SERIAL / COOKIE */
5788   serial = dbus_message_get_serial (message);
5789
5790   if (0 != serial)
5791     dbus_message_set_serial (ret, serial);
5792
5793   /* Field: REPLY_SERIAL */
5794   serial = dbus_message_get_reply_serial (message);
5795
5796   if (0 != serial && !dbus_message_set_reply_serial (ret, serial))
5797     goto err;
5798
5799   /* Field: SENDER */
5800   sender = dbus_message_get_sender (message);
5801
5802   if (NULL != sender && !dbus_message_set_sender (ret, sender))
5803     goto err;
5804
5805   /* BODY LENGTH */
5806   if (!gvariant)
5807     _dbus_header_update_lengths (&ret->header,
5808                                  _dbus_string_get_length (&ret->body));
5809     /* For GVariant: */
5810     /* Field: SIGNATURE to body; add body offset - this is done with dbus_message_lock() */
5811   else
5812     dbus_message_lock (ret);
5813
5814   return ret;
5815
5816 err:
5817   _dbus_header_free (&ret->header);
5818   _dbus_string_free (&ret->body);
5819
5820 #ifdef HAVE_UNIX_FD_PASSING
5821   if (ret->unix_fds)
5822     {
5823       close_unix_fds(ret->unix_fds, &ret->n_unix_fds);
5824       dbus_free(ret->unix_fds);
5825     }
5826 #endif
5827
5828   return NULL;
5829 }
5830
5831 void
5832 dbus_set_protocol_version (unsigned char version)
5833 {
5834   _dbus_default_protocol_version = version;
5835 }
5836
5837 static void
5838 protocol_strategy_first_type (int type)
5839 {
5840   /* change protocol once */
5841   if (!_dbus_first_bus_open)
5842     {
5843       _dbus_first_bus_open = TRUE;
5844       _dbus_default_protocol_version = type;
5845     }
5846 }
5847
5848 static void
5849 protocol_strategy_last_type (int type)
5850 {
5851   /* change protocol every time it is needed */
5852   if (_dbus_default_protocol_version != type)
5853     _dbus_default_protocol_version = type;
5854 }
5855
5856 static void
5857 protocol_strategy_static (int type)
5858 {
5859   /* do not change */
5860 }
5861
5862 void
5863 dbus_set_default_protocol_strategy (const char *strategy_name)
5864 {
5865   if (strcmp (strategy_name, "first-bus") == 0)
5866     {
5867       _dbus_protocol_strategy_bus_function = protocol_strategy_first_type;
5868       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5869     }
5870   else if (strcmp (strategy_name, "dbus1") == 0)
5871     {
5872       _dbus_default_protocol_version = DBUS_MAJOR_PROTOCOL_VERSION;
5873       _dbus_protocol_strategy_bus_function = protocol_strategy_static;
5874       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5875     }
5876   else if (strcmp (strategy_name, "gvariant") == 0)
5877     {
5878       _dbus_default_protocol_version = DBUS_PROTOCOL_VERSION_GVARIANT;
5879       _dbus_protocol_strategy_bus_function = protocol_strategy_static;
5880       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5881     }
5882   else if (strcmp (strategy_name, "last-message") == 0)
5883     {
5884       _dbus_protocol_strategy_bus_function = protocol_strategy_static;
5885       _dbus_protocol_strategy_message_function = protocol_strategy_last_type;
5886     }
5887   else /* "last-bus" is default strategy */
5888     {
5889       _dbus_protocol_strategy_bus_function = protocol_strategy_last_type;
5890       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5891     }
5892 }
5893
5894 DBusMessage *
5895 _dbus_generate_local_error_message (dbus_uint32_t serial,
5896                                     const char *error_name,
5897                                     const char *error_msg)
5898 {
5899   DBusMessage *message;
5900   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
5901   if (!message)
5902     goto out;
5903
5904   if (!dbus_message_set_error_name (message, error_name))
5905     {
5906       dbus_message_unref (message);
5907       message = NULL;
5908       goto out;
5909     }
5910
5911   dbus_message_set_no_reply (message, TRUE);
5912
5913   if (!dbus_message_set_reply_serial (message,
5914                                       serial))
5915     {
5916       dbus_message_unref (message);
5917       message = NULL;
5918       goto out;
5919     }
5920
5921   if (error_msg != NULL)
5922     {
5923       DBusMessageIter iter;
5924
5925       dbus_message_iter_init_append (message, &iter);
5926       if (!dbus_message_iter_append_basic (&iter,
5927                                            DBUS_TYPE_STRING,
5928                                            &error_msg))
5929         {
5930           dbus_message_unref (message);
5931           message = NULL;
5932           goto out;
5933         }
5934     }
5935
5936  out:
5937   return message;
5938 }
5939
5940 dbus_bool_t
5941 _dbus_message_assure_dbus1 (DBusMessage **message)
5942 {
5943   if ((*message)->header.protocol_version != DBUS_MAJOR_PROTOCOL_VERSION)
5944     {
5945       *message = _dbus_message_remarshal (*message, FALSE);
5946       return TRUE;
5947     }
5948   return FALSE;
5949 }
5950
5951 dbus_bool_t
5952 _dbus_message_assure_gvariant (DBusMessage **message)
5953 {
5954   if ((*message)->header.protocol_version != DBUS_PROTOCOL_VERSION_GVARIANT)
5955     {
5956       *message = _dbus_message_remarshal (*message, TRUE);
5957       return TRUE;
5958     }
5959   return FALSE;
5960 }
5961
5962 /**
5963  * An opaque data structure containing the serialized form of any single
5964  * D-Bus message item, whose signature is a single complete type.
5965  *
5966  * (Implementation detail: It's serialized as a single variant.)
5967  */
5968 struct DBusVariant
5969 {
5970   DBusString data;
5971 };
5972
5973 /**
5974  * Copy a single D-Bus message item from reader into a
5975  * newly-allocated #DBusVariant.
5976  *
5977  * For example, if a message contains three string arguments, and reader points
5978  * to the second string, the resulting DBusVariant will have signature
5979  * #DBUS_TYPE_STRING_AS_STRING and contain only that second string.
5980  *
5981  * @param reader An iterator over message items, pointing to one item to copy
5982  * @returns The variant, or #NULL if out of memory
5983  */
5984 DBusVariant *
5985 _dbus_variant_read (DBusMessageIter *reader)
5986 {
5987   DBusVariant *self = NULL;
5988   /* Points to the single item we will read from the reader */
5989   DBusMessageRealIter *real_reader = (DBusMessageRealIter *) reader;
5990   /* The position in self at which we will write a single variant
5991    * (it is position 0) */
5992   DBusTypeWriter items_writer;
5993   /* The position in self at which we will write a copy of reader
5994    * (it is inside the variant) */
5995   DBusTypeWriter variant_writer;
5996   /* 'v' */
5997   DBusString variant_signature;
5998   /* Whatever is the signature of the item we will copy from the reader */
5999   DBusString contained_signature;
6000   /* TRUE if self->data needs to be freed */
6001   dbus_bool_t data_inited = FALSE;
6002   /* The type of the item we will read from the reader */
6003   int type;
6004   /* The string, start position within that string, and length of the signature
6005    * of the single complete type of the item reader points to */
6006   const DBusString *sig;
6007   int start, len;
6008
6009   _dbus_assert (_dbus_message_iter_check (real_reader));
6010   _dbus_assert (real_reader->iter_type == DBUS_MESSAGE_ITER_TYPE_READER);
6011   _dbus_string_init_const (&variant_signature, DBUS_TYPE_VARIANT_AS_STRING);
6012   type = dbus_message_iter_get_arg_type (reader);
6013   _dbus_type_reader_get_signature (&real_reader->u.reader, &sig, &start, &len);
6014
6015   if (!_dbus_string_init (&contained_signature))
6016     return NULL;
6017
6018   if (!_dbus_string_copy_len (sig, start, len, &contained_signature, 0))
6019     goto oom;
6020
6021   self = dbus_new0 (DBusVariant, 1);
6022
6023   if (self == NULL)
6024     goto oom;
6025
6026   if (!_dbus_string_init (&self->data))
6027     goto oom;
6028
6029   data_inited = TRUE;
6030
6031   _dbus_type_writer_init_values_only (&items_writer, DBUS_COMPILER_BYTE_ORDER,
6032                                       &variant_signature, 0, &self->data, 0);
6033
6034   if (!_dbus_type_writer_recurse (&items_writer, DBUS_TYPE_VARIANT,
6035                                   &contained_signature, 0, &variant_writer))
6036     goto oom;
6037
6038   if (type == DBUS_TYPE_ARRAY)
6039     {
6040       /* Points to each item in turn inside the array we are copying */
6041       DBusMessageIter array_reader;
6042       /* Same as array_reader */
6043       DBusMessageRealIter *real_array_reader = (DBusMessageRealIter *) &array_reader;
6044       /* The position inside the copied array at which we will write
6045        * the copy of array_reader */
6046       DBusTypeWriter array_writer;
6047
6048       dbus_message_iter_recurse (reader, &array_reader);
6049
6050       if (!_dbus_type_writer_recurse (&variant_writer, type,
6051                                       &contained_signature, 1, &array_writer))
6052         goto oom;
6053
6054       if (!_dbus_type_writer_write_reader (&array_writer,
6055                                            &real_array_reader->u.reader))
6056         goto oom;
6057
6058       if (!_dbus_type_writer_unrecurse (&variant_writer, &array_writer))
6059         goto oom;
6060     }
6061   else if (type == DBUS_TYPE_DICT_ENTRY || type == DBUS_TYPE_VARIANT ||
6062            type == DBUS_TYPE_STRUCT)
6063     {
6064       /* Points to each item in turn inside the container we are copying */
6065       DBusMessageIter inner_reader;
6066       /* Same as inner_reader */
6067       DBusMessageRealIter *real_inner_reader = (DBusMessageRealIter *) &inner_reader;
6068       /* The position inside the copied container at which we will write the
6069        * copy of inner_reader */
6070       DBusTypeWriter inner_writer;
6071
6072       dbus_message_iter_recurse (reader, &inner_reader);
6073
6074       if (!_dbus_type_writer_recurse (&variant_writer, type, NULL, 0,
6075                                       &inner_writer))
6076         goto oom;
6077
6078       if (!_dbus_type_writer_write_reader (&inner_writer,
6079                                            &real_inner_reader->u.reader))
6080         goto oom;
6081
6082       if (!_dbus_type_writer_unrecurse (&variant_writer, &inner_writer))
6083         goto oom;
6084     }
6085   else
6086     {
6087       DBusBasicValue value;
6088
6089       /* We eliminated all the container types above */
6090       _dbus_assert (dbus_type_is_basic (type));
6091
6092       dbus_message_iter_get_basic (reader, &value);
6093
6094       if (!_dbus_type_writer_write_basic (&variant_writer, type, &value))
6095         goto oom;
6096     }
6097
6098   _dbus_string_free (&contained_signature);
6099   return self;
6100
6101 oom:
6102   if (self != NULL)
6103     {
6104       if (data_inited)
6105         _dbus_string_free (&self->data);
6106
6107       dbus_free (self);
6108     }
6109
6110   _dbus_string_free (&contained_signature);
6111   return NULL;
6112 }
6113
6114 /**
6115  * Return the signature of the item stored in self. It is a single complete
6116  * type.
6117  *
6118  * @param self the variant
6119  */
6120 const char *
6121 _dbus_variant_get_signature (DBusVariant *self)
6122 {
6123   unsigned char len;
6124   const char *ret;
6125
6126   _dbus_assert (self != NULL);
6127
6128   /* Here we make use of the fact that the serialization of a variant starts
6129    * with the 1-byte length, then that many bytes of signature, then \0. */
6130   len = _dbus_string_get_byte (&self->data, 0);
6131   ret = _dbus_string_get_const_data_len (&self->data, 1, len);
6132   _dbus_assert (strlen (ret) == len);
6133   return ret;
6134 }
6135
6136 /**
6137  * Copy the single D-Bus message item from self into writer.
6138  *
6139  * For example, if writer points into the body of an empty message and self has
6140  * signature #DBUS_TYPE_STRING_AS_STRING, then the message will
6141  * have signature #DBUS_TYPE_STRING_AS_STRING after this function returns
6142  *
6143  * @param self the variant
6144  * @param writer the place to write the contents of the variant
6145  * @returns #TRUE on success, #FALSE if out of memory
6146  */
6147 dbus_bool_t
6148 _dbus_variant_write (DBusVariant *self,
6149                      DBusMessageIter *writer)
6150 {
6151   /* 'v' */
6152   DBusString variant_signature;
6153   /* Points to the single item in self */
6154   DBusTypeReader variant_reader;
6155   /* Points to the single item (of whatever type) inside the variant */
6156   DBusTypeReader reader;
6157   /* The position at which we will copy reader */
6158   DBusMessageRealIter *real_writer = (DBusMessageRealIter *) writer;
6159   dbus_bool_t ret;
6160
6161   _dbus_assert (self != NULL);
6162   _dbus_assert (_dbus_message_iter_append_check (real_writer));
6163   _dbus_assert (real_writer->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
6164
6165   _dbus_string_init_const (&variant_signature, DBUS_TYPE_VARIANT_AS_STRING);
6166   _dbus_type_reader_init (&reader, DBUS_COMPILER_BYTE_ORDER,
6167                           &variant_signature, 0, &self->data, 0);
6168   _dbus_type_reader_recurse (&reader, &variant_reader);
6169
6170   if (!_dbus_message_iter_open_signature (real_writer))
6171     return FALSE;
6172
6173   ret = _dbus_type_writer_write_reader (&real_writer->u.writer,
6174                                         &variant_reader);
6175
6176   if (!_dbus_message_iter_close_signature (real_writer))
6177     return FALSE;
6178
6179   return ret;
6180 }
6181
6182 int
6183 _dbus_variant_get_length (DBusVariant *self)
6184 {
6185   _dbus_assert (self != NULL);
6186   return _dbus_string_get_length (&self->data);
6187 }
6188
6189 const DBusString *
6190 _dbus_variant_peek (DBusVariant *self)
6191 {
6192   _dbus_assert (self != NULL);
6193   return &self->data;
6194 }
6195
6196 void
6197 _dbus_variant_free (DBusVariant *self)
6198 {
6199   _dbus_assert (self != NULL);
6200   _dbus_string_free (&self->data);
6201   dbus_free (self);
6202 }
6203
6204 /** @} */
6205
6206 /* tests in dbus-message-util.c */