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