7d44a2e483ee6421d8c35899edcdb9a31ab236ca
[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   _dbus_message_trace_ref (retval, 0, 1, "copy");
1845   return retval;
1846
1847  failed_copy:
1848   _dbus_header_free (&retval->header);
1849   _dbus_string_free (&retval->body);
1850
1851 #ifdef HAVE_UNIX_FD_PASSING
1852   close_unix_fds(retval->unix_fds, &retval->n_unix_fds);
1853   dbus_free(retval->unix_fds);
1854 #endif
1855
1856   dbus_free (retval);
1857
1858   return NULL;
1859 }
1860
1861
1862 /**
1863  * Increments the reference count of a DBusMessage.
1864  *
1865  * @param message the message
1866  * @returns the message
1867  * @see dbus_message_unref
1868  */
1869 DBusMessage *
1870 dbus_message_ref (DBusMessage *message)
1871 {
1872   dbus_int32_t old_refcount;
1873
1874   _dbus_return_val_if_fail (message != NULL, NULL);
1875   _dbus_return_val_if_fail (message->generation == _dbus_current_generation, NULL);
1876   _dbus_return_val_if_fail (!message->in_cache, NULL);
1877
1878   old_refcount = _dbus_atomic_inc (&message->refcount);
1879   _dbus_assert (old_refcount >= 1);
1880   _dbus_message_trace_ref (message, old_refcount, old_refcount + 1, "ref");
1881
1882   return message;
1883 }
1884
1885 /**
1886  * Decrements the reference count of a DBusMessage, freeing the
1887  * message if the count reaches 0.
1888  *
1889  * @param message the message
1890  * @see dbus_message_ref
1891  */
1892 void
1893 dbus_message_unref (DBusMessage *message)
1894 {
1895  dbus_int32_t old_refcount;
1896
1897   _dbus_return_if_fail (message != NULL);
1898   _dbus_return_if_fail (message->generation == _dbus_current_generation);
1899   _dbus_return_if_fail (!message->in_cache);
1900
1901   old_refcount = _dbus_atomic_dec (&message->refcount);
1902
1903   _dbus_assert (old_refcount >= 1);
1904
1905   _dbus_message_trace_ref (message, old_refcount, old_refcount - 1, "unref");
1906
1907   if (old_refcount == 1)
1908     {
1909       /* Calls application callbacks! */
1910       dbus_message_cache_or_finalize (message);
1911     }
1912 }
1913
1914 /**
1915  * Gets the type of a message. Types include
1916  * #DBUS_MESSAGE_TYPE_METHOD_CALL, #DBUS_MESSAGE_TYPE_METHOD_RETURN,
1917  * #DBUS_MESSAGE_TYPE_ERROR, #DBUS_MESSAGE_TYPE_SIGNAL, but other
1918  * types are allowed and all code must silently ignore messages of
1919  * unknown type. #DBUS_MESSAGE_TYPE_INVALID will never be returned.
1920  *
1921  * @param message the message
1922  * @returns the type of the message
1923  */
1924 int
1925 dbus_message_get_type (DBusMessage *message)
1926 {
1927   _dbus_return_val_if_fail (message != NULL, DBUS_MESSAGE_TYPE_INVALID);
1928
1929   return _dbus_header_get_message_type (&message->header);
1930 }
1931
1932 /**
1933  * Appends fields to a message given a variable argument list. The
1934  * variable argument list should contain the type of each argument
1935  * followed by the value to append. Appendable types are basic types,
1936  * and arrays of fixed-length basic types (except arrays of Unix file
1937  * descriptors). To append variable-length basic types, or any more
1938  * complex value, you have to use an iterator rather than this
1939  * function.
1940  *
1941  * To append a basic type, specify its type code followed by the
1942  * address of the value. For example:
1943  *
1944  * @code
1945  *
1946  * dbus_int32_t v_INT32 = 42;
1947  * const char *v_STRING = "Hello World";
1948  * dbus_message_append_args (message,
1949  *                           DBUS_TYPE_INT32, &v_INT32,
1950  *                           DBUS_TYPE_STRING, &v_STRING,
1951  *                           DBUS_TYPE_INVALID);
1952  * @endcode
1953  *
1954  * To append an array of fixed-length basic types (except Unix file
1955  * descriptors), pass in the DBUS_TYPE_ARRAY typecode, the element
1956  * typecode, the address of the array pointer, and a 32-bit integer
1957  * giving the number of elements in the array. So for example:
1958  *
1959  * @code
1960  *
1961  * const dbus_int32_t array[] = { 1, 2, 3 };
1962  * const dbus_int32_t *v_ARRAY = array;
1963  * dbus_message_append_args (message,
1964  *                           DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY, 3,
1965  *                           DBUS_TYPE_INVALID);
1966  *
1967  * @endcode
1968  *
1969  * This function does not support arrays of Unix file descriptors. If
1970  * you need those you need to manually recurse into the array.
1971  *
1972  * For Unix file descriptors this function will internally duplicate
1973  * the descriptor you passed in. Hence you may close the descriptor
1974  * immediately after this call.
1975  *
1976  * @warning in C, given "int array[]", "&array == array" (the
1977  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
1978  * So if you're using an array instead of a pointer you have to create
1979  * a pointer variable, assign the array to it, then take the address
1980  * of the pointer variable. For strings it works to write
1981  * const char *array = "Hello" and then use &array though.
1982  *
1983  * The last argument to this function must be #DBUS_TYPE_INVALID,
1984  * marking the end of the argument list. If you don't do this
1985  * then libdbus won't know to stop and will read invalid memory.
1986  *
1987  * String/signature/path arrays should be passed in as "const char***
1988  * address_of_array" and "int n_elements"
1989  *
1990  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
1991  *
1992  * @todo If this fails due to lack of memory, the message is hosed and
1993  * you have to start over building the whole message.
1994  *
1995  * @param message the message
1996  * @param first_arg_type type of the first argument
1997  * @param ... value of first argument, list of additional type-value pairs
1998  * @returns #TRUE on success
1999  */
2000 dbus_bool_t
2001 dbus_message_append_args (DBusMessage *message,
2002                           int          first_arg_type,
2003                           ...)
2004 {
2005   dbus_bool_t retval;
2006   va_list var_args;
2007
2008   _dbus_return_val_if_fail (message != NULL, FALSE);
2009
2010   va_start (var_args, first_arg_type);
2011   retval = dbus_message_append_args_valist (message,
2012                                             first_arg_type,
2013                                             var_args);
2014   va_end (var_args);
2015
2016   return retval;
2017 }
2018
2019 /**
2020  * Like dbus_message_append_args() but takes a va_list for use by language bindings.
2021  *
2022  * @todo for now, if this function fails due to OOM it will leave
2023  * the message half-written and you have to discard the message
2024  * and start over.
2025  *
2026  * @see dbus_message_append_args.
2027  * @param message the message
2028  * @param first_arg_type type of first argument
2029  * @param var_args value of first argument, then list of type/value pairs
2030  * @returns #TRUE on success
2031  */
2032 dbus_bool_t
2033 dbus_message_append_args_valist (DBusMessage *message,
2034                                  int          first_arg_type,
2035                                  va_list      var_args)
2036 {
2037   int type;
2038   DBusMessageIter iter;
2039
2040   _dbus_return_val_if_fail (message != NULL, FALSE);
2041
2042   type = first_arg_type;
2043
2044   dbus_message_iter_init_append (message, &iter);
2045
2046   while (type != DBUS_TYPE_INVALID)
2047     {
2048       if (dbus_type_is_basic (type))
2049         {
2050           const DBusBasicValue *value;
2051           value = va_arg (var_args, const DBusBasicValue*);
2052
2053           if (!dbus_message_iter_append_basic (&iter,
2054                                                type,
2055                                                value))
2056             goto failed;
2057         }
2058       else if (type == DBUS_TYPE_ARRAY)
2059         {
2060           int element_type;
2061           DBusMessageIter array;
2062           char buf[2];
2063
2064           element_type = va_arg (var_args, int);
2065
2066           buf[0] = element_type;
2067           buf[1] = '\0';
2068           if (!dbus_message_iter_open_container (&iter,
2069                                                  DBUS_TYPE_ARRAY,
2070                                                  buf,
2071                                                  &array))
2072             goto failed;
2073
2074           if (dbus_type_is_fixed (element_type) &&
2075               element_type != DBUS_TYPE_UNIX_FD)
2076             {
2077               const DBusBasicValue **value;
2078               int n_elements;
2079
2080               value = va_arg (var_args, const DBusBasicValue**);
2081               n_elements = va_arg (var_args, int);
2082
2083               if (!dbus_message_iter_append_fixed_array (&array,
2084                                                          element_type,
2085                                                          value,
2086                                                          n_elements)) {
2087                 dbus_message_iter_abandon_container (&iter, &array);
2088                 goto failed;
2089               }
2090             }
2091           else if (_DBUS_TYPE_IS_STRINGLIKE (element_type))
2092             {
2093               const char ***value_p;
2094               const char **value;
2095               int n_elements;
2096               int i;
2097
2098               value_p = va_arg (var_args, const char***);
2099               n_elements = va_arg (var_args, int);
2100
2101               value = *value_p;
2102
2103               i = 0;
2104               while (i < n_elements)
2105                 {
2106                   if (!dbus_message_iter_append_basic (&array,
2107                                                        element_type,
2108                                                        &value[i])) {
2109                     dbus_message_iter_abandon_container (&iter, &array);
2110                     goto failed;
2111                   }
2112                   ++i;
2113                 }
2114             }
2115           else
2116             {
2117               _dbus_warn ("arrays of %s can't be appended with %s for now",
2118                           _dbus_type_to_string (element_type),
2119                           _DBUS_FUNCTION_NAME);
2120               dbus_message_iter_abandon_container (&iter, &array);
2121               goto failed;
2122             }
2123
2124           if (!dbus_message_iter_close_container (&iter, &array))
2125             goto failed;
2126         }
2127 #ifndef DBUS_DISABLE_CHECKS
2128       else
2129         {
2130           _dbus_warn ("type %s isn't supported yet in %s",
2131                       _dbus_type_to_string (type), _DBUS_FUNCTION_NAME);
2132           goto failed;
2133         }
2134 #endif
2135
2136       type = va_arg (var_args, int);
2137     }
2138
2139   return TRUE;
2140
2141  failed:
2142   return FALSE;
2143 }
2144
2145 /**
2146  * Gets arguments from a message given a variable argument list.  The
2147  * supported types include those supported by
2148  * dbus_message_append_args(); that is, basic types and arrays of
2149  * fixed-length basic types.  The arguments are the same as they would
2150  * be for dbus_message_iter_get_basic() or
2151  * dbus_message_iter_get_fixed_array().
2152  *
2153  * In addition to those types, arrays of string, object path, and
2154  * signature are supported; but these are returned as allocated memory
2155  * and must be freed with dbus_free_string_array(), while the other
2156  * types are returned as const references. To get a string array
2157  * pass in "char ***array_location" and "int *n_elements".
2158  *
2159  * Similar to dbus_message_get_fixed_array() this function does not
2160  * support arrays of type DBUS_TYPE_UNIX_FD. If you need to parse
2161  * messages with arrays of Unix file descriptors you need to recurse
2162  * into the array manually.
2163  *
2164  * Unix file descriptors that are read with this function will have
2165  * the FD_CLOEXEC flag set. If you need them without this flag set,
2166  * make sure to unset it with fcntl().
2167  *
2168  * The variable argument list should contain the type of the argument
2169  * followed by a pointer to where the value should be stored. The list
2170  * is terminated with #DBUS_TYPE_INVALID.
2171  *
2172  * Except for string arrays, the returned values are constant; do not
2173  * free them. They point into the #DBusMessage.
2174  *
2175  * If the requested arguments are not present, or do not have the
2176  * requested types, then an error will be set.
2177  *
2178  * If more arguments than requested are present, the requested
2179  * arguments are returned and the extra arguments are ignored.
2180  *
2181  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
2182  *
2183  * @param message the message
2184  * @param error error to be filled in on failure
2185  * @param first_arg_type the first argument type
2186  * @param ... location for first argument value, then list of type-location pairs
2187  * @returns #FALSE if the error was set
2188  */
2189 dbus_bool_t
2190 dbus_message_get_args (DBusMessage     *message,
2191                        DBusError       *error,
2192                        int              first_arg_type,
2193                        ...)
2194 {
2195   dbus_bool_t retval;
2196   va_list var_args;
2197
2198   _dbus_return_val_if_fail (message != NULL, FALSE);
2199   _dbus_return_val_if_error_is_set (error, FALSE);
2200
2201   va_start (var_args, first_arg_type);
2202   retval = dbus_message_get_args_valist (message, error, first_arg_type, var_args);
2203   va_end (var_args);
2204
2205   return retval;
2206 }
2207
2208 /**
2209  * Like dbus_message_get_args but takes a va_list for use by language bindings.
2210  *
2211  * @see dbus_message_get_args
2212  * @param message the message
2213  * @param error error to be filled in
2214  * @param first_arg_type type of the first argument
2215  * @param var_args return location for first argument, followed by list of type/location pairs
2216  * @returns #FALSE if error was set
2217  */
2218 dbus_bool_t
2219 dbus_message_get_args_valist (DBusMessage     *message,
2220                               DBusError       *error,
2221                               int              first_arg_type,
2222                               va_list          var_args)
2223 {
2224   DBusMessageIter iter;
2225
2226   _dbus_return_val_if_fail (message != NULL, FALSE);
2227   _dbus_return_val_if_error_is_set (error, FALSE);
2228
2229   dbus_message_iter_init (message, &iter);
2230   return _dbus_message_iter_get_args_valist (&iter, error, first_arg_type, var_args);
2231 }
2232
2233 static void
2234 _dbus_message_iter_init_common (DBusMessage         *message,
2235                                 DBusMessageRealIter *real,
2236                                 int                  iter_type)
2237 {
2238   /* If these static assertions fail on your platform, report it as a bug. */
2239   _DBUS_STATIC_ASSERT (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
2240   _DBUS_STATIC_ASSERT (_DBUS_ALIGNOF (DBusMessageRealIter) <=
2241       _DBUS_ALIGNOF (DBusMessageIter));
2242   /* A failure of these two assertions would indicate that we've broken
2243    * ABI on this platform since 1.10.0. */
2244   _DBUS_STATIC_ASSERT (sizeof (DBusMessageIter_1_10_0) ==
2245       sizeof (DBusMessageIter));
2246   _DBUS_STATIC_ASSERT (_DBUS_ALIGNOF (DBusMessageIter_1_10_0) ==
2247       _DBUS_ALIGNOF (DBusMessageIter));
2248   /* If this static assertion fails, it means the DBusMessageIter struct
2249    * is not "packed", which might result in "iter = other_iter" not copying
2250    * every byte. */
2251   _DBUS_STATIC_ASSERT (sizeof (DBusMessageIter) ==
2252       10 * sizeof (void *) + sizeof (dbus_uint32_t) + 3 * sizeof (int));
2253
2254   /* Since the iterator will read or write who-knows-what from the
2255    * message, we need to get in the right byte order
2256    */
2257   ensure_byte_order (message);
2258
2259   real->message = message;
2260   real->changed_stamp = message->changed_stamp;
2261   real->iter_type = iter_type;
2262   real->sig_refcount = 0;
2263 }
2264
2265 /**
2266  * Initializes a #DBusMessageIter for reading the arguments of the
2267  * message passed in.
2268  *
2269  * When possible, dbus_message_get_args() is much more convenient.
2270  * Some types of argument can only be read with #DBusMessageIter
2271  * however.
2272  *
2273  * The easiest way to iterate is like this:
2274  * @code
2275  * dbus_message_iter_init (message, &iter);
2276  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
2277  *   dbus_message_iter_next (&iter);
2278  * @endcode
2279  *
2280  * #DBusMessageIter contains no allocated memory; it need not be
2281  * freed, and can be copied by assignment or memcpy().
2282  *
2283  * @param message the message
2284  * @param iter pointer to an iterator to initialize
2285  * @returns #FALSE if the message has no arguments
2286  */
2287 dbus_bool_t
2288 dbus_message_iter_init (DBusMessage     *message,
2289                         DBusMessageIter *iter)
2290 {
2291   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2292   const DBusString *type_str;
2293   int type_pos;
2294
2295   BUILD_BUG_ON (sizeof(DBusMessageIter) != sizeof(DBusMessageRealIter));
2296
2297   _dbus_return_val_if_fail (message != NULL, FALSE);
2298   _dbus_return_val_if_fail (iter != NULL, FALSE);
2299
2300   get_const_signature (message, &type_str, &type_pos);
2301
2302   _dbus_message_iter_init_common (message, real,
2303                                   DBUS_MESSAGE_ITER_TYPE_READER);
2304
2305   _dbus_type_reader_init (&real->u.reader,
2306                                    _dbus_header_get_byte_order (&message->header),
2307                                    type_str, type_pos,
2308                                    &message->body,
2309                                    0);
2310
2311   if (_dbus_message_is_gvariant (message))
2312     _dbus_type_reader_gvariant_init (&real->u.reader, message);
2313
2314   return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
2315 }
2316
2317 /**
2318  * Checks if an iterator has any more fields.
2319  *
2320  * @param iter the message iter
2321  * @returns #TRUE if there are more fields following
2322  */
2323 dbus_bool_t
2324 dbus_message_iter_has_next (DBusMessageIter *iter)
2325 {
2326   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2327
2328   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
2329   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2330
2331   return _dbus_type_reader_has_next (&real->u.reader);
2332 }
2333
2334 /**
2335  * Moves the iterator to the next field, if any. If there's no next
2336  * field, returns #FALSE. If the iterator moves forward, returns
2337  * #TRUE.
2338  *
2339  * @param iter the message iter
2340  * @returns #TRUE if the iterator was moved to the next field
2341  */
2342 dbus_bool_t
2343 dbus_message_iter_next (DBusMessageIter *iter)
2344 {
2345   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2346
2347   _dbus_return_val_if_fail (_dbus_message_iter_check (real), FALSE);
2348   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2349
2350   return _dbus_type_reader_next (&real->u.reader);
2351 }
2352
2353 /**
2354  * Returns the argument type of the argument that the message iterator
2355  * points to. If the iterator is at the end of the message, returns
2356  * #DBUS_TYPE_INVALID. You can thus write a loop as follows:
2357  *
2358  * @code
2359  * dbus_message_iter_init (message, &iter);
2360  * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
2361  *   dbus_message_iter_next (&iter);
2362  * @endcode
2363  *
2364  * @param iter the message iter
2365  * @returns the argument type
2366  */
2367 int
2368 dbus_message_iter_get_arg_type (DBusMessageIter *iter)
2369 {
2370   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2371
2372   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2373   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, FALSE);
2374
2375   return _dbus_type_reader_get_current_type (&real->u.reader);
2376 }
2377
2378 /**
2379  * Returns the element type of the array that the message iterator
2380  * points to. Note that you need to check that the iterator points to
2381  * an array prior to using this function.
2382  *
2383  * @param iter the message iter
2384  * @returns the array element type
2385  */
2386 int
2387 dbus_message_iter_get_element_type (DBusMessageIter *iter)
2388 {
2389   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2390
2391   _dbus_return_val_if_fail (_dbus_message_iter_check (real), DBUS_TYPE_INVALID);
2392   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_READER, DBUS_TYPE_INVALID);
2393   _dbus_return_val_if_fail (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY, DBUS_TYPE_INVALID);
2394
2395   return _dbus_type_reader_get_element_type (&real->u.reader);
2396 }
2397
2398 /**
2399  * Recurses into a container value when reading values from a message,
2400  * initializing a sub-iterator to use for traversing the child values
2401  * of the container.
2402  *
2403  * Note that this recurses into a value, not a type, so you can only
2404  * recurse if the value exists. The main implication of this is that
2405  * if you have for example an empty array of array of int32, you can
2406  * recurse into the outermost array, but it will have no values, so
2407  * you won't be able to recurse further. There's no array of int32 to
2408  * recurse into.
2409  *
2410  * If a container is an array of fixed-length types (except Unix file
2411  * descriptors), it is much more efficient to use
2412  * dbus_message_iter_get_fixed_array() to get the whole array in one
2413  * shot, rather than individually walking over the array elements.
2414  *
2415  * Be sure you have somehow checked that
2416  * dbus_message_iter_get_arg_type() matches the type you are expecting
2417  * to recurse into. Results of this function are undefined if there is
2418  * no container to recurse into at the current iterator position.
2419  *
2420  * @param iter the message iterator
2421  * @param sub the sub-iterator to initialize
2422  */
2423 void
2424 dbus_message_iter_recurse (DBusMessageIter  *iter,
2425                            DBusMessageIter  *sub)
2426 {
2427   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2428   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
2429
2430   _dbus_return_if_fail (_dbus_message_iter_check (real));
2431   _dbus_return_if_fail (sub != NULL);
2432
2433   *real_sub = *real;
2434   _dbus_type_reader_recurse (&real->u.reader, &real_sub->u.reader);
2435 }
2436
2437 /**
2438  * Returns the current signature of a message iterator.  This
2439  * is useful primarily for dealing with variants; one can
2440  * recurse into a variant and determine the signature of
2441  * the variant's value.
2442  *
2443  * The returned string must be freed with dbus_free().
2444  *
2445  * @param iter the message iterator
2446  * @returns the contained signature, or NULL if out of memory
2447  */
2448 char *
2449 dbus_message_iter_get_signature (DBusMessageIter *iter)
2450 {
2451   const DBusString *sig;
2452   DBusString retstr;
2453   char *ret;
2454   int start, len;
2455   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2456
2457   _dbus_return_val_if_fail (_dbus_message_iter_check (real), NULL);
2458
2459   if (!_dbus_string_init (&retstr))
2460     return NULL;
2461
2462   _dbus_type_reader_get_signature (&real->u.reader, &sig,
2463                                    &start, &len);
2464   if (!_dbus_string_append_len (&retstr,
2465                                 _dbus_string_get_const_data (sig) + start,
2466                                 len))
2467     return NULL;
2468   if (!_dbus_string_steal_data (&retstr, &ret))
2469     return NULL;
2470   _dbus_string_free (&retstr);
2471   return ret;
2472 }
2473
2474 /**
2475  * Reads a basic-typed value from the message iterator.
2476  * Basic types are the non-containers such as integer and string.
2477  *
2478  * The value argument should be the address of a location to store
2479  * the returned value. So for int32 it should be a "dbus_int32_t*"
2480  * and for string a "const char**". The returned value is
2481  * by reference and should not be freed.
2482  *
2483  * This call duplicates Unix file descriptors when reading them. It is
2484  * your job to close them when you don't need them anymore.
2485  *
2486  * Unix file descriptors that are read with this function will have
2487  * the FD_CLOEXEC flag set. If you need them without this flag set,
2488  * make sure to unset it with fcntl().
2489  *
2490  * Be sure you have somehow checked that
2491  * dbus_message_iter_get_arg_type() matches the type you are
2492  * expecting, or you'll crash when you try to use an integer as a
2493  * string or something.
2494  *
2495  * To read any container type (array, struct, dict) you will need to
2496  * recurse into the container with dbus_message_iter_recurse().  If
2497  * the container is an array of fixed-length values (except Unix file
2498  * descriptors), you can get all the array elements at once with
2499  * dbus_message_iter_get_fixed_array(). Otherwise, you have to iterate
2500  * over the container's contents one value at a time.
2501  *
2502  * All basic-typed values are guaranteed to fit in a #DBusBasicValue,
2503  * so in versions of libdbus that have that type, you can write code like this:
2504  *
2505  * @code
2506  * DBusBasicValue value;
2507  * int type;
2508  * dbus_message_iter_get_basic (&read_iter, &value);
2509  * type = dbus_message_iter_get_arg_type (&read_iter);
2510  * dbus_message_iter_append_basic (&write_iter, type, &value);
2511  * @endcode
2512  *
2513  * (All D-Bus basic types are either numeric and 8 bytes or smaller, or
2514  * behave like a string; so in older versions of libdbus, DBusBasicValue
2515  * can be replaced with union { char *string; unsigned char bytes[8]; },
2516  * for instance.)
2517  *
2518  * @param iter the iterator
2519  * @param value location to store the value
2520  */
2521 void
2522 dbus_message_iter_get_basic (DBusMessageIter  *iter,
2523                              void             *value)
2524 {
2525   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2526
2527   _dbus_return_if_fail (_dbus_message_iter_check (real));
2528   _dbus_return_if_fail (value != NULL);
2529
2530   if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_UNIX_FD)
2531     {
2532 #ifdef HAVE_UNIX_FD_PASSING
2533       DBusBasicValue idx;
2534
2535       _dbus_type_reader_read_basic(&real->u.reader, &idx);
2536
2537       if (idx.u32 >= real->message->n_unix_fds) {
2538         /* Hmm, we cannot really signal an error here, so let's make
2539            sure to return an invalid fd. */
2540         *((int*) value) = -1;
2541         return;
2542       }
2543
2544       *((int*) value) = _dbus_dup(real->message->unix_fds[idx.u32], NULL);
2545 #else
2546       *((int*) value) = -1;
2547 #endif
2548     }
2549   else
2550     {
2551       _dbus_type_reader_read_basic (&real->u.reader,
2552                                     value);
2553     }
2554 }
2555
2556 /**
2557  * Returns the number of elements in the array-typed value pointed
2558  * to by the iterator.
2559  * Note that this function is O(1) for arrays of fixed-size types
2560  * but O(n) for arrays of variable-length types such as strings,
2561  * so it may be a bad idea to use it.
2562  *
2563  * @param iter the iterator
2564  * @returns the number of elements in the array
2565  */
2566 int
2567 dbus_message_iter_get_element_count (DBusMessageIter *iter)
2568 {
2569   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2570   DBusTypeReader array;
2571   int element_type;
2572   int n_elements = 0;
2573
2574   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2575   _dbus_return_val_if_fail (_dbus_type_reader_get_current_type (&real->u.reader)
2576                             == DBUS_TYPE_ARRAY, 0);
2577
2578   element_type = _dbus_type_reader_get_element_type (&real->u.reader);
2579   _dbus_type_reader_recurse (&real->u.reader, &array);
2580   if (dbus_type_is_fixed (element_type))
2581     {
2582       int alignment = _dbus_type_get_alignment (element_type);
2583       int total_len = _dbus_type_reader_get_array_length (&array);
2584       n_elements = total_len / alignment;
2585     }
2586   else
2587     {
2588       while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
2589         {
2590           ++n_elements;
2591           _dbus_type_reader_next (&array);
2592         }
2593     }
2594
2595    return n_elements;
2596 }
2597
2598 /**
2599  * Returns the number of bytes in the array as marshaled in the wire
2600  * protocol. The iterator must currently be inside an array-typed
2601  * value.
2602  *
2603  * This function is deprecated on the grounds that it is stupid.  Why
2604  * would you want to know how many bytes are in the array as marshaled
2605  * in the wire protocol?  Use dbus_message_iter_get_element_count() instead.
2606  *
2607  * @param iter the iterator
2608  * @returns the number of bytes in the array
2609  */
2610 int
2611 dbus_message_iter_get_array_len (DBusMessageIter *iter)
2612 {
2613   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2614
2615   _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
2616
2617   return _dbus_type_reader_get_array_length (&real->u.reader);
2618 }
2619
2620 /**
2621  * Reads a block of fixed-length values from the message iterator.
2622  * Fixed-length values are those basic types that are not string-like,
2623  * such as integers, bool, double. The returned block will be from the
2624  * current position in the array until the end of the array.
2625  *
2626  * There is one exception here: although DBUS_TYPE_UNIX_FD is
2627  * considered a 'fixed' type arrays of this type may not be read with
2628  * this function.
2629  *
2630  * The message iter should be "in" the array (that is, you recurse into the
2631  * array, and then you call dbus_message_iter_get_fixed_array() on the
2632  * "sub-iterator" created by dbus_message_iter_recurse()).
2633  *
2634  * The value argument should be the address of a location to store the
2635  * returned array. So for int32 it should be a "const dbus_int32_t**"
2636  * The returned value is by reference and should not be freed.
2637  *
2638  * This function should only be used if dbus_type_is_fixed() returns
2639  * #TRUE for the element type.
2640  *
2641  * If an array's elements are not fixed in size, you have to recurse
2642  * into the array with dbus_message_iter_recurse() and read the
2643  * elements one by one.
2644  *
2645  * Because the array is not copied, this function runs in constant
2646  * time and is fast; it's much preferred over walking the entire array
2647  * with an iterator. (However, you can always use
2648  * dbus_message_iter_recurse(), even for fixed-length types;
2649  * dbus_message_iter_get_fixed_array() is just an optimization.)
2650  *
2651  * @param iter the iterator
2652  * @param value location to store the block
2653  * @param n_elements number of elements in the block
2654  */
2655 void
2656 dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
2657                                    void             *value,
2658                                    int              *n_elements)
2659 {
2660   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2661 #ifndef DBUS_DISABLE_CHECKS
2662   int subtype = _dbus_type_reader_get_current_type(&real->u.reader);
2663
2664   _dbus_return_if_fail (_dbus_message_iter_check (real));
2665   _dbus_return_if_fail (value != NULL);
2666   _dbus_return_if_fail ((subtype == DBUS_TYPE_INVALID) ||
2667                         (dbus_type_is_fixed (subtype) && subtype != DBUS_TYPE_UNIX_FD));
2668 #endif
2669
2670   _dbus_type_reader_read_fixed_multi (&real->u.reader,
2671                                       value, n_elements);
2672 }
2673
2674 /**
2675  * Initializes a #DBusMessageIter for appending arguments to the end
2676  * of a message.
2677  *
2678  * @todo If appending any of the arguments fails due to lack of
2679  * memory, the message is hosed and you have to start over building
2680  * the whole message.
2681  *
2682  * @param message the message
2683  * @param iter pointer to an iterator to initialize
2684  */
2685 void
2686 dbus_message_iter_init_append (DBusMessage     *message,
2687                                DBusMessageIter *iter)
2688 {
2689   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2690
2691   _dbus_return_if_fail (message != NULL);
2692   _dbus_return_if_fail (iter != NULL);
2693
2694   _dbus_message_iter_init_common (message, real,
2695                                   DBUS_MESSAGE_ITER_TYPE_WRITER);
2696
2697   /* We create the signature string and point iterators at it "on demand"
2698    * when a value is actually appended. That means that init() never fails
2699    * due to OOM.
2700    */
2701   _dbus_type_writer_gvariant_init_types_delayed (
2702                               &real->u.writer,
2703                               _dbus_header_get_byte_order (&message->header),
2704                               &message->body,
2705                               _dbus_string_get_length (&message->body),
2706                               _dbus_message_is_gvariant (message),
2707                               &message->gvariant_body_last_offset,
2708                               &message->gvariant_body_last_pos);
2709 }
2710
2711 /**
2712  * Creates a temporary signature string containing the current
2713  * signature, stores it in the iterator, and points the iterator to
2714  * the end of it. Used any time we write to the message.
2715  *
2716  * @param real an iterator without a type_str
2717  * @returns #FALSE if no memory
2718  */
2719 static dbus_bool_t
2720 _dbus_message_iter_open_signature (DBusMessageRealIter *real)
2721 {
2722   DBusString *str;
2723   const DBusString *current_sig;
2724   int current_sig_pos;
2725
2726   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2727
2728   if (real->u.writer.type_str != NULL)
2729     {
2730       _dbus_assert (real->sig_refcount > 0);
2731       real->sig_refcount += 1;
2732       return TRUE;
2733     }
2734
2735   str = dbus_new (DBusString, 1);
2736   if (str == NULL)
2737     return FALSE;
2738
2739   if (!_dbus_header_get_field_raw (&real->message->header,
2740                                    DBUS_HEADER_FIELD_SIGNATURE,
2741                                    &current_sig, &current_sig_pos))
2742     current_sig = NULL;
2743
2744   if (current_sig)
2745     {
2746       int current_len;
2747       int additional_size_for_len = 0;
2748
2749       if (!real->u.writer.gvariant)
2750       {
2751         current_len = _dbus_string_get_byte (current_sig, current_sig_pos);
2752         current_sig_pos += 1; /* move on to sig data */
2753         additional_size_for_len = 4;
2754       }
2755       else
2756       {
2757         /* GVariant has no length field, simply string */
2758         current_len = strlen (_dbus_string_get_const_data (current_sig) + current_sig_pos);
2759       }
2760
2761       if (!_dbus_string_init_preallocated (str, current_len + additional_size_for_len))
2762         {
2763           dbus_free (str);
2764           return FALSE;
2765         }
2766
2767       if (!_dbus_string_copy_len (current_sig, current_sig_pos, current_len,
2768                                   str, 0))
2769         {
2770           _dbus_string_free (str);
2771           dbus_free (str);
2772           return FALSE;
2773         }
2774     }
2775   else
2776     {
2777       if (!_dbus_string_init_preallocated (str, 4))
2778         {
2779           dbus_free (str);
2780           return FALSE;
2781         }
2782     }
2783
2784   real->sig_refcount = 1;
2785
2786   /* If this assertion failed, then str would be neither stored in u.writer
2787    * nor freed by this function, resulting in a memory leak. */
2788   _dbus_assert (real->u.writer.type_str == NULL);
2789   _dbus_type_writer_add_types (&real->u.writer,
2790                                str, _dbus_string_get_length (str));
2791   return TRUE;
2792 }
2793
2794 /**
2795  * Sets the new signature as the message signature, frees the
2796  * signature string, and marks the iterator as not having a type_str
2797  * anymore. Frees the signature even if it fails, so you can't
2798  * really recover from failure. Kinda busted.
2799  *
2800  * @param real an iterator without a type_str
2801  * @returns #FALSE if no memory
2802  */
2803 static dbus_bool_t
2804 _dbus_message_iter_close_signature (DBusMessageRealIter *real)
2805 {
2806   DBusString *str;
2807   const char *v_STRING;
2808   dbus_bool_t retval;
2809
2810   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2811   _dbus_assert (real->u.writer.type_str != NULL);
2812   _dbus_assert (real->sig_refcount > 0);
2813
2814   real->sig_refcount -= 1;
2815
2816   if (real->sig_refcount > 0)
2817     return TRUE;
2818   _dbus_assert (real->sig_refcount == 0);
2819
2820   retval = TRUE;
2821
2822   str = real->u.writer.type_str;
2823
2824   v_STRING = _dbus_string_get_const_data (str);
2825   if (!_dbus_header_set_field_basic (&real->message->header,
2826                                      DBUS_HEADER_FIELD_SIGNATURE,
2827                                      DBUS_TYPE_SIGNATURE,
2828                                      &v_STRING))
2829     retval = FALSE;
2830
2831   _dbus_type_writer_remove_types (&real->u.writer);
2832   _dbus_string_free (str);
2833   dbus_free (str);
2834
2835   return retval;
2836 }
2837
2838 /**
2839  * Frees the signature string and marks the iterator as not having a
2840  * type_str anymore.  Since the new signature is not set, the message
2841  * will generally be hosed after this is called.
2842  *
2843  * @param real an iterator without a type_str
2844  */
2845 static void
2846 _dbus_message_iter_abandon_signature (DBusMessageRealIter *real)
2847 {
2848   DBusString *str;
2849
2850   _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
2851   _dbus_assert (real->u.writer.type_str != NULL);
2852   _dbus_assert (real->sig_refcount > 0);
2853
2854   real->sig_refcount -= 1;
2855
2856   if (real->sig_refcount > 0)
2857     return;
2858   _dbus_assert (real->sig_refcount == 0);
2859
2860   str = real->u.writer.type_str;
2861
2862   _dbus_type_writer_remove_types (&real->u.writer);
2863   _dbus_string_free (str);
2864   dbus_free (str);
2865 }
2866
2867 #ifndef DBUS_DISABLE_CHECKS
2868 static dbus_bool_t
2869 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
2870 {
2871   if (!_dbus_message_iter_check (iter))
2872     return FALSE;
2873
2874   if (iter->message->locked)
2875     {
2876       _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)");
2877       return FALSE;
2878     }
2879
2880   return TRUE;
2881 }
2882 #endif /* DBUS_DISABLE_CHECKS */
2883
2884 #ifdef HAVE_UNIX_FD_PASSING
2885 static int *
2886 expand_fd_array(DBusMessage *m,
2887                 unsigned     n)
2888 {
2889   _dbus_assert(m);
2890
2891   /* This makes space for adding n new fds to the array and returns a
2892      pointer to the place were the first fd should be put. */
2893
2894   if (m->n_unix_fds + n > m->n_unix_fds_allocated)
2895     {
2896       unsigned k;
2897       int *p;
2898
2899       /* Make twice as much space as necessary */
2900       k = (m->n_unix_fds + n) * 2;
2901
2902       /* Allocate at least four */
2903       if (k < 4)
2904         k = 4;
2905
2906       p = dbus_realloc(m->unix_fds, k * sizeof(int));
2907       if (p == NULL)
2908         return NULL;
2909
2910       m->unix_fds = p;
2911       m->n_unix_fds_allocated = k;
2912     }
2913
2914   return m->unix_fds + m->n_unix_fds;
2915 }
2916 #endif
2917
2918 /**
2919  * Appends a basic-typed value to the message. The basic types are the
2920  * non-container types such as integer and string.
2921  *
2922  * The "value" argument should be the address of a basic-typed value.
2923  * So for string, const char**. For integer, dbus_int32_t*.
2924  *
2925  * For Unix file descriptors this function will internally duplicate
2926  * the descriptor you passed in. Hence you may close the descriptor
2927  * immediately after this call.
2928  *
2929  * @todo If this fails due to lack of memory, the message is hosed and
2930  * you have to start over building the whole message.
2931  *
2932  * @param iter the append iterator
2933  * @param type the type of the value
2934  * @param value the address of the value
2935  * @returns #FALSE if not enough memory
2936  */
2937 dbus_bool_t
2938 dbus_message_iter_append_basic (DBusMessageIter *iter,
2939                                 int              type,
2940                                 const void      *value)
2941 {
2942   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
2943   dbus_bool_t ret;
2944
2945   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
2946   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
2947   _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
2948   _dbus_return_val_if_fail (value != NULL, FALSE);
2949
2950 #ifndef DBUS_DISABLE_CHECKS
2951   switch (type)
2952     {
2953       DBusString str;
2954       DBusValidity signature_validity;
2955       const char * const *string_p;
2956       const dbus_bool_t *bool_p;
2957
2958       case DBUS_TYPE_STRING:
2959         string_p = value;
2960         _dbus_return_val_if_fail (_dbus_check_is_valid_utf8 (*string_p), FALSE);
2961         break;
2962
2963       case DBUS_TYPE_OBJECT_PATH:
2964         string_p = value;
2965         _dbus_return_val_if_fail (_dbus_check_is_valid_path (*string_p), FALSE);
2966         break;
2967
2968       case DBUS_TYPE_SIGNATURE:
2969         string_p = value;
2970         _dbus_string_init_const (&str, *string_p);
2971         signature_validity = _dbus_validate_signature_with_reason (&str,
2972                                                                    0,
2973                                                                    _dbus_string_get_length (&str));
2974
2975         if (signature_validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
2976           return FALSE;
2977
2978         _dbus_return_val_if_fail (signature_validity == DBUS_VALID, FALSE);
2979         break;
2980
2981       case DBUS_TYPE_BOOLEAN:
2982         bool_p = value;
2983         _dbus_return_val_if_fail (*bool_p == 0 || *bool_p == 1, FALSE);
2984         break;
2985
2986       default:
2987           {
2988             /* nothing to check, all possible values are allowed */
2989           }
2990     }
2991 #endif
2992
2993   if (!_dbus_message_iter_open_signature (real))
2994     return FALSE;
2995
2996   if (type == DBUS_TYPE_UNIX_FD)
2997     {
2998 #ifdef HAVE_UNIX_FD_PASSING
2999       int *fds;
3000       dbus_uint32_t u;
3001
3002       ret = FALSE;
3003
3004       /* First step, include the fd in the fd list of this message */
3005       if (!(fds = expand_fd_array(real->message, 1)))
3006         goto out;
3007
3008       *fds = _dbus_dup(*(int*) value, NULL);
3009       if (*fds < 0)
3010         goto out;
3011
3012       u = real->message->n_unix_fds;
3013
3014       /* Second step, write the index to the fd */
3015       if (!(ret = _dbus_type_writer_write_basic (&real->u.writer, DBUS_TYPE_UNIX_FD, &u))) {
3016         _dbus_close(*fds, NULL);
3017         goto out;
3018       }
3019
3020       real->message->n_unix_fds += 1;
3021       u += 1;
3022
3023       /* Final step, update the header accordingly */
3024       ret = _dbus_header_set_field_basic (&real->message->header,
3025                                           DBUS_HEADER_FIELD_UNIX_FDS,
3026                                           DBUS_TYPE_UINT32,
3027                                           &u);
3028
3029       /* If any of these operations fail the message is
3030          hosed. However, no memory or fds should be leaked since what
3031          has been added to message has been added to the message, and
3032          can hence be accounted for when the message is being
3033          freed. */
3034 #else
3035       ret = FALSE;
3036       /* This is redundant (we could just fall through), but it avoids
3037        * -Wunused-label in builds that don't HAVE_UNIX_FD_PASSING */
3038       goto out;
3039 #endif
3040     }
3041   else
3042     {
3043       ret = _dbus_type_writer_write_basic (&real->u.writer, type, value);
3044     }
3045
3046 out:
3047   if (!_dbus_message_iter_close_signature (real))
3048     ret = FALSE;
3049
3050   return ret;
3051 }
3052
3053 /**
3054  * Appends a block of fixed-length values to an array. The
3055  * fixed-length types are all basic types that are not string-like. So
3056  * int32, double, bool, etc. (Unix file descriptors however are not
3057  * supported.) You must call dbus_message_iter_open_container() to
3058  * open an array of values before calling this function. You may call
3059  * this function multiple times (and intermixed with calls to
3060  * dbus_message_iter_append_basic()) for the same array.
3061  *
3062  * The "value" argument should be the address of the array.  So for
3063  * integer, "dbus_int32_t**" is expected for example.
3064  *
3065  * @warning in C, given "int array[]", "&array == array" (the
3066  * comp.lang.c FAQ says otherwise, but gcc and the FAQ don't agree).
3067  * So if you're using an array instead of a pointer you have to create
3068  * a pointer variable, assign the array to it, then take the address
3069  * of the pointer variable.
3070  * @code
3071  * const dbus_int32_t array[] = { 1, 2, 3 };
3072  * const dbus_int32_t *v_ARRAY = array;
3073  * if (!dbus_message_iter_append_fixed_array (&iter, DBUS_TYPE_INT32, &v_ARRAY, 3))
3074  *   fprintf (stderr, "No memory!\n");
3075  * @endcode
3076  * For strings it works to write const char *array = "Hello" and then
3077  * use &array though.
3078  *
3079  * @todo If this fails due to lack of memory, the message is hosed and
3080  * you have to start over building the whole message.
3081  *
3082  * @param iter the append iterator
3083  * @param element_type the type of the array elements
3084  * @param value the address of the array
3085  * @param n_elements the number of elements to append
3086  * @returns #FALSE if not enough memory
3087  */
3088 dbus_bool_t
3089 dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
3090                                       int              element_type,
3091                                       const void      *value,
3092                                       int              n_elements)
3093 {
3094   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3095   dbus_bool_t ret;
3096
3097   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
3098   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3099   _dbus_return_val_if_fail (dbus_type_is_fixed (element_type) && element_type != DBUS_TYPE_UNIX_FD, FALSE);
3100   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
3101   _dbus_return_val_if_fail (value != NULL, FALSE);
3102   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
3103   _dbus_return_val_if_fail (n_elements <=
3104                             DBUS_MAXIMUM_ARRAY_LENGTH / _dbus_type_get_alignment (element_type),
3105                             FALSE);
3106
3107 #ifndef DBUS_DISABLE_CHECKS
3108   if (element_type == DBUS_TYPE_BOOLEAN)
3109     {
3110       const dbus_bool_t * const *bools = value;
3111       int i;
3112
3113       for (i = 0; i < n_elements; i++)
3114         {
3115           _dbus_return_val_if_fail ((*bools)[i] == 0 || (*bools)[i] == 1, FALSE);
3116         }
3117     }
3118 #endif
3119
3120   ret = _dbus_type_writer_write_fixed_multi (&real->u.writer, element_type, value, n_elements);
3121
3122   return ret;
3123 }
3124
3125 /**
3126  * Appends a container-typed value to the message. On success, you are
3127  * required to append the contents of the container using the returned
3128  * sub-iterator, and then call
3129  * dbus_message_iter_close_container(). Container types are for
3130  * example struct, variant, and array. For variants, the
3131  * contained_signature should be the type of the single value inside
3132  * the variant. For structs and dict entries, contained_signature
3133  * should be #NULL; it will be set to whatever types you write into
3134  * the struct.  For arrays, contained_signature should be the type of
3135  * the array elements.
3136  *
3137  * @todo If this fails due to lack of memory, the message is hosed and
3138  * you have to start over building the whole message.
3139  *
3140  * If this function fails, the sub-iterator remains invalid, and must
3141  * not be closed with dbus_message_iter_close_container() or abandoned
3142  * with dbus_message_iter_abandon_container(). However, after this
3143  * function has either succeeded or failed, it is valid to call
3144  * dbus_message_iter_abandon_container_if_open().
3145  *
3146  * @param iter the append iterator
3147  * @param type the type of the value
3148  * @param contained_signature the type of container contents
3149  * @param sub sub-iterator to initialize
3150  * @returns #FALSE if not enough memory
3151  */
3152 dbus_bool_t
3153 dbus_message_iter_open_container (DBusMessageIter *iter,
3154                                   int              type,
3155                                   const char      *contained_signature,
3156                                   DBusMessageIter *sub)
3157 {
3158   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3159   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3160   DBusString contained_str;
3161   DBusValidity contained_signature_validity;
3162   dbus_bool_t ret;
3163
3164   _dbus_return_val_if_fail (sub != NULL, FALSE);
3165   /* Do our best to make sure the sub-iterator doesn't contain something
3166    * valid-looking on failure */
3167   _dbus_message_real_iter_zero (real_sub);
3168
3169   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
3170   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3171   _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
3172   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
3173                              contained_signature == NULL) ||
3174                             (type == DBUS_TYPE_DICT_ENTRY &&
3175                              contained_signature == NULL) ||
3176                             (type == DBUS_TYPE_VARIANT &&
3177                              contained_signature != NULL) ||
3178                             (type == DBUS_TYPE_ARRAY &&
3179                              contained_signature != NULL), FALSE);
3180
3181   /* this would fail if the contained_signature is a dict entry, since
3182    * dict entries are invalid signatures standalone (they must be in
3183    * an array)
3184    */
3185   if (contained_signature != NULL)
3186     {
3187       _dbus_string_init_const (&contained_str, contained_signature);
3188       contained_signature_validity = _dbus_validate_signature_with_reason (&contained_str,
3189           0,
3190           _dbus_string_get_length (&contained_str));
3191
3192       if (contained_signature_validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
3193         return FALSE;
3194     }
3195   else
3196     {
3197       /* just some placeholder value */
3198       contained_signature_validity = DBUS_VALID_BUT_INCOMPLETE;
3199     }
3200
3201   _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
3202                             contained_signature == NULL ||
3203                             contained_signature_validity == DBUS_VALID,
3204                             FALSE);
3205
3206   if (!_dbus_message_iter_open_signature (real))
3207     return FALSE;
3208
3209   ret = FALSE;
3210   *real_sub = *real;
3211
3212   if (contained_signature != NULL)
3213     {
3214       _dbus_string_init_const (&contained_str, contained_signature);
3215
3216       ret = _dbus_type_writer_recurse (&real->u.writer,
3217                                        type,
3218                                        &contained_str, 0,
3219                                        &real_sub->u.writer);
3220     }
3221   else
3222     {
3223       ret = _dbus_type_writer_recurse (&real->u.writer,
3224                                        type,
3225                                        NULL, 0,
3226                                        &real_sub->u.writer);
3227     }
3228
3229   if (!ret)
3230     _dbus_message_iter_abandon_signature (real);
3231
3232   return ret;
3233 }
3234
3235
3236 /**
3237  * Closes a container-typed value appended to the message; may write
3238  * out more information to the message known only after the entire
3239  * container is written, and may free resources created by
3240  * dbus_message_iter_open_container().
3241  *
3242  * Even if this function fails due to lack of memory, the sub-iterator sub
3243  * has been closed and invalidated. It must not be closed again with this
3244  * function, or abandoned with dbus_message_iter_abandon_container().
3245  * However, it remains valid to call
3246  * dbus_message_iter_abandon_container_if_open().
3247  *
3248  * @todo If this fails due to lack of memory, the message is hosed and
3249  * you have to start over building the whole message.
3250  *
3251  * @param iter the append iterator
3252  * @param sub sub-iterator to close
3253  * @returns #FALSE if not enough memory
3254  */
3255 dbus_bool_t
3256 dbus_message_iter_close_container (DBusMessageIter *iter,
3257                                    DBusMessageIter *sub)
3258 {
3259   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3260   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3261   dbus_bool_t ret;
3262
3263   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
3264   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3265   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real_sub), FALSE);
3266   _dbus_return_val_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
3267
3268   ret = _dbus_type_writer_unrecurse (&real->u.writer,
3269                                      &real_sub->u.writer);
3270   _dbus_message_real_iter_zero (real_sub);
3271
3272   if (!_dbus_message_iter_close_signature (real))
3273     ret = FALSE;
3274
3275   return ret;
3276 }
3277
3278 /**
3279  * Abandons creation of a contained-typed value and frees resources created
3280  * by dbus_message_iter_open_container().  Once this returns, the message
3281  * is hosed and you have to start over building the whole message.
3282  *
3283  * This should only be used to abandon creation of a message when you have
3284  * open containers.
3285  *
3286  * @param iter the append iterator
3287  * @param sub sub-iterator to close
3288  */
3289 void
3290 dbus_message_iter_abandon_container (DBusMessageIter *iter,
3291                                      DBusMessageIter *sub)
3292 {
3293   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3294   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3295
3296 #ifndef DBUS_DISABLE_CHECKS
3297   _dbus_return_if_fail (_dbus_message_iter_append_check (real));
3298   _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3299   _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
3300   _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3301 #endif
3302
3303   _dbus_message_iter_abandon_signature (real);
3304   _dbus_message_real_iter_zero (real_sub);
3305 }
3306
3307 /**
3308  * Abandons creation of a contained-typed value and frees resources created
3309  * by dbus_message_iter_open_container().  Once this returns, the message
3310  * is hosed and you have to start over building the whole message.
3311  *
3312  * Unlike dbus_message_iter_abandon_container(), it is valid to call this
3313  * function on an iterator that was initialized with
3314  * #DBUS_MESSAGE_ITER_INIT_CLOSED, or an iterator that was already closed
3315  * or abandoned. However, it is not valid to call this function on
3316  * uninitialized memory. This is intended to be used in error cleanup
3317  * code paths, similar to this pattern:
3318  *
3319  *       DBusMessageIter outer = DBUS_MESSAGE_ITER_INIT_CLOSED;
3320  *       DBusMessageIter inner = DBUS_MESSAGE_ITER_INIT_CLOSED;
3321  *       dbus_bool_t result = FALSE;
3322  *
3323  *       if (!dbus_message_iter_open_container (iter, ..., &outer))
3324  *         goto out;
3325  *
3326  *       if (!dbus_message_iter_open_container (&outer, ..., &inner))
3327  *         goto out;
3328  *
3329  *       if (!dbus_message_iter_append_basic (&inner, ...))
3330  *         goto out;
3331  *
3332  *       if (!dbus_message_iter_close_container (&outer, ..., &inner))
3333  *         goto out;
3334  *
3335  *       if (!dbus_message_iter_close_container (iter, ..., &outer))
3336  *         goto out;
3337  *
3338  *       result = TRUE;
3339  *
3340  *     out:
3341  *       dbus_message_iter_abandon_container_if_open (&outer, &inner);
3342  *       dbus_message_iter_abandon_container_if_open (iter, &outer);
3343  *       return result;
3344  *
3345  * @param iter the append iterator
3346  * @param sub sub-iterator to close
3347  */
3348 void
3349 dbus_message_iter_abandon_container_if_open (DBusMessageIter *iter,
3350                                              DBusMessageIter *sub)
3351 {
3352   DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
3353   DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
3354
3355   /* If both the parent and the child are zeroed out, then either we didn't
3356    * even get as far as successfully recursing into the parent, or we already
3357    * closed both the child and the parent. For example, in the code sample
3358    * in the doc-comment above, this happens for
3359    * abandon_container_if_open (&outer, &inner) if the first open_container
3360    * call failed, or if we reached result = TRUE and fell through. */
3361   if (_dbus_message_real_iter_is_zeroed (real) &&
3362       _dbus_message_real_iter_is_zeroed (real_sub))
3363     return;
3364
3365 #ifndef DBUS_DISABLE_CHECKS
3366   /* If the child is not zeroed out, but the parent is, then something has
3367    * gone horribly wrong (in practice that would probably mean both are
3368    * uninitialized or corrupt, and the parent happens to have ended up
3369    * all-bytes-zero). */
3370   _dbus_return_if_fail (_dbus_message_iter_append_check (real));
3371   _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3372 #endif
3373
3374   /* If the parent is not zeroed out, but the child is, then either we did
3375    * not successfully open the child, or we already closed the child. This
3376    * means we do not own a reference to the parent's signature, so it would
3377    * be wrong to release it; so we must not call abandon_signature() here.
3378    * In the code sample in the doc-comment above, this happens for
3379    * abandon_container_if_open (&outer, &inner) if the second open_container
3380    * call failed, or if the second close_container call failed. */
3381   if (_dbus_message_real_iter_is_zeroed (real_sub))
3382     return;
3383
3384 #ifndef DBUS_DISABLE_CHECKS
3385   _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
3386   _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
3387 #endif
3388
3389   /* If neither the parent nor the child is zeroed out, then we genuinely
3390    * have an open container; close it. In the code sample in the doc-comment,
3391    * this happens for abandon_container_if_open (&outer, &inner) if the
3392    * append_basic call failed. */
3393   _dbus_message_iter_abandon_signature (real);
3394   _dbus_message_real_iter_zero (real_sub);
3395 }
3396
3397 /**
3398  * Sets a flag indicating that the message does not want a reply; if
3399  * this flag is set, the other end of the connection may (but is not
3400  * required to) optimize by not sending method return or error
3401  * replies. If this flag is set, there is no way to know whether the
3402  * message successfully arrived at the remote end. Normally you know a
3403  * message was received when you receive the reply to it.
3404  *
3405  * The flag is #FALSE by default, that is by default the other end is
3406  * required to reply.
3407  *
3408  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
3409  *
3410  * @param message the message
3411  * @param no_reply #TRUE if no reply is desired
3412  */
3413 void
3414 dbus_message_set_no_reply (DBusMessage *message,
3415                            dbus_bool_t  no_reply)
3416 {
3417   _dbus_return_if_fail (message != NULL);
3418   _dbus_return_if_fail (!message->locked);
3419
3420   _dbus_header_toggle_flag (&message->header,
3421                             DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
3422                             no_reply);
3423 }
3424
3425 /**
3426  * Returns #TRUE if the message does not expect
3427  * a reply.
3428  *
3429  * @param message the message
3430  * @returns #TRUE if the message sender isn't waiting for a reply
3431  */
3432 dbus_bool_t
3433 dbus_message_get_no_reply (DBusMessage *message)
3434 {
3435   _dbus_return_val_if_fail (message != NULL, FALSE);
3436
3437   return _dbus_header_get_flag (&message->header,
3438                                 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED);
3439 }
3440
3441 /**
3442  * Sets a flag indicating that an owner for the destination name will
3443  * be automatically started before the message is delivered. When this
3444  * flag is set, the message is held until a name owner finishes
3445  * starting up, or fails to start up. In case of failure, the reply
3446  * will be an error.
3447  *
3448  * The flag is set to #TRUE by default, i.e. auto starting is the default.
3449  *
3450  * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
3451  *
3452  * @param message the message
3453  * @param auto_start #TRUE if auto-starting is desired
3454  */
3455 void
3456 dbus_message_set_auto_start (DBusMessage *message,
3457                              dbus_bool_t  auto_start)
3458 {
3459   _dbus_return_if_fail (message != NULL);
3460   _dbus_return_if_fail (!message->locked);
3461
3462   _dbus_header_toggle_flag (&message->header,
3463                             DBUS_HEADER_FLAG_NO_AUTO_START,
3464                             !auto_start);
3465 }
3466
3467 /**
3468  * Returns #TRUE if the message will cause an owner for
3469  * destination name to be auto-started.
3470  *
3471  * @param message the message
3472  * @returns #TRUE if the message will use auto-start
3473  */
3474 dbus_bool_t
3475 dbus_message_get_auto_start (DBusMessage *message)
3476 {
3477   _dbus_return_val_if_fail (message != NULL, FALSE);
3478
3479   return !_dbus_header_get_flag (&message->header,
3480                                  DBUS_HEADER_FLAG_NO_AUTO_START);
3481 }
3482
3483
3484 /**
3485  * Sets the object path this message is being sent to (for
3486  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
3487  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
3488  *
3489  * The path must contain only valid characters as defined
3490  * in the D-Bus specification.
3491  *
3492  * @param message the message
3493  * @param object_path the path or #NULL to unset
3494  * @returns #FALSE if not enough memory
3495  */
3496 dbus_bool_t
3497 dbus_message_set_path (DBusMessage   *message,
3498                        const char    *object_path)
3499 {
3500   _dbus_return_val_if_fail (message != NULL, FALSE);
3501   _dbus_return_val_if_fail (!message->locked, FALSE);
3502   _dbus_return_val_if_fail (object_path == NULL ||
3503                             _dbus_check_is_valid_path (object_path),
3504                             FALSE);
3505
3506   return set_or_delete_string_field (message,
3507                                      DBUS_HEADER_FIELD_PATH,
3508                                      DBUS_TYPE_OBJECT_PATH,
3509                                      object_path);
3510 }
3511
3512 /**
3513  * Gets the object path this message is being sent to (for
3514  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
3515  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3516  *
3517  * See also dbus_message_get_path_decomposed().
3518  *
3519  * The returned string becomes invalid if the message is
3520  * modified, since it points into the wire-marshaled message data.
3521  *
3522  * @param message the message
3523  * @returns the path (should not be freed) or #NULL
3524  */
3525 const char*
3526 dbus_message_get_path (DBusMessage   *message)
3527 {
3528   const char *v;
3529
3530   _dbus_return_val_if_fail (message != NULL, NULL);
3531
3532   v = NULL; /* in case field doesn't exist */
3533   _dbus_header_get_field_basic (&message->header,
3534                                 DBUS_HEADER_FIELD_PATH,
3535                                 DBUS_TYPE_OBJECT_PATH,
3536                                 (void *) &v);
3537   return v;
3538 }
3539
3540 /**
3541  * Checks if the message has a particular object path.  The object
3542  * path is the destination object for a method call or the emitting
3543  * object for a signal.
3544  *
3545  * @param message the message
3546  * @param path the path name
3547  * @returns #TRUE if there is a path field in the header
3548  */
3549 dbus_bool_t
3550 dbus_message_has_path (DBusMessage   *message,
3551                        const char    *path)
3552 {
3553   const char *msg_path;
3554   msg_path = dbus_message_get_path (message);
3555
3556   if (msg_path == NULL)
3557     {
3558       if (path == NULL)
3559         return TRUE;
3560       else
3561         return FALSE;
3562     }
3563
3564   if (path == NULL)
3565     return FALSE;
3566
3567   if (strcmp (msg_path, path) == 0)
3568     return TRUE;
3569
3570   return FALSE;
3571 }
3572
3573 /**
3574  * Gets the object path this message is being sent to
3575  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
3576  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
3577  * format (one array element per path component).
3578  * Free the returned array with dbus_free_string_array().
3579  *
3580  * An empty but non-NULL path array means the path "/".
3581  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
3582  * and the path "/" becomes { NULL }.
3583  *
3584  * See also dbus_message_get_path().
3585  *
3586  * @todo this could be optimized by using the len from the message
3587  * instead of calling strlen() again
3588  *
3589  * @param message the message
3590  * @param path place to store allocated array of path components; #NULL set here if no path field exists
3591  * @returns #FALSE if no memory to allocate the array
3592  */
3593 dbus_bool_t
3594 dbus_message_get_path_decomposed (DBusMessage   *message,
3595                                   char        ***path)
3596 {
3597   const char *v;
3598
3599   _dbus_return_val_if_fail (message != NULL, FALSE);
3600   _dbus_return_val_if_fail (path != NULL, FALSE);
3601
3602   *path = NULL;
3603
3604   v = dbus_message_get_path (message);
3605   if (v != NULL)
3606     {
3607       if (!_dbus_decompose_path (v, strlen (v),
3608                                  path, NULL))
3609         return FALSE;
3610     }
3611   return TRUE;
3612 }
3613
3614 /**
3615  * Sets the interface this message is being sent to
3616  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or
3617  * the interface a signal is being emitted from
3618  * (for DBUS_MESSAGE_TYPE_SIGNAL).
3619  *
3620  * The interface name must contain only valid characters as defined
3621  * in the D-Bus specification.
3622  *
3623  * @param message the message
3624  * @param iface the interface or #NULL to unset
3625  * @returns #FALSE if not enough memory
3626  */
3627 dbus_bool_t
3628 dbus_message_set_interface (DBusMessage  *message,
3629                             const char   *iface)
3630 {
3631   _dbus_return_val_if_fail (message != NULL, FALSE);
3632   _dbus_return_val_if_fail (!message->locked, FALSE);
3633   _dbus_return_val_if_fail (iface == NULL ||
3634                             _dbus_check_is_valid_interface (iface),
3635                             FALSE);
3636
3637   return set_or_delete_string_field (message,
3638                                      DBUS_HEADER_FIELD_INTERFACE,
3639                                      DBUS_TYPE_STRING,
3640                                      iface);
3641 }
3642
3643 /**
3644  * Gets the interface this message is being sent to
3645  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
3646  * from (for DBUS_MESSAGE_TYPE_SIGNAL).
3647  * The interface name is fully-qualified (namespaced).
3648  * Returns #NULL if none.
3649  *
3650  * The returned string becomes invalid if the message is
3651  * modified, since it points into the wire-marshaled message data.
3652  *
3653  * @param message the message
3654  * @returns the message interface (should not be freed) or #NULL
3655  */
3656 const char*
3657 dbus_message_get_interface (DBusMessage *message)
3658 {
3659   const char *v;
3660
3661   _dbus_return_val_if_fail (message != NULL, NULL);
3662
3663   v = NULL; /* in case field doesn't exist */
3664   _dbus_header_get_field_basic (&message->header,
3665                                 DBUS_HEADER_FIELD_INTERFACE,
3666                                 DBUS_TYPE_STRING,
3667                                 (void *) &v);
3668   return v;
3669 }
3670
3671 /**
3672  * Checks if the message has an interface
3673  *
3674  * @param message the message
3675  * @param iface the interface name
3676  * @returns #TRUE if the interface field in the header matches
3677  */
3678 dbus_bool_t
3679 dbus_message_has_interface (DBusMessage   *message,
3680                             const char    *iface)
3681 {
3682   const char *msg_interface;
3683   msg_interface = dbus_message_get_interface (message);
3684
3685   if (msg_interface == NULL)
3686     {
3687       if (iface == NULL)
3688         return TRUE;
3689       else
3690         return FALSE;
3691     }
3692
3693   if (iface == NULL)
3694     return FALSE;
3695
3696   if (strcmp (msg_interface, iface) == 0)
3697     return TRUE;
3698
3699   return FALSE;
3700
3701 }
3702
3703 /**
3704  * Sets the interface member being invoked
3705  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3706  * (DBUS_MESSAGE_TYPE_SIGNAL).
3707  *
3708  * The member name must contain only valid characters as defined
3709  * in the D-Bus specification.
3710  *
3711  * @param message the message
3712  * @param member the member or #NULL to unset
3713  * @returns #FALSE if not enough memory
3714  */
3715 dbus_bool_t
3716 dbus_message_set_member (DBusMessage  *message,
3717                          const char   *member)
3718 {
3719   _dbus_return_val_if_fail (message != NULL, FALSE);
3720   _dbus_return_val_if_fail (!message->locked, FALSE);
3721   _dbus_return_val_if_fail (member == NULL ||
3722                             _dbus_check_is_valid_member (member),
3723                             FALSE);
3724
3725   return set_or_delete_string_field (message,
3726                                      DBUS_HEADER_FIELD_MEMBER,
3727                                      DBUS_TYPE_STRING,
3728                                      member);
3729 }
3730
3731 /**
3732  * Gets the interface member being invoked
3733  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
3734  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
3735  *
3736  * The returned string becomes invalid if the message is
3737  * modified, since it points into the wire-marshaled message data.
3738  *
3739  * @param message the message
3740  * @returns the member name (should not be freed) or #NULL
3741  */
3742 const char*
3743 dbus_message_get_member (DBusMessage *message)
3744 {
3745   const char *v;
3746
3747   _dbus_return_val_if_fail (message != NULL, NULL);
3748
3749   v = NULL; /* in case field doesn't exist */
3750   _dbus_header_get_field_basic (&message->header,
3751                                 DBUS_HEADER_FIELD_MEMBER,
3752                                 DBUS_TYPE_STRING,
3753                                 (void *) &v);
3754   return v;
3755 }
3756
3757 /**
3758  * Checks if the message has an interface member
3759  *
3760  * @param message the message
3761  * @param member the member name
3762  * @returns #TRUE if there is a member field in the header
3763  */
3764 dbus_bool_t
3765 dbus_message_has_member (DBusMessage   *message,
3766                          const char    *member)
3767 {
3768   const char *msg_member;
3769   msg_member = dbus_message_get_member (message);
3770
3771   if (msg_member == NULL)
3772     {
3773       if (member == NULL)
3774         return TRUE;
3775       else
3776         return FALSE;
3777     }
3778
3779   if (member == NULL)
3780     return FALSE;
3781
3782   if (strcmp (msg_member, member) == 0)
3783     return TRUE;
3784
3785   return FALSE;
3786
3787 }
3788
3789 /**
3790  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
3791  * The name is fully-qualified (namespaced).
3792  *
3793  * The error name must contain only valid characters as defined
3794  * in the D-Bus specification.
3795  *
3796  * @param message the message
3797  * @param error_name the name or #NULL to unset
3798  * @returns #FALSE if not enough memory
3799  */
3800 dbus_bool_t
3801 dbus_message_set_error_name (DBusMessage  *message,
3802                              const char   *error_name)
3803 {
3804   _dbus_return_val_if_fail (message != NULL, FALSE);
3805   _dbus_return_val_if_fail (!message->locked, FALSE);
3806   _dbus_return_val_if_fail (error_name == NULL ||
3807                             _dbus_check_is_valid_error_name (error_name),
3808                             FALSE);
3809
3810   return set_or_delete_string_field (message,
3811                                      DBUS_HEADER_FIELD_ERROR_NAME,
3812                                      DBUS_TYPE_STRING,
3813                                      error_name);
3814 }
3815
3816 /**
3817  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
3818  * or #NULL if none.
3819  *
3820  * The returned string becomes invalid if the message is
3821  * modified, since it points into the wire-marshaled message data.
3822  *
3823  * @param message the message
3824  * @returns the error name (should not be freed) or #NULL
3825  */
3826 const char*
3827 dbus_message_get_error_name (DBusMessage *message)
3828 {
3829   const char *v;
3830
3831   _dbus_return_val_if_fail (message != NULL, NULL);
3832
3833   v = NULL; /* in case field doesn't exist */
3834   _dbus_header_get_field_basic (&message->header,
3835                                 DBUS_HEADER_FIELD_ERROR_NAME,
3836                                 DBUS_TYPE_STRING,
3837                                 (void *) &v);
3838   return v;
3839 }
3840
3841 /**
3842  * Sets the message's destination. The destination is the name of
3843  * another connection on the bus and may be either the unique name
3844  * assigned by the bus to each connection, or a well-known name
3845  * specified in advance.
3846  *
3847  * The destination name must contain only valid characters as defined
3848  * in the D-Bus specification.
3849  *
3850  * @param message the message
3851  * @param destination the destination name or #NULL to unset
3852  * @returns #FALSE if not enough memory
3853  */
3854 dbus_bool_t
3855 dbus_message_set_destination (DBusMessage  *message,
3856                               const char   *destination)
3857 {
3858   _dbus_return_val_if_fail (message != NULL, FALSE);
3859   _dbus_return_val_if_fail (!message->locked, FALSE);
3860   _dbus_return_val_if_fail (destination == NULL ||
3861                             _dbus_check_is_valid_bus_name (destination),
3862                             FALSE);
3863
3864   return set_or_delete_string_field (message,
3865                                      DBUS_HEADER_FIELD_DESTINATION,
3866                                      DBUS_TYPE_STRING,
3867                                      destination);
3868 }
3869
3870 /**
3871  * Gets the destination of a message or #NULL if there is none set.
3872  *
3873  * The returned string becomes invalid if the message is
3874  * modified, since it points into the wire-marshaled message data.
3875  *
3876  * @param message the message
3877  * @returns the message destination (should not be freed) or #NULL
3878  */
3879 const char*
3880 dbus_message_get_destination (DBusMessage *message)
3881 {
3882   const char *v;
3883
3884   _dbus_return_val_if_fail (message != NULL, NULL);
3885
3886   v = NULL; /* in case field doesn't exist */
3887   _dbus_header_get_field_basic (&message->header,
3888                                 DBUS_HEADER_FIELD_DESTINATION,
3889                                 DBUS_TYPE_STRING,
3890                                 (void *) &v);
3891   return v;
3892 }
3893
3894 /**
3895  * Sets the message sender.
3896  *
3897  * The sender must be a valid bus name as defined in the D-Bus
3898  * specification.
3899  *
3900  * Usually you don't want to call this. The message bus daemon will
3901  * call it to set the origin of each message. If you aren't implementing
3902  * a message bus daemon you shouldn't need to set the sender.
3903  *
3904  * @param message the message
3905  * @param sender the sender or #NULL to unset
3906  * @returns #FALSE if not enough memory
3907  */
3908 dbus_bool_t
3909 dbus_message_set_sender (DBusMessage  *message,
3910                          const char   *sender)
3911 {
3912   _dbus_return_val_if_fail (message != NULL, FALSE);
3913   _dbus_return_val_if_fail (!message->locked, FALSE);
3914   _dbus_return_val_if_fail (sender == NULL ||
3915                             _dbus_check_is_valid_bus_name (sender),
3916                             FALSE);
3917
3918   return set_or_delete_string_field (message,
3919                                      DBUS_HEADER_FIELD_SENDER,
3920                                      DBUS_TYPE_STRING,
3921                                      sender);
3922 }
3923
3924 /**
3925  * Gets the unique name of the connection which originated this
3926  * message, or #NULL if unknown or inapplicable. The sender is filled
3927  * in by the message bus.
3928  *
3929  * Note, the returned sender is always the unique bus name.
3930  * Connections may own multiple other bus names, but those
3931  * are not found in the sender field.
3932  *
3933  * The returned string becomes invalid if the message is
3934  * modified, since it points into the wire-marshaled message data.
3935  *
3936  * @param message the message
3937  * @returns the unique name of the sender or #NULL
3938  */
3939 const char*
3940 dbus_message_get_sender (DBusMessage *message)
3941 {
3942   const char *v;
3943
3944   _dbus_return_val_if_fail (message != NULL, NULL);
3945
3946   if (NULL != message->unique_sender)
3947     return _dbus_string_get_const_data (message->unique_sender);
3948
3949   v = NULL; /* in case field doesn't exist */
3950   _dbus_header_get_field_basic (&message->header,
3951                                 DBUS_HEADER_FIELD_SENDER,
3952                                 DBUS_TYPE_STRING,
3953                                 (void *) &v);
3954   return v;
3955 }
3956
3957 /**
3958  * Gets the type signature of the message, i.e. the arguments in the
3959  * message payload. The signature includes only "in" arguments for
3960  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
3961  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
3962  * what you might expect (that is, it does not include the signature of the
3963  * entire C++-style method).
3964  *
3965  * The signature is a string made up of type codes such as
3966  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
3967  * the value of #DBUS_TYPE_INVALID).
3968  *
3969  * The returned string becomes invalid if the message is
3970  * modified, since it points into the wire-marshaled message data.
3971  *
3972  * @param message the message
3973  * @returns the type signature
3974  */
3975 const char*
3976 dbus_message_get_signature (DBusMessage *message)
3977 {
3978   const DBusString *type_str;
3979   int type_pos;
3980
3981   _dbus_return_val_if_fail (message != NULL, NULL);
3982
3983   get_const_signature (message, &type_str, &type_pos);
3984
3985   return _dbus_string_get_const_data_len (type_str, type_pos, 0);
3986 }
3987
3988 static dbus_bool_t
3989 _dbus_message_has_type_interface_member (DBusMessage *message,
3990                                          int          type,
3991                                          const char  *iface,
3992                                          const char  *member)
3993 {
3994   const char *n;
3995
3996   _dbus_assert (message != NULL);
3997   _dbus_assert (iface != NULL);
3998   _dbus_assert (member != NULL);
3999
4000   if (dbus_message_get_type (message) != type)
4001     return FALSE;
4002
4003   /* Optimize by checking the short member name first
4004    * instead of the longer interface name
4005    */
4006
4007   n = dbus_message_get_member (message);
4008
4009   if (n && strcmp (n, member) == 0)
4010     {
4011       n = dbus_message_get_interface (message);
4012
4013       if (n == NULL || strcmp (n, iface) == 0)
4014         return TRUE;
4015     }
4016
4017   return FALSE;
4018 }
4019
4020 /**
4021  * Checks whether the message is a method call with the given
4022  * interface and member fields.  If the message is not
4023  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
4024  * member field, returns #FALSE. If the interface field is missing,
4025  * then it will be assumed equal to the provided interface.  The D-Bus
4026  * protocol allows method callers to leave out the interface name.
4027  *
4028  * @param message the message
4029  * @param iface the name to check (must not be #NULL)
4030  * @param method the name to check (must not be #NULL)
4031  *
4032  * @returns #TRUE if the message is the specified method call
4033  */
4034 dbus_bool_t
4035 dbus_message_is_method_call (DBusMessage *message,
4036                              const char  *iface,
4037                              const char  *method)
4038 {
4039   _dbus_return_val_if_fail (message != NULL, FALSE);
4040   _dbus_return_val_if_fail (iface != NULL, FALSE);
4041   _dbus_return_val_if_fail (method != NULL, FALSE);
4042   /* don't check that interface/method are valid since it would be
4043    * expensive, and not catch many common errors
4044    */
4045
4046   return _dbus_message_has_type_interface_member (message,
4047                                                   DBUS_MESSAGE_TYPE_METHOD_CALL,
4048                                                   iface, method);
4049 }
4050
4051 /**
4052  * Checks whether the message is a signal with the given interface and
4053  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
4054  * has a different interface or member field, returns #FALSE.
4055  *
4056  * @param message the message
4057  * @param iface the name to check (must not be #NULL)
4058  * @param signal_name the name to check (must not be #NULL)
4059  *
4060  * @returns #TRUE if the message is the specified signal
4061  */
4062 dbus_bool_t
4063 dbus_message_is_signal (DBusMessage *message,
4064                         const char  *iface,
4065                         const char  *signal_name)
4066 {
4067   _dbus_return_val_if_fail (message != NULL, FALSE);
4068   _dbus_return_val_if_fail (iface != NULL, FALSE);
4069   _dbus_return_val_if_fail (signal_name != NULL, FALSE);
4070   /* don't check that interface/name are valid since it would be
4071    * expensive, and not catch many common errors
4072    */
4073
4074   return _dbus_message_has_type_interface_member (message,
4075                                                   DBUS_MESSAGE_TYPE_SIGNAL,
4076                                                   iface, signal_name);
4077 }
4078
4079 /**
4080  * Checks whether the message is an error reply with the given error
4081  * name.  If the message is not #DBUS_MESSAGE_TYPE_ERROR, or has a
4082  * different name, returns #FALSE.
4083  *
4084  * @param message the message
4085  * @param error_name the name to check (must not be #NULL)
4086  *
4087  * @returns #TRUE if the message is the specified error
4088  */
4089 dbus_bool_t
4090 dbus_message_is_error (DBusMessage *message,
4091                        const char  *error_name)
4092 {
4093   const char *n;
4094
4095   _dbus_return_val_if_fail (message != NULL, FALSE);
4096   _dbus_return_val_if_fail (error_name != NULL, FALSE);
4097   /* don't check that error_name is valid since it would be expensive,
4098    * and not catch many common errors
4099    */
4100
4101   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
4102     return FALSE;
4103
4104   n = dbus_message_get_error_name (message);
4105
4106   if (n && strcmp (n, error_name) == 0)
4107     return TRUE;
4108   else
4109     return FALSE;
4110 }
4111
4112 /**
4113  * Checks whether the message was sent to the given name.  If the
4114  * message has no destination specified or has a different
4115  * destination, returns #FALSE.
4116  *
4117  * @param message the message
4118  * @param name the name to check (must not be #NULL)
4119  *
4120  * @returns #TRUE if the message has the given destination name
4121  */
4122 dbus_bool_t
4123 dbus_message_has_destination (DBusMessage  *message,
4124                               const char   *name)
4125 {
4126   const char *s;
4127
4128   _dbus_return_val_if_fail (message != NULL, FALSE);
4129   _dbus_return_val_if_fail (name != NULL, FALSE);
4130   /* don't check that name is valid since it would be expensive, and
4131    * not catch many common errors
4132    */
4133
4134   s = dbus_message_get_destination (message);
4135
4136   if (s && strcmp (s, name) == 0)
4137     return TRUE;
4138   else
4139     return FALSE;
4140 }
4141
4142 /**
4143  * Checks whether the message has the given unique name as its sender.
4144  * If the message has no sender specified or has a different sender,
4145  * returns #FALSE. Note that a peer application will always have the
4146  * unique name of the connection as the sender. So you can't use this
4147  * function to see whether a sender owned a well-known name.
4148  *
4149  * Messages from the bus itself will have #DBUS_SERVICE_DBUS
4150  * as the sender.
4151  *
4152  * @param message the message
4153  * @param name the name to check (must not be #NULL)
4154  *
4155  * @returns #TRUE if the message has the given sender
4156  */
4157 dbus_bool_t
4158 dbus_message_has_sender (DBusMessage  *message,
4159                          const char   *name)
4160 {
4161   const char *s;
4162
4163   _dbus_return_val_if_fail (message != NULL, FALSE);
4164   _dbus_return_val_if_fail (name != NULL, FALSE);
4165   /* don't check that name is valid since it would be expensive, and
4166    * not catch many common errors
4167    */
4168
4169   s = dbus_message_get_sender (message);
4170
4171   if (s && strcmp (s, name) == 0)
4172     return TRUE;
4173   else
4174     return FALSE;
4175 }
4176
4177 /**
4178  * Checks whether the message has the given signature; see
4179  * dbus_message_get_signature() for more details on what the signature
4180  * looks like.
4181  *
4182  * @param message the message
4183  * @param signature typecode array
4184  * @returns #TRUE if message has the given signature
4185 */
4186 dbus_bool_t
4187 dbus_message_has_signature (DBusMessage   *message,
4188                             const char    *signature)
4189 {
4190   const char *s;
4191
4192   _dbus_return_val_if_fail (message != NULL, FALSE);
4193   _dbus_return_val_if_fail (signature != NULL, FALSE);
4194   /* don't check that signature is valid since it would be expensive,
4195    * and not catch many common errors
4196    */
4197
4198   s = dbus_message_get_signature (message);
4199
4200   if (s && strcmp (s, signature) == 0)
4201     return TRUE;
4202   else
4203     return FALSE;
4204 }
4205
4206 /**
4207  * Sets a #DBusError based on the contents of the given
4208  * message. The error is only set if the message
4209  * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
4210  * The name of the error is set to the name of the message,
4211  * and the error message is set to the first argument
4212  * if the argument exists and is a string.
4213  *
4214  * The return value indicates whether the error was set (the error is
4215  * set if and only if the message is an error message).  So you can
4216  * check for an error reply and convert it to DBusError in one go:
4217  * @code
4218  *  if (dbus_set_error_from_message (error, reply))
4219  *    return error;
4220  *  else
4221  *    process reply;
4222  * @endcode
4223  *
4224  * @param error the error to set
4225  * @param message the message to set it from
4226  * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
4227  */
4228 dbus_bool_t
4229 dbus_set_error_from_message (DBusError   *error,
4230                              DBusMessage *message)
4231 {
4232   const char *str;
4233
4234   _dbus_return_val_if_fail (message != NULL, FALSE);
4235   _dbus_return_val_if_error_is_set (error, FALSE);
4236
4237   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_ERROR)
4238     return FALSE;
4239
4240   str = NULL;
4241   dbus_message_get_args (message, NULL,
4242                          DBUS_TYPE_STRING, &str,
4243                          DBUS_TYPE_INVALID);
4244
4245   dbus_set_error (error, dbus_message_get_error_name (message),
4246                   str ? "%s" : NULL, str);
4247
4248   return TRUE;
4249 }
4250
4251 /**
4252  * Checks whether a message contains unix fds
4253  *
4254  * @param message the message
4255  * @returns #TRUE if the message contains unix fds
4256  */
4257 dbus_bool_t
4258 dbus_message_contains_unix_fds(DBusMessage *message)
4259 {
4260 #ifdef HAVE_UNIX_FD_PASSING
4261   _dbus_assert(message);
4262
4263   return message->n_unix_fds > 0;
4264 #else
4265   return FALSE;
4266 #endif
4267 }
4268
4269 /** @} */
4270
4271 /**
4272  * @addtogroup DBusMessageInternals
4273  *
4274  * @{
4275  */
4276
4277 /**
4278  * The initial buffer size of the message loader.
4279  *
4280  * @todo this should be based on min header size plus some average
4281  * body size, or something. Or rather, the min header size only, if we
4282  * want to try to read only the header, store that in a DBusMessage,
4283  * then read only the body and store that, etc., depends on
4284  * how we optimize _dbus_message_loader_get_buffer() and what
4285  * the exact message format is.
4286  */
4287 #define INITIAL_LOADER_DATA_LEN 32
4288
4289 /**
4290  * Creates a new message loader. Returns #NULL if memory can't
4291  * be allocated.
4292  *
4293  * @returns new loader, or #NULL.
4294  */
4295 DBusMessageLoader*
4296 _dbus_message_loader_new (void)
4297 {
4298   DBusMessageLoader *loader;
4299
4300   loader = dbus_new0 (DBusMessageLoader, 1);
4301   if (loader == NULL)
4302     return NULL;
4303
4304   loader->refcount = 1;
4305
4306   loader->corrupted = FALSE;
4307   loader->corruption_reason = DBUS_VALID;
4308
4309   /* this can be configured by the app, but defaults to the protocol max */
4310   loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
4311
4312   /* We set a very relatively conservative default here since due to how
4313   SCM_RIGHTS works we need to preallocate an fd array of the maximum
4314   number of unix fds we want to receive in advance. A
4315   try-and-reallocate loop is not possible. */
4316   loader->max_message_unix_fds = DBUS_DEFAULT_MESSAGE_UNIX_FDS;
4317
4318   if (!_dbus_string_init (&loader->data))
4319     {
4320       dbus_free (loader);
4321       return NULL;
4322     }
4323
4324   /* preallocate the buffer for speed, ignore failure */
4325   _dbus_string_set_length (&loader->data, INITIAL_LOADER_DATA_LEN);
4326   _dbus_string_set_length (&loader->data, 0);
4327
4328 #ifdef HAVE_UNIX_FD_PASSING
4329   loader->unix_fds = NULL;
4330   loader->n_unix_fds = loader->n_unix_fds_allocated = 0;
4331   loader->unix_fds_outstanding = FALSE;
4332 #endif
4333
4334   return loader;
4335 }
4336
4337 /**
4338  * Increments the reference count of the loader.
4339  *
4340  * @param loader the loader.
4341  * @returns the loader
4342  */
4343 DBusMessageLoader *
4344 _dbus_message_loader_ref (DBusMessageLoader *loader)
4345 {
4346   loader->refcount += 1;
4347
4348   return loader;
4349 }
4350
4351 /**
4352  * Decrements the reference count of the loader and finalizes the
4353  * loader when the count reaches zero.
4354  *
4355  * @param loader the loader.
4356  */
4357 void
4358 _dbus_message_loader_unref (DBusMessageLoader *loader)
4359 {
4360   loader->refcount -= 1;
4361   if (loader->refcount == 0)
4362     {
4363 #ifdef HAVE_UNIX_FD_PASSING
4364       close_unix_fds(loader->unix_fds, &loader->n_unix_fds);
4365       dbus_free(loader->unix_fds);
4366 #endif
4367       _dbus_list_foreach (&loader->messages,
4368                           (DBusForeachFunction) dbus_message_unref,
4369                           NULL);
4370       _dbus_list_clear (&loader->messages);
4371       _dbus_string_free (&loader->data);
4372       dbus_free (loader);
4373     }
4374 }
4375
4376 /**
4377  * Gets the buffer to use for reading data from the network.  Network
4378  * data is read directly into an allocated buffer, which is then used
4379  * in the DBusMessage, to avoid as many extra memcpy's as possible.
4380  * The buffer must always be returned immediately using
4381  * _dbus_message_loader_return_buffer(), even if no bytes are
4382  * successfully read.
4383  *
4384  * @todo this function can be a lot more clever. For example
4385  * it can probably always return a buffer size to read exactly
4386  * the body of the next message, thus avoiding any memory wastage
4387  * or reallocs.
4388  *
4389  * @todo we need to enforce a max length on strings in header fields.
4390  *
4391  * @param loader the message loader.
4392  * @param buffer the buffer
4393  */
4394 void
4395 _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
4396                                  DBusString        **buffer,
4397                                  int                *max_to_read,
4398                                  dbus_bool_t        *may_read_fds)
4399 {
4400   _dbus_assert (!loader->buffer_outstanding);
4401
4402   *buffer = &loader->data;
4403
4404   loader->buffer_outstanding = TRUE;
4405
4406   if (max_to_read != NULL)
4407     {
4408 #ifdef HAVE_UNIX_FD_PASSING
4409       int offset = 0;
4410       int remain;
4411       int byte_order;
4412       int fields_array_len;
4413       int header_len;
4414       int body_len;
4415 #endif
4416
4417       *max_to_read = DBUS_MAXIMUM_MESSAGE_LENGTH;
4418       *may_read_fds = TRUE;
4419
4420 #ifdef HAVE_UNIX_FD_PASSING
4421       /* If we aren't holding onto any fds, we can read as much as we want
4422        * (fast path). */
4423       if (loader->n_unix_fds == 0)
4424         return;
4425
4426       /* Slow path: we have a message with some fds in it. We don't want
4427        * to start on the next message until this one is out of the way;
4428        * otherwise a legitimate sender can keep us processing messages
4429        * containing fds, until we disconnect it for having had fds pending
4430        * for too long, a limit that is in place to stop malicious senders
4431        * from setting up recursive fd-passing that takes up our quota and
4432        * will never go away. */
4433
4434       remain = _dbus_string_get_length (&loader->data);
4435
4436       while (remain > 0)
4437         {
4438           DBusValidity validity = DBUS_VALIDITY_UNKNOWN;
4439           int needed;
4440           dbus_bool_t is_gvariant;
4441
4442           /* If 0 < remain < DBUS_MINIMUM_HEADER_SIZE, then we've had at
4443            * least the first byte of a message, but we don't know how
4444            * much more to read. Only read the rest of the
4445            * DBUS_MINIMUM_HEADER_SIZE for now; then we'll know. */
4446           if (remain < DBUS_MINIMUM_HEADER_SIZE)
4447             {
4448               *max_to_read = DBUS_MINIMUM_HEADER_SIZE - remain;
4449               *may_read_fds = FALSE;
4450               return;
4451             }
4452
4453           if (!_dbus_header_have_message_untrusted (loader->max_message_size,
4454                                                     &validity,
4455                                                     &byte_order,
4456                                                     &fields_array_len,
4457                                                     &header_len,
4458                                                     &body_len,
4459                                                     &loader->data,
4460                                                     offset,
4461                                                     remain,
4462                                                     &is_gvariant))
4463             {
4464               /* If a message in the buffer is invalid, we're going to
4465                * disconnect the sender anyway, so reading an arbitrary amount
4466                * is fine. */
4467               if (validity != DBUS_VALID)
4468                 return;
4469
4470               /* We have a partial message, with the
4471                * DBUS_MINIMUM_HEADER_SIZE-byte fixed part of the header (which
4472                * lets us work out how much more we need), but no more. Read
4473                * the rest of the message. */
4474               needed = header_len + body_len;
4475               _dbus_assert (needed > remain);
4476               *max_to_read = needed - remain;
4477               *may_read_fds = FALSE;
4478               return;
4479             }
4480
4481           /* Skip over entire messages until we have less than a message
4482            * remaining. */
4483           needed = header_len + body_len;
4484           _dbus_assert (needed > DBUS_MINIMUM_HEADER_SIZE);
4485           _dbus_assert (remain >= needed);
4486           remain -= needed;
4487           offset += needed;
4488         }
4489 #endif
4490     }
4491 }
4492
4493 /**
4494  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
4495  * indicating to the loader how many bytes of the buffer were filled
4496  * in. This function must always be called, even if no bytes were
4497  * successfully read.
4498  *
4499  * @param loader the loader.
4500  * @param buffer the buffer.
4501  */
4502 void
4503 _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
4504                                     DBusString         *buffer)
4505 {
4506   _dbus_assert (loader->buffer_outstanding);
4507   _dbus_assert (buffer == &loader->data);
4508
4509   loader->buffer_outstanding = FALSE;
4510 }
4511
4512 #ifdef HAVE_UNIX_FD_PASSING
4513 /**
4514  * Gets the buffer to use for reading unix fds from the network.
4515  *
4516  * This works similar to _dbus_message_loader_get_buffer()
4517  *
4518  * @param loader the message loader.
4519  * @param fds the array to read fds into
4520  * @param max_n_fds how many fds to read at most
4521  * @return TRUE on success, FALSE on OOM
4522  */
4523 dbus_bool_t
4524 _dbus_message_loader_get_unix_fds(DBusMessageLoader  *loader,
4525                                   int               **fds,
4526                                   unsigned           *max_n_fds)
4527 {
4528   _dbus_assert (!loader->unix_fds_outstanding);
4529
4530   /* Allocate space where we can put the fds we read. We allocate
4531      space for max_message_unix_fds since this is an
4532      upper limit how many fds can be received within a single
4533      message. Since SCM_RIGHTS doesn't allow a reallocate+retry logic
4534      we are allocating the maximum possible array size right from the
4535      beginning. This sucks a bit, however unless SCM_RIGHTS is fixed
4536      there is no better way. */
4537
4538   if (loader->n_unix_fds_allocated < loader->max_message_unix_fds)
4539     {
4540       int *a = dbus_realloc(loader->unix_fds,
4541                             loader->max_message_unix_fds * sizeof(loader->unix_fds[0]));
4542
4543       if (!a)
4544         return FALSE;
4545
4546       loader->unix_fds = a;
4547       loader->n_unix_fds_allocated = loader->max_message_unix_fds;
4548     }
4549
4550   *fds = loader->unix_fds + loader->n_unix_fds;
4551   *max_n_fds = loader->n_unix_fds_allocated - loader->n_unix_fds;
4552
4553   loader->unix_fds_outstanding = TRUE;
4554   return TRUE;
4555 }
4556
4557 /**
4558  * Returns a buffer obtained from _dbus_message_loader_get_unix_fds().
4559  *
4560  * This works similar to _dbus_message_loader_return_buffer()
4561  *
4562  * @param loader the message loader.
4563  * @param fds the array fds were read into
4564  * @param n_fds how many fds were read
4565  */
4566
4567 void
4568 _dbus_message_loader_return_unix_fds(DBusMessageLoader  *loader,
4569                                      int                *fds,
4570                                      unsigned            n_fds)
4571 {
4572   _dbus_assert(loader->unix_fds_outstanding);
4573   _dbus_assert(loader->unix_fds + loader->n_unix_fds == fds);
4574   _dbus_assert(loader->n_unix_fds + n_fds <= loader->n_unix_fds_allocated);
4575
4576   loader->n_unix_fds += n_fds;
4577   loader->unix_fds_outstanding = FALSE;
4578
4579   if (n_fds && loader->unix_fds_change)
4580     loader->unix_fds_change (loader->unix_fds_change_data);
4581 }
4582 #endif
4583
4584 /*
4585  * FIXME when we move the header out of the buffer, that memmoves all
4586  * buffered messages. Kind of crappy.
4587  *
4588  * Also we copy the header and body, which is kind of crappy.  To
4589  * avoid this, we have to allow header and body to be in a single
4590  * memory block, which is good for messages we read and bad for
4591  * messages we are creating. But we could move_len() the buffer into
4592  * this single memory block, and move_len() will just swap the buffers
4593  * if you're moving the entire buffer replacing the dest string.
4594  *
4595  * We could also have the message loader tell the transport how many
4596  * bytes to read; so it would first ask for some arbitrary number like
4597  * 256, then if the message was incomplete it would use the
4598  * header/body len to ask for exactly the size of the message (or
4599  * blocks the size of a typical kernel buffer for the socket). That
4600  * way we don't get trailing bytes in the buffer that have to be
4601  * memmoved. Though I suppose we also don't have a chance of reading a
4602  * bunch of small messages at once, so the optimization may be stupid.
4603  *
4604  * Another approach would be to keep a "start" index into
4605  * loader->data and only delete it occasionally, instead of after
4606  * each message is loaded.
4607  *
4608  * load_message() returns FALSE if not enough memory OR the loader was corrupted
4609  */
4610 static dbus_bool_t
4611 load_message (DBusMessageLoader *loader,
4612               DBusMessage       *message,
4613               int                byte_order,
4614               int                fields_array_len,
4615               int                header_len,
4616               int                body_len)
4617 {
4618   dbus_bool_t oom;
4619   DBusValidity validity;
4620   const DBusString *type_str;
4621   int type_pos;
4622   DBusValidationMode mode;
4623   dbus_uint32_t n_unix_fds = 0;
4624
4625   mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
4626
4627   oom = FALSE;
4628
4629 #if 0
4630   _dbus_verbose_bytes_of_string (&loader->data, 0, header_len /* + body_len */);
4631 #endif
4632
4633   /* 1. VALIDATE AND COPY OVER HEADER */
4634   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
4635   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
4636
4637   if (!_dbus_header_load (&message->header,
4638                           mode,
4639                           &validity,
4640                           byte_order,
4641                           fields_array_len,
4642                           header_len,
4643                           body_len,
4644                           &loader->data, 0,
4645                           _dbus_string_get_length (&loader->data)))
4646     {
4647       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
4648
4649       /* assert here so we can catch any code that still uses DBUS_VALID to indicate
4650          oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
4651       _dbus_assert (validity != DBUS_VALID);
4652
4653       if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
4654         oom = TRUE;
4655       else
4656         {
4657           loader->corrupted = TRUE;
4658           loader->corruption_reason = validity;
4659         }
4660       goto failed;
4661     }
4662
4663   _dbus_assert (validity == DBUS_VALID);
4664
4665   /* 2. VALIDATE BODY */
4666   if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
4667     {
4668       if (_dbus_message_is_gvariant (message))
4669         {
4670           type_str = NULL;
4671           type_pos = 0;
4672           validity = _dbus_validate_gvariant_body_with_reason (type_str,
4673                                                                type_pos,
4674                                                                byte_order,
4675                                                                NULL,
4676                                                                &loader->data,
4677                                                                header_len,
4678                                                                body_len);
4679         }
4680       else
4681         {
4682
4683           get_const_signature (message, &type_str, &type_pos);
4684
4685           /* Because the bytes_remaining arg is NULL, this validates that the
4686            * body is the right length
4687            */
4688
4689           validity = _dbus_validate_body_with_reason (type_str,
4690                                                       type_pos,
4691                                                       byte_order,
4692                                                       NULL,
4693                                                       &loader->data,
4694                                                       header_len,
4695                                                       body_len);
4696         }
4697       if (validity != DBUS_VALID)
4698         {
4699           _dbus_verbose ("Failed to validate message body code %d\n", validity);
4700
4701           loader->corrupted = TRUE;
4702           loader->corruption_reason = validity;
4703
4704           goto failed;
4705         }
4706     }
4707
4708   /* 3. COPY OVER UNIX FDS */
4709   _dbus_header_get_field_basic(&message->header,
4710                                DBUS_HEADER_FIELD_UNIX_FDS,
4711                                DBUS_TYPE_UINT32,
4712                                &n_unix_fds);
4713
4714 #ifdef HAVE_UNIX_FD_PASSING
4715
4716   if (n_unix_fds > loader->n_unix_fds)
4717     {
4718       _dbus_verbose("Message contains references to more unix fds than were sent %u != %u\n",
4719                     n_unix_fds, loader->n_unix_fds);
4720
4721       loader->corrupted = TRUE;
4722       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
4723       goto failed;
4724     }
4725
4726   /* If this was a recycled message there might still be
4727      some memory allocated for the fds */
4728   dbus_free(message->unix_fds);
4729
4730   if (n_unix_fds > 0)
4731     {
4732       message->unix_fds = _dbus_memdup(loader->unix_fds, n_unix_fds * sizeof(message->unix_fds[0]));
4733       if (message->unix_fds == NULL)
4734         {
4735           _dbus_verbose ("Failed to allocate file descriptor array\n");
4736           oom = TRUE;
4737           goto failed;
4738         }
4739
4740       message->n_unix_fds_allocated = message->n_unix_fds = n_unix_fds;
4741       loader->n_unix_fds -= n_unix_fds;
4742       memmove (loader->unix_fds, loader->unix_fds + n_unix_fds, loader->n_unix_fds * sizeof (loader->unix_fds[0]));
4743
4744       if (loader->unix_fds_change)
4745         loader->unix_fds_change (loader->unix_fds_change_data);
4746     }
4747   else
4748     message->unix_fds = NULL;
4749
4750 #else
4751
4752   if (n_unix_fds > 0)
4753     {
4754       _dbus_verbose ("Hmm, message claims to come with file descriptors "
4755                      "but that's not supported on our platform, disconnecting.\n");
4756
4757       loader->corrupted = TRUE;
4758       loader->corruption_reason = DBUS_INVALID_MISSING_UNIX_FDS;
4759       goto failed;
4760     }
4761
4762 #endif
4763
4764   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
4765
4766   if (!_dbus_list_append (&loader->messages, message))
4767     {
4768       _dbus_verbose ("Failed to append new message to loader queue\n");
4769       oom = TRUE;
4770       goto failed;
4771     }
4772
4773   _dbus_assert (_dbus_string_get_length (&message->body) == 0);
4774   _dbus_assert (_dbus_string_get_length (&loader->data) >=
4775                 (header_len + body_len));
4776
4777   if (!_dbus_string_copy_len (&loader->data, header_len, body_len, &message->body, 0))
4778     {
4779       _dbus_verbose ("Failed to move body into new message\n");
4780       oom = TRUE;
4781       goto failed;
4782     }
4783
4784   _dbus_string_delete (&loader->data, 0, header_len + body_len);
4785
4786   /* don't waste more than 2k of memory */
4787   _dbus_string_compact (&loader->data, 2048);
4788
4789   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
4790   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
4791
4792   _dbus_verbose ("Loaded message %p\n", message);
4793
4794   _dbus_assert (!oom);
4795   _dbus_assert (!loader->corrupted);
4796   _dbus_assert (loader->messages != NULL);
4797   _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4798
4799   return TRUE;
4800
4801  failed:
4802
4803   /* Clean up */
4804
4805   /* does nothing if the message isn't in the list */
4806   _dbus_list_remove_last (&loader->messages, message);
4807
4808   if (oom)
4809     _dbus_assert (!loader->corrupted);
4810   else
4811     _dbus_assert (loader->corrupted);
4812
4813   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
4814
4815   return FALSE;
4816 }
4817
4818 static dbus_bool_t
4819 set_unique_sender (DBusMessage *message, uint64_t unique_sender_id)
4820 {
4821   if (NULL == message->unique_sender)
4822     {
4823       message->unique_sender = dbus_new (DBusString, 1);
4824       if (NULL == message->unique_sender)
4825         return FALSE;
4826
4827       if (!_dbus_string_init (message->unique_sender))
4828         return FALSE;
4829     }
4830
4831   _dbus_string_set_length (message->unique_sender, 0);
4832
4833   if (!_dbus_string_append_printf (message->unique_sender, ":1.%llu", (unsigned long long)unique_sender_id))
4834     {
4835       _dbus_string_free (message->unique_sender);
4836       dbus_free (message->unique_sender);
4837       message->unique_sender = NULL;
4838       return FALSE;
4839     }
4840
4841   return TRUE;
4842 }
4843
4844 /**
4845  * Converts buffered data into messages, if we have enough data.  If
4846  * we don't have enough data, does nothing.
4847  *
4848  * @todo we need to check that the proper named header fields exist
4849  * for each message type.
4850  *
4851  * @todo If a message has unknown type, we should probably eat it
4852  * right here rather than passing it out to applications.  However
4853  * it's not an error to see messages of unknown type.
4854  *
4855  * @param loader the loader.
4856  * @returns #TRUE if we had enough memory to finish.
4857  */
4858 dbus_bool_t
4859 _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
4860 {
4861   while (!loader->corrupted &&
4862          _dbus_string_get_length (&loader->data) >= DBUS_MINIMUM_HEADER_SIZE)
4863     {
4864       DBusValidity validity;
4865       int byte_order, fields_array_len, header_len, body_len;
4866       dbus_bool_t is_gvariant;
4867
4868       if (_dbus_header_have_message_untrusted (loader->max_message_size,
4869                                                &validity,
4870                                                &byte_order,
4871                                                &fields_array_len,
4872                                                &header_len,
4873                                                &body_len,
4874                                                &loader->data, 0,
4875                                                _dbus_string_get_length (&loader->data),
4876                                                &is_gvariant))
4877         {
4878           DBusMessage *message;
4879
4880           _dbus_assert (validity == DBUS_VALID);
4881
4882           message = dbus_message_new_empty_header (is_gvariant);
4883           if (message == NULL)
4884             return FALSE;
4885
4886           if (!load_message (loader, message,
4887                              byte_order, fields_array_len,
4888                              header_len, body_len))
4889             {
4890               dbus_message_unref (message);
4891               /* load_message() returns false if corrupted or OOM; if
4892                * corrupted then return TRUE for not OOM
4893                */
4894               return loader->corrupted;
4895             }
4896
4897           if (_dbus_message_is_gvariant (message))
4898             {
4899               set_unique_sender (message, _dbus_message_loader_get_unique_sender_id (loader));
4900               message->locked = TRUE;
4901             }
4902
4903           _dbus_assert (loader->messages != NULL);
4904           _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
4905         }
4906       else
4907         {
4908           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
4909                          validity);
4910           if (validity != DBUS_VALID)
4911             {
4912               loader->corrupted = TRUE;
4913               loader->corruption_reason = validity;
4914             }
4915           return TRUE;
4916         }
4917     }
4918
4919   return TRUE;
4920 }
4921
4922 DBusMessage *
4923 _dbus_decode_kmsg (DBusString  *data,
4924                    uint64_t     sender_id,
4925                    int         *fds,
4926                    unsigned     n_fds)
4927 {
4928   if (_dbus_string_get_length (data) >= DBUS_MINIMUM_HEADER_SIZE)
4929     {
4930
4931       DBusValidity validity;
4932       int byte_order, fields_array_len, header_len, body_len;
4933       dbus_bool_t is_gvariant;
4934
4935       if (_dbus_header_have_message_untrusted (DBUS_MAXIMUM_MESSAGE_LENGTH,
4936                                                &validity,
4937                                                &byte_order,
4938                                                &fields_array_len,
4939                                                &header_len,
4940                                                &body_len,
4941                                                data, 0,
4942                                                _dbus_string_get_length (data),
4943                                                &is_gvariant))
4944         {
4945           DBusMessage *message;
4946           dbus_uint32_t n_unix_fds = 0;
4947           const DBusString *type_str = NULL;
4948           int type_pos = 0;
4949
4950           _dbus_assert (validity == DBUS_VALID);
4951
4952           message = dbus_message_new_empty_header (is_gvariant);
4953           if (message == NULL)
4954             return NULL;
4955
4956           /*
4957            * Validate and copy over header
4958            */
4959           _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
4960           _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (data));
4961
4962           if (!_dbus_header_load (&message->header,
4963                                   DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED,
4964                                   &validity,
4965                                   byte_order,
4966                                   fields_array_len,
4967                                   header_len,
4968                                   body_len,
4969                                   data, 0,
4970                                   _dbus_string_get_length (data)))
4971             {
4972               _dbus_verbose ("Failed to load header for new message code %d\n", validity);
4973               dbus_message_unref (message);
4974               return NULL;
4975             }
4976
4977           _dbus_assert (validity == DBUS_VALID);
4978
4979           /*
4980            * Validate body
4981            */
4982           if (_dbus_message_is_gvariant (message))
4983             {
4984               validity = _dbus_validate_gvariant_body_with_reason (type_str,
4985                                                                    type_pos,
4986                                                                    byte_order,
4987                                                                    NULL,
4988                                                                    data,
4989                                                                    header_len,
4990                                                                    body_len);
4991             }
4992           else
4993             {
4994               _dbus_verbose ("Not valid GVariant dbus message\n");
4995               dbus_message_unref (message);
4996               return NULL;
4997             }
4998
4999           if (validity != DBUS_VALID)
5000             {
5001               _dbus_verbose ("Failed to validate message body code %d\n", validity);
5002               dbus_message_unref (message);
5003               return NULL;
5004             }
5005
5006           /*
5007            * Copy over Unix FDS
5008            */
5009           _dbus_header_get_field_basic(&message->header,
5010                                        DBUS_HEADER_FIELD_UNIX_FDS,
5011                                        DBUS_TYPE_UINT32,
5012                                        &n_unix_fds);
5013
5014 #ifdef HAVE_UNIX_FD_PASSING
5015
5016           if (n_unix_fds > n_fds)
5017             {
5018               _dbus_verbose("Message contains references to more unix fds than were sent %u != %u\n",
5019                             n_unix_fds, message->n_unix_fds);
5020               dbus_message_unref (message);
5021               return NULL;
5022             }
5023
5024           /* If this was a recycled message there might still be
5025              some memory allocated for the fds */
5026           dbus_free(message->unix_fds);
5027
5028           if (n_unix_fds > 0)
5029             {
5030               message->unix_fds = _dbus_memdup(fds, n_unix_fds * sizeof(message->unix_fds[0]));
5031               if (message->unix_fds == NULL)
5032                 {
5033                   _dbus_verbose ("Failed to allocate file descriptor array\n");
5034                   dbus_message_unref (message);
5035                   return NULL;
5036                 }
5037
5038               message->n_unix_fds_allocated = message->n_unix_fds = n_unix_fds;
5039             }
5040           else
5041             message->unix_fds = NULL;
5042 #else
5043           if (n_unix_fds > 0)
5044             {
5045               _dbus_verbose ("Hmm, message claims to come with file descriptors "
5046                              "but that's not supported on our platform, disconnecting.\n");
5047               dbus_message_unref (message);
5048               return NULL;
5049             }
5050 #endif
5051
5052           /*
5053            * Copy over message body
5054            */
5055           _dbus_assert (_dbus_string_get_length (&message->body) == 0);
5056           _dbus_assert (_dbus_string_get_length (data) >= (header_len + body_len));
5057
5058           if (!_dbus_string_copy_len (data, header_len, body_len, &message->body, 0))
5059             {
5060               _dbus_verbose ("Failed to move body into new message\n");
5061               dbus_message_unref (message);
5062               return NULL;
5063             }
5064
5065           _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
5066           _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
5067
5068            set_unique_sender (message, sender_id);
5069            message->locked = TRUE;
5070
5071            /* Yupi, we have DBusMessage* */
5072            return message;
5073         }
5074       else
5075         {
5076           _dbus_verbose ("Data broken with invalid code %d\n", validity);
5077           return NULL;
5078         } /* if _dbus_header_have_message_untrusted() */
5079
5080     }
5081   else
5082     {
5083       _dbus_verbose ("message size < DBUS_MINIMUM_HEADER_SIZE\n");
5084       return NULL;
5085     } /* if DBUS_MINIMUM_HEADER_SIZE */
5086 }
5087
5088 /**
5089  * Peeks at first loaded message, returns #NULL if no messages have
5090  * been queued.
5091  *
5092  * @param loader the loader.
5093  * @returns the next message, or #NULL if none.
5094  */
5095 DBusMessage*
5096 _dbus_message_loader_peek_message (DBusMessageLoader *loader)
5097 {
5098   if (loader->messages)
5099     return loader->messages->data;
5100   else
5101     return NULL;
5102 }
5103
5104 /**
5105  * Pops a loaded message (passing ownership of the message
5106  * to the caller). Returns #NULL if no messages have been
5107  * queued.
5108  *
5109  * @param loader the loader.
5110  * @returns the next message, or #NULL if none.
5111  */
5112 DBusMessage*
5113 _dbus_message_loader_pop_message (DBusMessageLoader *loader)
5114 {
5115   return _dbus_list_pop_first (&loader->messages);
5116 }
5117
5118 /**
5119  * Pops a loaded message inside a list link (passing ownership of the
5120  * message and link to the caller). Returns #NULL if no messages have
5121  * been loaded.
5122  *
5123  * @param loader the loader.
5124  * @returns the next message link, or #NULL if none.
5125  */
5126 DBusList*
5127 _dbus_message_loader_pop_message_link (DBusMessageLoader *loader)
5128 {
5129   return _dbus_list_pop_first_link (&loader->messages);
5130 }
5131
5132 /**
5133  * Returns a popped message link, used to undo a pop.
5134  *
5135  * @param loader the loader
5136  * @param link the link with a message in it
5137  */
5138 void
5139 _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
5140                                            DBusList           *link)
5141 {
5142   _dbus_list_prepend_link (&loader->messages, link);
5143 }
5144
5145 /**
5146  * Checks whether the loader is confused due to bad data.
5147  * If messages are received that are invalid, the
5148  * loader gets confused and gives up permanently.
5149  * This state is called "corrupted."
5150  *
5151  * @param loader the loader
5152  * @returns #TRUE if the loader is hosed.
5153  */
5154 dbus_bool_t
5155 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
5156 {
5157   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
5158                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
5159   return loader->corrupted;
5160 }
5161
5162 /**
5163  * Checks what kind of bad data confused the loader.
5164  *
5165  * @param loader the loader
5166  * @returns why the loader is hosed, or DBUS_VALID if it isn't.
5167  */
5168 DBusValidity
5169 _dbus_message_loader_get_corruption_reason (DBusMessageLoader *loader)
5170 {
5171   _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
5172                 (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
5173
5174   return loader->corruption_reason;
5175 }
5176
5177 /**
5178  * Sets the maximum size message we allow.
5179  *
5180  * @param loader the loader
5181  * @param size the max message size in bytes
5182  */
5183 void
5184 _dbus_message_loader_set_max_message_size (DBusMessageLoader  *loader,
5185                                            long                size)
5186 {
5187   if (size > DBUS_MAXIMUM_MESSAGE_LENGTH)
5188     {
5189       _dbus_verbose ("clamping requested max message size %ld to %d\n",
5190                      size, DBUS_MAXIMUM_MESSAGE_LENGTH);
5191       size = DBUS_MAXIMUM_MESSAGE_LENGTH;
5192     }
5193   loader->max_message_size = size;
5194 }
5195
5196 /**
5197  * Gets the maximum allowed message size in bytes.
5198  *
5199  * @param loader the loader
5200  * @returns max size in bytes
5201  */
5202 long
5203 _dbus_message_loader_get_max_message_size (DBusMessageLoader  *loader)
5204 {
5205   return loader->max_message_size;
5206 }
5207
5208 /**
5209  * Sets the maximum unix fds per message we allow.
5210  *
5211  * @param loader the loader
5212  * @param n the max number of unix fds in a message
5213  */
5214 void
5215 _dbus_message_loader_set_max_message_unix_fds (DBusMessageLoader  *loader,
5216                                                long                n)
5217 {
5218   if (n > DBUS_MAXIMUM_MESSAGE_UNIX_FDS)
5219     {
5220       _dbus_verbose ("clamping requested max message unix_fds %ld to %d\n",
5221                      n, DBUS_MAXIMUM_MESSAGE_UNIX_FDS);
5222       n = DBUS_MAXIMUM_MESSAGE_UNIX_FDS;
5223     }
5224   loader->max_message_unix_fds = n;
5225 }
5226
5227 /**
5228  * Gets the maximum allowed number of unix fds per message
5229  *
5230  * @param loader the loader
5231  * @returns max unix fds
5232  */
5233 long
5234 _dbus_message_loader_get_max_message_unix_fds (DBusMessageLoader  *loader)
5235 {
5236   return loader->max_message_unix_fds;
5237 }
5238
5239 /**
5240  * Return how many file descriptors are pending in the loader
5241  *
5242  * @param loader the loader
5243  */
5244 int
5245 _dbus_message_loader_get_pending_fds_count (DBusMessageLoader *loader)
5246 {
5247 #ifdef HAVE_UNIX_FD_PASSING
5248   return loader->n_unix_fds;
5249 #else
5250   return 0;
5251 #endif
5252 }
5253
5254 /**
5255  * Register a function to be called whenever the number of pending file
5256  * descriptors in the loader change.
5257  *
5258  * @param loader the loader
5259  * @param callback the callback
5260  * @param data the data for the callback
5261  */
5262 void
5263 _dbus_message_loader_set_pending_fds_function (DBusMessageLoader *loader,
5264                                                void (* callback) (void *),
5265                                                void *data)
5266 {
5267 #ifdef HAVE_UNIX_FD_PASSING
5268   loader->unix_fds_change = callback;
5269   loader->unix_fds_change_data = data;
5270 #endif
5271 }
5272
5273 void
5274 _dbus_message_loader_set_unique_sender_id (DBusMessageLoader *loader,
5275                                            uint64_t           id)
5276 {
5277   loader->unique_sender_id = id;
5278 }
5279
5280 uint64_t
5281 _dbus_message_loader_get_unique_sender_id (DBusMessageLoader *loader)
5282 {
5283   return loader->unique_sender_id;
5284 }
5285
5286 static DBusDataSlotAllocator slot_allocator =
5287   _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (message_slots));
5288
5289 /**
5290  * Allocates an integer ID to be used for storing application-specific
5291  * data on any DBusMessage. The allocated ID may then be used
5292  * with dbus_message_set_data() and dbus_message_get_data().
5293  * The passed-in slot must be initialized to -1, and is filled in
5294  * with the slot ID. If the passed-in slot is not -1, it's assumed
5295  * to be already allocated, and its refcount is incremented.
5296  *
5297  * The allocated slot is global, i.e. all DBusMessage objects will
5298  * have a slot with the given integer ID reserved.
5299  *
5300  * @param slot_p address of a global variable storing the slot
5301  * @returns #FALSE on failure (no memory)
5302  */
5303 dbus_bool_t
5304 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
5305 {
5306   return _dbus_data_slot_allocator_alloc (&slot_allocator,
5307                                           slot_p);
5308 }
5309
5310 /**
5311  * Deallocates a global ID for message data slots.
5312  * dbus_message_get_data() and dbus_message_set_data() may no
5313  * longer be used with this slot.  Existing data stored on existing
5314  * DBusMessage objects will be freed when the message is
5315  * finalized, but may not be retrieved (and may only be replaced if
5316  * someone else reallocates the slot).  When the refcount on the
5317  * passed-in slot reaches 0, it is set to -1.
5318  *
5319  * @param slot_p address storing the slot to deallocate
5320  */
5321 void
5322 dbus_message_free_data_slot (dbus_int32_t *slot_p)
5323 {
5324   _dbus_return_if_fail (*slot_p >= 0);
5325
5326   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5327 }
5328
5329 /**
5330  * Stores a pointer on a DBusMessage, along
5331  * with an optional function to be used for freeing
5332  * the data when the data is set again, or when
5333  * the message is finalized. The slot number
5334  * must have been allocated with dbus_message_allocate_data_slot().
5335  *
5336  * @param message the message
5337  * @param slot the slot number
5338  * @param data the data to store
5339  * @param free_data_func finalizer function for the data
5340  * @returns #TRUE if there was enough memory to store the data
5341  */
5342 dbus_bool_t
5343 dbus_message_set_data (DBusMessage     *message,
5344                        dbus_int32_t     slot,
5345                        void            *data,
5346                        DBusFreeFunction free_data_func)
5347 {
5348   DBusFreeFunction old_free_func;
5349   void *old_data;
5350   dbus_bool_t retval;
5351
5352   _dbus_return_val_if_fail (message != NULL, FALSE);
5353   _dbus_return_val_if_fail (slot >= 0, FALSE);
5354
5355   retval = _dbus_data_slot_list_set (&slot_allocator,
5356                                      &message->slot_list,
5357                                      slot, data, free_data_func,
5358                                      &old_free_func, &old_data);
5359
5360   if (retval)
5361     {
5362       /* Do the actual free outside the message lock */
5363       if (old_free_func)
5364         (* old_free_func) (old_data);
5365     }
5366
5367   return retval;
5368 }
5369
5370 /**
5371  * Retrieves data previously set with dbus_message_set_data().
5372  * The slot must still be allocated (must not have been freed).
5373  *
5374  * @param message the message
5375  * @param slot the slot to get data from
5376  * @returns the data, or #NULL if not found
5377  */
5378 void*
5379 dbus_message_get_data (DBusMessage   *message,
5380                        dbus_int32_t   slot)
5381 {
5382   void *res;
5383
5384   _dbus_return_val_if_fail (message != NULL, NULL);
5385
5386   res = _dbus_data_slot_list_get (&slot_allocator,
5387                                   &message->slot_list,
5388                                   slot);
5389
5390   return res;
5391 }
5392
5393 /**
5394  * Utility function to convert a machine-readable (not translated)
5395  * string into a D-Bus message type.
5396  *
5397  * @code
5398  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
5399  *   "method_return"  -> DBUS_MESSAGE_TYPE_METHOD_RETURN
5400  *   "signal"         -> DBUS_MESSAGE_TYPE_SIGNAL
5401  *   "error"          -> DBUS_MESSAGE_TYPE_ERROR
5402  *   anything else    -> DBUS_MESSAGE_TYPE_INVALID
5403  * @endcode
5404  *
5405  */
5406 int
5407 dbus_message_type_from_string (const char *type_str)
5408 {
5409   if (strcmp (type_str, "method_call") == 0)
5410     return DBUS_MESSAGE_TYPE_METHOD_CALL;
5411   if (strcmp (type_str, "method_return") == 0)
5412     return DBUS_MESSAGE_TYPE_METHOD_RETURN;
5413   else if (strcmp (type_str, "signal") == 0)
5414     return DBUS_MESSAGE_TYPE_SIGNAL;
5415   else if (strcmp (type_str, "error") == 0)
5416     return DBUS_MESSAGE_TYPE_ERROR;
5417   else
5418     return DBUS_MESSAGE_TYPE_INVALID;
5419 }
5420
5421 /**
5422  * Utility function to convert a D-Bus message type into a
5423  * machine-readable string (not translated).
5424  *
5425  * @code
5426  *   DBUS_MESSAGE_TYPE_METHOD_CALL    -> "method_call"
5427  *   DBUS_MESSAGE_TYPE_METHOD_RETURN  -> "method_return"
5428  *   DBUS_MESSAGE_TYPE_SIGNAL         -> "signal"
5429  *   DBUS_MESSAGE_TYPE_ERROR          -> "error"
5430  *   DBUS_MESSAGE_TYPE_INVALID        -> "invalid"
5431  * @endcode
5432  *
5433  */
5434 const char *
5435 dbus_message_type_to_string (int type)
5436 {
5437   switch (type)
5438     {
5439     case DBUS_MESSAGE_TYPE_METHOD_CALL:
5440       return "method_call";
5441     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
5442       return "method_return";
5443     case DBUS_MESSAGE_TYPE_SIGNAL:
5444       return "signal";
5445     case DBUS_MESSAGE_TYPE_ERROR:
5446       return "error";
5447     default:
5448       return "invalid";
5449     }
5450 }
5451
5452 /**
5453  * Turn a DBusMessage into the marshalled form as described in the D-Bus
5454  * specification.
5455  *
5456  * Generally, this function is only useful for encapsulating D-Bus messages in
5457  * a different protocol.
5458  *
5459  * @param msg the DBusMessage
5460  * @param marshalled_data_p the location to save the marshalled form to
5461  * @param len_p the location to save the length of the marshalled form to
5462  * @returns #FALSE if there was not enough memory
5463  */
5464 dbus_bool_t
5465 dbus_message_marshal (DBusMessage  *msg,
5466                       char        **marshalled_data_p,
5467                       int          *len_p)
5468 {
5469   DBusString tmp;
5470   dbus_bool_t was_locked;
5471
5472   _dbus_return_val_if_fail (msg != NULL, FALSE);
5473   _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
5474   _dbus_return_val_if_fail (len_p != NULL, FALSE);
5475
5476   if (!_dbus_string_init (&tmp))
5477     return FALSE;
5478
5479   /* Ensure the message is locked, to ensure the length header is filled in. */
5480   was_locked = msg->locked;
5481
5482   if (!was_locked)
5483     dbus_message_lock (msg);
5484
5485   if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
5486     goto fail;
5487
5488   *len_p = _dbus_string_get_length (&tmp);
5489
5490   if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
5491     goto fail;
5492
5493   *len_p = _dbus_string_get_length (&tmp);
5494
5495   if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
5496     goto fail;
5497
5498   _dbus_string_free (&tmp);
5499
5500   if (!was_locked)
5501     msg->locked = FALSE;
5502
5503   return TRUE;
5504
5505  fail:
5506   _dbus_string_free (&tmp);
5507
5508   if (!was_locked)
5509     msg->locked = FALSE;
5510
5511   return FALSE;
5512 }
5513
5514 /**
5515  * Demarshal a D-Bus message from the format described in the D-Bus
5516  * specification.
5517  *
5518  * Generally, this function is only useful for encapsulating D-Bus messages in
5519  * a different protocol.
5520  *
5521  * @param str the marshalled DBusMessage
5522  * @param len the length of str
5523  * @param error the location to save errors to
5524  * @returns #NULL if there was an error
5525  */
5526 DBusMessage *
5527 dbus_message_demarshal (const char *str,
5528                         int         len,
5529                         DBusError  *error)
5530 {
5531   DBusMessageLoader *loader;
5532   DBusString *buffer;
5533   DBusMessage *msg;
5534
5535   _dbus_return_val_if_fail (str != NULL, NULL);
5536
5537   loader = _dbus_message_loader_new ();
5538
5539   if (loader == NULL)
5540     return NULL;
5541
5542   _dbus_message_loader_get_buffer (loader, &buffer, NULL, NULL);
5543
5544   if (!_dbus_string_append_len (buffer, str, len))
5545     goto fail_oom;
5546
5547   _dbus_message_loader_return_buffer (loader, buffer);
5548
5549   if (!_dbus_message_loader_queue_messages (loader))
5550     goto fail_oom;
5551
5552   if (_dbus_message_loader_get_is_corrupted (loader))
5553     goto fail_corrupt;
5554
5555   msg = _dbus_message_loader_pop_message (loader);
5556
5557   if (!msg)
5558     goto fail_oom;
5559
5560   _dbus_message_loader_unref (loader);
5561   return msg;
5562
5563  fail_corrupt:
5564   dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted (%s)",
5565                   _dbus_validity_to_error_message (loader->corruption_reason));
5566   _dbus_message_loader_unref (loader);
5567   return NULL;
5568
5569  fail_oom:
5570   _DBUS_SET_OOM (error);
5571   _dbus_message_loader_unref (loader);
5572   return NULL;
5573 }
5574
5575 /**
5576  * Returns the number of bytes required to be in the buffer to demarshal a
5577  * D-Bus message.
5578  *
5579  * Generally, this function is only useful for encapsulating D-Bus messages in
5580  * a different protocol.
5581  *
5582  * @param buf data to be marshalled
5583  * @param len the length of @p buf
5584  * @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
5585  *
5586  */
5587 int
5588 dbus_message_demarshal_bytes_needed(const char *buf,
5589                                     int         len)
5590 {
5591   DBusString str;
5592   int byte_order, fields_array_len, header_len, body_len;
5593   DBusValidity validity = DBUS_VALID;
5594   int have_message;
5595   dbus_bool_t is_gvariant;
5596
5597   if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
5598     return 0;
5599
5600   if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
5601     len = DBUS_MAXIMUM_MESSAGE_LENGTH;
5602   _dbus_string_init_const_len (&str, buf, len);
5603
5604   validity = DBUS_VALID;
5605   have_message
5606     = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
5607                                           &validity, &byte_order,
5608                                           &fields_array_len,
5609                                           &header_len,
5610                                           &body_len,
5611                                           &str, 0,
5612                                           len,
5613                                           &is_gvariant);
5614   _dbus_string_free (&str);
5615
5616   if (validity == DBUS_VALID)
5617     {
5618       _dbus_assert (have_message || (header_len + body_len) > len);
5619       (void) have_message; /* unused unless asserting */
5620       return header_len + body_len;
5621     }
5622   else
5623     {
5624       return -1; /* broken! */
5625     }
5626 }
5627
5628 static dbus_bool_t
5629 _dbus_message_copy_recursive(DBusMessageIter *iter, DBusMessageIter *dest)
5630 {
5631   dbus_bool_t res = TRUE;
5632   int current_type;
5633
5634   while ((current_type = dbus_message_iter_get_arg_type (iter)) != DBUS_TYPE_INVALID) {
5635     if (dbus_type_is_basic(current_type)) {
5636       DBusBasicValue value;
5637       dbus_message_iter_get_basic (iter, &value);
5638       dbus_message_iter_append_basic (dest, current_type, &value);
5639     }
5640     else {
5641       DBusMessageIter sub;
5642       DBusMessageIter dest_sub;
5643       char *sig = NULL;
5644
5645       dbus_message_iter_recurse (iter, &sub);
5646       if (DBUS_TYPE_VARIANT == current_type)
5647         sig = dbus_message_iter_get_signature (&sub);
5648       else if (DBUS_TYPE_ARRAY == current_type)
5649         sig = dbus_message_iter_get_signature (&sub);
5650
5651       res = res && dbus_message_iter_open_container (dest, current_type, sig, &dest_sub);
5652       dbus_free(sig);
5653       res = res && _dbus_message_copy_recursive (&sub, &dest_sub);
5654       res = res && dbus_message_iter_close_container (dest, &dest_sub);
5655
5656       if (!res) {
5657         return FALSE;
5658       }
5659    }
5660
5661    dbus_message_iter_next (iter);
5662   }
5663
5664   return TRUE;
5665 }
5666
5667 void
5668 _dbus_on_new_bus (int type)
5669 {
5670   _dbus_assert (type == DBUS_MAJOR_PROTOCOL_VERSION || type == DBUS_PROTOCOL_VERSION_GVARIANT);
5671   _dbus_protocol_strategy_bus_function (type);
5672 }
5673
5674 static void
5675 _dbus_on_send_message (int type)
5676 {
5677   _dbus_assert (type == DBUS_MAJOR_PROTOCOL_VERSION || type == DBUS_PROTOCOL_VERSION_GVARIANT);
5678   _dbus_protocol_strategy_message_function (type);
5679 }
5680
5681 DBusMessage *
5682 _dbus_message_remarshal (DBusMessage *message, dbus_bool_t gvariant)
5683 {
5684   DBusMessage *ret;
5685   DBusMessageIter iter, ret_iter;
5686   size_t i;
5687   dbus_uint32_t serial;
5688   const char *sender;
5689
5690   _dbus_assert (message->locked);
5691
5692   _dbus_on_send_message (gvariant ? DBUS_PROTOCOL_VERSION_GVARIANT : DBUS_MAJOR_PROTOCOL_VERSION);
5693
5694   ret = _dbus_message_create_protocol_version (dbus_message_get_type(message),
5695                                                dbus_message_get_destination(message),
5696                                                dbus_message_get_path(message),
5697                                                dbus_message_get_interface(message),
5698                                                dbus_message_get_member(message),
5699                                                dbus_message_get_error_name(message),
5700                                                gvariant);
5701
5702   dbus_message_iter_init (message, &iter);
5703   dbus_message_iter_init_append (ret, &ret_iter);
5704   if (!_dbus_message_copy_recursive(&iter, &ret_iter))
5705     return NULL;
5706
5707 #ifdef HAVE_UNIX_FD_PASSING
5708   ret->unix_fds = dbus_new(int, message->n_unix_fds);
5709   if (ret->unix_fds == NULL && message->n_unix_fds > 0)
5710     goto err;
5711
5712   ret->n_unix_fds_allocated = message->n_unix_fds;
5713
5714   for (i = 0; i < message->n_unix_fds; ++i) {
5715     ret->unix_fds[i] = _dbus_dup(message->unix_fds[i], NULL);
5716
5717     if (ret->unix_fds[i] < 0) {
5718       ret->n_unix_fds = i;
5719       goto err;
5720     }
5721   }
5722
5723   ret->n_unix_fds = message->n_unix_fds;
5724 #endif
5725
5726   /* Remarshal data in header:
5727      byte order (already set)
5728      type (already set)
5729      flags - only those we understand
5730      version (already set)
5731      body length
5732      serial
5733      fields array (length)
5734      fields:
5735          path (already set)
5736          interface (already set)
5737          member (already set)
5738          error name (already set)
5739          reply serial
5740          destination (already set)
5741          sender
5742          signature (set during copy, but an action needed for conversion to GVariant)
5743          unix fds
5744    */
5745
5746   /* FLAGS */
5747   _dbus_header_toggle_flag (&ret->header, DBUS_HEADER_FLAG_NO_REPLY_EXPECTED,
5748       _dbus_header_get_flag (&message->header, DBUS_HEADER_FLAG_NO_REPLY_EXPECTED));
5749
5750   _dbus_header_toggle_flag (&ret->header, DBUS_HEADER_FLAG_NO_AUTO_START,
5751       _dbus_header_get_flag (&message->header, DBUS_HEADER_FLAG_NO_AUTO_START));
5752
5753   /* SERIAL / COOKIE */
5754   serial = dbus_message_get_serial (message);
5755
5756   if (0 != serial)
5757     dbus_message_set_serial (ret, serial);
5758
5759   /* Field: REPLY_SERIAL */
5760   serial = dbus_message_get_reply_serial (message);
5761
5762   if (0 != serial && !dbus_message_set_reply_serial (ret, serial))
5763     goto err;
5764
5765   /* Field: SENDER */
5766   sender = dbus_message_get_sender (message);
5767
5768   if (NULL != sender && !dbus_message_set_sender (ret, sender))
5769     goto err;
5770
5771   /* BODY LENGTH */
5772   if (!gvariant)
5773     _dbus_header_update_lengths (&ret->header,
5774                                  _dbus_string_get_length (&ret->body));
5775     /* For GVariant: */
5776     /* Field: SIGNATURE to body; add body offset - this is done with dbus_message_lock() */
5777   else
5778     dbus_message_lock (ret);
5779
5780   return ret;
5781
5782 err:
5783   _dbus_header_free (&ret->header);
5784   _dbus_string_free (&ret->body);
5785
5786 #ifdef HAVE_UNIX_FD_PASSING
5787   if (ret->unix_fds)
5788     {
5789       close_unix_fds(ret->unix_fds, &ret->n_unix_fds);
5790       dbus_free(ret->unix_fds);
5791     }
5792 #endif
5793
5794   return NULL;
5795 }
5796
5797 void
5798 dbus_set_protocol_version (unsigned char version)
5799 {
5800   _dbus_default_protocol_version = version;
5801 }
5802
5803 static void
5804 protocol_strategy_first_type (int type)
5805 {
5806   /* change protocol once */
5807   if (!_dbus_first_bus_open)
5808     {
5809       _dbus_first_bus_open = TRUE;
5810       _dbus_default_protocol_version = type;
5811     }
5812 }
5813
5814 static void
5815 protocol_strategy_last_type (int type)
5816 {
5817   /* change protocol every time it is needed */
5818   if (_dbus_default_protocol_version != type)
5819     _dbus_default_protocol_version = type;
5820 }
5821
5822 static void
5823 protocol_strategy_static (int type)
5824 {
5825   /* do not change */
5826 }
5827
5828 void
5829 dbus_set_default_protocol_strategy (const char *strategy_name)
5830 {
5831   if (strcmp (strategy_name, "first-bus") == 0)
5832     {
5833       _dbus_protocol_strategy_bus_function = protocol_strategy_first_type;
5834       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5835     }
5836   else if (strcmp (strategy_name, "dbus1") == 0)
5837     {
5838       _dbus_default_protocol_version = DBUS_MAJOR_PROTOCOL_VERSION;
5839       _dbus_protocol_strategy_bus_function = protocol_strategy_static;
5840       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5841     }
5842   else if (strcmp (strategy_name, "gvariant") == 0)
5843     {
5844       _dbus_default_protocol_version = DBUS_PROTOCOL_VERSION_GVARIANT;
5845       _dbus_protocol_strategy_bus_function = protocol_strategy_static;
5846       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5847     }
5848   else if (strcmp (strategy_name, "last-message") == 0)
5849     {
5850       _dbus_protocol_strategy_bus_function = protocol_strategy_static;
5851       _dbus_protocol_strategy_message_function = protocol_strategy_last_type;
5852     }
5853   else /* "last-bus" is default strategy */
5854     {
5855       _dbus_protocol_strategy_bus_function = protocol_strategy_last_type;
5856       _dbus_protocol_strategy_message_function = protocol_strategy_static;
5857     }
5858 }
5859
5860 DBusMessage *
5861 _dbus_generate_local_error_message (dbus_uint32_t serial,
5862                                     const char *error_name,
5863                                     const char *error_msg)
5864 {
5865   DBusMessage *message;
5866   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
5867   if (!message)
5868     goto out;
5869
5870   if (!dbus_message_set_error_name (message, error_name))
5871     {
5872       dbus_message_unref (message);
5873       message = NULL;
5874       goto out;
5875     }
5876
5877   dbus_message_set_no_reply (message, TRUE);
5878
5879   if (!dbus_message_set_reply_serial (message,
5880                                       serial))
5881     {
5882       dbus_message_unref (message);
5883       message = NULL;
5884       goto out;
5885     }
5886
5887   if (error_msg != NULL)
5888     {
5889       DBusMessageIter iter;
5890
5891       dbus_message_iter_init_append (message, &iter);
5892       if (!dbus_message_iter_append_basic (&iter,
5893                                            DBUS_TYPE_STRING,
5894                                            &error_msg))
5895         {
5896           dbus_message_unref (message);
5897           message = NULL;
5898           goto out;
5899         }
5900     }
5901
5902  out:
5903   return message;
5904 }
5905
5906 dbus_bool_t
5907 _dbus_message_assure_dbus1 (DBusMessage **message)
5908 {
5909   if ((*message)->header.protocol_version != DBUS_MAJOR_PROTOCOL_VERSION)
5910     {
5911       *message = _dbus_message_remarshal (*message, FALSE);
5912       return TRUE;
5913     }
5914   return FALSE;
5915 }
5916
5917 dbus_bool_t
5918 _dbus_message_assure_gvariant (DBusMessage **message)
5919 {
5920   if ((*message)->header.protocol_version != DBUS_PROTOCOL_VERSION_GVARIANT)
5921     {
5922       *message = _dbus_message_remarshal (*message, TRUE);
5923       return TRUE;
5924     }
5925   return FALSE;
5926 }
5927
5928 /**
5929  * An opaque data structure containing the serialized form of any single
5930  * D-Bus message item, whose signature is a single complete type.
5931  *
5932  * (Implementation detail: It's serialized as a single variant.)
5933  */
5934 struct DBusVariant
5935 {
5936   DBusString data;
5937 };
5938
5939 /**
5940  * Copy a single D-Bus message item from reader into a
5941  * newly-allocated #DBusVariant.
5942  *
5943  * For example, if a message contains three string arguments, and reader points
5944  * to the second string, the resulting DBusVariant will have signature
5945  * #DBUS_TYPE_STRING_AS_STRING and contain only that second string.
5946  *
5947  * @param reader An iterator over message items, pointing to one item to copy
5948  * @returns The variant, or #NULL if out of memory
5949  */
5950 DBusVariant *
5951 _dbus_variant_read (DBusMessageIter *reader)
5952 {
5953   DBusVariant *self = NULL;
5954   /* Points to the single item we will read from the reader */
5955   DBusMessageRealIter *real_reader = (DBusMessageRealIter *) reader;
5956   /* The position in self at which we will write a single variant
5957    * (it is position 0) */
5958   DBusTypeWriter items_writer;
5959   /* The position in self at which we will write a copy of reader
5960    * (it is inside the variant) */
5961   DBusTypeWriter variant_writer;
5962   /* 'v' */
5963   DBusString variant_signature;
5964   /* Whatever is the signature of the item we will copy from the reader */
5965   DBusString contained_signature;
5966   /* TRUE if self->data needs to be freed */
5967   dbus_bool_t data_inited = FALSE;
5968   /* The type of the item we will read from the reader */
5969   int type;
5970   /* The string, start position within that string, and length of the signature
5971    * of the single complete type of the item reader points to */
5972   const DBusString *sig;
5973   int start, len;
5974
5975   _dbus_assert (_dbus_message_iter_check (real_reader));
5976   _dbus_assert (real_reader->iter_type == DBUS_MESSAGE_ITER_TYPE_READER);
5977   _dbus_string_init_const (&variant_signature, DBUS_TYPE_VARIANT_AS_STRING);
5978   type = dbus_message_iter_get_arg_type (reader);
5979   _dbus_type_reader_get_signature (&real_reader->u.reader, &sig, &start, &len);
5980
5981   if (!_dbus_string_init (&contained_signature))
5982     return NULL;
5983
5984   if (!_dbus_string_copy_len (sig, start, len, &contained_signature, 0))
5985     goto oom;
5986
5987   self = dbus_new0 (DBusVariant, 1);
5988
5989   if (self == NULL)
5990     goto oom;
5991
5992   if (!_dbus_string_init (&self->data))
5993     goto oom;
5994
5995   data_inited = TRUE;
5996
5997   _dbus_type_writer_init_values_only (&items_writer, DBUS_COMPILER_BYTE_ORDER,
5998                                       &variant_signature, 0, &self->data, 0);
5999
6000   if (!_dbus_type_writer_recurse (&items_writer, DBUS_TYPE_VARIANT,
6001                                   &contained_signature, 0, &variant_writer))
6002     goto oom;
6003
6004   if (type == DBUS_TYPE_ARRAY)
6005     {
6006       /* Points to each item in turn inside the array we are copying */
6007       DBusMessageIter array_reader;
6008       /* Same as array_reader */
6009       DBusMessageRealIter *real_array_reader = (DBusMessageRealIter *) &array_reader;
6010       /* The position inside the copied array at which we will write
6011        * the copy of array_reader */
6012       DBusTypeWriter array_writer;
6013
6014       dbus_message_iter_recurse (reader, &array_reader);
6015
6016       if (!_dbus_type_writer_recurse (&variant_writer, type,
6017                                       &contained_signature, 1, &array_writer))
6018         goto oom;
6019
6020       if (!_dbus_type_writer_write_reader (&array_writer,
6021                                            &real_array_reader->u.reader))
6022         goto oom;
6023
6024       if (!_dbus_type_writer_unrecurse (&variant_writer, &array_writer))
6025         goto oom;
6026     }
6027   else if (type == DBUS_TYPE_DICT_ENTRY || type == DBUS_TYPE_VARIANT ||
6028            type == DBUS_TYPE_STRUCT)
6029     {
6030       /* Points to each item in turn inside the container we are copying */
6031       DBusMessageIter inner_reader;
6032       /* Same as inner_reader */
6033       DBusMessageRealIter *real_inner_reader = (DBusMessageRealIter *) &inner_reader;
6034       /* The position inside the copied container at which we will write the
6035        * copy of inner_reader */
6036       DBusTypeWriter inner_writer;
6037
6038       dbus_message_iter_recurse (reader, &inner_reader);
6039
6040       if (!_dbus_type_writer_recurse (&variant_writer, type, NULL, 0,
6041                                       &inner_writer))
6042         goto oom;
6043
6044       if (!_dbus_type_writer_write_reader (&inner_writer,
6045                                            &real_inner_reader->u.reader))
6046         goto oom;
6047
6048       if (!_dbus_type_writer_unrecurse (&variant_writer, &inner_writer))
6049         goto oom;
6050     }
6051   else
6052     {
6053       DBusBasicValue value;
6054
6055       /* We eliminated all the container types above */
6056       _dbus_assert (dbus_type_is_basic (type));
6057
6058       dbus_message_iter_get_basic (reader, &value);
6059
6060       if (!_dbus_type_writer_write_basic (&variant_writer, type, &value))
6061         goto oom;
6062     }
6063
6064   _dbus_string_free (&contained_signature);
6065   return self;
6066
6067 oom:
6068   if (self != NULL)
6069     {
6070       if (data_inited)
6071         _dbus_string_free (&self->data);
6072
6073       dbus_free (self);
6074     }
6075
6076   _dbus_string_free (&contained_signature);
6077   return NULL;
6078 }
6079
6080 /**
6081  * Return the signature of the item stored in self. It is a single complete
6082  * type.
6083  *
6084  * @param self the variant
6085  */
6086 const char *
6087 _dbus_variant_get_signature (DBusVariant *self)
6088 {
6089   unsigned char len;
6090   const char *ret;
6091
6092   _dbus_assert (self != NULL);
6093
6094   /* Here we make use of the fact that the serialization of a variant starts
6095    * with the 1-byte length, then that many bytes of signature, then \0. */
6096   len = _dbus_string_get_byte (&self->data, 0);
6097   ret = _dbus_string_get_const_data_len (&self->data, 1, len);
6098   _dbus_assert (strlen (ret) == len);
6099   return ret;
6100 }
6101
6102 /**
6103  * Copy the single D-Bus message item from self into writer.
6104  *
6105  * For example, if writer points into the body of an empty message and self has
6106  * signature #DBUS_TYPE_STRING_AS_STRING, then the message will
6107  * have signature #DBUS_TYPE_STRING_AS_STRING after this function returns
6108  *
6109  * @param self the variant
6110  * @param writer the place to write the contents of the variant
6111  * @returns #TRUE on success, #FALSE if out of memory
6112  */
6113 dbus_bool_t
6114 _dbus_variant_write (DBusVariant *self,
6115                      DBusMessageIter *writer)
6116 {
6117   /* 'v' */
6118   DBusString variant_signature;
6119   /* Points to the single item in self */
6120   DBusTypeReader variant_reader;
6121   /* Points to the single item (of whatever type) inside the variant */
6122   DBusTypeReader reader;
6123   /* The position at which we will copy reader */
6124   DBusMessageRealIter *real_writer = (DBusMessageRealIter *) writer;
6125   dbus_bool_t ret;
6126
6127   _dbus_assert (self != NULL);
6128   _dbus_assert (_dbus_message_iter_append_check (real_writer));
6129   _dbus_assert (real_writer->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
6130
6131   _dbus_string_init_const (&variant_signature, DBUS_TYPE_VARIANT_AS_STRING);
6132   _dbus_type_reader_init (&reader, DBUS_COMPILER_BYTE_ORDER,
6133                           &variant_signature, 0, &self->data, 0);
6134   _dbus_type_reader_recurse (&reader, &variant_reader);
6135
6136   if (!_dbus_message_iter_open_signature (real_writer))
6137     return FALSE;
6138
6139   ret = _dbus_type_writer_write_reader (&real_writer->u.writer,
6140                                         &variant_reader);
6141
6142   if (!_dbus_message_iter_close_signature (real_writer))
6143     return FALSE;
6144
6145   return ret;
6146 }
6147
6148 int
6149 _dbus_variant_get_length (DBusVariant *self)
6150 {
6151   _dbus_assert (self != NULL);
6152   return _dbus_string_get_length (&self->data);
6153 }
6154
6155 const DBusString *
6156 _dbus_variant_peek (DBusVariant *self)
6157 {
6158   _dbus_assert (self != NULL);
6159   return &self->data;
6160 }
6161
6162 void
6163 _dbus_variant_free (DBusVariant *self)
6164 {
6165   _dbus_assert (self != NULL);
6166   _dbus_string_free (&self->data);
6167   dbus_free (self);
6168 }
6169
6170 /** @} */
6171
6172 /* tests in dbus-message-util.c */